您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

app.bundle.js 1013KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765
  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. // Copyright Joyent, Inc. and other Node contributors.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a
  5. // copy of this software and associated documentation files (the
  6. // "Software"), to deal in the Software without restriction, including
  7. // without limitation the rights to use, copy, modify, merge, publish,
  8. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9. // persons to whom the Software is furnished to do so, subject to the
  10. // following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included
  13. // in all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  16. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  18. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  19. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  20. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  21. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. function EventEmitter() {
  23. this._events = this._events || {};
  24. this._maxListeners = this._maxListeners || undefined;
  25. }
  26. module.exports = EventEmitter;
  27. // Backwards-compat with node 0.10.x
  28. EventEmitter.EventEmitter = EventEmitter;
  29. EventEmitter.prototype._events = undefined;
  30. EventEmitter.prototype._maxListeners = undefined;
  31. // By default EventEmitters will print a warning if more than 10 listeners are
  32. // added to it. This is a useful default which helps finding memory leaks.
  33. EventEmitter.defaultMaxListeners = 10;
  34. // Obviously not all Emitters should be limited to 10. This function allows
  35. // that to be increased. Set to zero for unlimited.
  36. EventEmitter.prototype.setMaxListeners = function(n) {
  37. if (!isNumber(n) || n < 0 || isNaN(n))
  38. throw TypeError('n must be a positive number');
  39. this._maxListeners = n;
  40. return this;
  41. };
  42. EventEmitter.prototype.emit = function(type) {
  43. var er, handler, len, args, i, listeners;
  44. if (!this._events)
  45. this._events = {};
  46. // If there is no 'error' event listener then throw.
  47. if (type === 'error') {
  48. if (!this._events.error ||
  49. (isObject(this._events.error) && !this._events.error.length)) {
  50. er = arguments[1];
  51. if (er instanceof Error) {
  52. throw er; // Unhandled 'error' event
  53. }
  54. throw TypeError('Uncaught, unspecified "error" event.');
  55. }
  56. }
  57. handler = this._events[type];
  58. if (isUndefined(handler))
  59. return false;
  60. if (isFunction(handler)) {
  61. switch (arguments.length) {
  62. // fast cases
  63. case 1:
  64. handler.call(this);
  65. break;
  66. case 2:
  67. handler.call(this, arguments[1]);
  68. break;
  69. case 3:
  70. handler.call(this, arguments[1], arguments[2]);
  71. break;
  72. // slower
  73. default:
  74. len = arguments.length;
  75. args = new Array(len - 1);
  76. for (i = 1; i < len; i++)
  77. args[i - 1] = arguments[i];
  78. handler.apply(this, args);
  79. }
  80. } else if (isObject(handler)) {
  81. len = arguments.length;
  82. args = new Array(len - 1);
  83. for (i = 1; i < len; i++)
  84. args[i - 1] = arguments[i];
  85. listeners = handler.slice();
  86. len = listeners.length;
  87. for (i = 0; i < len; i++)
  88. listeners[i].apply(this, args);
  89. }
  90. return true;
  91. };
  92. EventEmitter.prototype.addListener = function(type, listener) {
  93. var m;
  94. if (!isFunction(listener))
  95. throw TypeError('listener must be a function');
  96. if (!this._events)
  97. this._events = {};
  98. // To avoid recursion in the case that type === "newListener"! Before
  99. // adding it to the listeners, first emit "newListener".
  100. if (this._events.newListener)
  101. this.emit('newListener', type,
  102. isFunction(listener.listener) ?
  103. listener.listener : listener);
  104. if (!this._events[type])
  105. // Optimize the case of one listener. Don't need the extra array object.
  106. this._events[type] = listener;
  107. else if (isObject(this._events[type]))
  108. // If we've already got an array, just append.
  109. this._events[type].push(listener);
  110. else
  111. // Adding the second element, need to change to array.
  112. this._events[type] = [this._events[type], listener];
  113. // Check for listener leak
  114. if (isObject(this._events[type]) && !this._events[type].warned) {
  115. var m;
  116. if (!isUndefined(this._maxListeners)) {
  117. m = this._maxListeners;
  118. } else {
  119. m = EventEmitter.defaultMaxListeners;
  120. }
  121. if (m && m > 0 && this._events[type].length > m) {
  122. this._events[type].warned = true;
  123. console.error('(node) warning: possible EventEmitter memory ' +
  124. 'leak detected. %d listeners added. ' +
  125. 'Use emitter.setMaxListeners() to increase limit.',
  126. this._events[type].length);
  127. if (typeof console.trace === 'function') {
  128. // not supported in IE 10
  129. console.trace();
  130. }
  131. }
  132. }
  133. return this;
  134. };
  135. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  136. EventEmitter.prototype.once = function(type, listener) {
  137. if (!isFunction(listener))
  138. throw TypeError('listener must be a function');
  139. var fired = false;
  140. function g() {
  141. this.removeListener(type, g);
  142. if (!fired) {
  143. fired = true;
  144. listener.apply(this, arguments);
  145. }
  146. }
  147. g.listener = listener;
  148. this.on(type, g);
  149. return this;
  150. };
  151. // emits a 'removeListener' event iff the listener was removed
  152. EventEmitter.prototype.removeListener = function(type, listener) {
  153. var list, position, length, i;
  154. if (!isFunction(listener))
  155. throw TypeError('listener must be a function');
  156. if (!this._events || !this._events[type])
  157. return this;
  158. list = this._events[type];
  159. length = list.length;
  160. position = -1;
  161. if (list === listener ||
  162. (isFunction(list.listener) && list.listener === listener)) {
  163. delete this._events[type];
  164. if (this._events.removeListener)
  165. this.emit('removeListener', type, listener);
  166. } else if (isObject(list)) {
  167. for (i = length; i-- > 0;) {
  168. if (list[i] === listener ||
  169. (list[i].listener && list[i].listener === listener)) {
  170. position = i;
  171. break;
  172. }
  173. }
  174. if (position < 0)
  175. return this;
  176. if (list.length === 1) {
  177. list.length = 0;
  178. delete this._events[type];
  179. } else {
  180. list.splice(position, 1);
  181. }
  182. if (this._events.removeListener)
  183. this.emit('removeListener', type, listener);
  184. }
  185. return this;
  186. };
  187. EventEmitter.prototype.removeAllListeners = function(type) {
  188. var key, listeners;
  189. if (!this._events)
  190. return this;
  191. // not listening for removeListener, no need to emit
  192. if (!this._events.removeListener) {
  193. if (arguments.length === 0)
  194. this._events = {};
  195. else if (this._events[type])
  196. delete this._events[type];
  197. return this;
  198. }
  199. // emit removeListener for all listeners on all events
  200. if (arguments.length === 0) {
  201. for (key in this._events) {
  202. if (key === 'removeListener') continue;
  203. this.removeAllListeners(key);
  204. }
  205. this.removeAllListeners('removeListener');
  206. this._events = {};
  207. return this;
  208. }
  209. listeners = this._events[type];
  210. if (isFunction(listeners)) {
  211. this.removeListener(type, listeners);
  212. } else {
  213. // LIFO order
  214. while (listeners.length)
  215. this.removeListener(type, listeners[listeners.length - 1]);
  216. }
  217. delete this._events[type];
  218. return this;
  219. };
  220. EventEmitter.prototype.listeners = function(type) {
  221. var ret;
  222. if (!this._events || !this._events[type])
  223. ret = [];
  224. else if (isFunction(this._events[type]))
  225. ret = [this._events[type]];
  226. else
  227. ret = this._events[type].slice();
  228. return ret;
  229. };
  230. EventEmitter.listenerCount = function(emitter, type) {
  231. var ret;
  232. if (!emitter._events || !emitter._events[type])
  233. ret = 0;
  234. else if (isFunction(emitter._events[type]))
  235. ret = 1;
  236. else
  237. ret = emitter._events[type].length;
  238. return ret;
  239. };
  240. function isFunction(arg) {
  241. return typeof arg === 'function';
  242. }
  243. function isNumber(arg) {
  244. return typeof arg === 'number';
  245. }
  246. function isObject(arg) {
  247. return typeof arg === 'object' && arg !== null;
  248. }
  249. function isUndefined(arg) {
  250. return arg === void 0;
  251. }
  252. },{}],2:[function(require,module,exports){
  253. // shim for using process in browser
  254. var process = module.exports = {};
  255. var queue = [];
  256. var draining = false;
  257. var currentQueue;
  258. var queueIndex = -1;
  259. function cleanUpNextTick() {
  260. draining = false;
  261. if (currentQueue.length) {
  262. queue = currentQueue.concat(queue);
  263. } else {
  264. queueIndex = -1;
  265. }
  266. if (queue.length) {
  267. drainQueue();
  268. }
  269. }
  270. function drainQueue() {
  271. if (draining) {
  272. return;
  273. }
  274. var timeout = setTimeout(cleanUpNextTick);
  275. draining = true;
  276. var len = queue.length;
  277. while(len) {
  278. currentQueue = queue;
  279. queue = [];
  280. while (++queueIndex < len) {
  281. currentQueue[queueIndex].run();
  282. }
  283. queueIndex = -1;
  284. len = queue.length;
  285. }
  286. currentQueue = null;
  287. draining = false;
  288. clearTimeout(timeout);
  289. }
  290. process.nextTick = function (fun) {
  291. var args = new Array(arguments.length - 1);
  292. if (arguments.length > 1) {
  293. for (var i = 1; i < arguments.length; i++) {
  294. args[i - 1] = arguments[i];
  295. }
  296. }
  297. queue.push(new Item(fun, args));
  298. if (queue.length === 1 && !draining) {
  299. setTimeout(drainQueue, 0);
  300. }
  301. };
  302. // v8 likes predictible objects
  303. function Item(fun, array) {
  304. this.fun = fun;
  305. this.array = array;
  306. }
  307. Item.prototype.run = function () {
  308. this.fun.apply(null, this.array);
  309. };
  310. process.title = 'browser';
  311. process.browser = true;
  312. process.env = {};
  313. process.argv = [];
  314. process.version = ''; // empty string to avoid regexp issues
  315. process.versions = {};
  316. function noop() {}
  317. process.on = noop;
  318. process.addListener = noop;
  319. process.once = noop;
  320. process.off = noop;
  321. process.removeListener = noop;
  322. process.removeAllListeners = noop;
  323. process.emit = noop;
  324. process.binding = function (name) {
  325. throw new Error('process.binding is not supported');
  326. };
  327. // TODO(shtylman)
  328. process.cwd = function () { return '/' };
  329. process.chdir = function (dir) {
  330. throw new Error('process.chdir is not supported');
  331. };
  332. process.umask = function() { return 0; };
  333. },{}],3:[function(require,module,exports){
  334. /* jshint -W117 */
  335. /* application specific logic */
  336. var APP =
  337. {
  338. init: function () {
  339. this.UI = require("./modules/UI/UI");
  340. this.API = require("./modules/API/API");
  341. this.connectionquality = require("./modules/connectionquality/connectionquality");
  342. this.statistics = require("./modules/statistics/statistics");
  343. this.RTC = require("./modules/RTC/RTC");
  344. this.desktopsharing = require("./modules/desktopsharing/desktopsharing");
  345. this.xmpp = require("./modules/xmpp/xmpp");
  346. this.keyboardshortcut = require("./modules/keyboardshortcut/keyboardshortcut");
  347. this.translation = require("./modules/translation/translation");
  348. this.settings = require("./modules/settings/Settings");
  349. this.DTMF = require("./modules/DTMF/DTMF");
  350. this.members = require("./modules/members/MemberList");
  351. }
  352. };
  353. function init() {
  354. APP.desktopsharing.init();
  355. APP.RTC.start();
  356. APP.xmpp.start();
  357. APP.statistics.start();
  358. APP.connectionquality.init();
  359. APP.keyboardshortcut.init();
  360. APP.members.start();
  361. }
  362. $(document).ready(function () {
  363. var URLProcessor = require("./modules/URLProcessor/URLProcessor");
  364. URLProcessor.setConfigParametersFromUrl();
  365. APP.init();
  366. APP.translation.init();
  367. if(APP.API.isEnabled())
  368. APP.API.init();
  369. APP.UI.start(init);
  370. });
  371. $(window).bind('beforeunload', function () {
  372. if(APP.API.isEnabled())
  373. APP.API.dispose();
  374. });
  375. module.exports = APP;
  376. },{"./modules/API/API":4,"./modules/DTMF/DTMF":5,"./modules/RTC/RTC":9,"./modules/UI/UI":13,"./modules/URLProcessor/URLProcessor":44,"./modules/connectionquality/connectionquality":45,"./modules/desktopsharing/desktopsharing":46,"./modules/keyboardshortcut/keyboardshortcut":47,"./modules/members/MemberList":48,"./modules/settings/Settings":49,"./modules/statistics/statistics":53,"./modules/translation/translation":54,"./modules/xmpp/xmpp":69}],4:[function(require,module,exports){
  377. /* global APP */
  378. /**
  379. * Implements API class that communicates with external api class
  380. * and provides interface to access Jitsi Meet features by external
  381. * applications that embed Jitsi Meet
  382. */
  383. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  384. /**
  385. * List of the available commands.
  386. * @type {{
  387. * displayName: inputDisplayNameHandler,
  388. * toggleAudio: toggleAudio,
  389. * toggleVideo: toggleVideo,
  390. * toggleFilmStrip: toggleFilmStrip,
  391. * toggleChat: toggleChat,
  392. * toggleContactList: toggleContactList
  393. * }}
  394. */
  395. var commands = {};
  396. function initCommands() {
  397. commands = {
  398. displayName: APP.UI.inputDisplayNameHandler,
  399. toggleAudio: APP.UI.toggleAudio,
  400. toggleVideo: APP.UI.toggleVideo,
  401. toggleFilmStrip: APP.UI.toggleFilmStrip,
  402. toggleChat: APP.UI.toggleChat,
  403. toggleContactList: APP.UI.toggleContactList
  404. };
  405. }
  406. /**
  407. * Maps the supported events and their status
  408. * (true it the event is enabled and false if it is disabled)
  409. * @type {{
  410. * incomingMessage: boolean,
  411. * outgoingMessage: boolean,
  412. * displayNameChange: boolean,
  413. * participantJoined: boolean,
  414. * participantLeft: boolean
  415. * }}
  416. */
  417. var events = {
  418. incomingMessage: false,
  419. outgoingMessage:false,
  420. displayNameChange: false,
  421. participantJoined: false,
  422. participantLeft: false
  423. };
  424. var displayName = {};
  425. /**
  426. * Processes commands from external application.
  427. * @param message the object with the command
  428. */
  429. function processCommand(message) {
  430. if (message.action != "execute") {
  431. console.error("Unknown action of the message");
  432. return;
  433. }
  434. for (var key in message) {
  435. if(commands[key])
  436. commands[key].apply(null, message[key]);
  437. }
  438. }
  439. /**
  440. * Processes events objects from external applications
  441. * @param event the event
  442. */
  443. function processEvent(event) {
  444. if (!event.action) {
  445. console.error("Event with no action is received.");
  446. return;
  447. }
  448. var i = 0;
  449. switch(event.action) {
  450. case "add":
  451. for (; i < event.events.length; i++) {
  452. events[event.events[i]] = true;
  453. }
  454. break;
  455. case "remove":
  456. for (; i < event.events.length; i++) {
  457. events[event.events[i]] = false;
  458. }
  459. break;
  460. default:
  461. console.error("Unknown action for event.");
  462. }
  463. }
  464. /**
  465. * Sends message to the external application.
  466. * @param object
  467. */
  468. function sendMessage(object) {
  469. window.parent.postMessage(JSON.stringify(object), "*");
  470. }
  471. /**
  472. * Processes a message event from the external application
  473. * @param event the message event
  474. */
  475. function processMessage(event) {
  476. var message;
  477. try {
  478. message = JSON.parse(event.data);
  479. } catch (e) {}
  480. if(!message.type)
  481. return;
  482. switch (message.type) {
  483. case "command":
  484. processCommand(message);
  485. break;
  486. case "event":
  487. processEvent(message);
  488. break;
  489. default:
  490. console.error("Unknown type of the message");
  491. return;
  492. }
  493. }
  494. function setupListeners() {
  495. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, function (from) {
  496. API.triggerEvent("participantJoined", {jid: from});
  497. });
  498. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid, stamp) {
  499. if (from != myjid)
  500. API.triggerEvent("incomingMessage",
  501. {"from": from, "nick": nick, "message": txt, "stamp": stamp});
  502. });
  503. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, function (jid) {
  504. API.triggerEvent("participantLeft", {jid: jid});
  505. });
  506. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {
  507. var name = displayName[jid];
  508. if(!name || name != newDisplayName) {
  509. API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});
  510. displayName[jid] = newDisplayName;
  511. }
  512. });
  513. APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {
  514. APP.API.triggerEvent("outgoingMessage", {"message": body});
  515. });
  516. }
  517. var API = {
  518. /**
  519. * Check whether the API should be enabled or not.
  520. * @returns {boolean}
  521. */
  522. isEnabled: function () {
  523. var hash = location.hash;
  524. if (hash && hash.indexOf("external") > -1 && window.postMessage)
  525. return true;
  526. return false;
  527. },
  528. /**
  529. * Initializes the APIConnector. Setups message event listeners that will
  530. * receive information from external applications that embed Jitsi Meet.
  531. * It also sends a message to the external application that APIConnector
  532. * is initialized.
  533. */
  534. init: function () {
  535. initCommands();
  536. if (window.addEventListener) {
  537. window.addEventListener('message',
  538. processMessage, false);
  539. }
  540. else {
  541. window.attachEvent('onmessage', processMessage);
  542. }
  543. sendMessage({type: "system", loaded: true});
  544. setupListeners();
  545. },
  546. /**
  547. * Checks whether the event is enabled ot not.
  548. * @param name the name of the event.
  549. * @returns {*}
  550. */
  551. isEventEnabled: function (name) {
  552. return events[name];
  553. },
  554. /**
  555. * Sends event object to the external application that has been subscribed
  556. * for that event.
  557. * @param name the name event
  558. * @param object data associated with the event
  559. */
  560. triggerEvent: function (name, object) {
  561. if(this.isEnabled() && this.isEventEnabled(name))
  562. sendMessage({
  563. type: "event", action: "result", event: name, result: object});
  564. },
  565. /**
  566. * Removes the listeners.
  567. */
  568. dispose: function () {
  569. if(window.removeEventListener) {
  570. window.removeEventListener("message",
  571. processMessage, false);
  572. }
  573. else {
  574. window.detachEvent('onmessage', processMessage);
  575. }
  576. }
  577. };
  578. module.exports = API;
  579. },{"../../service/xmpp/XMPPEvents":119}],5:[function(require,module,exports){
  580. /* global APP */
  581. /**
  582. * A module for sending DTMF tones.
  583. */
  584. var DTMFSender;
  585. var initDtmfSender = function() {
  586. // TODO: This needs to reset this if the peerconnection changes
  587. // (e.g. the call is re-made)
  588. if (DTMFSender)
  589. return;
  590. var localAudio = APP.RTC.localAudio;
  591. if (localAudio && localAudio.getTracks().length > 0)
  592. {
  593. var peerconnection
  594. = APP.xmpp.getConnection().jingle.activecall.peerconnection;
  595. if (peerconnection) {
  596. DTMFSender =
  597. peerconnection.peerconnection
  598. .createDTMFSender(localAudio.getTracks()[0]);
  599. console.log("Initialized DTMFSender");
  600. }
  601. else {
  602. console.log("Failed to initialize DTMFSender: no PeerConnection.");
  603. }
  604. }
  605. else {
  606. console.log("Failed to initialize DTMFSender: no audio track.");
  607. }
  608. };
  609. var DTMF = {
  610. sendTones: function (tones, duration, pause) {
  611. if (!DTMFSender)
  612. initDtmfSender();
  613. if (DTMFSender){
  614. DTMFSender.insertDTMF(tones,
  615. (duration || 200),
  616. (pause || 200));
  617. }
  618. }
  619. };
  620. module.exports = DTMF;
  621. },{}],6:[function(require,module,exports){
  622. /* global config, APP, Strophe */
  623. // cache datachannels to avoid garbage collection
  624. // https://code.google.com/p/chromium/issues/detail?id=405545
  625. var RTCEvents = require("../../service/RTC/RTCEvents");
  626. var _dataChannels = [];
  627. var eventEmitter = null;
  628. var DataChannels = {
  629. /**
  630. * Callback triggered by PeerConnection when new data channel is opened
  631. * on the bridge.
  632. * @param event the event info object.
  633. */
  634. onDataChannel: function (event) {
  635. var dataChannel = event.channel;
  636. dataChannel.onopen = function () {
  637. console.info("Data channel opened by the Videobridge!", dataChannel);
  638. // Code sample for sending string and/or binary data
  639. // Sends String message to the bridge
  640. //dataChannel.send("Hello bridge!");
  641. // Sends 12 bytes binary message to the bridge
  642. //dataChannel.send(new ArrayBuffer(12));
  643. eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  644. };
  645. dataChannel.onerror = function (error) {
  646. console.error("Data Channel Error:", error, dataChannel);
  647. };
  648. dataChannel.onmessage = function (event) {
  649. var data = event.data;
  650. // JSON
  651. var obj;
  652. try {
  653. obj = JSON.parse(data);
  654. }
  655. catch (e) {
  656. console.error(
  657. "Failed to parse data channel message as JSON: ",
  658. data,
  659. dataChannel);
  660. }
  661. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  662. var colibriClass = obj.colibriClass;
  663. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  664. // Endpoint ID from the Videobridge.
  665. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  666. console.info(
  667. "Data channel new dominant speaker event: ",
  668. dominantSpeakerEndpoint);
  669. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  670. }
  671. else if ("InLastNChangeEvent" === colibriClass) {
  672. var oldValue = obj.oldValue;
  673. var newValue = obj.newValue;
  674. // Make sure that oldValue and newValue are of type boolean.
  675. var type;
  676. if ((type = typeof oldValue) !== 'boolean') {
  677. if (type === 'string') {
  678. oldValue = (oldValue == "true");
  679. } else {
  680. oldValue = new Boolean(oldValue).valueOf();
  681. }
  682. }
  683. if ((type = typeof newValue) !== 'boolean') {
  684. if (type === 'string') {
  685. newValue = (newValue == "true");
  686. } else {
  687. newValue = new Boolean(newValue).valueOf();
  688. }
  689. }
  690. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  691. }
  692. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  693. // The new/latest list of last-n endpoint IDs.
  694. var lastNEndpoints = obj.lastNEndpoints;
  695. // The list of endpoint IDs which are entering the list of
  696. // last-n at this time i.e. were not in the old list of last-n
  697. // endpoint IDs.
  698. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  699. console.log(
  700. "Data channel new last-n event: ",
  701. lastNEndpoints, endpointsEnteringLastN, obj);
  702. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  703. lastNEndpoints, endpointsEnteringLastN, obj);
  704. }
  705. else {
  706. console.debug("Data channel JSON-formatted message: ", obj);
  707. }
  708. }
  709. };
  710. dataChannel.onclose = function () {
  711. console.info("The Data Channel closed", dataChannel);
  712. var idx = _dataChannels.indexOf(dataChannel);
  713. if (idx > -1)
  714. _dataChannels = _dataChannels.splice(idx, 1);
  715. };
  716. _dataChannels.push(dataChannel);
  717. },
  718. /**
  719. * Binds "ondatachannel" event listener to given PeerConnection instance.
  720. * @param peerConnection WebRTC peer connection instance.
  721. */
  722. init: function (peerConnection, emitter) {
  723. if(!config.openSctp)
  724. return;
  725. peerConnection.ondatachannel = this.onDataChannel;
  726. eventEmitter = emitter;
  727. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  728. // Although it's not a requirement to open separate channels from both bridge
  729. // and peer as single channel can be used for sending and receiving data.
  730. // So either channel opened by the bridge or the one opened here is enough
  731. // for communication with the bridge.
  732. /*var dataChannelOptions =
  733. {
  734. reliable: true
  735. };
  736. var dataChannel
  737. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  738. // Can be used only when is in open state
  739. dataChannel.onopen = function ()
  740. {
  741. dataChannel.send("My channel !!!");
  742. };
  743. dataChannel.onmessage = function (event)
  744. {
  745. var msgData = event.data;
  746. console.info("Got My Data Channel Message:", msgData, dataChannel);
  747. };*/
  748. },
  749. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  750. handlePinnedEndpointEvent: onPinnedEndpointChanged
  751. };
  752. function onSelectedEndpointChanged(userResource) {
  753. console.log('selected endpoint changed: ', userResource);
  754. if (_dataChannels && _dataChannels.length != 0) {
  755. _dataChannels.some(function (dataChannel) {
  756. if (dataChannel.readyState == 'open') {
  757. console.log('sending selected endpoint changed ' +
  758. 'notification to the bridge: ', userResource);
  759. dataChannel.send(JSON.stringify({
  760. 'colibriClass': 'SelectedEndpointChangedEvent',
  761. 'selectedEndpoint':
  762. (!userResource || userResource === null)?
  763. null : userResource
  764. }));
  765. return true;
  766. }
  767. });
  768. }
  769. }
  770. function onPinnedEndpointChanged(userResource) {
  771. console.log('pinned endpoint changed: ', userResource);
  772. if (_dataChannels && _dataChannels.length != 0) {
  773. _dataChannels.some(function (dataChannel) {
  774. if (dataChannel.readyState == 'open') {
  775. dataChannel.send(JSON.stringify({
  776. 'colibriClass': 'PinnedEndpointChangedEvent',
  777. 'pinnedEndpoint':
  778. (!userResource || userResource == null)?
  779. null : userResource
  780. }));
  781. return true;
  782. }
  783. });
  784. }
  785. }
  786. module.exports = DataChannels;
  787. },{"../../service/RTC/RTCEvents":110}],7:[function(require,module,exports){
  788. /* global APP */
  789. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  790. var RTCEvents = require("../../service/RTC/RTCEvents");
  791. function LocalStream(stream, type, eventEmitter, videoType, isGUMStream) {
  792. this.stream = stream;
  793. this.eventEmitter = eventEmitter;
  794. this.type = type;
  795. this.videoType = videoType;
  796. this.isGUMStream = true;
  797. if(isGUMStream === false)
  798. this.isGUMStream = isGUMStream;
  799. var self = this;
  800. if(type == "audio") {
  801. this.getTracks = function () {
  802. return self.stream.getAudioTracks();
  803. };
  804. } else {
  805. this.getTracks = function () {
  806. return self.stream.getVideoTracks();
  807. };
  808. }
  809. this.stream.onended = function() {
  810. self.streamEnded();
  811. };
  812. }
  813. LocalStream.prototype.streamEnded = function () {
  814. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  815. };
  816. LocalStream.prototype.getOriginalStream = function()
  817. {
  818. return this.stream;
  819. };
  820. LocalStream.prototype.isAudioStream = function () {
  821. return this.type === "audio";
  822. };
  823. LocalStream.prototype.setMute = function (mute)
  824. {
  825. var isAudio = this.isAudioStream();
  826. var eventType = isAudio ? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE;
  827. if ((window.location.protocol != "https:" && this.isGUMStream) ||
  828. (isAudio && this.isGUMStream) || this.videoType === "screen") {
  829. var tracks = this.getTracks();
  830. for (var idx = 0; idx < tracks.length; idx++) {
  831. tracks[idx].enabled = !mute;
  832. }
  833. this.eventEmitter.emit(eventType, mute);
  834. } else {
  835. if (mute) {
  836. APP.xmpp.removeStream(this.stream);
  837. this.stream.stop();
  838. this.eventEmitter.emit(eventType, true);
  839. } else {
  840. var self = this;
  841. APP.RTC.rtcUtils.obtainAudioAndVideoPermissions(
  842. (this.isAudioStream() ? ["audio"] : ["video"]),
  843. function (stream) {
  844. if (isAudio) {
  845. APP.RTC.changeLocalAudio(stream,
  846. function () {
  847. self.eventEmitter.emit(eventType, false);
  848. });
  849. } else {
  850. APP.RTC.changeLocalVideo(stream, false,
  851. function () {
  852. self.eventEmitter.emit(eventType, false);
  853. });
  854. }
  855. });
  856. }
  857. }
  858. };
  859. LocalStream.prototype.isMuted = function () {
  860. var tracks = [];
  861. if (this.isAudioStream()) {
  862. tracks = this.stream.getAudioTracks();
  863. } else {
  864. if (this.stream.ended)
  865. return true;
  866. tracks = this.stream.getVideoTracks();
  867. }
  868. for (var idx = 0; idx < tracks.length; idx++) {
  869. if(tracks[idx].enabled)
  870. return false;
  871. }
  872. return true;
  873. };
  874. LocalStream.prototype.getId = function () {
  875. return this.stream.getTracks()[0].id;
  876. };
  877. module.exports = LocalStream;
  878. },{"../../service/RTC/RTCEvents":110,"../../service/RTC/StreamEventTypes.js":112}],8:[function(require,module,exports){
  879. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  880. /**
  881. * Creates a MediaStream object for the given data, session id and ssrc.
  882. * It is a wrapper class for the MediaStream.
  883. *
  884. * @param data the data object from which we obtain the stream,
  885. * the peerjid, etc.
  886. * @param sid the session id
  887. * @param ssrc the ssrc corresponding to this MediaStream
  888. *
  889. * @constructor
  890. */
  891. function MediaStream(data, sid, ssrc, browser, eventEmitter) {
  892. // XXX(gp) to minimize headaches in the future, we should build our
  893. // abstractions around tracks and not streams. ORTC is track based API.
  894. // Mozilla expects m-lines to represent media tracks.
  895. //
  896. // Practically, what I'm saying is that we should have a MediaTrack class
  897. // and not a MediaStream class.
  898. //
  899. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  900. // a track might have an associated RTX and FEC sources.
  901. this.sid = sid;
  902. this.stream = data.stream;
  903. this.peerjid = data.peerjid;
  904. this.videoType = data.videoType;
  905. this.ssrc = ssrc;
  906. this.type = (this.stream.getVideoTracks().length > 0)?
  907. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  908. this.muted = false;
  909. this.eventEmitter = eventEmitter;
  910. }
  911. MediaStream.prototype.getOriginalStream = function() {
  912. return this.stream;
  913. };
  914. MediaStream.prototype.setMute = function (value) {
  915. this.stream.muted = value;
  916. this.muted = value;
  917. };
  918. module.exports = MediaStream;
  919. },{"../../service/RTC/MediaStreamTypes":109}],9:[function(require,module,exports){
  920. /* global APP */
  921. var EventEmitter = require("events");
  922. var RTCBrowserType = require("./RTCBrowserType");
  923. var RTCUtils = require("./RTCUtils.js");
  924. var LocalStream = require("./LocalStream.js");
  925. var DataChannels = require("./DataChannels");
  926. var MediaStream = require("./MediaStream.js");
  927. var DesktopSharingEventTypes
  928. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  929. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  930. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  931. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  932. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  933. var UIEvents = require("../../service/UI/UIEvents");
  934. var eventEmitter = new EventEmitter();
  935. function getMediaStreamUsage()
  936. {
  937. var result = {
  938. audio: true,
  939. video: true
  940. };
  941. /** There are some issues with the desktop sharing
  942. * when this property is enabled.
  943. * WARNING: We must change the implementation to start video/audio if we
  944. * receive from the focus that the peer is not muted.
  945. var isSecureConnection = window.location.protocol == "https:";
  946. if(config.disableEarlyMediaPermissionRequests || !isSecureConnection)
  947. {
  948. result = {
  949. audio: false,
  950. video: false
  951. };
  952. }
  953. **/
  954. return result;
  955. }
  956. var RTC = {
  957. rtcUtils: null,
  958. devices: {
  959. audio: true,
  960. video: true
  961. },
  962. localStreams: [],
  963. remoteStreams: {},
  964. localAudio: null,
  965. localVideo: null,
  966. addStreamListener: function (listener, eventType) {
  967. eventEmitter.on(eventType, listener);
  968. },
  969. addListener: function (type, listener) {
  970. eventEmitter.on(type, listener);
  971. },
  972. removeStreamListener: function (listener, eventType) {
  973. if(!(eventType instanceof StreamEventTypes))
  974. throw "Illegal argument";
  975. eventEmitter.removeListener(eventType, listener);
  976. },
  977. createLocalStream: function (stream, type, change, videoType, isMuted, isGUMStream) {
  978. var localStream = new LocalStream(stream, type, eventEmitter, videoType, isGUMStream);
  979. //in firefox we have only one stream object
  980. if(this.localStreams.length == 0 ||
  981. this.localStreams[0].getOriginalStream() != stream)
  982. this.localStreams.push(localStream);
  983. if(isMuted === true)
  984. localStream.setMute(true);
  985. if(type == "audio") {
  986. this.localAudio = localStream;
  987. } else {
  988. this.localVideo = localStream;
  989. }
  990. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  991. if(change)
  992. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  993. eventEmitter.emit(eventType, localStream, isMuted);
  994. return localStream;
  995. },
  996. removeLocalStream: function (stream) {
  997. for(var i = 0; i < this.localStreams.length; i++) {
  998. if(this.localStreams[i].getOriginalStream() === stream) {
  999. delete this.localStreams[i];
  1000. return;
  1001. }
  1002. }
  1003. },
  1004. createRemoteStream: function (data, sid, thessrc) {
  1005. var remoteStream = new MediaStream(data, sid, thessrc,
  1006. RTCBrowserType.getBrowserType(), eventEmitter);
  1007. var jid = data.peerjid || APP.xmpp.myJid();
  1008. if(!this.remoteStreams[jid]) {
  1009. this.remoteStreams[jid] = {};
  1010. }
  1011. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  1012. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  1013. return remoteStream;
  1014. },
  1015. getPCConstraints: function () {
  1016. return this.rtcUtils.pc_constraints;
  1017. },
  1018. getUserMediaWithConstraints:function(um, success_callback,
  1019. failure_callback, resolution,
  1020. bandwidth, fps, desktopStream)
  1021. {
  1022. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  1023. failure_callback, resolution, bandwidth, fps, desktopStream);
  1024. },
  1025. attachMediaStream: function (elSelector, stream) {
  1026. this.rtcUtils.attachMediaStream(elSelector, stream);
  1027. },
  1028. getStreamID: function (stream) {
  1029. return this.rtcUtils.getStreamID(stream);
  1030. },
  1031. getVideoSrc: function (element) {
  1032. return this.rtcUtils.getVideoSrc(element);
  1033. },
  1034. setVideoSrc: function (element, src) {
  1035. this.rtcUtils.setVideoSrc(element, src);
  1036. },
  1037. getVideoElementName: function () {
  1038. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  1039. },
  1040. dispose: function() {
  1041. if (this.rtcUtils) {
  1042. this.rtcUtils = null;
  1043. }
  1044. },
  1045. stop: function () {
  1046. this.dispose();
  1047. },
  1048. start: function () {
  1049. var self = this;
  1050. APP.desktopsharing.addListener(
  1051. function (stream, isUsingScreenStream, callback) {
  1052. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  1053. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  1054. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  1055. DataChannels.init(event.peerconnection, eventEmitter);
  1056. });
  1057. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  1058. DataChannels.handleSelectedEndpointEvent);
  1059. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  1060. DataChannels.handlePinnedEndpointEvent);
  1061. // In case of IE we continue from 'onReady' callback
  1062. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  1063. // once it is initialized.
  1064. var onReady = function () {
  1065. eventEmitter.emit(RTCEvents.RTC_READY, true);
  1066. self.rtcUtils.obtainAudioAndVideoPermissions(
  1067. null, null, getMediaStreamUsage());
  1068. };
  1069. this.rtcUtils = new RTCUtils(this, onReady);
  1070. // Call onReady() if Temasys plugin is not used
  1071. if (!RTCBrowserType.isTemasysPluginUsed()) {
  1072. onReady();
  1073. }
  1074. },
  1075. muteRemoteVideoStream: function (jid, value) {
  1076. var stream;
  1077. if(this.remoteStreams[jid] &&
  1078. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  1079. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  1080. }
  1081. if(!stream)
  1082. return true;
  1083. if (value != stream.muted) {
  1084. stream.setMute(value);
  1085. return true;
  1086. }
  1087. return false;
  1088. },
  1089. switchVideoStreams: function (new_stream) {
  1090. this.localVideo.stream = new_stream;
  1091. this.localStreams = [];
  1092. //in firefox we have only one stream object
  1093. if (this.localAudio.getOriginalStream() != new_stream)
  1094. this.localStreams.push(this.localAudio);
  1095. this.localStreams.push(this.localVideo);
  1096. },
  1097. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  1098. var oldStream = this.localVideo.getOriginalStream();
  1099. var type = (isUsingScreenStream ? "screen" : "camera");
  1100. var localCallback = callback;
  1101. if(this.localVideo.isMuted() && this.localVideo.videoType !== type) {
  1102. localCallback = function() {
  1103. APP.xmpp.setVideoMute(false, function(mute) {
  1104. eventEmitter.emit(RTCEvents.VIDEO_MUTE, mute);
  1105. });
  1106. callback();
  1107. };
  1108. }
  1109. // FIXME: Workaround for FF/IE/Safari
  1110. if (stream && stream.videoStream) {
  1111. stream = stream.videoStream;
  1112. }
  1113. var videoStream = this.rtcUtils.createStream(stream, true);
  1114. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  1115. // Stop the stream to trigger onended event for old stream
  1116. oldStream.stop();
  1117. this.switchVideoStreams(videoStream, oldStream);
  1118. APP.xmpp.switchStreams(videoStream, oldStream,localCallback);
  1119. },
  1120. changeLocalAudio: function (stream, callback) {
  1121. var oldStream = this.localAudio.getOriginalStream();
  1122. var newStream = this.rtcUtils.createStream(stream);
  1123. this.localAudio = this.createLocalStream(newStream, "audio", true);
  1124. // Stop the stream to trigger onended event for old stream
  1125. oldStream.stop();
  1126. APP.xmpp.switchStreams(newStream, oldStream, callback, true);
  1127. },
  1128. isVideoMuted: function (jid) {
  1129. if (jid === APP.xmpp.myJid()) {
  1130. var localVideo = APP.RTC.localVideo;
  1131. return (!localVideo || localVideo.isMuted());
  1132. } else {
  1133. if (!APP.RTC.remoteStreams[jid] ||
  1134. !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  1135. return null;
  1136. }
  1137. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  1138. }
  1139. },
  1140. setVideoMute: function (mute, callback, options) {
  1141. if (!this.localVideo)
  1142. return;
  1143. if (mute == APP.RTC.localVideo.isMuted())
  1144. {
  1145. APP.xmpp.sendVideoInfoPresence(mute);
  1146. if (callback)
  1147. callback(mute);
  1148. }
  1149. else
  1150. {
  1151. APP.RTC.localVideo.setMute(mute);
  1152. APP.xmpp.setVideoMute(
  1153. mute,
  1154. callback,
  1155. options);
  1156. }
  1157. },
  1158. setDeviceAvailability: function (devices) {
  1159. if(!devices)
  1160. return;
  1161. if(devices.audio === true || devices.audio === false)
  1162. this.devices.audio = devices.audio;
  1163. if(devices.video === true || devices.video === false)
  1164. this.devices.video = devices.video;
  1165. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  1166. }
  1167. };
  1168. module.exports = RTC;
  1169. },{"../../service/RTC/MediaStreamTypes":109,"../../service/RTC/RTCEvents.js":110,"../../service/RTC/StreamEventTypes.js":112,"../../service/UI/UIEvents":113,"../../service/desktopsharing/DesktopSharingEventTypes":116,"../../service/xmpp/XMPPEvents":119,"./DataChannels":6,"./LocalStream.js":7,"./MediaStream.js":8,"./RTCBrowserType":10,"./RTCUtils.js":11,"events":1}],10:[function(require,module,exports){
  1170. var currentBrowser;
  1171. var browserVersion;
  1172. var RTCBrowserType = {
  1173. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  1174. RTC_BROWSER_OPERA: "rtc_browser.opera",
  1175. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  1176. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  1177. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  1178. getBrowserType: function () {
  1179. return currentBrowser;
  1180. },
  1181. isChrome: function () {
  1182. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  1183. },
  1184. isOpera: function () {
  1185. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  1186. },
  1187. isFirefox: function () {
  1188. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  1189. },
  1190. isIExplorer: function () {
  1191. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1192. },
  1193. isSafari: function () {
  1194. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  1195. },
  1196. isTemasysPluginUsed: function () {
  1197. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  1198. },
  1199. getFirefoxVersion: function () {
  1200. return RTCBrowserType.isFirefox() ? browserVersion : null;
  1201. },
  1202. getChromeVersion: function () {
  1203. return RTCBrowserType.isChrome() ? browserVersion : null;
  1204. },
  1205. usesPlanB: function() {
  1206. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  1207. RTCBrowserType.isTemasysPluginUsed();
  1208. },
  1209. usesUnifiedPlan: function() {
  1210. return RTCBrowserType.isFirefox();
  1211. }
  1212. // Add version getters for other browsers when needed
  1213. };
  1214. // detectOpera() must be called before detectChrome() !!!
  1215. // otherwise Opera wil be detected as Chrome
  1216. function detectChrome() {
  1217. if (navigator.webkitGetUserMedia) {
  1218. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  1219. var userAgent = navigator.userAgent.toLowerCase();
  1220. // We can assume that user agent is chrome, because it's
  1221. // enforced when 'ext' streaming method is set
  1222. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  1223. console.log("This appears to be Chrome, ver: " + ver);
  1224. return ver;
  1225. }
  1226. return null;
  1227. }
  1228. function detectOpera() {
  1229. var userAgent = navigator.userAgent;
  1230. if (userAgent.match(/Opera|OPR/)) {
  1231. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  1232. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  1233. console.info("This appears to be Opera, ver: " + version);
  1234. return version;
  1235. }
  1236. return null;
  1237. }
  1238. function detectFirefox() {
  1239. if (navigator.mozGetUserMedia) {
  1240. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  1241. var version = parseInt(
  1242. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1243. console.log('This appears to be Firefox, ver: ' + version);
  1244. return version;
  1245. }
  1246. return null;
  1247. }
  1248. function detectSafari() {
  1249. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  1250. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  1251. console.info("This appears to be Safari");
  1252. // FIXME detect Safari version when needed
  1253. return 1;
  1254. }
  1255. return null;
  1256. }
  1257. function detectIE() {
  1258. var version;
  1259. var ua = window.navigator.userAgent;
  1260. var msie = ua.indexOf('MSIE ');
  1261. if (msie > 0) {
  1262. // IE 10 or older => return version number
  1263. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  1264. }
  1265. var trident = ua.indexOf('Trident/');
  1266. if (!version && trident > 0) {
  1267. // IE 11 => return version number
  1268. var rv = ua.indexOf('rv:');
  1269. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  1270. }
  1271. var edge = ua.indexOf('Edge/');
  1272. if (!version && edge > 0) {
  1273. // IE 12 => return version number
  1274. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  1275. }
  1276. if (version) {
  1277. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1278. console.info("This appears to be IExplorer, ver: " + version);
  1279. }
  1280. return version;
  1281. }
  1282. function detectBrowser() {
  1283. var version;
  1284. var detectors = [
  1285. detectOpera,
  1286. detectChrome,
  1287. detectFirefox,
  1288. detectIE,
  1289. detectSafari
  1290. ];
  1291. // Try all browser detectors
  1292. for (var i = 0; i < detectors.length; i++) {
  1293. version = detectors[i]();
  1294. if (version)
  1295. return version;
  1296. }
  1297. console.error("Failed to detect browser type");
  1298. return undefined;
  1299. }
  1300. browserVersion = detectBrowser();
  1301. module.exports = RTCBrowserType;
  1302. },{}],11:[function(require,module,exports){
  1303. /* global config, require, attachMediaStream, getUserMedia */
  1304. var RTCBrowserType = require("./RTCBrowserType");
  1305. var Resolutions = require("../../service/RTC/Resolutions");
  1306. var AdapterJS = require("./adapter.screenshare");
  1307. var SDPUtil = require("../xmpp/SDPUtil");
  1308. var currentResolution = null;
  1309. function getPreviousResolution(resolution) {
  1310. if(!Resolutions[resolution])
  1311. return null;
  1312. var order = Resolutions[resolution].order;
  1313. var res = null;
  1314. var resName = null;
  1315. for(var i in Resolutions) {
  1316. var tmp = Resolutions[i];
  1317. if(res == null || (res.order < tmp.order && tmp.order < order)) {
  1318. resName = i;
  1319. res = tmp;
  1320. }
  1321. }
  1322. return resName;
  1323. }
  1324. function setResolutionConstraints(constraints, resolution, isAndroid) {
  1325. if (resolution && !constraints.video || isAndroid) {
  1326. // same behaviour as true
  1327. constraints.video = { mandatory: {}, optional: [] };
  1328. }
  1329. if(Resolutions[resolution]) {
  1330. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1331. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1332. }
  1333. else {
  1334. if (isAndroid) {
  1335. constraints.video.mandatory.minWidth = 320;
  1336. constraints.video.mandatory.minHeight = 240;
  1337. constraints.video.mandatory.maxFrameRate = 15;
  1338. }
  1339. }
  1340. if (constraints.video.mandatory.minWidth)
  1341. constraints.video.mandatory.maxWidth =
  1342. constraints.video.mandatory.minWidth;
  1343. if (constraints.video.mandatory.minHeight)
  1344. constraints.video.mandatory.maxHeight =
  1345. constraints.video.mandatory.minHeight;
  1346. }
  1347. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  1348. {
  1349. var constraints = {audio: false, video: false};
  1350. if (um.indexOf('video') >= 0) {
  1351. // same behaviour as true
  1352. constraints.video = { mandatory: {}, optional: [] };
  1353. }
  1354. if (um.indexOf('audio') >= 0) {
  1355. // same behaviour as true
  1356. constraints.audio = { mandatory: {}, optional: []};
  1357. }
  1358. if (um.indexOf('screen') >= 0) {
  1359. if (RTCBrowserType.isChrome()) {
  1360. constraints.video = {
  1361. mandatory: {
  1362. chromeMediaSource: "screen",
  1363. googLeakyBucket: true,
  1364. maxWidth: window.screen.width,
  1365. maxHeight: window.screen.height,
  1366. maxFrameRate: 3
  1367. },
  1368. optional: []
  1369. };
  1370. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  1371. constraints.video = {
  1372. optional: [
  1373. {
  1374. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  1375. }
  1376. ]
  1377. };
  1378. } else {
  1379. console.error(
  1380. "'screen' WebRTC media source is supported only in Chrome" +
  1381. " and with Temasys plugin");
  1382. }
  1383. }
  1384. if (um.indexOf('desktop') >= 0) {
  1385. constraints.video = {
  1386. mandatory: {
  1387. chromeMediaSource: "desktop",
  1388. chromeMediaSourceId: desktopStream,
  1389. googLeakyBucket: true,
  1390. maxWidth: window.screen.width,
  1391. maxHeight: window.screen.height,
  1392. maxFrameRate: 3
  1393. },
  1394. optional: []
  1395. };
  1396. }
  1397. if (constraints.audio) {
  1398. // if it is good enough for hangouts...
  1399. constraints.audio.optional.push(
  1400. {googEchoCancellation: true},
  1401. {googAutoGainControl: true},
  1402. {googNoiseSupression: true},
  1403. {googHighpassFilter: true},
  1404. {googNoisesuppression2: true},
  1405. {googEchoCancellation2: true},
  1406. {googAutoGainControl2: true}
  1407. );
  1408. }
  1409. if (constraints.video) {
  1410. if (um.indexOf('video') >= 0) {
  1411. constraints.video.optional.push(
  1412. {googLeakyBucket: true}
  1413. );
  1414. }
  1415. }
  1416. if (um.indexOf('video') >= 0) {
  1417. setResolutionConstraints(constraints, resolution, isAndroid);
  1418. }
  1419. if (bandwidth) {
  1420. if (!constraints.video) {
  1421. //same behaviour as true
  1422. constraints.video = {mandatory: {}, optional: []};
  1423. }
  1424. constraints.video.optional.push({bandwidth: bandwidth});
  1425. }
  1426. if (fps) {
  1427. // for some cameras it might be necessary to request 30fps
  1428. // so they choose 30fps mjpg over 10fps yuy2
  1429. if (!constraints.video) {
  1430. // same behaviour as true;
  1431. constraints.video = {mandatory: {}, optional: []};
  1432. }
  1433. constraints.video.mandatory.minFrameRate = fps;
  1434. }
  1435. return constraints;
  1436. }
  1437. function RTCUtils(RTCService, onTemasysPluginReady)
  1438. {
  1439. var self = this;
  1440. this.service = RTCService;
  1441. if (RTCBrowserType.isFirefox()) {
  1442. var FFversion = RTCBrowserType.getFirefoxVersion();
  1443. if (FFversion >= 40) {
  1444. this.peerconnection = mozRTCPeerConnection;
  1445. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1446. this.pc_constraints = {};
  1447. this.attachMediaStream = function (element, stream) {
  1448. // srcObject is being standardized and FF will eventually
  1449. // support that unprefixed. FF also supports the
  1450. // "element.src = URL.createObjectURL(...)" combo, but that
  1451. // will be deprecated in favour of srcObject.
  1452. //
  1453. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1454. // https://github.com/webrtc/samples/issues/302
  1455. if(!element[0])
  1456. return;
  1457. element[0].mozSrcObject = stream;
  1458. element[0].play();
  1459. };
  1460. this.getStreamID = function (stream) {
  1461. var id = stream.id;
  1462. if (!id) {
  1463. var tracks = stream.getVideoTracks();
  1464. if (!tracks || tracks.length === 0) {
  1465. tracks = stream.getAudioTracks();
  1466. }
  1467. id = tracks[0].id;
  1468. }
  1469. return SDPUtil.filter_special_chars(id);
  1470. };
  1471. this.getVideoSrc = function (element) {
  1472. if(!element)
  1473. return null;
  1474. return element.mozSrcObject;
  1475. };
  1476. this.setVideoSrc = function (element, src) {
  1477. if(element)
  1478. element.mozSrcObject = src;
  1479. };
  1480. RTCSessionDescription = mozRTCSessionDescription;
  1481. RTCIceCandidate = mozRTCIceCandidate;
  1482. } else {
  1483. console.error(
  1484. "Firefox version too old: " + FFversion + ". Required >= 40.");
  1485. window.location.href = 'unsupported_browser.html';
  1486. return;
  1487. }
  1488. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  1489. this.peerconnection = webkitRTCPeerConnection;
  1490. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1491. this.attachMediaStream = function (element, stream) {
  1492. element.attr('src', webkitURL.createObjectURL(stream));
  1493. };
  1494. this.getStreamID = function (stream) {
  1495. // streams from FF endpoints have the characters '{' and '}'
  1496. // that make jQuery choke.
  1497. return SDPUtil.filter_special_chars(stream.id);
  1498. };
  1499. this.getVideoSrc = function (element) {
  1500. if(!element)
  1501. return null;
  1502. return element.getAttribute("src");
  1503. };
  1504. this.setVideoSrc = function (element, src) {
  1505. if(element)
  1506. element.setAttribute("src", src);
  1507. };
  1508. // DTLS should now be enabled by default but..
  1509. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  1510. if (navigator.userAgent.indexOf('Android') != -1) {
  1511. this.pc_constraints = {}; // disable DTLS on Android
  1512. }
  1513. if (!webkitMediaStream.prototype.getVideoTracks) {
  1514. webkitMediaStream.prototype.getVideoTracks = function () {
  1515. return this.videoTracks;
  1516. };
  1517. }
  1518. if (!webkitMediaStream.prototype.getAudioTracks) {
  1519. webkitMediaStream.prototype.getAudioTracks = function () {
  1520. return this.audioTracks;
  1521. };
  1522. }
  1523. }
  1524. // Detect IE/Safari
  1525. else if (RTCBrowserType.isTemasysPluginUsed()) {
  1526. //AdapterJS.WebRTCPlugin.setLogLevel(
  1527. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  1528. AdapterJS.webRTCReady(function (isPlugin) {
  1529. self.peerconnection = RTCPeerConnection;
  1530. self.getUserMedia = getUserMedia;
  1531. self.attachMediaStream = function (elSel, stream) {
  1532. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  1533. return;
  1534. }
  1535. attachMediaStream(elSel[0], stream);
  1536. };
  1537. self.getStreamID = function (stream) {
  1538. var id = SDPUtil.filter_special_chars(stream.label);
  1539. return id;
  1540. };
  1541. self.getVideoSrc = function (element) {
  1542. if (!element) {
  1543. console.warn("Attempt to get video SRC of null element");
  1544. return null;
  1545. }
  1546. var children = element.children;
  1547. for (var i = 0; i !== children.length; ++i) {
  1548. if (children[i].name === 'streamId') {
  1549. return children[i].value;
  1550. }
  1551. }
  1552. //console.info(element.id + " SRC: " + src);
  1553. return null;
  1554. };
  1555. self.setVideoSrc = function (element, src) {
  1556. //console.info("Set video src: ", element, src);
  1557. if (!src) {
  1558. console.warn("Not attaching video stream, 'src' is null");
  1559. return;
  1560. }
  1561. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  1562. var stream = AdapterJS.WebRTCPlugin.plugin
  1563. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  1564. attachMediaStream(element, stream);
  1565. };
  1566. onTemasysPluginReady(isPlugin);
  1567. });
  1568. } else {
  1569. try {
  1570. console.log('Browser does not appear to be WebRTC-capable');
  1571. } catch (e) { }
  1572. window.location.href = 'unsupported_browser.html';
  1573. }
  1574. }
  1575. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1576. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1577. desktopStream) {
  1578. currentResolution = resolution;
  1579. // Check if we are running on Android device
  1580. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1581. var constraints = getConstraints(
  1582. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1583. console.info("Get media constraints", constraints);
  1584. var self = this;
  1585. try {
  1586. this.getUserMedia(constraints,
  1587. function (stream) {
  1588. console.log('onUserMediaSuccess');
  1589. self.setAvailableDevices(um, true);
  1590. success_callback(stream);
  1591. },
  1592. function (error) {
  1593. self.setAvailableDevices(um, false);
  1594. console.warn('Failed to get access to local media. Error ',
  1595. error, constraints);
  1596. if (failure_callback) {
  1597. failure_callback(error);
  1598. }
  1599. });
  1600. } catch (e) {
  1601. console.error('GUM failed: ', e);
  1602. if(failure_callback) {
  1603. failure_callback(e);
  1604. }
  1605. }
  1606. };
  1607. RTCUtils.prototype.setAvailableDevices = function (um, available) {
  1608. var devices = {};
  1609. if(um.indexOf("video") != -1) {
  1610. devices.video = available;
  1611. }
  1612. if(um.indexOf("audio") != -1) {
  1613. devices.audio = available;
  1614. }
  1615. this.service.setDeviceAvailability(devices);
  1616. };
  1617. /**
  1618. * We ask for audio and video combined stream in order to get permissions and
  1619. * not to ask twice.
  1620. */
  1621. RTCUtils.prototype.obtainAudioAndVideoPermissions =
  1622. function(devices, callback, usageOptions)
  1623. {
  1624. var self = this;
  1625. // Get AV
  1626. var successCallback = function (stream) {
  1627. if(callback)
  1628. callback(stream, usageOptions);
  1629. else
  1630. self.successCallback(stream, usageOptions);
  1631. };
  1632. if(!devices)
  1633. devices = ['audio', 'video'];
  1634. var newDevices = [];
  1635. if(usageOptions)
  1636. for(var i = 0; i < devices.length; i++) {
  1637. var device = devices[i];
  1638. if(usageOptions[device] === true)
  1639. newDevices.push(device);
  1640. }
  1641. else
  1642. newDevices = devices;
  1643. if(newDevices.length === 0) {
  1644. successCallback();
  1645. return;
  1646. }
  1647. if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {
  1648. // With FF/IE we can't split the stream into audio and video because FF
  1649. // doesn't support media stream constructors. So, we need to get the
  1650. // audio stream separately from the video stream using two distinct GUM
  1651. // calls. Not very user friendly :-( but we don't have many other
  1652. // options neither.
  1653. //
  1654. // Note that we pack those 2 streams in a single object and pass it to
  1655. // the successCallback method.
  1656. var obtainVideo = function (audioStream) {
  1657. self.getUserMediaWithConstraints(
  1658. ['video'],
  1659. function (videoStream) {
  1660. return successCallback({
  1661. audioStream: audioStream,
  1662. videoStream: videoStream
  1663. });
  1664. },
  1665. function (error) {
  1666. console.error(
  1667. 'failed to obtain video stream - stop', error);
  1668. self.errorCallback(error);
  1669. },
  1670. config.resolution || '360');
  1671. };
  1672. var obtainAudio = function () {
  1673. self.getUserMediaWithConstraints(
  1674. ['audio'],
  1675. function (audioStream) {
  1676. if (newDevices.indexOf('video') !== -1)
  1677. obtainVideo(audioStream);
  1678. },
  1679. function (error) {
  1680. console.error(
  1681. 'failed to obtain audio stream - stop', error);
  1682. self.errorCallback(error);
  1683. }
  1684. );
  1685. };
  1686. if (newDevices.indexOf('audio') !== -1) {
  1687. obtainAudio();
  1688. } else {
  1689. obtainVideo(null);
  1690. }
  1691. } else {
  1692. this.getUserMediaWithConstraints(
  1693. newDevices,
  1694. function (stream) {
  1695. successCallback(stream);
  1696. },
  1697. function (error) {
  1698. self.errorCallback(error);
  1699. },
  1700. config.resolution || '360');
  1701. }
  1702. };
  1703. RTCUtils.prototype.successCallback = function (stream, usageOptions) {
  1704. // If this is FF or IE, the stream parameter is *not* a MediaStream object,
  1705. // it's an object with two properties: audioStream, videoStream.
  1706. if (stream && stream.getAudioTracks && stream.getVideoTracks)
  1707. console.log('got', stream, stream.getAudioTracks().length,
  1708. stream.getVideoTracks().length);
  1709. this.handleLocalStream(stream, usageOptions);
  1710. };
  1711. RTCUtils.prototype.errorCallback = function (error) {
  1712. var self = this;
  1713. console.error('failed to obtain audio/video stream - trying audio only', error);
  1714. var resolution = getPreviousResolution(currentResolution);
  1715. if(typeof error == "object" && error.constraintName && error.name
  1716. && (error.name == "ConstraintNotSatisfiedError" ||
  1717. error.name == "OverconstrainedError") &&
  1718. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1719. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1720. && resolution != null)
  1721. {
  1722. self.getUserMediaWithConstraints(['audio', 'video'],
  1723. function (stream) {
  1724. return self.successCallback(stream);
  1725. }, function (error) {
  1726. return self.errorCallback(error);
  1727. }, resolution);
  1728. }
  1729. else {
  1730. self.getUserMediaWithConstraints(
  1731. ['audio'],
  1732. function (stream) {
  1733. return self.successCallback(stream);
  1734. },
  1735. function (error) {
  1736. console.error('failed to obtain audio/video stream - stop',
  1737. error);
  1738. return self.successCallback(null);
  1739. }
  1740. );
  1741. }
  1742. };
  1743. RTCUtils.prototype.handleLocalStream = function(stream, usageOptions) {
  1744. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1745. // an object with two properties: audioStream, videoStream.
  1746. var audioStream, videoStream;
  1747. if(window.webkitMediaStream)
  1748. {
  1749. audioStream = new webkitMediaStream();
  1750. videoStream = new webkitMediaStream();
  1751. if(stream) {
  1752. var audioTracks = stream.getAudioTracks();
  1753. for (var i = 0; i < audioTracks.length; i++) {
  1754. audioStream.addTrack(audioTracks[i]);
  1755. }
  1756. var videoTracks = stream.getVideoTracks();
  1757. for (i = 0; i < videoTracks.length; i++) {
  1758. videoStream.addTrack(videoTracks[i]);
  1759. }
  1760. }
  1761. }
  1762. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed())
  1763. { // Firefox and Temasys plugin
  1764. if (stream && stream.audioStream)
  1765. audioStream = stream.audioStream;
  1766. else
  1767. audioStream = new DummyMediaStream("dummyAudio");
  1768. if (stream && stream.videoStream)
  1769. videoStream = stream.videoStream;
  1770. else
  1771. videoStream = new DummyMediaStream("dummyVideo");
  1772. }
  1773. var audioMuted = (usageOptions && usageOptions.audio === false),
  1774. videoMuted = (usageOptions && usageOptions.video === false);
  1775. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  1776. videoGUM = (!usageOptions || usageOptions.video !== false);
  1777. this.service.createLocalStream(audioStream, "audio", null, null,
  1778. audioMuted, audioGUM);
  1779. this.service.createLocalStream(videoStream, "video", null, 'camera',
  1780. videoMuted, videoGUM);
  1781. };
  1782. function DummyMediaStream(id) {
  1783. this.id = id;
  1784. this.label = id;
  1785. this.stop = function() { };
  1786. this.getAudioTracks = function() { return []; };
  1787. this.getVideoTracks = function() { return []; };
  1788. }
  1789. RTCUtils.prototype.createStream = function(stream, isVideo) {
  1790. var newStream = null;
  1791. if (window.webkitMediaStream) {
  1792. newStream = new webkitMediaStream();
  1793. if (newStream) {
  1794. var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());
  1795. for (var i = 0; i < tracks.length; i++) {
  1796. newStream.addTrack(tracks[i]);
  1797. }
  1798. }
  1799. }
  1800. else {
  1801. // FIXME: this is duplicated with 'handleLocalStream' !!!
  1802. if (stream) {
  1803. newStream = stream;
  1804. } else {
  1805. newStream =
  1806. new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  1807. }
  1808. }
  1809. return newStream;
  1810. };
  1811. module.exports = RTCUtils;
  1812. },{"../../service/RTC/Resolutions":111,"../xmpp/SDPUtil":58,"./RTCBrowserType":10,"./adapter.screenshare":12}],12:[function(require,module,exports){
  1813. /*! adapterjs - v0.11.0 - 2015-06-08 */
  1814. // Adapter's interface.
  1815. var AdapterJS = AdapterJS || {};
  1816. // Browserify compatibility
  1817. if(typeof exports !== 'undefined') {
  1818. module.exports = AdapterJS;
  1819. }
  1820. AdapterJS.options = AdapterJS.options || {};
  1821. // uncomment to get virtual webcams
  1822. // AdapterJS.options.getAllCams = true;
  1823. // uncomment to prevent the install prompt when the plugin in not yet installed
  1824. // AdapterJS.options.hidePluginInstallPrompt = true;
  1825. // AdapterJS version
  1826. AdapterJS.VERSION = '0.11.0';
  1827. // This function will be called when the WebRTC API is ready to be used
  1828. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  1829. // the plugin
  1830. // You may Override this function to synchronise the start of your application
  1831. // with the WebRTC API being ready.
  1832. // If you decide not to override use this synchronisation, it may result in
  1833. // an extensive CPU usage on the plugin start (once per tab loaded)
  1834. // Params:
  1835. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  1836. //
  1837. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  1838. // The WebRTC API is ready.
  1839. // Override me and do whatever you want here
  1840. };
  1841. // Sets a callback function to be called when the WebRTC interface is ready.
  1842. // The first argument is the function to callback.\
  1843. // Throws an error if the first argument is not a function
  1844. AdapterJS.webRTCReady = function (callback) {
  1845. if (typeof callback !== 'function') {
  1846. throw new Error('Callback provided is not a function');
  1847. }
  1848. if (true === AdapterJS.onwebrtcreadyDone) {
  1849. // All WebRTC interfaces are ready, just call the callback
  1850. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  1851. } else {
  1852. // will be triggered automatically when your browser/plugin is ready.
  1853. AdapterJS.onwebrtcready = callback;
  1854. }
  1855. };
  1856. // Plugin namespace
  1857. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  1858. // The object to store plugin information
  1859. AdapterJS.WebRTCPlugin.pluginInfo = {
  1860. prefix : 'Tem',
  1861. plugName : 'TemWebRTCPlugin',
  1862. pluginId : 'plugin0',
  1863. type : 'application/x-temwebrtcplugin',
  1864. onload : '__TemWebRTCReady0',
  1865. portalLink : 'http://skylink.io/plugin/',
  1866. downloadLink : null, //set below
  1867. companyName: 'Temasys'
  1868. };
  1869. if(!!navigator.platform.match(/^Mac/i)) {
  1870. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  1871. }
  1872. else if(!!navigator.platform.match(/^Win/i)) {
  1873. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  1874. }
  1875. // Unique identifier of each opened page
  1876. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  1877. // Use this whenever you want to call the plugin.
  1878. AdapterJS.WebRTCPlugin.plugin = null;
  1879. // Set log level for the plugin once it is ready.
  1880. // The different values are
  1881. // This is an asynchronous function that will run when the plugin is ready
  1882. AdapterJS.WebRTCPlugin.setLogLevel = null;
  1883. // Defines webrtc's JS interface according to the plugin's implementation.
  1884. // Define plugin Browsers as WebRTC Interface.
  1885. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  1886. // This function detects whether or not a plugin is installed.
  1887. // Checks if Not IE (firefox, for example), else if it's IE,
  1888. // we're running IE and do something. If not it is not supported.
  1889. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  1890. // Lets adapter.js wait until the the document is ready before injecting the plugin
  1891. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  1892. // Inject the HTML DOM object element into the page.
  1893. AdapterJS.WebRTCPlugin.injectPlugin = null;
  1894. // States of readiness that the plugin goes through when
  1895. // being injected and stated
  1896. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  1897. NONE : 0, // no plugin use
  1898. INITIALIZING : 1, // Detected need for plugin
  1899. INJECTING : 2, // Injecting plugin
  1900. INJECTED: 3, // Plugin element injected but not usable yet
  1901. READY: 4 // Plugin ready to be used
  1902. };
  1903. // Current state of the plugin. You cannot use the plugin before this is
  1904. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  1905. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  1906. // True is AdapterJS.onwebrtcready was already called, false otherwise
  1907. // Used to make sure AdapterJS.onwebrtcready is only called once
  1908. AdapterJS.onwebrtcreadyDone = false;
  1909. // Log levels for the plugin.
  1910. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  1911. /*
  1912. Log outputs are prefixed in some cases.
  1913. INFO: Information reported by the plugin.
  1914. ERROR: Errors originating from within the plugin.
  1915. WEBRTC: Error originating from within the libWebRTC library
  1916. */
  1917. // From the least verbose to the most verbose
  1918. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  1919. NONE : 'NONE',
  1920. ERROR : 'ERROR',
  1921. WARNING : 'WARNING',
  1922. INFO: 'INFO',
  1923. VERBOSE: 'VERBOSE',
  1924. SENSITIVE: 'SENSITIVE'
  1925. };
  1926. // Does a waiting check before proceeding to load the plugin.
  1927. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  1928. // This methid will use an interval to wait for the plugin to be ready.
  1929. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  1930. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  1931. // This function will be called when plugin is ready. It sends necessary
  1932. // details to the plugin.
  1933. // The function will wait for the document to be ready and the set the
  1934. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  1935. // indicating that it can start being requested.
  1936. // This function is not in the IE/Safari condition brackets so that
  1937. // TemPluginLoaded function might be called on Chrome/Firefox.
  1938. // This function is the only private function that is not encapsulated to
  1939. // allow the plugin method to be called.
  1940. __TemWebRTCReady0 = function () {
  1941. if (document.readyState === 'complete') {
  1942. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1943. AdapterJS.maybeThroughWebRTCReady();
  1944. } else {
  1945. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  1946. if (document.readyState === 'complete') {
  1947. // TODO: update comments, we wait for the document to be ready
  1948. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  1949. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1950. AdapterJS.maybeThroughWebRTCReady();
  1951. }
  1952. }, 100);
  1953. }
  1954. };
  1955. AdapterJS.maybeThroughWebRTCReady = function() {
  1956. if (!AdapterJS.onwebrtcreadyDone) {
  1957. AdapterJS.onwebrtcreadyDone = true;
  1958. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  1959. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  1960. }
  1961. }
  1962. };
  1963. // Text namespace
  1964. AdapterJS.TEXT = {
  1965. PLUGIN: {
  1966. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  1967. 'to work on this browser.',
  1968. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  1969. BUTTON: 'Install Now'
  1970. },
  1971. REFRESH: {
  1972. REQUIRE_REFRESH: 'Please refresh page',
  1973. BUTTON: 'Refresh Page'
  1974. }
  1975. };
  1976. // The result of ice connection states.
  1977. // - starting: Ice connection is starting.
  1978. // - checking: Ice connection is checking.
  1979. // - connected Ice connection is connected.
  1980. // - completed Ice connection is connected.
  1981. // - done Ice connection has been completed.
  1982. // - disconnected Ice connection has been disconnected.
  1983. // - failed Ice connection has failed.
  1984. // - closed Ice connection is closed.
  1985. AdapterJS._iceConnectionStates = {
  1986. starting : 'starting',
  1987. checking : 'checking',
  1988. connected : 'connected',
  1989. completed : 'connected',
  1990. done : 'completed',
  1991. disconnected : 'disconnected',
  1992. failed : 'failed',
  1993. closed : 'closed'
  1994. };
  1995. //The IceConnection states that has been fired for each peer.
  1996. AdapterJS._iceConnectionFiredStates = [];
  1997. // Check if WebRTC Interface is defined.
  1998. AdapterJS.isDefined = null;
  1999. // This function helps to retrieve the webrtc detected browser information.
  2000. // This sets:
  2001. // - webrtcDetectedBrowser: The browser agent name.
  2002. // - webrtcDetectedVersion: The browser version.
  2003. // - webrtcDetectedType: The types of webRTC support.
  2004. // - 'moz': Mozilla implementation of webRTC.
  2005. // - 'webkit': WebKit implementation of webRTC.
  2006. // - 'plugin': Using the plugin implementation.
  2007. AdapterJS.parseWebrtcDetectedBrowser = function () {
  2008. var hasMatch, checkMatch = navigator.userAgent.match(
  2009. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  2010. if (/trident/i.test(checkMatch[1])) {
  2011. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  2012. webrtcDetectedBrowser = 'IE';
  2013. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  2014. } else if (checkMatch[1] === 'Chrome') {
  2015. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2016. if (hasMatch !== null) {
  2017. webrtcDetectedBrowser = 'opera';
  2018. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  2019. }
  2020. }
  2021. if (navigator.userAgent.indexOf('Safari')) {
  2022. if (typeof InstallTrigger !== 'undefined') {
  2023. webrtcDetectedBrowser = 'firefox';
  2024. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  2025. webrtcDetectedBrowser = 'IE';
  2026. } else if (
  2027. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  2028. webrtcDetectedBrowser = 'safari';
  2029. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  2030. webrtcDetectedBrowser = 'opera';
  2031. } else if (!!window.chrome) {
  2032. webrtcDetectedBrowser = 'chrome';
  2033. }
  2034. }
  2035. if (!webrtcDetectedBrowser) {
  2036. webrtcDetectedVersion = checkMatch[1];
  2037. }
  2038. if (!webrtcDetectedVersion) {
  2039. try {
  2040. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  2041. [navigator.appName, navigator.appVersion, '-?'];
  2042. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  2043. checkMatch.splice(1, 1, hasMatch[1]);
  2044. }
  2045. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  2046. } catch (error) { }
  2047. }
  2048. };
  2049. // To fix configuration as some browsers does not support
  2050. // the 'urls' attribute.
  2051. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  2052. if (pcConfig === null) {
  2053. return;
  2054. }
  2055. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  2056. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  2057. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  2058. delete pcConfig.iceServers[i].urls;
  2059. }
  2060. }
  2061. };
  2062. AdapterJS.addEvent = function(elem, evnt, func) {
  2063. if (elem.addEventListener) { // W3C DOM
  2064. elem.addEventListener(evnt, func, false);
  2065. } else if (elem.attachEvent) {// OLD IE DOM
  2066. elem.attachEvent('on'+evnt, func);
  2067. } else { // No much to do
  2068. elem[evnt] = func;
  2069. }
  2070. };
  2071. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  2072. // only inject once the page is ready
  2073. if (document.readyState !== 'complete') {
  2074. return;
  2075. }
  2076. var w = window;
  2077. var i = document.createElement('iframe');
  2078. i.style.position = 'fixed';
  2079. i.style.top = '-41px';
  2080. i.style.left = 0;
  2081. i.style.right = 0;
  2082. i.style.width = '100%';
  2083. i.style.height = '40px';
  2084. i.style.backgroundColor = '#ffffe1';
  2085. i.style.border = 'none';
  2086. i.style.borderBottom = '1px solid #888888';
  2087. i.style.zIndex = '9999999';
  2088. if(typeof i.style.webkitTransition === 'string') {
  2089. i.style.webkitTransition = 'all .5s ease-out';
  2090. } else if(typeof i.style.transition === 'string') {
  2091. i.style.transition = 'all .5s ease-out';
  2092. }
  2093. document.body.appendChild(i);
  2094. c = (i.contentWindow) ? i.contentWindow :
  2095. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  2096. c.document.open();
  2097. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  2098. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  2099. 'middle; cursor: default;">' + text + '</span>');
  2100. if(buttonText && buttonLink) {
  2101. c.document.write('<button id="okay">' + buttonText + '</button><button>Cancel</button>');
  2102. c.document.close();
  2103. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  2104. if (!!displayRefreshBar) {
  2105. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  2106. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  2107. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  2108. }
  2109. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  2110. e.preventDefault();
  2111. try {
  2112. event.cancelBubble = true;
  2113. } catch(error) { }
  2114. });
  2115. }
  2116. else {
  2117. c.document.close();
  2118. }
  2119. AdapterJS.addEvent(c.document, 'click', function() {
  2120. w.document.body.removeChild(i);
  2121. });
  2122. setTimeout(function() {
  2123. if(typeof i.style.webkitTransform === 'string') {
  2124. i.style.webkitTransform = 'translateY(40px)';
  2125. } else if(typeof i.style.transform === 'string') {
  2126. i.style.transform = 'translateY(40px)';
  2127. } else {
  2128. i.style.top = '0px';
  2129. }
  2130. }, 300);
  2131. };
  2132. // -----------------------------------------------------------
  2133. // Detected webrtc implementation. Types are:
  2134. // - 'moz': Mozilla implementation of webRTC.
  2135. // - 'webkit': WebKit implementation of webRTC.
  2136. // - 'plugin': Using the plugin implementation.
  2137. webrtcDetectedType = null;
  2138. // Detected webrtc datachannel support. Types are:
  2139. // - 'SCTP': SCTP datachannel support.
  2140. // - 'RTP': RTP datachannel support.
  2141. webrtcDetectedDCSupport = null;
  2142. // Set the settings for creating DataChannels, MediaStream for
  2143. // Cross-browser compability.
  2144. // - This is only for SCTP based support browsers.
  2145. // the 'urls' attribute.
  2146. checkMediaDataChannelSettings =
  2147. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  2148. if (typeof callback !== 'function') {
  2149. return;
  2150. }
  2151. var beOfferer = true;
  2152. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  2153. // Nightly version does not require MozDontOfferDataChannel for interop
  2154. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  2155. var isPeerFirefox = peerBrowserAgent === 'firefox';
  2156. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  2157. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  2158. // Resends an updated version of constraints for MozDataChannel to work
  2159. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  2160. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  2161. try {
  2162. delete constraints.mandatory.MozDontOfferDataChannel;
  2163. } catch (error) {
  2164. console.error('Failed deleting MozDontOfferDataChannel');
  2165. console.error(error);
  2166. }
  2167. } else if ((isLocalFirefox && !isPeerFirefox)) {
  2168. constraints.mandatory.MozDontOfferDataChannel = true;
  2169. }
  2170. if (!isLocalFirefox) {
  2171. // temporary measure to remove Moz* constraints in non Firefox browsers
  2172. for (var prop in constraints.mandatory) {
  2173. if (constraints.mandatory.hasOwnProperty(prop)) {
  2174. if (prop.indexOf('Moz') !== -1) {
  2175. delete constraints.mandatory[prop];
  2176. }
  2177. }
  2178. }
  2179. }
  2180. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  2181. // interopability of the media stream
  2182. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  2183. beOfferer = false;
  2184. }
  2185. callback(beOfferer, constraints);
  2186. };
  2187. // Handles the differences for all browsers ice connection state output.
  2188. // - Tested outcomes are:
  2189. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  2190. // - Chrome (answerer) : 'checking' > 'connected'
  2191. // - Firefox (offerer) : 'checking' > 'connected'
  2192. // - Firefox (answerer): 'checking' > 'connected'
  2193. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  2194. if (typeof callback !== 'function') {
  2195. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  2196. return;
  2197. }
  2198. peerId = (peerId) ? peerId : 'peer';
  2199. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  2200. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  2201. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  2202. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  2203. AdapterJS._iceConnectionFiredStates[peerId] = [];
  2204. }
  2205. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  2206. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  2207. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  2208. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  2209. setTimeout(function () {
  2210. AdapterJS._iceConnectionFiredStates[peerId]
  2211. .push(AdapterJS._iceConnectionStates.done);
  2212. callback(AdapterJS._iceConnectionStates.done);
  2213. }, 1000);
  2214. }
  2215. callback(iceConnectionState);
  2216. }
  2217. return;
  2218. };
  2219. // Firefox:
  2220. // - Creates iceServer from the url for Firefox.
  2221. // - Create iceServer with stun url.
  2222. // - Create iceServer with turn url.
  2223. // - Ignore the transport parameter from TURN url for FF version <=27.
  2224. // - Return null for createIceServer if transport=tcp.
  2225. // - FF 27 and above supports transport parameters in TURN url,
  2226. // - So passing in the full url to create iceServer.
  2227. // Chrome:
  2228. // - Creates iceServer from the url for Chrome M33 and earlier.
  2229. // - Create iceServer with stun url.
  2230. // - Chrome M28 & above uses below TURN format.
  2231. // Plugin:
  2232. // - Creates Ice Server for Plugin Browsers
  2233. // - If Stun - Create iceServer with stun url.
  2234. // - Else - Create iceServer with turn url
  2235. // - This is a WebRTC Function
  2236. createIceServer = null;
  2237. // Firefox:
  2238. // - Creates IceServers for Firefox
  2239. // - Use .url for FireFox.
  2240. // - Multiple Urls support
  2241. // Chrome:
  2242. // - Creates iceServers from the urls for Chrome M34 and above.
  2243. // - .urls is supported since Chrome M34.
  2244. // - Multiple Urls support
  2245. // Plugin:
  2246. // - Creates Ice Servers for Plugin Browsers
  2247. // - Multiple Urls support
  2248. // - This is a WebRTC Function
  2249. createIceServers = null;
  2250. //------------------------------------------------------------
  2251. //The RTCPeerConnection object.
  2252. RTCPeerConnection = null;
  2253. // Creates RTCSessionDescription object for Plugin Browsers
  2254. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  2255. RTCSessionDescription : null;
  2256. // Creates RTCIceCandidate object for Plugin Browsers
  2257. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  2258. RTCIceCandidate : null;
  2259. // Get UserMedia (only difference is the prefix).
  2260. // Code from Adam Barth.
  2261. getUserMedia = null;
  2262. // Attach a media stream to an element.
  2263. attachMediaStream = null;
  2264. // Re-attach a media stream to an element.
  2265. reattachMediaStream = null;
  2266. // Detected browser agent name. Types are:
  2267. // - 'firefox': Firefox browser.
  2268. // - 'chrome': Chrome browser.
  2269. // - 'opera': Opera browser.
  2270. // - 'safari': Safari browser.
  2271. // - 'IE' - Internet Explorer browser.
  2272. webrtcDetectedBrowser = null;
  2273. // Detected browser version.
  2274. webrtcDetectedVersion = null;
  2275. // Check for browser types and react accordingly
  2276. if (navigator.mozGetUserMedia) {
  2277. webrtcDetectedBrowser = 'firefox';
  2278. webrtcDetectedVersion = parseInt(navigator
  2279. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2280. webrtcDetectedType = 'moz';
  2281. webrtcDetectedDCSupport = 'SCTP';
  2282. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2283. AdapterJS.maybeFixConfiguration(pcConfig);
  2284. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  2285. };
  2286. // The RTCSessionDescription object.
  2287. RTCSessionDescription = mozRTCSessionDescription;
  2288. window.RTCSessionDescription = RTCSessionDescription;
  2289. // The RTCIceCandidate object.
  2290. RTCIceCandidate = mozRTCIceCandidate;
  2291. window.RTCIceCandidate = RTCIceCandidate;
  2292. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  2293. navigator.getUserMedia = window.getUserMedia;
  2294. // Shim for MediaStreamTrack.getSources.
  2295. MediaStreamTrack.getSources = function(successCb) {
  2296. setTimeout(function() {
  2297. var infos = [
  2298. { kind: 'audio', id: 'default', label:'', facing:'' },
  2299. { kind: 'video', id: 'default', label:'', facing:'' }
  2300. ];
  2301. successCb(infos);
  2302. }, 0);
  2303. };
  2304. createIceServer = function (url, username, password) {
  2305. var iceServer = null;
  2306. var url_parts = url.split(':');
  2307. if (url_parts[0].indexOf('stun') === 0) {
  2308. iceServer = { url : url };
  2309. } else if (url_parts[0].indexOf('turn') === 0) {
  2310. if (webrtcDetectedVersion < 27) {
  2311. var turn_url_parts = url.split('?');
  2312. if (turn_url_parts.length === 1 ||
  2313. turn_url_parts[1].indexOf('transport=udp') === 0) {
  2314. iceServer = {
  2315. url : turn_url_parts[0],
  2316. credential : password,
  2317. username : username
  2318. };
  2319. }
  2320. } else {
  2321. iceServer = {
  2322. url : url,
  2323. credential : password,
  2324. username : username
  2325. };
  2326. }
  2327. }
  2328. return iceServer;
  2329. };
  2330. createIceServers = function (urls, username, password) {
  2331. var iceServers = [];
  2332. for (i = 0; i < urls.length; i++) {
  2333. var iceServer = createIceServer(urls[i], username, password);
  2334. if (iceServer !== null) {
  2335. iceServers.push(iceServer);
  2336. }
  2337. }
  2338. return iceServers;
  2339. };
  2340. attachMediaStream = function (element, stream) {
  2341. element.mozSrcObject = stream;
  2342. if (stream !== null)
  2343. element.play();
  2344. return element;
  2345. };
  2346. reattachMediaStream = function (to, from) {
  2347. to.mozSrcObject = from.mozSrcObject;
  2348. to.play();
  2349. return to;
  2350. };
  2351. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  2352. if (!callback) {
  2353. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  2354. ': 1 argument required, but only 0 present.');
  2355. }
  2356. return callback([]);
  2357. };
  2358. // Fake get{Video,Audio}Tracks
  2359. if (!MediaStream.prototype.getVideoTracks) {
  2360. MediaStream.prototype.getVideoTracks = function () {
  2361. return [];
  2362. };
  2363. }
  2364. if (!MediaStream.prototype.getAudioTracks) {
  2365. MediaStream.prototype.getAudioTracks = function () {
  2366. return [];
  2367. };
  2368. }
  2369. AdapterJS.maybeThroughWebRTCReady();
  2370. } else if (navigator.webkitGetUserMedia) {
  2371. webrtcDetectedBrowser = 'chrome';
  2372. webrtcDetectedType = 'webkit';
  2373. webrtcDetectedVersion = parseInt(navigator
  2374. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  2375. // check if browser is opera 20+
  2376. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2377. if (checkIfOpera !== null) {
  2378. webrtcDetectedBrowser = 'opera';
  2379. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  2380. }
  2381. // check browser datachannel support
  2382. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  2383. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  2384. webrtcDetectedDCSupport = 'SCTP';
  2385. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  2386. webrtcDetectedVersion > 24) {
  2387. webrtcDetectedDCSupport = 'RTP';
  2388. } else {
  2389. webrtcDetectedDCSupport = '';
  2390. }
  2391. createIceServer = function (url, username, password) {
  2392. var iceServer = null;
  2393. var url_parts = url.split(':');
  2394. if (url_parts[0].indexOf('stun') === 0) {
  2395. iceServer = { 'url' : url };
  2396. } else if (url_parts[0].indexOf('turn') === 0) {
  2397. iceServer = {
  2398. 'url' : url,
  2399. 'credential' : password,
  2400. 'username' : username
  2401. };
  2402. }
  2403. return iceServer;
  2404. };
  2405. createIceServers = function (urls, username, password) {
  2406. var iceServers = [];
  2407. if (webrtcDetectedVersion >= 34) {
  2408. iceServers = {
  2409. 'urls' : urls,
  2410. 'credential' : password,
  2411. 'username' : username
  2412. };
  2413. } else {
  2414. for (i = 0; i < urls.length; i++) {
  2415. var iceServer = createIceServer(urls[i], username, password);
  2416. if (iceServer !== null) {
  2417. iceServers.push(iceServer);
  2418. }
  2419. }
  2420. }
  2421. return iceServers;
  2422. };
  2423. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2424. if (webrtcDetectedVersion < 34) {
  2425. AdapterJS.maybeFixConfiguration(pcConfig);
  2426. }
  2427. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  2428. };
  2429. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2430. navigator.getUserMedia = window.getUserMedia;
  2431. attachMediaStream = function (element, stream) {
  2432. if (typeof element.srcObject !== 'undefined') {
  2433. element.srcObject = stream;
  2434. } else if (typeof element.mozSrcObject !== 'undefined') {
  2435. element.mozSrcObject = stream;
  2436. } else if (typeof element.src !== 'undefined') {
  2437. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  2438. } else {
  2439. console.log('Error attaching stream to element.');
  2440. }
  2441. return element;
  2442. };
  2443. reattachMediaStream = function (to, from) {
  2444. to.src = from.src;
  2445. return to;
  2446. };
  2447. AdapterJS.maybeThroughWebRTCReady();
  2448. } else { // TRY TO USE PLUGIN
  2449. // IE 9 is not offering an implementation of console.log until you open a console
  2450. if (typeof console !== 'object' || typeof console.log !== 'function') {
  2451. /* jshint -W020 */
  2452. console = {} || console;
  2453. // Implemented based on console specs from MDN
  2454. // You may override these functions
  2455. console.log = function (arg) {};
  2456. console.info = function (arg) {};
  2457. console.error = function (arg) {};
  2458. console.dir = function (arg) {};
  2459. console.exception = function (arg) {};
  2460. console.trace = function (arg) {};
  2461. console.warn = function (arg) {};
  2462. console.count = function (arg) {};
  2463. console.debug = function (arg) {};
  2464. console.count = function (arg) {};
  2465. console.time = function (arg) {};
  2466. console.timeEnd = function (arg) {};
  2467. console.group = function (arg) {};
  2468. console.groupCollapsed = function (arg) {};
  2469. console.groupEnd = function (arg) {};
  2470. /* jshint +W020 */
  2471. }
  2472. webrtcDetectedType = 'plugin';
  2473. webrtcDetectedDCSupport = 'plugin';
  2474. AdapterJS.parseWebrtcDetectedBrowser();
  2475. isIE = webrtcDetectedBrowser === 'IE';
  2476. /* jshint -W035 */
  2477. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  2478. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2479. /* empty because it needs to prevent the function from running. */
  2480. }
  2481. };
  2482. /* jshint +W035 */
  2483. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  2484. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2485. // Call immediately if possible
  2486. // Once the plugin is set, the code will always take this path
  2487. callback();
  2488. } else {
  2489. // otherwise start a 100ms interval
  2490. var checkPluginReadyState = setInterval(function () {
  2491. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2492. clearInterval(checkPluginReadyState);
  2493. callback();
  2494. }
  2495. }, 100);
  2496. }
  2497. };
  2498. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  2499. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2500. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  2501. });
  2502. };
  2503. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  2504. // only inject once the page is ready
  2505. if (document.readyState !== 'complete') {
  2506. return;
  2507. }
  2508. // Prevent multiple injections
  2509. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  2510. return;
  2511. }
  2512. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  2513. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  2514. var frag = document.createDocumentFragment();
  2515. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  2516. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  2517. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  2518. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  2519. '<param name="pluginId" value="' +
  2520. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  2521. '<param name="windowless" value="false" /> ' +
  2522. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2523. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload +
  2524. '" />' +
  2525. // uncomment to be able to use virtual cams
  2526. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2527. '</object>';
  2528. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  2529. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  2530. }
  2531. document.body.appendChild(frag);
  2532. // Need to re-fetch the plugin
  2533. AdapterJS.WebRTCPlugin.plugin =
  2534. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  2535. } else {
  2536. // Load Plugin
  2537. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  2538. AdapterJS.WebRTCPlugin.plugin.id =
  2539. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  2540. // IE will only start the plugin if it's ACTUALLY visible
  2541. if (isIE) {
  2542. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  2543. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  2544. } else { // The size of the plugin on Safari should be 0x0px
  2545. // so that the autorisation prompt is at the top
  2546. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  2547. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  2548. }
  2549. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  2550. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  2551. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  2552. '<param name="pluginId" value="' +
  2553. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  2554. '<param name="windowless" value="false" /> ' +
  2555. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2556. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">';
  2557. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  2558. }
  2559. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  2560. };
  2561. AdapterJS.WebRTCPlugin.isPluginInstalled =
  2562. function (comName, plugName, installedCb, notInstalledCb) {
  2563. if (!isIE) {
  2564. var pluginArray = navigator.plugins;
  2565. for (var i = 0; i < pluginArray.length; i++) {
  2566. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  2567. installedCb();
  2568. return;
  2569. }
  2570. }
  2571. notInstalledCb();
  2572. } else {
  2573. try {
  2574. var axo = new ActiveXObject(comName + '.' + plugName);
  2575. } catch (e) {
  2576. notInstalledCb();
  2577. return;
  2578. }
  2579. installedCb();
  2580. }
  2581. };
  2582. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  2583. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  2584. AdapterJS.isDefined = function (variable) {
  2585. return variable !== null && variable !== undefined;
  2586. };
  2587. createIceServer = function (url, username, password) {
  2588. var iceServer = null;
  2589. var url_parts = url.split(':');
  2590. if (url_parts[0].indexOf('stun') === 0) {
  2591. iceServer = {
  2592. 'url' : url,
  2593. 'hasCredentials' : false
  2594. };
  2595. } else if (url_parts[0].indexOf('turn') === 0) {
  2596. iceServer = {
  2597. 'url' : url,
  2598. 'hasCredentials' : true,
  2599. 'credential' : password,
  2600. 'username' : username
  2601. };
  2602. }
  2603. return iceServer;
  2604. };
  2605. createIceServers = function (urls, username, password) {
  2606. var iceServers = [];
  2607. for (var i = 0; i < urls.length; ++i) {
  2608. iceServers.push(createIceServer(urls[i], username, password));
  2609. }
  2610. return iceServers;
  2611. };
  2612. RTCSessionDescription = function (info) {
  2613. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2614. return AdapterJS.WebRTCPlugin.plugin.
  2615. ConstructSessionDescription(info.type, info.sdp);
  2616. };
  2617. RTCPeerConnection = function (servers, constraints) {
  2618. var iceServers = null;
  2619. if (servers) {
  2620. iceServers = servers.iceServers;
  2621. for (var i = 0; i < iceServers.length; i++) {
  2622. if (iceServers[i].urls && !iceServers[i].url) {
  2623. iceServers[i].url = iceServers[i].urls;
  2624. }
  2625. iceServers[i].hasCredentials = AdapterJS.
  2626. isDefined(iceServers[i].username) &&
  2627. AdapterJS.isDefined(iceServers[i].credential);
  2628. }
  2629. }
  2630. var mandatory = (constraints && constraints.mandatory) ?
  2631. constraints.mandatory : null;
  2632. var optional = (constraints && constraints.optional) ?
  2633. constraints.optional : null;
  2634. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2635. return AdapterJS.WebRTCPlugin.plugin.
  2636. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  2637. iceServers, mandatory, optional);
  2638. };
  2639. MediaStreamTrack = {};
  2640. MediaStreamTrack.getSources = function (callback) {
  2641. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2642. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  2643. });
  2644. };
  2645. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  2646. constraints.audio = constraints.audio || false;
  2647. constraints.video = constraints.video || false;
  2648. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2649. AdapterJS.WebRTCPlugin.plugin.
  2650. getUserMedia(constraints, successCallback, failureCallback);
  2651. });
  2652. };
  2653. window.navigator.getUserMedia = window.getUserMedia;
  2654. attachMediaStream = function (element, stream) {
  2655. if (!element || !element.parentNode) {
  2656. return;
  2657. }
  2658. var streamId
  2659. if (stream === null) {
  2660. streamId = '';
  2661. }
  2662. else {
  2663. stream.enableSoundTracks(true);
  2664. streamId = stream.id;
  2665. }
  2666. if (element.nodeName.toLowerCase() !== 'audio') {
  2667. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  2668. if (!element.isWebRTCPlugin || !element.isWebRTCPlugin()) {
  2669. var frag = document.createDocumentFragment();
  2670. var temp = document.createElement('div');
  2671. var classHTML = '';
  2672. if (element.className) {
  2673. classHTML = 'class="' + element.className + '" ';
  2674. } else if (element.attributes && element.attributes['class']) {
  2675. classHTML = 'class="' + element.attributes['class'].value + '" ';
  2676. }
  2677. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  2678. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  2679. '<param name="pluginId" value="' + elementId + '" /> ' +
  2680. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2681. '<param name="windowless" value="true" /> ' +
  2682. '<param name="streamId" value="' + streamId + '" /> ' +
  2683. '</object>';
  2684. while (temp.firstChild) {
  2685. frag.appendChild(temp.firstChild);
  2686. }
  2687. var height = '';
  2688. var width = '';
  2689. if (element.getBoundingClientRect) {
  2690. var rectObject = element.getBoundingClientRect();
  2691. width = rectObject.width + 'px';
  2692. height = rectObject.height + 'px';
  2693. }
  2694. else if (element.width) {
  2695. width = element.width;
  2696. height = element.height;
  2697. } else {
  2698. // TODO: What scenario could bring us here?
  2699. }
  2700. element.parentNode.insertBefore(frag, element);
  2701. frag = document.getElementById(elementId);
  2702. frag.width = width;
  2703. frag.height = height;
  2704. element.parentNode.removeChild(element);
  2705. } else {
  2706. var children = element.children;
  2707. for (var i = 0; i !== children.length; ++i) {
  2708. if (children[i].name === 'streamId') {
  2709. children[i].value = streamId;
  2710. break;
  2711. }
  2712. }
  2713. element.setStreamId(streamId);
  2714. }
  2715. var newElement = document.getElementById(elementId);
  2716. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  2717. if (isIE) { // on IE the event needs to be plugged manually
  2718. newElement.attachEvent('onplaying', newElement.onplaying);
  2719. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  2720. newElement._TemOnClick = function (id) {
  2721. var arg = {
  2722. srcElement : document.getElementById(id)
  2723. };
  2724. newElement.onclick(arg);
  2725. };
  2726. }
  2727. return newElement;
  2728. } else {
  2729. return element;
  2730. }
  2731. };
  2732. reattachMediaStream = function (to, from) {
  2733. var stream = null;
  2734. var children = from.children;
  2735. for (var i = 0; i !== children.length; ++i) {
  2736. if (children[i].name === 'streamId') {
  2737. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2738. stream = AdapterJS.WebRTCPlugin.plugin
  2739. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  2740. break;
  2741. }
  2742. }
  2743. if (stream !== null) {
  2744. return attachMediaStream(to, stream);
  2745. } else {
  2746. console.log('Could not find the stream associated with this element');
  2747. }
  2748. };
  2749. RTCIceCandidate = function (candidate) {
  2750. if (!candidate.sdpMid) {
  2751. candidate.sdpMid = '';
  2752. }
  2753. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2754. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  2755. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  2756. );
  2757. };
  2758. // inject plugin
  2759. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  2760. AdapterJS.WebRTCPlugin.injectPlugin();
  2761. };
  2762. // This function will be called if the plugin is needed (browser different
  2763. // from Chrome or Firefox), but the plugin is not installed.
  2764. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  2765. function() {
  2766. AdapterJS.addEvent(document,
  2767. 'readystatechange',
  2768. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  2769. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  2770. };
  2771. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  2772. if (AdapterJS.options.hidePluginInstallPrompt) {
  2773. return;
  2774. }
  2775. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  2776. if(downloadLink) { // if download link
  2777. var popupString;
  2778. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  2779. popupString = 'This website requires you to install the ' +
  2780. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  2781. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  2782. ' WebRTC Plugin</a>' +
  2783. ' to work on this browser.';
  2784. } else { // no portal link, just print a generic explanation
  2785. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  2786. }
  2787. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  2788. } else { // no download link, just print a generic explanation
  2789. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  2790. }
  2791. };
  2792. // Try to detect the plugin and act accordingly
  2793. AdapterJS.WebRTCPlugin.isPluginInstalled(
  2794. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  2795. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  2796. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  2797. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  2798. }
  2799. (function () {
  2800. 'use strict';
  2801. var baseGetUserMedia = null;
  2802. AdapterJS.TEXT.EXTENSION = {
  2803. REQUIRE_INSTALLATION_FF: 'To enable screensharing you need to install the Skylink WebRTC tools Firefox Add-on.',
  2804. REQUIRE_INSTALLATION_CHROME: 'To enable screensharing you need to install the Skylink WebRTC tools Chrome Extension.',
  2805. REQUIRE_REFRESH: 'Please refresh this page after the Skylink WebRTC tools extension has been installed.',
  2806. BUTTON_FF: 'Install Now',
  2807. BUTTON_CHROME: 'Go to Chrome Web Store'
  2808. };
  2809. var clone = function(obj) {
  2810. if (null == obj || "object" != typeof obj) return obj;
  2811. var copy = obj.constructor();
  2812. for (var attr in obj) {
  2813. if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
  2814. }
  2815. return copy;
  2816. };
  2817. if (window.navigator.mozGetUserMedia) {
  2818. baseGetUserMedia = window.navigator.getUserMedia;
  2819. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2820. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2821. // intercepting screensharing requests
  2822. if (constraints.video.mediaSource !== 'screen' && constraints.video.mediaSource !== 'window') {
  2823. throw new Error('Only "screen" and "window" option is available as mediaSource');
  2824. }
  2825. var updatedConstraints = clone(constraints);
  2826. //constraints.video.mediaSource = constraints.video.mediaSource;
  2827. updatedConstraints.video.mozMediaSource = updatedConstraints.video.mediaSource;
  2828. // so generally, it requires for document.readyState to be completed before the getUserMedia could be invoked.
  2829. // strange but this works anyway
  2830. var checkIfReady = setInterval(function () {
  2831. if (document.readyState === 'complete') {
  2832. clearInterval(checkIfReady);
  2833. baseGetUserMedia(updatedConstraints, successCb, function (error) {
  2834. if (error.name === 'PermissionDeniedError' && window.parent.location.protocol === 'https:') {
  2835. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_FF,
  2836. AdapterJS.TEXT.EXTENSION.BUTTON_FF,
  2837. 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname, false, true);
  2838. //window.location.href = 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname;
  2839. } else {
  2840. failureCb(error);
  2841. }
  2842. });
  2843. }
  2844. }, 1);
  2845. } else { // regular GetUserMediaRequest
  2846. baseGetUserMedia(constraints, successCb, failureCb);
  2847. }
  2848. };
  2849. getUserMedia = navigator.getUserMedia;
  2850. } else if (window.navigator.webkitGetUserMedia) {
  2851. baseGetUserMedia = window.navigator.getUserMedia;
  2852. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2853. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2854. if (window.webrtcDetectedBrowser !== 'chrome') {
  2855. throw new Error('Current browser does not support screensharing');
  2856. }
  2857. // would be fine since no methods
  2858. var updatedConstraints = clone(constraints);
  2859. var chromeCallback = function(error, sourceId) {
  2860. if(!error) {
  2861. updatedConstraints.video.mandatory = updatedConstraints.video.mandatory || {};
  2862. updatedConstraints.video.mandatory.chromeMediaSource = 'desktop';
  2863. updatedConstraints.video.mandatory.maxWidth = window.screen.width > 1920 ? window.screen.width : 1920;
  2864. updatedConstraints.video.mandatory.maxHeight = window.screen.height > 1080 ? window.screen.height : 1080;
  2865. if (sourceId) {
  2866. updatedConstraints.video.mandatory.chromeMediaSourceId = sourceId;
  2867. }
  2868. delete updatedConstraints.video.mediaSource;
  2869. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2870. } else {
  2871. if (error === 'permission-denied') {
  2872. throw new Error('Permission denied for screen retrieval');
  2873. } else {
  2874. throw new Error('Failed retrieving selected screen');
  2875. }
  2876. }
  2877. };
  2878. var onIFrameCallback = function (event) {
  2879. if (!event.data) {
  2880. return;
  2881. }
  2882. if (event.data.chromeMediaSourceId) {
  2883. if (event.data.chromeMediaSourceId === 'PermissionDeniedError') {
  2884. chromeCallback('permission-denied');
  2885. } else {
  2886. chromeCallback(null, event.data.chromeMediaSourceId);
  2887. }
  2888. }
  2889. if (event.data.chromeExtensionStatus) {
  2890. if (event.data.chromeExtensionStatus === 'not-installed') {
  2891. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_CHROME,
  2892. AdapterJS.TEXT.EXTENSION.BUTTON_CHROME,
  2893. event.data.data, true, true);
  2894. } else {
  2895. chromeCallback(event.data.chromeExtensionStatus, null);
  2896. }
  2897. }
  2898. // this event listener is no more needed
  2899. window.removeEventListener('message', onIFrameCallback);
  2900. };
  2901. window.addEventListener('message', onIFrameCallback);
  2902. postFrameMessage({
  2903. captureSourceId: true
  2904. });
  2905. } else {
  2906. baseGetUserMedia(constraints, successCb, failureCb);
  2907. }
  2908. };
  2909. getUserMedia = navigator.getUserMedia;
  2910. } else {
  2911. baseGetUserMedia = window.navigator.getUserMedia;
  2912. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2913. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2914. // would be fine since no methods
  2915. var updatedConstraints = clone(constraints);
  2916. // wait for plugin to be ready
  2917. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2918. // check if screensharing feature is available
  2919. if (!!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature &&
  2920. !!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  2921. // set the constraints
  2922. updatedConstraints.video.optional = updatedConstraints.video.optional || [];
  2923. updatedConstraints.video.optional.push({
  2924. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey || 'Screensharing'
  2925. });
  2926. delete updatedConstraints.video.mediaSource;
  2927. } else {
  2928. throw new Error('Your WebRTC plugin does not support screensharing');
  2929. }
  2930. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2931. });
  2932. } else {
  2933. baseGetUserMedia(constraints, successCb, failureCb);
  2934. }
  2935. };
  2936. getUserMedia = window.navigator.getUserMedia;
  2937. }
  2938. if (window.webrtcDetectedBrowser === 'chrome') {
  2939. var iframe = document.createElement('iframe');
  2940. iframe.onload = function() {
  2941. iframe.isLoaded = true;
  2942. };
  2943. iframe.src = 'https://cdn.temasys.com.sg/skylink/extensions/detectRTC.html';
  2944. //'https://temasys-cdn.s3.amazonaws.com/skylink/extensions/detection-script-dev/detectRTC.html';
  2945. iframe.style.display = 'none';
  2946. (document.body || document.documentElement).appendChild(iframe);
  2947. var postFrameMessage = function (object) {
  2948. object = object || {};
  2949. if (!iframe.isLoaded) {
  2950. setTimeout(function () {
  2951. iframe.contentWindow.postMessage(object, '*');
  2952. }, 100);
  2953. return;
  2954. }
  2955. iframe.contentWindow.postMessage(object, '*');
  2956. };
  2957. }
  2958. })();
  2959. },{}],13:[function(require,module,exports){
  2960. /* global Strophe, APP, $, config, interfaceConfig, toastr */
  2961. var UI = {};
  2962. var VideoLayout = require("./videolayout/VideoLayout.js");
  2963. var AudioLevels = require("./audio_levels/AudioLevels.js");
  2964. var Prezi = require("./prezi/Prezi.js");
  2965. var Etherpad = require("./etherpad/Etherpad.js");
  2966. var Chat = require("./side_pannels/chat/Chat.js");
  2967. var Toolbar = require("./toolbars/Toolbar");
  2968. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  2969. var BottomToolbar = require("./toolbars/BottomToolbar");
  2970. var ContactList = require("./side_pannels/contactlist/ContactList");
  2971. var Avatar = require("./avatar/Avatar");
  2972. var EventEmitter = require("events");
  2973. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  2974. var Settings = require("./../settings/Settings");
  2975. var PanelToggler = require("./side_pannels/SidePanelToggler");
  2976. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  2977. UI.messageHandler = require("./util/MessageHandler");
  2978. var messageHandler = UI.messageHandler;
  2979. var Authentication = require("./authentication/Authentication");
  2980. var UIUtil = require("./util/UIUtil");
  2981. var NicknameHandler = require("./util/NicknameHandler");
  2982. var CQEvents = require("../../service/connectionquality/CQEvents");
  2983. var DesktopSharingEventTypes
  2984. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  2985. var RTCEvents = require("../../service/RTC/RTCEvents");
  2986. var RTCBrowserType = require("../RTC/RTCBrowserType");
  2987. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  2988. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  2989. var UIEvents = require("../../service/UI/UIEvents");
  2990. var MemberEvents = require("../../service/members/Events");
  2991. var eventEmitter = new EventEmitter();
  2992. var roomName = null;
  2993. function promptDisplayName() {
  2994. var message = '<h2 data-i18n="dialog.displayNameRequired">';
  2995. message += APP.translation.translateString(
  2996. "dialog.displayNameRequired");
  2997. message += '</h2>' +
  2998. '<input name="displayName" type="text" data-i18n=' +
  2999. '"[placeholder]defaultNickname" placeholder="' +
  3000. APP.translation.translateString(
  3001. "defaultNickname", {name: "Jane Pink"}) +
  3002. '" autofocus>';
  3003. var buttonTxt
  3004. = APP.translation.generateTranslationHTML("dialog.Ok");
  3005. var buttons = [];
  3006. buttons.push({title: buttonTxt, value: "ok"});
  3007. messageHandler.openDialog(null, message,
  3008. true,
  3009. buttons,
  3010. function (e, v, m, f) {
  3011. if (v == "ok") {
  3012. var displayName = f.displayName;
  3013. if (displayName) {
  3014. VideoLayout.inputDisplayNameHandler(displayName);
  3015. return true;
  3016. }
  3017. }
  3018. e.preventDefault();
  3019. },
  3020. function () {
  3021. var form = $.prompt.getPrompt();
  3022. var input = form.find("input[name='displayName']");
  3023. input.focus();
  3024. var button = form.find("button");
  3025. button.attr("disabled", "disabled");
  3026. input.keyup(function () {
  3027. if(!input.val())
  3028. button.attr("disabled", "disabled");
  3029. else
  3030. button.removeAttr("disabled");
  3031. });
  3032. }
  3033. );
  3034. }
  3035. function notifyForInitialMute() {
  3036. messageHandler.notify(null, "notify.mutedTitle", "connected",
  3037. "notify.muted", null, {timeOut: 120000});
  3038. }
  3039. function setupPrezi() {
  3040. $("#reloadPresentationLink").click(function() {
  3041. Prezi.reloadPresentation();
  3042. });
  3043. }
  3044. function setupChat() {
  3045. Chat.init();
  3046. $("#toggle_smileys").click(function() {
  3047. Chat.toggleSmileys();
  3048. });
  3049. }
  3050. function setupToolbars() {
  3051. Toolbar.init(UI);
  3052. Toolbar.setupButtonsFromConfig();
  3053. BottomToolbar.init();
  3054. }
  3055. function streamHandler(stream, isMuted) {
  3056. switch (stream.type) {
  3057. case "audio":
  3058. VideoLayout.changeLocalAudio(stream, isMuted);
  3059. break;
  3060. case "video":
  3061. VideoLayout.changeLocalVideo(stream, isMuted);
  3062. break;
  3063. case "stream":
  3064. VideoLayout.changeLocalStream(stream, isMuted);
  3065. break;
  3066. }
  3067. }
  3068. function onXmppConnectionFailed(stropheErrorMsg) {
  3069. var title = APP.translation.generateTranslationHTML(
  3070. "dialog.error");
  3071. var message;
  3072. if (stropheErrorMsg) {
  3073. message = APP.translation.generateTranslationHTML(
  3074. "dialog.connectErrorWithMsg", {msg: stropheErrorMsg});
  3075. } else {
  3076. message = APP.translation.generateTranslationHTML(
  3077. "dialog.connectError");
  3078. }
  3079. messageHandler.openDialog(
  3080. title, message, true, {}, function (e, v, m, f) { return false; });
  3081. }
  3082. function onDisposeConference(unload) {
  3083. Toolbar.showAuthenticateButton(false);
  3084. }
  3085. function onDisplayNameChanged(jid, displayName) {
  3086. ContactList.onDisplayNameChange(jid, displayName);
  3087. SettingsMenu.onDisplayNameChange(jid, displayName);
  3088. VideoLayout.onDisplayNameChanged(jid, displayName);
  3089. }
  3090. function registerListeners() {
  3091. APP.RTC.addStreamListener(streamHandler,
  3092. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  3093. APP.RTC.addStreamListener(streamHandler,
  3094. StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  3095. APP.RTC.addStreamListener(function (stream) {
  3096. VideoLayout.onRemoteStreamAdded(stream);
  3097. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  3098. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  3099. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED,
  3100. function (resourceJid) {
  3101. VideoLayout.onDominantSpeakerChanged(resourceJid);
  3102. });
  3103. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  3104. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  3105. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  3106. endpointsEnteringLastN, stream);
  3107. });
  3108. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED,
  3109. function (devices) {
  3110. VideoLayout.setDeviceAvailabilityIcons(null, devices);
  3111. });
  3112. APP.RTC.addListener(RTCEvents.VIDEO_MUTE, UI.setVideoMuteButtonsState);
  3113. APP.RTC.addListener(RTCEvents.DATA_CHANNEL_OPEN, function() {
  3114. // when the data channel becomes available, tell the bridge about video
  3115. // selections so that it can do adaptive simulcast,
  3116. // we want the notification to trigger even if userJid is undefined,
  3117. // or null.
  3118. var userJid = APP.UI.getLargeVideoJid();
  3119. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT, userJid);
  3120. });
  3121. APP.statistics.addAudioLevelListener(function(jid, audioLevel) {
  3122. var resourceJid;
  3123. if(jid === APP.statistics.LOCAL_JID) {
  3124. resourceJid = AudioLevels.LOCAL_LEVEL;
  3125. if(APP.RTC.localAudio.isMuted()) {
  3126. audioLevel = 0;
  3127. }
  3128. } else {
  3129. resourceJid = Strophe.getResourceFromJid(jid);
  3130. }
  3131. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  3132. UI.getLargeVideoJid());
  3133. });
  3134. APP.desktopsharing.addListener(function () {
  3135. ToolbarToggler.showDesktopSharingButton();
  3136. }, DesktopSharingEventTypes.INIT);
  3137. APP.desktopsharing.addListener(
  3138. Toolbar.changeDesktopSharingButtonState,
  3139. DesktopSharingEventTypes.SWITCHING_DONE);
  3140. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  3141. VideoLayout.updateLocalConnectionStats);
  3142. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  3143. VideoLayout.updateConnectionStats);
  3144. APP.connectionquality.addListener(CQEvents.STOP,
  3145. VideoLayout.onStatsStop);
  3146. APP.xmpp.addListener(XMPPEvents.CONNECTION_FAILED, onXmppConnectionFailed);
  3147. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  3148. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  3149. messageHandler.openMessageDialog(
  3150. 'dialog.serviceUnavailable',
  3151. 'dialog.gracefulShutdown'
  3152. );
  3153. });
  3154. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  3155. var title = APP.translation.generateTranslationHTML(
  3156. "dialog.reservationError");
  3157. var message = APP.translation.generateTranslationHTML(
  3158. "dialog.reservationErrorMsg", {code: code, msg: msg});
  3159. messageHandler.openDialog(
  3160. title,
  3161. message,
  3162. true, {},
  3163. function (event, value, message, formVals) {
  3164. return false;
  3165. }
  3166. );
  3167. });
  3168. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  3169. messageHandler.openMessageDialog("dialog.sessTerminated",
  3170. "dialog.kickMessage");
  3171. });
  3172. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  3173. //FIXME: use Session Terminated from translation, but
  3174. // 'reason' text comes from XMPP packet and is not translated
  3175. var title = APP.translation.generateTranslationHTML("dialog.sessTerminated");
  3176. messageHandler.openDialog(
  3177. title, reason, true, {},
  3178. function (event, value, message, formVals) {
  3179. return false;
  3180. }
  3181. );
  3182. });
  3183. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  3184. messageHandler.showError("dialog.error",
  3185. "dialog.bridgeUnavailable");
  3186. });
  3187. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  3188. Avatar.setUserAvatar(from, id);
  3189. });
  3190. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  3191. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  3192. APP.xmpp.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, onLocalRoleChanged);
  3193. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  3194. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  3195. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  3196. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  3197. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  3198. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  3199. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordRequired);
  3200. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  3201. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  3202. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED,
  3203. onAuthenticationRequired);
  3204. APP.xmpp.addListener(XMPPEvents.VIDEO_TYPE, onPeerVideoTypeChanged);
  3205. APP.xmpp.addListener(XMPPEvents.DEVICE_AVAILABLE,
  3206. function (resource, devices) {
  3207. VideoLayout.setDeviceAvailabilityIcons(resource, devices);
  3208. });
  3209. APP.xmpp.addListener(XMPPEvents.AUDIO_MUTED, VideoLayout.onAudioMute);
  3210. APP.xmpp.addListener(XMPPEvents.VIDEO_MUTED, VideoLayout.onVideoMute);
  3211. APP.xmpp.addListener(XMPPEvents.AUDIO_MUTED_BY_FOCUS, function(doMuteAudio) {
  3212. UI.setAudioMuted(doMuteAudio);
  3213. });
  3214. APP.members.addListener(MemberEvents.DTMF_SUPPORT_CHANGED,
  3215. onDtmfSupportChanged);
  3216. APP.xmpp.addListener(XMPPEvents.START_MUTED_SETTING_CHANGED, function (audio, video) {
  3217. SettingsMenu.setStartMuted(audio, video);
  3218. });
  3219. APP.xmpp.addListener(XMPPEvents.START_MUTED_FROM_FOCUS, function (audio, video) {
  3220. UI.setInitialMuteFromFocus(audio, video);
  3221. });
  3222. APP.xmpp.addListener(XMPPEvents.JINGLE_FATAL_ERROR, function (session, error) {
  3223. UI.messageHandler.showError("dialog.sorry",
  3224. "dialog.internalError");
  3225. });
  3226. APP.xmpp.addListener(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR, function() {
  3227. messageHandler.showError("dialog.error",
  3228. "dialog.SLDFailure");
  3229. });
  3230. APP.xmpp.addListener(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR, function() {
  3231. messageHandler.showError("dialog.error",
  3232. "dialog.SRDFailure");
  3233. });
  3234. APP.xmpp.addListener(XMPPEvents.CREATE_ANSWER_ERROR, function() {
  3235. messageHandler.showError();
  3236. });
  3237. APP.xmpp.addListener(XMPPEvents.PROMPT_FOR_LOGIN, function() {
  3238. // FIXME: re-use LoginDialog which supports retries
  3239. UI.showLoginPopup(connect);
  3240. });
  3241. APP.xmpp.addListener(XMPPEvents.FOCUS_DISCONNECTED, function(focusComponent, retrySec) {
  3242. UI.messageHandler.notify(
  3243. null, "notify.focus",
  3244. 'disconnected', "notify.focusFail",
  3245. {component: focusComponent, ms: retrySec});
  3246. });
  3247. APP.xmpp.addListener(XMPPEvents.ROOM_JOIN_ERROR, function(pres) {
  3248. UI.messageHandler.openReportDialog(null,
  3249. "dialog.joinError", pres);
  3250. });
  3251. APP.xmpp.addListener(XMPPEvents.ROOM_CONNECT_ERROR, function(pres) {
  3252. UI.messageHandler.openReportDialog(null,
  3253. "dialog.connectError", pres);
  3254. });
  3255. APP.xmpp.addListener(XMPPEvents.READY_TO_JOIN, function() {
  3256. var roomName = UI.generateRoomName();
  3257. APP.xmpp.allocateConferenceFocus(roomName, UI.checkForNicknameAndJoin);
  3258. });
  3259. //NicknameHandler emits this event
  3260. UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  3261. APP.xmpp.addToPresence("displayName", nickname);
  3262. });
  3263. UI.addListener(UIEvents.LARGEVIDEO_INIT, function () {
  3264. AudioLevels.init();
  3265. });
  3266. // Listens for video interruption events.
  3267. APP.xmpp.addListener(XMPPEvents.CONNECTION_INTERRUPTED, VideoLayout.onVideoInterrupted);
  3268. // Listens for video restores events.
  3269. APP.xmpp.addListener(XMPPEvents.CONNECTION_RESTORED, VideoLayout.onVideoRestored);
  3270. }
  3271. /**
  3272. * Mutes/unmutes the local video.
  3273. *
  3274. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  3275. * @param options an object which specifies optional arguments such as the
  3276. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  3277. * specifies whether the method was initiated in response to a user command (in
  3278. * contrast to an automatic decision taken by the application logic)
  3279. */
  3280. function setVideoMute(mute, options) {
  3281. APP.RTC.setVideoMute(mute,
  3282. UI.setVideoMuteButtonsState,
  3283. options);
  3284. }
  3285. function onResize() {
  3286. Chat.resizeChat();
  3287. VideoLayout.resizeLargeVideoContainer();
  3288. }
  3289. function bindEvents() {
  3290. /**
  3291. * Resizes and repositions videos in full screen mode.
  3292. */
  3293. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  3294. onResize);
  3295. $(window).resize(onResize);
  3296. }
  3297. UI.start = function (init) {
  3298. document.title = interfaceConfig.APP_NAME;
  3299. var setupWelcomePage = null;
  3300. if(config.enableWelcomePage && window.location.pathname == "/" &&
  3301. (!window.localStorage.welcomePageDisabled ||
  3302. window.localStorage.welcomePageDisabled == "false")) {
  3303. $("#videoconference_page").hide();
  3304. if (!setupWelcomePage)
  3305. setupWelcomePage = require("./welcome_page/WelcomePage");
  3306. setupWelcomePage();
  3307. return;
  3308. }
  3309. $("#welcome_page").hide();
  3310. $("#videospace").mousemove(function () {
  3311. return ToolbarToggler.showToolbar();
  3312. });
  3313. // Set the defaults for prompt dialogs.
  3314. $.prompt.setDefaults({persistent: false});
  3315. registerListeners();
  3316. VideoLayout.init(eventEmitter);
  3317. NicknameHandler.init(eventEmitter);
  3318. bindEvents();
  3319. setupPrezi();
  3320. setupToolbars();
  3321. setupChat();
  3322. document.title = interfaceConfig.APP_NAME;
  3323. $("#downloadlog").click(function (event) {
  3324. dump(event.target);
  3325. });
  3326. if(config.enableWelcomePage && window.location.pathname == "/" &&
  3327. (!window.localStorage.welcomePageDisabled ||
  3328. window.localStorage.welcomePageDisabled == "false")) {
  3329. $("#videoconference_page").hide();
  3330. if (!setupWelcomePage)
  3331. setupWelcomePage = require("./welcome_page/WelcomePage");
  3332. setupWelcomePage();
  3333. return;
  3334. }
  3335. $("#welcome_page").hide();
  3336. // Display notice message at the top of the toolbar
  3337. if (config.noticeMessage) {
  3338. $('#noticeText').text(config.noticeMessage);
  3339. $('#notice').css({display: 'block'});
  3340. }
  3341. if(config.requireDisplayName) {
  3342. var currentSettings = Settings.getSettings();
  3343. if (!currentSettings.displayName) {
  3344. promptDisplayName();
  3345. }
  3346. }
  3347. init();
  3348. toastr.options = {
  3349. "closeButton": true,
  3350. "debug": false,
  3351. "positionClass": "notification-bottom-right",
  3352. "onclick": null,
  3353. "showDuration": "300",
  3354. "hideDuration": "1000",
  3355. "timeOut": "2000",
  3356. "extendedTimeOut": "1000",
  3357. "showEasing": "swing",
  3358. "hideEasing": "linear",
  3359. "showMethod": "fadeIn",
  3360. "hideMethod": "fadeOut",
  3361. "reposition": function() {
  3362. if(PanelToggler.isVisible()) {
  3363. $("#toast-container").addClass("notification-bottom-right-center");
  3364. } else {
  3365. $("#toast-container").removeClass("notification-bottom-right-center");
  3366. }
  3367. },
  3368. "newestOnTop": false
  3369. };
  3370. SettingsMenu.init();
  3371. };
  3372. function chatAddError(errorMessage, originalText) {
  3373. return Chat.chatAddError(errorMessage, originalText);
  3374. }
  3375. function chatSetSubject(text) {
  3376. return Chat.chatSetSubject(text);
  3377. }
  3378. function updateChatConversation(from, displayName, message, myjid, stamp) {
  3379. return Chat.updateChatConversation(from, displayName, message, myjid, stamp);
  3380. }
  3381. function onMucJoined(jid, info) {
  3382. Toolbar.updateRoomUrl(window.location.href);
  3383. var meHTML = APP.translation.generateTranslationHTML("me");
  3384. $("#localNick").html(Strophe.getResourceFromJid(jid) + " (" + meHTML + ")");
  3385. var settings = Settings.getSettings();
  3386. // Make sure we configure our avatar id, before creating avatar for us
  3387. Avatar.setUserAvatar(jid, settings.email || settings.uid);
  3388. // Add myself to the contact list.
  3389. ContactList.addContact(jid);
  3390. // Once we've joined the muc show the toolbar
  3391. ToolbarToggler.showToolbar();
  3392. var displayName =
  3393. config.displayJids ? Strophe.getResourceFromJid(jid) : info.displayName;
  3394. if (displayName)
  3395. onDisplayNameChanged('localVideoContainer', displayName);
  3396. VideoLayout.mucJoined();
  3397. }
  3398. function initEtherpad(name) {
  3399. Etherpad.init(name);
  3400. }
  3401. function onMucMemberLeft(jid) {
  3402. console.log('left.muc', jid);
  3403. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  3404. '>.displayname').html();
  3405. messageHandler.notify(displayName,'notify.somebody',
  3406. 'disconnected',
  3407. 'notify.disconnected');
  3408. if (!config.startAudioMuted ||
  3409. config.startAudioMuted > APP.members.size()) {
  3410. UIUtil.playSoundNotification('userLeft');
  3411. }
  3412. ContactList.removeContact(jid);
  3413. VideoLayout.participantLeft(jid);
  3414. }
  3415. function onLocalRoleChanged(jid, info, pres, isModerator) {
  3416. console.info("My role changed, new role: " + info.role);
  3417. onModeratorStatusChanged(isModerator);
  3418. VideoLayout.showModeratorIndicator();
  3419. SettingsMenu.onRoleChanged();
  3420. if (isModerator) {
  3421. Authentication.closeAuthenticationWindow();
  3422. messageHandler.notify(null, "notify.me",
  3423. 'connected', "notify.moderator");
  3424. }
  3425. }
  3426. function onModeratorStatusChanged(isModerator) {
  3427. Toolbar.showSipCallButton(isModerator);
  3428. Toolbar.showRecordingButton(
  3429. isModerator); //&&
  3430. // FIXME:
  3431. // Recording visible if
  3432. // there are at least 2(+ 1 focus) participants
  3433. //Object.keys(connection.emuc.members).length >= 3);
  3434. }
  3435. function onPasswordRequired(callback) {
  3436. // password is required
  3437. Toolbar.lockLockButton();
  3438. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3439. message += APP.translation.translateString(
  3440. "dialog.passwordRequired");
  3441. message += '</h2>' +
  3442. '<input name="lockKey" type="text" data-i18n=' +
  3443. '"[placeholder]dialog.password" placeholder="' +
  3444. APP.translation.translateString("dialog.password") +
  3445. '" autofocus>';
  3446. messageHandler.openTwoButtonDialog(null, null, null, message,
  3447. true,
  3448. "dialog.Ok",
  3449. function (e, v, m, f) {},
  3450. null,
  3451. function (e, v, m, f) {
  3452. if (v) {
  3453. var lockKey = f.lockKey;
  3454. if (lockKey) {
  3455. Toolbar.setSharedKey(lockKey);
  3456. callback(lockKey);
  3457. }
  3458. }
  3459. },
  3460. ':input:first'
  3461. );
  3462. }
  3463. /**
  3464. * The dialpad button is shown iff there is at least one member that supports
  3465. * DTMF (e.g. jigasi).
  3466. */
  3467. function onDtmfSupportChanged(dtmfSupport) {
  3468. //TODO: enable when the UI is ready
  3469. //Toolbar.showDialPadButton(dtmfSupport);
  3470. }
  3471. function onMucMemberJoined(jid, id, displayName) {
  3472. messageHandler.notify(displayName,'notify.somebody',
  3473. 'connected',
  3474. 'notify.connected');
  3475. if (!config.startAudioMuted ||
  3476. config.startAudioMuted > APP.members.size())
  3477. UIUtil.playSoundNotification('userJoined');
  3478. // Configure avatar
  3479. Avatar.setUserAvatar(jid, id);
  3480. // Add Peer's container
  3481. VideoLayout.ensurePeerContainerExists(jid);
  3482. }
  3483. function onMucPresenceStatus(jid, info) {
  3484. VideoLayout.setPresenceStatus(Strophe.getResourceFromJid(jid), info.status);
  3485. }
  3486. function onPeerVideoTypeChanged(resourceJid, newVideoType) {
  3487. VideoLayout.onVideoTypeChanged(resourceJid, newVideoType);
  3488. }
  3489. function onMucRoleChanged(role, displayName) {
  3490. VideoLayout.showModeratorIndicator();
  3491. if (role === 'moderator') {
  3492. var messageKey, messageOptions = {};
  3493. if (!displayName) {
  3494. messageKey = "notify.grantedToUnknown";
  3495. }
  3496. else {
  3497. messageKey = "notify.grantedTo";
  3498. messageOptions = {to: displayName};
  3499. }
  3500. messageHandler.notify(
  3501. displayName,'notify.somebody',
  3502. 'connected', messageKey,
  3503. messageOptions);
  3504. }
  3505. }
  3506. function onAuthenticationRequired(intervalCallback) {
  3507. Authentication.openAuthenticationDialog(
  3508. roomName, intervalCallback, function () {
  3509. Toolbar.authenticateClicked();
  3510. });
  3511. }
  3512. function onLastNChanged(oldValue, newValue) {
  3513. if (config.muteLocalVideoIfNotInLastN) {
  3514. setVideoMute(!newValue, { 'byUser': false });
  3515. }
  3516. }
  3517. UI.toggleSmileys = function () {
  3518. Chat.toggleSmileys();
  3519. };
  3520. UI.getSettings = function () {
  3521. return Settings.getSettings();
  3522. };
  3523. UI.toggleFilmStrip = function () {
  3524. return BottomToolbar.toggleFilmStrip();
  3525. };
  3526. UI.toggleChat = function () {
  3527. return BottomToolbar.toggleChat();
  3528. };
  3529. UI.toggleContactList = function () {
  3530. return BottomToolbar.toggleContactList();
  3531. };
  3532. UI.inputDisplayNameHandler = function (value) {
  3533. VideoLayout.inputDisplayNameHandler(value);
  3534. };
  3535. UI.getLargeVideoJid = function() {
  3536. return VideoLayout.getLargeVideoJid();
  3537. };
  3538. UI.generateRoomName = function() {
  3539. if(roomName)
  3540. return roomName;
  3541. var roomnode = null;
  3542. var path = window.location.pathname;
  3543. // determinde the room node from the url
  3544. // TODO: just the roomnode or the whole bare jid?
  3545. if (config.getroomnode && typeof config.getroomnode === 'function') {
  3546. // custom function might be responsible for doing the pushstate
  3547. roomnode = config.getroomnode(path);
  3548. } else {
  3549. /* fall back to default strategy
  3550. * this is making assumptions about how the URL->room mapping happens.
  3551. * It currently assumes deployment at root, with a rewrite like the
  3552. * following one (for nginx):
  3553. location ~ ^/([a-zA-Z0-9]+)$ {
  3554. rewrite ^/(.*)$ / break;
  3555. }
  3556. */
  3557. if (path.length > 1) {
  3558. roomnode = path.substr(1).toLowerCase();
  3559. } else {
  3560. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  3561. roomnode = word.toLowerCase();
  3562. window.history.pushState('VideoChat',
  3563. 'Room: ' + word, window.location.pathname + word);
  3564. }
  3565. }
  3566. roomName = roomnode + '@' + config.hosts.muc;
  3567. return roomName;
  3568. };
  3569. UI.connectionIndicatorShowMore = function(jid) {
  3570. return VideoLayout.showMore(jid);
  3571. };
  3572. UI.showLoginPopup = function(callback) {
  3573. console.log('password is required');
  3574. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3575. message += APP.translation.translateString(
  3576. "dialog.passwordRequired");
  3577. message += '</h2>' +
  3578. '<input name="username" type="text" ' +
  3579. 'placeholder="user@domain.net" autofocus>' +
  3580. '<input name="password" ' +
  3581. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  3582. ' placeholder="user password">';
  3583. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  3584. true,
  3585. "dialog.Ok",
  3586. function (e, v, m, f) {
  3587. if (v) {
  3588. if (f.username !== null && f.password != null) {
  3589. callback(f.username, f.password);
  3590. }
  3591. }
  3592. },
  3593. null, null, ':input:first'
  3594. );
  3595. };
  3596. UI.checkForNicknameAndJoin = function () {
  3597. Authentication.closeAuthenticationDialog();
  3598. Authentication.stopInterval();
  3599. var nick = null;
  3600. if (config.useNicks) {
  3601. nick = window.prompt('Your nickname (optional)');
  3602. }
  3603. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  3604. };
  3605. function dump(elem, filename) {
  3606. elem = elem.parentNode;
  3607. elem.download = filename || 'meetlog.json';
  3608. elem.href = 'data:application/json;charset=utf-8,\n';
  3609. var data = APP.xmpp.getJingleLog();
  3610. var metadata = {};
  3611. metadata.time = new Date();
  3612. metadata.url = window.location.href;
  3613. metadata.ua = navigator.userAgent;
  3614. var log = APP.xmpp.getXmppLog();
  3615. if (log) {
  3616. metadata.xmpp = log;
  3617. }
  3618. data.metadata = metadata;
  3619. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  3620. return false;
  3621. }
  3622. UI.getRoomName = function () {
  3623. return roomName;
  3624. };
  3625. UI.setInitialMuteFromFocus = function (muteAudio, muteVideo) {
  3626. if (muteAudio || muteVideo)
  3627. notifyForInitialMute();
  3628. if (muteAudio)
  3629. UI.setAudioMuted(true);
  3630. if (muteVideo)
  3631. UI.setVideoMute(true);
  3632. };
  3633. /**
  3634. * Mutes/unmutes the local video.
  3635. */
  3636. UI.toggleVideo = function () {
  3637. setVideoMute(!APP.RTC.localVideo.isMuted());
  3638. };
  3639. /**
  3640. * Mutes / unmutes audio for the local participant.
  3641. */
  3642. UI.toggleAudio = function() {
  3643. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  3644. };
  3645. /**
  3646. * Sets muted audio state for the local participant.
  3647. */
  3648. UI.setAudioMuted = function (mute, earlyMute) {
  3649. var audioMute = null;
  3650. if (earlyMute)
  3651. audioMute = function (mute, cb) {
  3652. return APP.xmpp.sendAudioInfoPresence(mute, cb);
  3653. };
  3654. else
  3655. audioMute = function (mute, cb) {
  3656. return APP.xmpp.setAudioMute(mute, cb);
  3657. };
  3658. if (!audioMute(mute, function () {
  3659. VideoLayout.showLocalAudioIndicator(mute);
  3660. UIUtil.buttonClick("#toolbar_button_mute", "icon-microphone icon-mic-disabled");
  3661. })) {
  3662. // We still click the button.
  3663. UIUtil.buttonClick("#toolbar_button_mute", "icon-microphone icon-mic-disabled");
  3664. return;
  3665. }
  3666. };
  3667. UI.addListener = function (type, listener) {
  3668. eventEmitter.on(type, listener);
  3669. };
  3670. UI.clickOnVideo = function (videoNumber) {
  3671. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  3672. if (remoteVideos.length > videoNumber) {
  3673. remoteVideos[videoNumber].click();
  3674. }
  3675. };
  3676. //Used by torture
  3677. UI.showToolbar = function () {
  3678. return ToolbarToggler.showToolbar();
  3679. };
  3680. //Used by torture
  3681. UI.dockToolbar = function (isDock) {
  3682. return ToolbarToggler.dockToolbar(isDock);
  3683. };
  3684. UI.setVideoMuteButtonsState = function (mute) {
  3685. var video = $('#toolbar_button_camera');
  3686. var communicativeClass = "icon-camera";
  3687. var muteClass = "icon-camera icon-camera-disabled";
  3688. if (mute) {
  3689. video.removeClass(communicativeClass);
  3690. video.addClass(muteClass);
  3691. } else {
  3692. video.removeClass(muteClass);
  3693. video.addClass(communicativeClass);
  3694. }
  3695. };
  3696. UI.userAvatarChanged = function (resourceJid, thumbUrl, contactListUrl) {
  3697. VideoLayout.userAvatarChanged(resourceJid, thumbUrl);
  3698. ContactList.userAvatarChanged(resourceJid, contactListUrl);
  3699. if(resourceJid === APP.xmpp.myResource())
  3700. SettingsMenu.changeAvatar(thumbUrl);
  3701. };
  3702. UI.setVideoMute = setVideoMute;
  3703. module.exports = UI;
  3704. },{"../../service/RTC/RTCEvents":110,"../../service/RTC/StreamEventTypes":112,"../../service/UI/UIEvents":113,"../../service/connectionquality/CQEvents":115,"../../service/desktopsharing/DesktopSharingEventTypes":116,"../../service/members/Events":117,"../../service/xmpp/XMPPEvents":119,"../RTC/RTCBrowserType":10,"./../settings/Settings":49,"./audio_levels/AudioLevels.js":14,"./authentication/Authentication":16,"./avatar/Avatar":18,"./etherpad/Etherpad.js":19,"./prezi/Prezi.js":20,"./side_pannels/SidePanelToggler":22,"./side_pannels/chat/Chat.js":23,"./side_pannels/contactlist/ContactList":27,"./side_pannels/settings/SettingsMenu":28,"./toolbars/BottomToolbar":29,"./toolbars/Toolbar":30,"./toolbars/ToolbarToggler":31,"./util/MessageHandler":33,"./util/NicknameHandler":34,"./util/UIUtil":35,"./videolayout/VideoLayout.js":41,"./welcome_page/RoomnameGenerator":42,"./welcome_page/WelcomePage":43,"events":1}],14:[function(require,module,exports){
  3705. /* global APP, interfaceConfig, $, Strophe */
  3706. var CanvasUtil = require("./CanvasUtils");
  3707. var ASDrawContext = null;
  3708. function initActiveSpeakerAudioLevels() {
  3709. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  3710. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  3711. // Draw a circle.
  3712. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  3713. // Add a shadow around the circle
  3714. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  3715. ASDrawContext.shadowOffsetX = 0;
  3716. ASDrawContext.shadowOffsetY = 0;
  3717. }
  3718. /**
  3719. * The audio Levels plugin.
  3720. */
  3721. var AudioLevels = (function(my) {
  3722. var audioLevelCanvasCache = {};
  3723. my.LOCAL_LEVEL = 'local';
  3724. my.init = function () {
  3725. ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  3726. initActiveSpeakerAudioLevels();
  3727. };
  3728. /**
  3729. * Updates the audio level canvas for the given peerJid. If the canvas
  3730. * didn't exist we create it.
  3731. */
  3732. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  3733. var resourceJid = null;
  3734. var videoSpanId = null;
  3735. if (!peerJid)
  3736. videoSpanId = 'localVideoContainer';
  3737. else {
  3738. resourceJid = Strophe.getResourceFromJid(peerJid);
  3739. videoSpanId = 'participant_' + resourceJid;
  3740. }
  3741. var videoSpan = document.getElementById(videoSpanId);
  3742. if (!videoSpan) {
  3743. if (resourceJid)
  3744. console.error("No video element for jid", resourceJid);
  3745. else
  3746. console.error("No video element for local video.");
  3747. return;
  3748. }
  3749. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  3750. var videoSpaceWidth = $('#remoteVideos').width();
  3751. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  3752. var thumbnailWidth = thumbnailSize[0];
  3753. var thumbnailHeight = thumbnailSize[1];
  3754. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  3755. audioLevelCanvas = document.createElement('canvas');
  3756. audioLevelCanvas.className = "audiolevel";
  3757. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3758. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3759. resizeAudioLevelCanvas( audioLevelCanvas,
  3760. thumbnailWidth,
  3761. thumbnailHeight);
  3762. videoSpan.appendChild(audioLevelCanvas);
  3763. } else {
  3764. audioLevelCanvas = audioLevelCanvas.get(0);
  3765. resizeAudioLevelCanvas( audioLevelCanvas,
  3766. thumbnailWidth,
  3767. thumbnailHeight);
  3768. }
  3769. };
  3770. /**
  3771. * Updates the audio level UI for the given resourceJid.
  3772. *
  3773. * @param resourceJid the resource jid indicating the video element for
  3774. * which we draw the audio level
  3775. * @param audioLevel the newAudio level to render
  3776. */
  3777. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  3778. drawAudioLevelCanvas(resourceJid, audioLevel);
  3779. var videoSpanId = getVideoSpanId(resourceJid);
  3780. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  3781. if (!audioLevelCanvas)
  3782. return;
  3783. var drawContext = audioLevelCanvas.getContext('2d');
  3784. var canvasCache = audioLevelCanvasCache[resourceJid];
  3785. drawContext.clearRect (0, 0,
  3786. audioLevelCanvas.width, audioLevelCanvas.height);
  3787. drawContext.drawImage(canvasCache, 0, 0);
  3788. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  3789. if(!APP.xmpp.myJid()) {
  3790. return;
  3791. }
  3792. resourceJid = APP.xmpp.myResource();
  3793. }
  3794. if(resourceJid === largeVideoResourceJid) {
  3795. window.requestAnimationFrame(function () {
  3796. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  3797. });
  3798. }
  3799. };
  3800. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  3801. if($("#activeSpeaker").css("visibility") == "hidden" || ASDrawContext === null)
  3802. return;
  3803. ASDrawContext.clearRect(0, 0, 300, 300);
  3804. if(audioLevel == 0)
  3805. return;
  3806. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  3807. // Fill the shape.
  3808. ASDrawContext.fill();
  3809. };
  3810. /**
  3811. * Resizes the given audio level canvas to match the given thumbnail size.
  3812. */
  3813. function resizeAudioLevelCanvas(audioLevelCanvas,
  3814. thumbnailWidth,
  3815. thumbnailHeight) {
  3816. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  3817. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  3818. }
  3819. /**
  3820. * Draws the audio level canvas into the cached canvas object.
  3821. *
  3822. * @param resourceJid the resource jid indicating the video element for
  3823. * which we draw the audio level
  3824. * @param audioLevel the newAudio level to render
  3825. */
  3826. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  3827. if (!audioLevelCanvasCache[resourceJid]) {
  3828. var videoSpanId = getVideoSpanId(resourceJid);
  3829. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  3830. /*
  3831. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  3832. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  3833. * error. Since audio levels are frequently updated, the errors have
  3834. * been observed to pile into the console, strain the CPU.
  3835. */
  3836. if (audioLevelCanvasOrig) {
  3837. audioLevelCanvasCache[resourceJid] =
  3838. CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  3839. }
  3840. }
  3841. var canvas = audioLevelCanvasCache[resourceJid];
  3842. if (!canvas)
  3843. return;
  3844. var drawContext = canvas.getContext('2d');
  3845. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  3846. var shadowLevel = getShadowLevel(audioLevel);
  3847. if (shadowLevel > 0) {
  3848. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  3849. CanvasUtil.drawRoundRectGlow(drawContext,
  3850. interfaceConfig.CANVAS_EXTRA / 2, interfaceConfig.CANVAS_EXTRA / 2,
  3851. canvas.width - interfaceConfig.CANVAS_EXTRA,
  3852. canvas.height - interfaceConfig.CANVAS_EXTRA,
  3853. interfaceConfig.CANVAS_RADIUS,
  3854. interfaceConfig.SHADOW_COLOR,
  3855. shadowLevel);
  3856. }
  3857. }
  3858. /**
  3859. * Returns the shadow/glow level for the given audio level.
  3860. *
  3861. * @param audioLevel the audio level from which we determine the shadow
  3862. * level
  3863. */
  3864. function getShadowLevel (audioLevel) {
  3865. var shadowLevel = 0;
  3866. if (audioLevel <= 0.3) {
  3867. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  3868. }
  3869. else if (audioLevel <= 0.6) {
  3870. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  3871. }
  3872. else {
  3873. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  3874. }
  3875. return shadowLevel;
  3876. }
  3877. /**
  3878. * Returns the video span id corresponding to the given resourceJid or local
  3879. * user.
  3880. */
  3881. function getVideoSpanId(resourceJid) {
  3882. var videoSpanId = null;
  3883. if (resourceJid === AudioLevels.LOCAL_LEVEL ||
  3884. (APP.xmpp.myResource() && resourceJid === APP.xmpp.myResource()))
  3885. videoSpanId = 'localVideoContainer';
  3886. else
  3887. videoSpanId = 'participant_' + resourceJid;
  3888. return videoSpanId;
  3889. }
  3890. /**
  3891. * Indicates that the remote video has been resized.
  3892. */
  3893. $(document).bind('remotevideo.resized', function (event, width, height) {
  3894. var resized = false;
  3895. $('#remoteVideos>span>canvas').each(function() {
  3896. var canvas = $(this).get(0);
  3897. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  3898. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  3899. resized = true;
  3900. }
  3901. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  3902. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  3903. resized = true;
  3904. }
  3905. });
  3906. if (resized)
  3907. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  3908. audioLevelCanvasCache[resourceJid].width =
  3909. width + interfaceConfig.CANVAS_EXTRA;
  3910. audioLevelCanvasCache[resourceJid].height =
  3911. height + interfaceConfig.CANVAS_EXTRA;
  3912. });
  3913. });
  3914. return my;
  3915. })(AudioLevels || {});
  3916. module.exports = AudioLevels;
  3917. },{"./CanvasUtils":15}],15:[function(require,module,exports){
  3918. /**
  3919. * Utility class for drawing canvas shapes.
  3920. */
  3921. var CanvasUtil = (function(my) {
  3922. /**
  3923. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  3924. * of the glow.
  3925. *
  3926. * @param drawContext the context of the canvas to draw to
  3927. * @param x the x coordinate of the round rectangle
  3928. * @param y the y coordinate of the round rectangle
  3929. * @param w the width of the round rectangle
  3930. * @param h the height of the round rectangle
  3931. * @param glowColor the color of the glow
  3932. * @param glowWidth the width of the glow
  3933. */
  3934. my.drawRoundRectGlow
  3935. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  3936. // Save the previous state of the context.
  3937. drawContext.save();
  3938. if (w < 2 * r) r = w / 2;
  3939. if (h < 2 * r) r = h / 2;
  3940. // Draw a round rectangle.
  3941. drawContext.beginPath();
  3942. drawContext.moveTo(x+r, y);
  3943. drawContext.arcTo(x+w, y, x+w, y+h, r);
  3944. drawContext.arcTo(x+w, y+h, x, y+h, r);
  3945. drawContext.arcTo(x, y+h, x, y, r);
  3946. drawContext.arcTo(x, y, x+w, y, r);
  3947. drawContext.closePath();
  3948. // Add a shadow around the rectangle
  3949. drawContext.shadowColor = glowColor;
  3950. drawContext.shadowBlur = glowWidth;
  3951. drawContext.shadowOffsetX = 0;
  3952. drawContext.shadowOffsetY = 0;
  3953. // Fill the shape.
  3954. drawContext.fill();
  3955. drawContext.save();
  3956. drawContext.restore();
  3957. // 1) Uncomment this line to use Composite Operation, which is doing the
  3958. // same as the clip function below and is also antialiasing the round
  3959. // border, but is said to be less fast performance wise.
  3960. // drawContext.globalCompositeOperation='destination-out';
  3961. drawContext.beginPath();
  3962. drawContext.moveTo(x+r, y);
  3963. drawContext.arcTo(x+w, y, x+w, y+h, r);
  3964. drawContext.arcTo(x+w, y+h, x, y+h, r);
  3965. drawContext.arcTo(x, y+h, x, y, r);
  3966. drawContext.arcTo(x, y, x+w, y, r);
  3967. drawContext.closePath();
  3968. // 2) Uncomment this line to use Composite Operation, which is doing the
  3969. // same as the clip function below and is also antialiasing the round
  3970. // border, but is said to be less fast performance wise.
  3971. // drawContext.fill();
  3972. // Comment these two lines if choosing to do the same with composite
  3973. // operation above 1 and 2.
  3974. drawContext.clip();
  3975. drawContext.clearRect(0, 0, 277, 200);
  3976. // Restore the previous context state.
  3977. drawContext.restore();
  3978. };
  3979. /**
  3980. * Clones the given canvas.
  3981. *
  3982. * @return the new cloned canvas.
  3983. */
  3984. my.cloneCanvas = function (oldCanvas) {
  3985. /*
  3986. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  3987. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  3988. * levels are frequently updated, the errors have been observed to pile
  3989. * into the console, strain the CPU.
  3990. */
  3991. if (!oldCanvas)
  3992. return oldCanvas;
  3993. //create a new canvas
  3994. var newCanvas = document.createElement('canvas');
  3995. var context = newCanvas.getContext('2d');
  3996. //set dimensions
  3997. newCanvas.width = oldCanvas.width;
  3998. newCanvas.height = oldCanvas.height;
  3999. //apply the old canvas to the new one
  4000. context.drawImage(oldCanvas, 0, 0);
  4001. //return the new canvas
  4002. return newCanvas;
  4003. };
  4004. return my;
  4005. })(CanvasUtil || {});
  4006. module.exports = CanvasUtil;
  4007. },{}],16:[function(require,module,exports){
  4008. /* global $, APP*/
  4009. var LoginDialog = require('./LoginDialog');
  4010. var Moderator = require('../../xmpp/moderator');
  4011. /* Initial "authentication required" dialog */
  4012. var authDialog = null;
  4013. /* Loop retry ID that wits for other user to create the room */
  4014. var authRetryId = null;
  4015. var authenticationWindow = null;
  4016. var Authentication = {
  4017. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  4018. // This is the loop that will wait for the room to be created by
  4019. // someone else. 'auth_required.moderator' will bring us back here.
  4020. authRetryId = window.setTimeout(intervalCallback, 5000);
  4021. // Show prompt only if it's not open
  4022. if (authDialog !== null) {
  4023. return;
  4024. }
  4025. // extract room name from 'room@muc.server.net'
  4026. var room = roomName.substr(0, roomName.indexOf('@'));
  4027. var title
  4028. = APP.translation.generateTranslationHTML("dialog.WaitingForHost");
  4029. var msg
  4030. = APP.translation.generateTranslationHTML(
  4031. "dialog.WaitForHostMsg", {room: room});
  4032. var buttonTxt
  4033. = APP.translation.generateTranslationHTML("dialog.IamHost");
  4034. var buttons = [];
  4035. buttons.push({title: buttonTxt, value: "authNow"});
  4036. authDialog = APP.UI.messageHandler.openDialog(
  4037. title,
  4038. msg,
  4039. true,
  4040. buttons,
  4041. function (onSubmitEvent, submitValue) {
  4042. // Do not close the dialog yet
  4043. onSubmitEvent.preventDefault();
  4044. // Open login popup
  4045. if (submitValue === 'authNow') {
  4046. callback();
  4047. }
  4048. }
  4049. );
  4050. },
  4051. closeAuthenticationWindow: function () {
  4052. if (authenticationWindow) {
  4053. authenticationWindow.close();
  4054. authenticationWindow = null;
  4055. }
  4056. },
  4057. xmppAuthenticate: function () {
  4058. var loginDialog = LoginDialog.show(
  4059. function (connection, state) {
  4060. if (!state) {
  4061. // User cancelled
  4062. loginDialog.close();
  4063. return;
  4064. } else if (state == APP.xmpp.Status.CONNECTED) {
  4065. loginDialog.close();
  4066. Authentication.stopInterval();
  4067. Authentication.closeAuthenticationDialog();
  4068. // Close the connection as anonymous one will be used
  4069. // to create the conference. Session-id will authorize
  4070. // the request.
  4071. connection.disconnect();
  4072. var roomName = APP.UI.generateRoomName();
  4073. Moderator.allocateConferenceFocus(roomName, function () {
  4074. // If it's not "on the fly" authentication now join
  4075. // the conference room
  4076. if (!APP.xmpp.isMUCJoined()) {
  4077. APP.UI.checkForNicknameAndJoin();
  4078. }
  4079. });
  4080. }
  4081. }, true);
  4082. },
  4083. focusAuthenticationWindow: function () {
  4084. // If auth window exists just bring it to the front
  4085. if (authenticationWindow) {
  4086. authenticationWindow.focus();
  4087. return;
  4088. }
  4089. },
  4090. closeAuthenticationDialog: function () {
  4091. // Close authentication dialog if opened
  4092. if (authDialog) {
  4093. authDialog.close();
  4094. authDialog = null;
  4095. }
  4096. },
  4097. createAuthenticationWindow: function (callback, url) {
  4098. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  4099. url, 910, 660,
  4100. // On closed
  4101. function () {
  4102. // Close authentication dialog if opened
  4103. Authentication.closeAuthenticationDialog();
  4104. callback();
  4105. authenticationWindow = null;
  4106. });
  4107. return authenticationWindow;
  4108. },
  4109. stopInterval: function () {
  4110. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  4111. if (authRetryId) {
  4112. window.clearTimeout(authRetryId);
  4113. authRetryId = null;
  4114. }
  4115. }
  4116. };
  4117. module.exports = Authentication;
  4118. },{"../../xmpp/moderator":61,"./LoginDialog":17}],17:[function(require,module,exports){
  4119. /* global $, APP, config*/
  4120. var XMPP = require('../../xmpp/xmpp');
  4121. var Moderator = require('../../xmpp/moderator');
  4122. //FIXME: use LoginDialog to add retries to XMPP.connect method used when
  4123. // anonymous domain is not enabled
  4124. /**
  4125. * Creates new <tt>Dialog</tt> instance.
  4126. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt> called
  4127. * when we either fail to connect or succeed(check Strophe.Status).
  4128. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to Jicofo
  4129. * in order to create session-id after the connection is established.
  4130. * @constructor
  4131. */
  4132. function Dialog(callback, obtainSession) {
  4133. var self = this;
  4134. var stop = false;
  4135. var connection = APP.xmpp.createConnection();
  4136. var message = '<h2 data-i18n="dialog.passwordRequired">';
  4137. message += APP.translation.translateString("dialog.passwordRequired");
  4138. message += '</h2>' +
  4139. '<input name="username" type="text" ' +
  4140. 'placeholder="user@domain.net" autofocus>' +
  4141. '<input name="password" ' +
  4142. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  4143. ' placeholder="user password">';
  4144. var okButton = APP.translation.generateTranslationHTML("dialog.Ok");
  4145. var cancelButton = APP.translation.generateTranslationHTML("dialog.Cancel");
  4146. var states = {
  4147. login: {
  4148. html: message,
  4149. buttons: [
  4150. { title: okButton, value: true},
  4151. { title: cancelButton, value: false}
  4152. ],
  4153. focus: ':input:first',
  4154. submit: function (e, v, m, f) {
  4155. e.preventDefault();
  4156. if (v) {
  4157. var jid = f.username;
  4158. var password = f.password;
  4159. if (jid && password) {
  4160. stop = false;
  4161. connection.reset();
  4162. connDialog.goToState('connecting');
  4163. connection.connect(jid, password, stateHandler);
  4164. }
  4165. } else {
  4166. // User cancelled
  4167. stop = true;
  4168. callback();
  4169. }
  4170. }
  4171. },
  4172. connecting: {
  4173. title: APP.translation.translateString('dialog.connecting'),
  4174. html: '<div id="connectionStatus"></div>',
  4175. buttons: [],
  4176. defaultButton: 0
  4177. },
  4178. finished: {
  4179. title: APP.translation.translateString('dialog.error'),
  4180. html: '<div id="errorMessage"></div>',
  4181. buttons: [
  4182. {
  4183. title: APP.translation.translateString('dialog.retry'),
  4184. value: 'retry'
  4185. },
  4186. {
  4187. title: APP.translation.translateString('dialog.Cancel'),
  4188. value: 'cancel'
  4189. },
  4190. ],
  4191. defaultButton: 0,
  4192. submit: function (e, v, m, f) {
  4193. e.preventDefault();
  4194. if (v === 'retry')
  4195. connDialog.goToState('login');
  4196. else
  4197. callback();
  4198. }
  4199. }
  4200. };
  4201. var connDialog
  4202. = APP.UI.messageHandler.openDialogWithStates(states,
  4203. { persistent: true, closeText: '' }, null);
  4204. var stateHandler = function (status, message) {
  4205. if (stop) {
  4206. return;
  4207. }
  4208. var translateKey = "connection." + XMPP.getStatusString(status);
  4209. var statusStr = APP.translation.translateString(translateKey);
  4210. // Display current state
  4211. var connectionStatus =
  4212. connDialog.getState('connecting').find('#connectionStatus');
  4213. connectionStatus.text(statusStr);
  4214. switch (status) {
  4215. case XMPP.Status.CONNECTED:
  4216. stop = true;
  4217. if (!obtainSession) {
  4218. callback(connection, status);
  4219. return;
  4220. }
  4221. // Obtaining session-id status
  4222. connectionStatus.text(
  4223. APP.translation.translateString(
  4224. 'connection.FETCH_SESSION_ID'));
  4225. // Authenticate with Jicofo and obtain session-id
  4226. var roomName = APP.UI.generateRoomName();
  4227. // Jicofo will return new session-id when connected
  4228. // from authenticated domain
  4229. connection.sendIQ(
  4230. Moderator.createConferenceIq(roomName),
  4231. function (result) {
  4232. connectionStatus.text(
  4233. APP.translation.translateString(
  4234. 'connection.GOT_SESSION_ID'));
  4235. stop = true;
  4236. // Parse session-id
  4237. Moderator.parseSessionId(result);
  4238. callback(connection, status);
  4239. },
  4240. function (error) {
  4241. console.error("Auth on the fly failed", error);
  4242. stop = true;
  4243. var errorMsg =
  4244. APP.translation.translateString(
  4245. 'connection.GET_SESSION_ID_ERROR') +
  4246. $(error).find('>error').attr('code');
  4247. self.displayError(errorMsg);
  4248. connection.disconnect();
  4249. });
  4250. break;
  4251. case XMPP.Status.AUTHFAIL:
  4252. case XMPP.Status.CONNFAIL:
  4253. case XMPP.Status.DISCONNECTED:
  4254. stop = true;
  4255. callback(connection, status);
  4256. var errorMessage = statusStr;
  4257. if (message)
  4258. {
  4259. errorMessage += ': ' + message;
  4260. }
  4261. self.displayError(errorMessage);
  4262. break;
  4263. default:
  4264. break;
  4265. }
  4266. };
  4267. /**
  4268. * Displays error message in 'finished' state which allows either to cancel
  4269. * or retry.
  4270. * @param message the final message to be displayed.
  4271. */
  4272. this.displayError = function (message) {
  4273. var finishedState = connDialog.getState('finished');
  4274. var errorMessageElem = finishedState.find('#errorMessage');
  4275. errorMessageElem.text(message);
  4276. connDialog.goToState('finished');
  4277. };
  4278. /**
  4279. * Closes LoginDialog.
  4280. */
  4281. this.close = function () {
  4282. stop = true;
  4283. connDialog.close();
  4284. };
  4285. }
  4286. var LoginDialog = {
  4287. /**
  4288. * Displays login prompt used to establish new XMPP connection. Given
  4289. * <tt>callback(Strophe.Connection, Strophe.Status)</tt> function will be
  4290. * called when we connect successfully(status === CONNECTED) or when we fail
  4291. * to do so. On connection failure program can call Dialog.close() method in
  4292. * order to cancel or do nothing to let the user retry.
  4293. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt>
  4294. * called when we either fail to connect or succeed(check
  4295. * Strophe.Status).
  4296. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to
  4297. * Jicofo in order to create session-id after the connection is
  4298. * established.
  4299. * @returns {Dialog}
  4300. */
  4301. show: function (callback, obtainSession) {
  4302. return new Dialog(callback, obtainSession);
  4303. }
  4304. };
  4305. module.exports = LoginDialog;
  4306. },{"../../xmpp/moderator":61,"../../xmpp/xmpp":69}],18:[function(require,module,exports){
  4307. var Settings = require("../../settings/Settings");
  4308. var users = {};
  4309. var Avatar = {
  4310. /**
  4311. * Sets the user's avatar in the settings menu(if local user), contact list
  4312. * and thumbnail
  4313. * @param jid jid of the user
  4314. * @param id email or userID to be used as a hash
  4315. */
  4316. setUserAvatar: function (jid, id) {
  4317. if (id) {
  4318. if (users[jid] === id) {
  4319. return;
  4320. }
  4321. users[jid] = id;
  4322. }
  4323. var thumbUrl = this.getThumbUrl(jid);
  4324. var contactListUrl = this.getContactListUrl(jid);
  4325. var resourceJid = Strophe.getResourceFromJid(jid);
  4326. APP.UI.userAvatarChanged(resourceJid, thumbUrl, contactListUrl);
  4327. },
  4328. /**
  4329. * Returns image URL for the avatar to be displayed on large video area
  4330. * where current active speaker is presented.
  4331. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4332. */
  4333. getActiveSpeakerUrl: function (jid) {
  4334. return this.getGravatarUrl(jid, 100);
  4335. },
  4336. /**
  4337. * Returns image URL for the avatar to be displayed on small video thumbnail
  4338. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4339. */
  4340. getThumbUrl: function (jid) {
  4341. return this.getGravatarUrl(jid, 100);
  4342. },
  4343. /**
  4344. * Returns the URL for the avatar to be displayed as contactlist item
  4345. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4346. */
  4347. getContactListUrl: function (jid) {
  4348. return this.getGravatarUrl(jid, 30);
  4349. },
  4350. getGravatarUrl: function (jid, size) {
  4351. if (!jid) {
  4352. console.error("Get gravatar - jid is undefined");
  4353. return null;
  4354. }
  4355. var id = users[jid];
  4356. if (!id) {
  4357. console.warn(
  4358. "No avatar stored yet for " + jid + " - using JID as ID");
  4359. id = jid;
  4360. }
  4361. return 'https://www.gravatar.com/avatar/' +
  4362. MD5.hexdigest(id.trim().toLowerCase()) +
  4363. "?d=wavatar&size=" + (size || "30");
  4364. }
  4365. };
  4366. module.exports = Avatar;
  4367. },{"../../settings/Settings":49}],19:[function(require,module,exports){
  4368. /* global $, config,
  4369. setLargeVideoVisible, Util */
  4370. var VideoLayout = require("../videolayout/VideoLayout");
  4371. var Prezi = require("../prezi/Prezi");
  4372. var UIUtil = require("../util/UIUtil");
  4373. var etherpadName = null;
  4374. var etherpadIFrame = null;
  4375. var domain = null;
  4376. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  4377. /**
  4378. * Resizes the etherpad.
  4379. */
  4380. function resize() {
  4381. if ($('#etherpad>iframe').length) {
  4382. var remoteVideos = $('#remoteVideos');
  4383. var availableHeight
  4384. = window.innerHeight - remoteVideos.outerHeight();
  4385. var availableWidth = UIUtil.getAvailableVideoWidth();
  4386. $('#etherpad>iframe').width(availableWidth);
  4387. $('#etherpad>iframe').height(availableHeight);
  4388. }
  4389. }
  4390. /**
  4391. * Creates the Etherpad button and adds it to the toolbar.
  4392. */
  4393. function enableEtherpadButton() {
  4394. if (!$('#toolbar_button_etherpad').is(":visible"))
  4395. $('#toolbar_button_etherpad').css({display: 'inline-block'});
  4396. }
  4397. /**
  4398. * Creates the IFrame for the etherpad.
  4399. */
  4400. function createIFrame() {
  4401. etherpadIFrame = VideoLayout.createEtherpadIframe(
  4402. domain + etherpadName + options, function() {
  4403. document.domain = document.domain;
  4404. bubbleIframeMouseMove(etherpadIFrame);
  4405. setTimeout(function() {
  4406. // the iframes inside of the etherpad are
  4407. // not yet loaded when the etherpad iframe is loaded
  4408. var outer = etherpadIFrame.
  4409. contentDocument.getElementsByName("ace_outer")[0];
  4410. bubbleIframeMouseMove(outer);
  4411. var inner = outer.
  4412. contentDocument.getElementsByName("ace_inner")[0];
  4413. bubbleIframeMouseMove(inner);
  4414. }, 2000);
  4415. });
  4416. }
  4417. function bubbleIframeMouseMove(iframe){
  4418. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  4419. iframe.contentWindow.onmousemove = function(e){
  4420. if(existingOnMouseMove) existingOnMouseMove(e);
  4421. var evt = document.createEvent("MouseEvents");
  4422. var boundingClientRect = iframe.getBoundingClientRect();
  4423. evt.initMouseEvent(
  4424. "mousemove",
  4425. true, // bubbles
  4426. false, // not cancelable
  4427. window,
  4428. e.detail,
  4429. e.screenX,
  4430. e.screenY,
  4431. e.clientX + boundingClientRect.left,
  4432. e.clientY + boundingClientRect.top,
  4433. e.ctrlKey,
  4434. e.altKey,
  4435. e.shiftKey,
  4436. e.metaKey,
  4437. e.button,
  4438. null // no related element
  4439. );
  4440. iframe.dispatchEvent(evt);
  4441. };
  4442. }
  4443. var Etherpad = {
  4444. /**
  4445. * Initializes the etherpad.
  4446. */
  4447. init: function (name) {
  4448. if (config.etherpad_base && !etherpadName && name) {
  4449. domain = config.etherpad_base;
  4450. etherpadName = name;
  4451. enableEtherpadButton();
  4452. /**
  4453. * Resizes the etherpad, when the window is resized.
  4454. */
  4455. $(window).resize(function () {
  4456. resize();
  4457. });
  4458. }
  4459. },
  4460. /**
  4461. * Opens/hides the Etherpad.
  4462. */
  4463. toggleEtherpad: function (isPresentation) {
  4464. if (!etherpadIFrame)
  4465. createIFrame();
  4466. if(VideoLayout.getLargeVideoState() === "etherpad")
  4467. {
  4468. VideoLayout.setLargeVideoState("video");
  4469. }
  4470. else
  4471. {
  4472. VideoLayout.setLargeVideoState("etherpad");
  4473. }
  4474. resize();
  4475. }
  4476. };
  4477. module.exports = Etherpad;
  4478. },{"../prezi/Prezi":20,"../util/UIUtil":35,"../videolayout/VideoLayout":41}],20:[function(require,module,exports){
  4479. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  4480. var UIUtil = require("../util/UIUtil");
  4481. var VideoLayout = require("../videolayout/VideoLayout");
  4482. var messageHandler = require("../util/MessageHandler");
  4483. var PreziPlayer = require("./PreziPlayer");
  4484. var preziPlayer = null;
  4485. /**
  4486. * Shows/hides a presentation.
  4487. */
  4488. function setPresentationVisible(visible) {
  4489. if (visible) {
  4490. VideoLayout.setLargeVideoState("prezi");
  4491. }
  4492. else {
  4493. VideoLayout.setLargeVideoState("video");
  4494. }
  4495. }
  4496. var Prezi = {
  4497. /**
  4498. * Reloads the current presentation.
  4499. */
  4500. reloadPresentation: function() {
  4501. var iframe = document.getElementById(preziPlayer.options.preziId);
  4502. iframe.src = iframe.src;
  4503. },
  4504. /**
  4505. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  4506. * otherwise.
  4507. */
  4508. isPresentationVisible: function () {
  4509. return ($('#presentation>iframe') != null
  4510. && $('#presentation>iframe').css('opacity') == 1);
  4511. },
  4512. /**
  4513. * Opens the Prezi dialog, from which the user could choose a presentation
  4514. * to load.
  4515. */
  4516. openPreziDialog: function() {
  4517. var myprezi = APP.xmpp.getPrezi();
  4518. if (myprezi) {
  4519. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  4520. null,
  4521. "dialog.removePreziMsg",
  4522. null,
  4523. false,
  4524. "dialog.Remove",
  4525. function(e,v,m,f) {
  4526. if(v) {
  4527. APP.xmpp.removePreziFromPresence();
  4528. }
  4529. }
  4530. );
  4531. }
  4532. else if (preziPlayer != null) {
  4533. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  4534. null, "dialog.sharePreziMsg",
  4535. null,
  4536. false,
  4537. "dialog.Ok",
  4538. function(e,v,m,f) {
  4539. $.prompt.close();
  4540. }
  4541. );
  4542. }
  4543. else {
  4544. var html = APP.translation.generateTranslationHTML(
  4545. "dialog.sharePreziTitle");
  4546. var cancelButton = APP.translation.generateTranslationHTML(
  4547. "dialog.Cancel");
  4548. var shareButton = APP.translation.generateTranslationHTML(
  4549. "dialog.Share");
  4550. var backButton = APP.translation.generateTranslationHTML(
  4551. "dialog.Back");
  4552. var buttons = [];
  4553. var buttons1 = [];
  4554. // Cancel button to both states
  4555. buttons.push({title: cancelButton, value: false});
  4556. buttons1.push({title: cancelButton, value: false});
  4557. // Share button
  4558. buttons.push({title: shareButton, value: true});
  4559. // Back button
  4560. buttons1.push({title: backButton, value: true});
  4561. var linkError = APP.translation.generateTranslationHTML(
  4562. "dialog.preziLinkError");
  4563. var defaultUrl = APP.translation.translateString("defaultPreziLink",
  4564. {url: "http://prezi.com/wz7vhjycl7e6/my-prezi"});
  4565. var openPreziState = {
  4566. state0: {
  4567. html: '<h2>' + html + '</h2>' +
  4568. '<input name="preziUrl" type="text" ' +
  4569. 'data-i18n="[placeholder]defaultPreziLink" data-i18n-options=\'' +
  4570. JSON.stringify({"url": "http://prezi.com/wz7vhjycl7e6/my-prezi"}) +
  4571. '\' placeholder="' + defaultUrl + '" autofocus>',
  4572. persistent: false,
  4573. buttons: buttons,
  4574. focus: ':input:first',
  4575. defaultButton: 0,
  4576. submit: function (e, v, m, f) {
  4577. e.preventDefault();
  4578. if(v)
  4579. {
  4580. var preziUrl = f.preziUrl;
  4581. if (preziUrl)
  4582. {
  4583. var urlValue
  4584. = encodeURI(UIUtil.escapeHtml(preziUrl));
  4585. if (urlValue.indexOf('http://prezi.com/') != 0
  4586. && urlValue.indexOf('https://prezi.com/') != 0)
  4587. {
  4588. $.prompt.goToState('state1');
  4589. return false;
  4590. }
  4591. else {
  4592. var presIdTmp = urlValue.substring(
  4593. urlValue.indexOf("prezi.com/") + 10);
  4594. if (!isAlphanumeric(presIdTmp)
  4595. || presIdTmp.indexOf('/') < 2) {
  4596. $.prompt.goToState('state1');
  4597. return false;
  4598. }
  4599. else {
  4600. APP.xmpp.addToPresence("prezi", urlValue);
  4601. $.prompt.close();
  4602. }
  4603. }
  4604. }
  4605. }
  4606. else
  4607. $.prompt.close();
  4608. }
  4609. },
  4610. state1: {
  4611. html: '<h2>' + html + '</h2>' +
  4612. linkError,
  4613. persistent: false,
  4614. buttons: buttons1,
  4615. focus: ':input:first',
  4616. defaultButton: 1,
  4617. submit: function (e, v, m, f) {
  4618. e.preventDefault();
  4619. if (v === 0)
  4620. $.prompt.close();
  4621. else
  4622. $.prompt.goToState('state0');
  4623. }
  4624. }
  4625. };
  4626. messageHandler.openDialogWithStates(openPreziState);
  4627. }
  4628. }
  4629. };
  4630. /**
  4631. * A new presentation has been added.
  4632. *
  4633. * @param event the event indicating the add of a presentation
  4634. * @param jid the jid from which the presentation was added
  4635. * @param presUrl url of the presentation
  4636. * @param currentSlide the current slide to which we should move
  4637. */
  4638. function presentationAdded(event, jid, presUrl, currentSlide) {
  4639. console.log("presentation added", presUrl);
  4640. var presId = getPresentationId(presUrl);
  4641. var elementId = 'participant_'
  4642. + Strophe.getResourceFromJid(jid)
  4643. + '_' + presId;
  4644. VideoLayout.addPreziContainer(elementId);
  4645. var controlsEnabled = false;
  4646. if (jid === APP.xmpp.myJid())
  4647. controlsEnabled = true;
  4648. setPresentationVisible(true);
  4649. VideoLayout.setLargeVideoHover(
  4650. function (event) {
  4651. if (Prezi.isPresentationVisible()) {
  4652. var reloadButtonRight = window.innerWidth
  4653. - $('#presentation>iframe').offset().left
  4654. - $('#presentation>iframe').width();
  4655. $('#reloadPresentation').css({ right: reloadButtonRight,
  4656. display:'inline-block'});
  4657. }
  4658. },
  4659. function (event) {
  4660. if (!Prezi.isPresentationVisible())
  4661. $('#reloadPresentation').css({display:'none'});
  4662. else {
  4663. var e = event.toElement || event.relatedTarget;
  4664. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  4665. $('#reloadPresentation').css({display:'none'});
  4666. }
  4667. });
  4668. preziPlayer = new PreziPlayer(
  4669. 'presentation',
  4670. {preziId: presId,
  4671. width: getPresentationWidth(),
  4672. height: getPresentationHeihgt(),
  4673. controls: controlsEnabled,
  4674. debug: true
  4675. });
  4676. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  4677. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  4678. console.log("prezi status", event.value);
  4679. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  4680. if (jid != APP.xmpp.myJid())
  4681. preziPlayer.flyToStep(currentSlide);
  4682. }
  4683. });
  4684. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  4685. console.log("event value", event.value);
  4686. APP.xmpp.addToPresence("preziSlide", event.value);
  4687. });
  4688. $("#" + elementId).css( 'background-image',
  4689. 'url(../images/avatarprezi.png)');
  4690. $("#" + elementId).click(
  4691. function () {
  4692. setPresentationVisible(true);
  4693. }
  4694. );
  4695. };
  4696. /**
  4697. * A presentation has been removed.
  4698. *
  4699. * @param event the event indicating the remove of a presentation
  4700. * @param jid the jid for which the presentation was removed
  4701. * @param the url of the presentation
  4702. */
  4703. function presentationRemoved(event, jid, presUrl) {
  4704. console.log('presentation removed', presUrl);
  4705. var presId = getPresentationId(presUrl);
  4706. setPresentationVisible(false);
  4707. $('#participant_'
  4708. + Strophe.getResourceFromJid(jid)
  4709. + '_' + presId).remove();
  4710. $('#presentation>iframe').remove();
  4711. if (preziPlayer != null) {
  4712. preziPlayer.destroy();
  4713. preziPlayer = null;
  4714. }
  4715. };
  4716. /**
  4717. * Indicates if the given string is an alphanumeric string.
  4718. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  4719. * purpose of checking URIs.
  4720. */
  4721. function isAlphanumeric(unsafeText) {
  4722. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  4723. return regex.test(unsafeText);
  4724. }
  4725. /**
  4726. * Returns the presentation id from the given url.
  4727. */
  4728. function getPresentationId (presUrl) {
  4729. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  4730. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  4731. }
  4732. /**
  4733. * Returns the presentation width.
  4734. */
  4735. function getPresentationWidth() {
  4736. var availableWidth = UIUtil.getAvailableVideoWidth();
  4737. var availableHeight = getPresentationHeihgt();
  4738. var aspectRatio = 16.0 / 9.0;
  4739. if (availableHeight < availableWidth / aspectRatio) {
  4740. availableWidth = Math.floor(availableHeight * aspectRatio);
  4741. }
  4742. return availableWidth;
  4743. }
  4744. /**
  4745. * Returns the presentation height.
  4746. */
  4747. function getPresentationHeihgt() {
  4748. var remoteVideos = $('#remoteVideos');
  4749. return window.innerHeight - remoteVideos.outerHeight();
  4750. }
  4751. /**
  4752. * Resizes the presentation iframe.
  4753. */
  4754. function resize() {
  4755. if ($('#presentation>iframe')) {
  4756. $('#presentation>iframe').width(getPresentationWidth());
  4757. $('#presentation>iframe').height(getPresentationHeihgt());
  4758. }
  4759. }
  4760. /**
  4761. * Presentation has been removed.
  4762. */
  4763. $(document).bind('presentationremoved.muc', presentationRemoved);
  4764. /**
  4765. * Presentation has been added.
  4766. */
  4767. $(document).bind('presentationadded.muc', presentationAdded);
  4768. /*
  4769. * Indicates presentation slide change.
  4770. */
  4771. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  4772. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  4773. preziPlayer.flyToStep(current);
  4774. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  4775. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  4776. preziPlayer.flyToStep(current, i);
  4777. }
  4778. }
  4779. });
  4780. $(window).resize(function () {
  4781. resize();
  4782. });
  4783. module.exports = Prezi;
  4784. },{"../toolbars/ToolbarToggler":31,"../util/MessageHandler":33,"../util/UIUtil":35,"../videolayout/VideoLayout":41,"./PreziPlayer":21}],21:[function(require,module,exports){
  4785. (function() {
  4786. "use strict";
  4787. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  4788. window.PreziPlayer = (function() {
  4789. PreziPlayer.API_VERSION = 1;
  4790. PreziPlayer.CURRENT_STEP = 'currentStep';
  4791. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  4792. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  4793. PreziPlayer.STATUS_LOADING = 'loading';
  4794. PreziPlayer.STATUS_READY = 'ready';
  4795. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  4796. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  4797. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  4798. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  4799. PreziPlayer.EVENT_STATUS = "statusChange";
  4800. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  4801. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  4802. PreziPlayer.domain = "https://prezi.com";
  4803. PreziPlayer.path = "/player/";
  4804. PreziPlayer.players = {};
  4805. PreziPlayer.binded_methods = ['changesHandler'];
  4806. PreziPlayer.createMultiplePlayers = function(optionArray){
  4807. for(var i=0; i<optionArray.length; i++) {
  4808. var optionSet = optionArray[i];
  4809. new PreziPlayer(optionSet.id, optionSet);
  4810. };
  4811. };
  4812. PreziPlayer.messageReceived = function(event){
  4813. var message, item, player;
  4814. try {
  4815. message = JSON.parse(event.data);
  4816. if (message.id && (player = PreziPlayer.players[message.id])) {
  4817. if (player.options.debug === true) {
  4818. if (console && console.log)
  4819. console.log('received', message);
  4820. }
  4821. if (message.type === "changes") {
  4822. player.changesHandler(message);
  4823. }
  4824. for (var i = 0; i < player.callbacks.length; i++) {
  4825. item = player.callbacks[i];
  4826. if (item && message.type === item.event) {
  4827. item.callback(message);
  4828. }
  4829. }
  4830. }
  4831. } catch (e) { }
  4832. };
  4833. function PreziPlayer(id, options) {
  4834. var params, paramString = "", _this = this;
  4835. if (PreziPlayer.players[id]){
  4836. PreziPlayer.players[id].destroy();
  4837. }
  4838. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  4839. var method_name = PreziPlayer.binded_methods[i];
  4840. _this[method_name] = __bind(_this[method_name], _this);
  4841. };
  4842. options = options || {};
  4843. this.options = options;
  4844. this.values = {'status': PreziPlayer.STATUS_LOADING};
  4845. this.values[PreziPlayer.CURRENT_STEP] = 0;
  4846. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  4847. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  4848. this.callbacks = [];
  4849. this.id = id;
  4850. this.embedTo = document.getElementById(id);
  4851. if (!this.embedTo) {
  4852. throw "The element id is not available.";
  4853. }
  4854. this.iframe = document.createElement('iframe');
  4855. params = [
  4856. { name: 'oid', value: options.preziId },
  4857. { name: 'explorable', value: options.explorable ? 1 : 0 },
  4858. { name: 'controls', value: options.controls ? 1 : 0 }
  4859. ];
  4860. for(var i=0; i<params.length; i++) {
  4861. var param = params[i];
  4862. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  4863. };
  4864. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  4865. this.iframe.frameBorder = 0;
  4866. this.iframe.scrolling = "no";
  4867. this.iframe.width = options.width || 640;
  4868. this.iframe.height = options.height || 480;
  4869. this.embedTo.innerHTML = '';
  4870. // JITSI: IN CASE SOMETHING GOES WRONG.
  4871. try {
  4872. this.embedTo.appendChild(this.iframe);
  4873. }
  4874. catch (err) {
  4875. console.log("CATCH ERROR");
  4876. }
  4877. // JITSI: Increase interval from 200 to 500, which fixes prezi
  4878. // crashes for us.
  4879. this.initPollInterval = setInterval(function(){
  4880. _this.sendMessage({'action': 'init'});
  4881. }, 500);
  4882. PreziPlayer.players[id] = this;
  4883. }
  4884. PreziPlayer.prototype.changesHandler = function(message) {
  4885. var key, value, j, item;
  4886. if (this.initPollInterval) {
  4887. clearInterval(this.initPollInterval);
  4888. this.initPollInterval = false;
  4889. }
  4890. for (key in message.data) {
  4891. if (message.data.hasOwnProperty(key)){
  4892. value = message.data[key];
  4893. this.values[key] = value;
  4894. for (j=0; j<this.callbacks.length; j++) {
  4895. item = this.callbacks[j];
  4896. if (item && item.event === key + "Change"){
  4897. item.callback({type: item.event, value: value});
  4898. }
  4899. }
  4900. }
  4901. }
  4902. };
  4903. PreziPlayer.prototype.destroy = function() {
  4904. if (this.initPollInterval) {
  4905. clearInterval(this.initPollInterval);
  4906. this.initPollInterval = false;
  4907. }
  4908. this.embedTo.innerHTML = '';
  4909. };
  4910. PreziPlayer.prototype.sendMessage = function(message) {
  4911. if (this.options.debug === true) {
  4912. if (console && console.log) console.log('sent', message);
  4913. }
  4914. message.version = PreziPlayer.API_VERSION;
  4915. message.id = this.id;
  4916. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  4917. };
  4918. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  4919. PreziPlayer.prototype.flyToNextStep = function() {
  4920. return this.sendMessage({
  4921. 'action': 'present',
  4922. 'data': ['moveToNextStep']
  4923. });
  4924. };
  4925. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  4926. PreziPlayer.prototype.flyToPreviousStep = function() {
  4927. return this.sendMessage({
  4928. 'action': 'present',
  4929. 'data': ['moveToPrevStep']
  4930. });
  4931. };
  4932. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  4933. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  4934. var obj = this;
  4935. // check animation_step
  4936. if (animation_step > 0 &&
  4937. obj.values.animationCountOnSteps &&
  4938. obj.values.animationCountOnSteps[step] <= animation_step) {
  4939. animation_step = obj.values.animationCountOnSteps[step];
  4940. }
  4941. // jump to animation steps by calling flyToNextStep()
  4942. function doAnimationSteps() {
  4943. if (obj.values.isMoving == true) {
  4944. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  4945. return;
  4946. }
  4947. while (animation_step-- > 0) {
  4948. obj.flyToNextStep(); // do the animation steps
  4949. }
  4950. }
  4951. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  4952. // jump to the step
  4953. return this.sendMessage({
  4954. 'action': 'present',
  4955. 'data': ['moveToStep', step]
  4956. });
  4957. };
  4958. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  4959. PreziPlayer.prototype.flyToObject = function(objectId) {
  4960. return this.sendMessage({
  4961. 'action': 'present',
  4962. 'data': ['moveToObject', objectId]
  4963. });
  4964. };
  4965. PreziPlayer.prototype.play = function(defaultDelay) {
  4966. return this.sendMessage({
  4967. 'action': 'present',
  4968. 'data': ['startAutoPlay', defaultDelay]
  4969. });
  4970. };
  4971. PreziPlayer.prototype.stop = function() {
  4972. return this.sendMessage({
  4973. 'action': 'present',
  4974. 'data': ['stopAutoPlay']
  4975. });
  4976. };
  4977. PreziPlayer.prototype.pause = function(defaultDelay) {
  4978. return this.sendMessage({
  4979. 'action': 'present',
  4980. 'data': ['pauseAutoPlay', defaultDelay]
  4981. });
  4982. };
  4983. PreziPlayer.prototype.getCurrentStep = function() {
  4984. return this.values.currentStep;
  4985. };
  4986. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  4987. return this.values.currentAnimationStep;
  4988. };
  4989. PreziPlayer.prototype.getCurrentObject = function() {
  4990. return this.values.currentObject;
  4991. };
  4992. PreziPlayer.prototype.getStatus = function() {
  4993. return this.values.status;
  4994. };
  4995. PreziPlayer.prototype.isPlaying = function() {
  4996. return this.values.isAutoPlaying;
  4997. };
  4998. PreziPlayer.prototype.getStepCount = function() {
  4999. return this.values.stepCount;
  5000. };
  5001. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  5002. return this.values.animationCountOnSteps;
  5003. };
  5004. PreziPlayer.prototype.getTitle = function() {
  5005. return this.values.title;
  5006. };
  5007. PreziPlayer.prototype.setDimensions = function(dims) {
  5008. for (var parameter in dims) {
  5009. this.iframe[parameter] = dims[parameter];
  5010. }
  5011. }
  5012. PreziPlayer.prototype.getDimensions = function() {
  5013. return {
  5014. width: parseInt(this.iframe.width, 10),
  5015. height: parseInt(this.iframe.height, 10)
  5016. }
  5017. }
  5018. PreziPlayer.prototype.on = function(event, callback) {
  5019. this.callbacks.push({
  5020. event: event,
  5021. callback: callback
  5022. });
  5023. };
  5024. PreziPlayer.prototype.off = function(event, callback) {
  5025. var j, item;
  5026. if (event === undefined) {
  5027. this.callbacks = [];
  5028. }
  5029. j = this.callbacks.length;
  5030. while (j--) {
  5031. item = this.callbacks[j];
  5032. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  5033. this.callbacks.splice(j, 1);
  5034. }
  5035. }
  5036. };
  5037. if (window.addEventListener) {
  5038. window.addEventListener('message', PreziPlayer.messageReceived, false);
  5039. } else {
  5040. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  5041. }
  5042. return PreziPlayer;
  5043. })();
  5044. })();
  5045. module.exports = PreziPlayer;
  5046. },{}],22:[function(require,module,exports){
  5047. /* global require, $ */
  5048. var Chat = require("./chat/Chat");
  5049. var ContactList = require("./contactlist/ContactList");
  5050. var Settings = require("./../../settings/Settings");
  5051. var SettingsMenu = require("./settings/SettingsMenu");
  5052. var VideoLayout = require("../videolayout/VideoLayout");
  5053. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  5054. var UIUtil = require("../util/UIUtil");
  5055. var LargeVideo = require("../videolayout/LargeVideo");
  5056. /**
  5057. * Toggler for the chat, contact list, settings menu, etc..
  5058. */
  5059. var PanelToggler = (function(my) {
  5060. var currentlyOpen = null;
  5061. var buttons = {
  5062. '#chatspace': '#chatBottomButton',
  5063. '#contactlist': '#contactListButton',
  5064. '#settingsmenu': '#toolbar_button_settings'
  5065. };
  5066. /**
  5067. * Toggles the windows in the side panel
  5068. * @param object the window that should be shown
  5069. * @param selector the selector for the element containing the panel
  5070. * @param onOpenComplete function to be called when the panel is opened
  5071. * @param onOpen function to be called if the window is going to be opened
  5072. * @param onClose function to be called if the window is going to be closed
  5073. */
  5074. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  5075. UIUtil.buttonClick(buttons[selector], "active");
  5076. if (object.isVisible()) {
  5077. $("#toast-container").animate({
  5078. right: '5px'
  5079. },
  5080. {
  5081. queue: false,
  5082. duration: 500
  5083. });
  5084. $(selector).hide("slide", {
  5085. direction: "right",
  5086. queue: false,
  5087. duration: 500
  5088. });
  5089. if(typeof onClose === "function") {
  5090. onClose();
  5091. }
  5092. currentlyOpen = null;
  5093. }
  5094. else {
  5095. // Undock the toolbar when the chat is shown and if we're in a
  5096. // video mode.
  5097. if (LargeVideo.isLargeVideoVisible()) {
  5098. ToolbarToggler.dockToolbar(false);
  5099. }
  5100. if(currentlyOpen) {
  5101. var current = $(currentlyOpen);
  5102. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  5103. current.css('z-index', 4);
  5104. setTimeout(function () {
  5105. current.css('display', 'none');
  5106. current.css('z-index', 5);
  5107. }, 500);
  5108. }
  5109. $("#toast-container").animate({
  5110. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  5111. },
  5112. {
  5113. queue: false,
  5114. duration: 500
  5115. });
  5116. $(selector).show("slide", {
  5117. direction: "right",
  5118. queue: false,
  5119. duration: 500,
  5120. complete: onOpenComplete
  5121. });
  5122. if(typeof onOpen === "function") {
  5123. onOpen();
  5124. }
  5125. currentlyOpen = selector;
  5126. }
  5127. };
  5128. /**
  5129. * Opens / closes the chat area.
  5130. */
  5131. my.toggleChat = function() {
  5132. var chatCompleteFunction = Chat.isVisible() ?
  5133. function() {} : function () {
  5134. Chat.scrollChatToBottom();
  5135. $('#chatspace').trigger('shown');
  5136. };
  5137. VideoLayout.resizeVideoArea(!Chat.isVisible(), chatCompleteFunction);
  5138. toggle(Chat,
  5139. '#chatspace',
  5140. function () {
  5141. // Request the focus in the nickname field or the chat input field.
  5142. if ($('#nickname').css('visibility') === 'visible') {
  5143. $('#nickinput').focus();
  5144. } else {
  5145. $('#usermsg').focus();
  5146. }
  5147. },
  5148. null,
  5149. Chat.resizeChat,
  5150. null);
  5151. };
  5152. /**
  5153. * Opens / closes the contact list area.
  5154. */
  5155. my.toggleContactList = function () {
  5156. var completeFunction = ContactList.isVisible() ?
  5157. function() {} : function () { $('#contactlist').trigger('shown');};
  5158. VideoLayout.resizeVideoArea(!ContactList.isVisible(), completeFunction);
  5159. toggle(ContactList,
  5160. '#contactlist',
  5161. null,
  5162. function() {
  5163. ContactList.setVisualNotification(false);
  5164. },
  5165. null);
  5166. };
  5167. /**
  5168. * Opens / closes the settings menu
  5169. */
  5170. my.toggleSettingsMenu = function() {
  5171. VideoLayout.resizeVideoArea(!SettingsMenu.isVisible(), function (){});
  5172. toggle(SettingsMenu,
  5173. '#settingsmenu',
  5174. null,
  5175. function() {
  5176. var settings = Settings.getSettings();
  5177. $('#setDisplayName').get(0).value = settings.displayName;
  5178. $('#setEmail').get(0).value = settings.email;
  5179. },
  5180. null);
  5181. };
  5182. /**
  5183. * Returns the size of the side panel.
  5184. */
  5185. my.getPanelSize = function () {
  5186. var availableHeight = window.innerHeight;
  5187. var availableWidth = window.innerWidth;
  5188. var panelWidth = 200;
  5189. if (availableWidth * 0.2 < 200) {
  5190. panelWidth = availableWidth * 0.2;
  5191. }
  5192. return [panelWidth, availableHeight];
  5193. };
  5194. my.isVisible = function() {
  5195. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  5196. };
  5197. return my;
  5198. }(PanelToggler || {}));
  5199. module.exports = PanelToggler;
  5200. },{"../toolbars/ToolbarToggler":31,"../util/UIUtil":35,"../videolayout/LargeVideo":37,"../videolayout/VideoLayout":41,"./../../settings/Settings":49,"./chat/Chat":23,"./contactlist/ContactList":27,"./settings/SettingsMenu":28}],23:[function(require,module,exports){
  5201. /* global APP, $, Util, nickname:true */
  5202. var Replacement = require("./Replacement");
  5203. var CommandsProcessor = require("./Commands");
  5204. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  5205. var smileys = require("./smileys.json").smileys;
  5206. var NicknameHandler = require("../../util/NicknameHandler");
  5207. var UIUtil = require("../../util/UIUtil");
  5208. var UIEvents = require("../../../../service/UI/UIEvents");
  5209. var notificationInterval = false;
  5210. var unreadMessages = 0;
  5211. /**
  5212. * Shows/hides a visual notification, indicating that a message has arrived.
  5213. */
  5214. function setVisualNotification(show) {
  5215. var unreadMsgElement = document.getElementById('unreadMessages');
  5216. var unreadMsgBottomElement
  5217. = document.getElementById('bottomUnreadMessages');
  5218. var glower = $('#toolbar_button_chat');
  5219. var bottomGlower = $('#chatBottomButton');
  5220. if (unreadMessages) {
  5221. unreadMsgElement.innerHTML = unreadMessages.toString();
  5222. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  5223. ToolbarToggler.dockToolbar(true);
  5224. var chatButtonElement
  5225. = document.getElementById('toolbar_button_chat');
  5226. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  5227. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  5228. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  5229. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  5230. unreadMsgElement.setAttribute(
  5231. 'style',
  5232. 'top:' + topIndent +
  5233. '; left:' + leftIndent + ';');
  5234. var chatBottomButtonElement
  5235. = document.getElementById('chatBottomButton').parentNode;
  5236. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  5237. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  5238. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  5239. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  5240. unreadMsgBottomElement.setAttribute(
  5241. 'style',
  5242. 'top:' + bottomTopIndent +
  5243. '; left:' + bottomLeftIndent + ';');
  5244. if (!glower.hasClass('icon-chat-simple')) {
  5245. glower.removeClass('icon-chat');
  5246. glower.addClass('icon-chat-simple');
  5247. }
  5248. }
  5249. else {
  5250. unreadMsgElement.innerHTML = '';
  5251. unreadMsgBottomElement.innerHTML = '';
  5252. glower.removeClass('icon-chat-simple');
  5253. glower.addClass('icon-chat');
  5254. }
  5255. if (show && !notificationInterval) {
  5256. notificationInterval = window.setInterval(function () {
  5257. glower.toggleClass('active');
  5258. bottomGlower.toggleClass('active glowing');
  5259. }, 800);
  5260. }
  5261. else if (!show && notificationInterval) {
  5262. window.clearInterval(notificationInterval);
  5263. notificationInterval = false;
  5264. glower.removeClass('active');
  5265. bottomGlower.removeClass('glowing');
  5266. bottomGlower.addClass('active');
  5267. }
  5268. }
  5269. /**
  5270. * Returns the current time in the format it is shown to the user
  5271. * @returns {string}
  5272. */
  5273. function getCurrentTime(stamp) {
  5274. var now = (stamp? new Date(stamp): new Date());
  5275. var hour = now.getHours();
  5276. var minute = now.getMinutes();
  5277. var second = now.getSeconds();
  5278. if(hour.toString().length === 1) {
  5279. hour = '0'+hour;
  5280. }
  5281. if(minute.toString().length === 1) {
  5282. minute = '0'+minute;
  5283. }
  5284. if(second.toString().length === 1) {
  5285. second = '0'+second;
  5286. }
  5287. return hour+':'+minute+':'+second;
  5288. }
  5289. function toggleSmileys() {
  5290. var smileys = $('#smileysContainer');
  5291. if(!smileys.is(':visible')) {
  5292. smileys.show("slide", { direction: "down", duration: 300});
  5293. } else {
  5294. smileys.hide("slide", { direction: "down", duration: 300});
  5295. }
  5296. $('#usermsg').focus();
  5297. }
  5298. function addClickFunction(smiley, number) {
  5299. smiley.onclick = function addSmileyToMessage() {
  5300. var usermsg = $('#usermsg');
  5301. var message = usermsg.val();
  5302. message += smileys['smiley' + number];
  5303. usermsg.val(message);
  5304. usermsg.get(0).setSelectionRange(message.length, message.length);
  5305. toggleSmileys();
  5306. usermsg.focus();
  5307. };
  5308. }
  5309. /**
  5310. * Adds the smileys container to the chat
  5311. */
  5312. function addSmileys() {
  5313. var smileysContainer = document.createElement('div');
  5314. smileysContainer.id = 'smileysContainer';
  5315. for(var i = 1; i <= 21; i++) {
  5316. var smileyContainer = document.createElement('div');
  5317. smileyContainer.id = 'smiley' + i;
  5318. smileyContainer.className = 'smileyContainer';
  5319. var smiley = document.createElement('img');
  5320. smiley.src = 'images/smileys/smiley' + i + '.svg';
  5321. smiley.className = 'smiley';
  5322. addClickFunction(smiley, i);
  5323. smileyContainer.appendChild(smiley);
  5324. smileysContainer.appendChild(smileyContainer);
  5325. }
  5326. $("#chatspace").append(smileysContainer);
  5327. }
  5328. /**
  5329. * Resizes the chat conversation.
  5330. */
  5331. function resizeChatConversation() {
  5332. var msgareaHeight = $('#usermsg').outerHeight();
  5333. var chatspace = $('#chatspace');
  5334. var width = chatspace.width();
  5335. var chat = $('#chatconversation');
  5336. var smileys = $('#smileysarea');
  5337. smileys.height(msgareaHeight);
  5338. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  5339. $('#smileysContainer').css('bottom', msgareaHeight);
  5340. chat.width(width - 10);
  5341. chat.height(window.innerHeight - 15 - msgareaHeight);
  5342. }
  5343. /**
  5344. * Chat related user interface.
  5345. */
  5346. var Chat = (function (my) {
  5347. /**
  5348. * Initializes chat related interface.
  5349. */
  5350. my.init = function () {
  5351. if(NicknameHandler.getNickname())
  5352. Chat.setChatConversationMode(true);
  5353. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  5354. function (nickname) {
  5355. Chat.setChatConversationMode(true);
  5356. });
  5357. $('#nickinput').keydown(function (event) {
  5358. if (event.keyCode === 13) {
  5359. event.preventDefault();
  5360. var val = UIUtil.escapeHtml(this.value);
  5361. this.value = '';
  5362. if (!NicknameHandler.getNickname()) {
  5363. NicknameHandler.setNickname(val);
  5364. return;
  5365. }
  5366. }
  5367. });
  5368. var usermsg = $('#usermsg');
  5369. usermsg.keydown(function (event) {
  5370. if (event.keyCode === 13) {
  5371. event.preventDefault();
  5372. var value = this.value;
  5373. usermsg.val('').trigger('autosize.resize');
  5374. this.focus();
  5375. var command = new CommandsProcessor(value);
  5376. if(command.isCommand()) {
  5377. command.processCommand();
  5378. }
  5379. else {
  5380. var message = UIUtil.escapeHtml(value);
  5381. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  5382. }
  5383. }
  5384. });
  5385. var onTextAreaResize = function () {
  5386. resizeChatConversation();
  5387. Chat.scrollChatToBottom();
  5388. };
  5389. usermsg.autosize({callback: onTextAreaResize});
  5390. $("#chatspace").bind("shown",
  5391. function () {
  5392. unreadMessages = 0;
  5393. setVisualNotification(false);
  5394. });
  5395. addSmileys();
  5396. };
  5397. /**
  5398. * Appends the given message to the chat conversation.
  5399. */
  5400. my.updateChatConversation =
  5401. function (from, displayName, message, myjid, stamp) {
  5402. var divClassName = '';
  5403. if (APP.xmpp.myJid() === from) {
  5404. divClassName = "localuser";
  5405. }
  5406. else {
  5407. divClassName = "remoteuser";
  5408. if (!Chat.isVisible()) {
  5409. unreadMessages++;
  5410. UIUtil.playSoundNotification('chatNotification');
  5411. setVisualNotification(true);
  5412. }
  5413. }
  5414. // replace links and smileys
  5415. // Strophe already escapes special symbols on sending,
  5416. // so we escape here only tags to avoid double &amp;
  5417. var escMessage = message.replace(/</g, '&lt;').
  5418. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  5419. var escDisplayName = UIUtil.escapeHtml(displayName);
  5420. message = Replacement.processReplacements(escMessage);
  5421. var messageContainer =
  5422. '<div class="chatmessage">'+
  5423. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  5424. '<div class="username ' + divClassName +'">' + escDisplayName +
  5425. '</div>' + '<div class="timestamp">' + getCurrentTime(stamp) +
  5426. '</div>' + '<div class="usermessage">' + message + '</div>' +
  5427. '</div>';
  5428. $('#chatconversation').append(messageContainer);
  5429. $('#chatconversation').animate(
  5430. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5431. };
  5432. /**
  5433. * Appends error message to the conversation
  5434. * @param errorMessage the received error message.
  5435. * @param originalText the original message.
  5436. */
  5437. my.chatAddError = function(errorMessage, originalText) {
  5438. errorMessage = UIUtil.escapeHtml(errorMessage);
  5439. originalText = UIUtil.escapeHtml(originalText);
  5440. $('#chatconversation').append(
  5441. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  5442. (originalText? (' \"'+ originalText + '\"') : "") +
  5443. ' was not sent.' +
  5444. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  5445. $('#chatconversation').animate(
  5446. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5447. };
  5448. /**
  5449. * Sets the subject to the UI
  5450. * @param subject the subject
  5451. */
  5452. my.chatSetSubject = function(subject) {
  5453. if (subject)
  5454. subject = subject.trim();
  5455. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  5456. if(subject === "") {
  5457. $("#subject").css({display: "none"});
  5458. }
  5459. else {
  5460. $("#subject").css({display: "block"});
  5461. }
  5462. };
  5463. /**
  5464. * Sets the chat conversation mode.
  5465. */
  5466. my.setChatConversationMode = function (isConversationMode) {
  5467. if (isConversationMode) {
  5468. $('#nickname').css({visibility: 'hidden'});
  5469. $('#chatconversation').css({visibility: 'visible'});
  5470. $('#usermsg').css({visibility: 'visible'});
  5471. $('#smileysarea').css({visibility: 'visible'});
  5472. $('#usermsg').focus();
  5473. }
  5474. };
  5475. /**
  5476. * Resizes the chat area.
  5477. */
  5478. my.resizeChat = function () {
  5479. var chatSize = require("../SidePanelToggler").getPanelSize();
  5480. $('#chatspace').width(chatSize[0]);
  5481. $('#chatspace').height(chatSize[1]);
  5482. resizeChatConversation();
  5483. };
  5484. /**
  5485. * Indicates if the chat is currently visible.
  5486. */
  5487. my.isVisible = function () {
  5488. return $('#chatspace').is(":visible");
  5489. };
  5490. /**
  5491. * Shows and hides the window with the smileys
  5492. */
  5493. my.toggleSmileys = toggleSmileys;
  5494. /**
  5495. * Scrolls chat to the bottom.
  5496. */
  5497. my.scrollChatToBottom = function() {
  5498. setTimeout(function () {
  5499. $('#chatconversation').scrollTop(
  5500. $('#chatconversation')[0].scrollHeight);
  5501. }, 5);
  5502. };
  5503. return my;
  5504. }(Chat || {}));
  5505. module.exports = Chat;
  5506. },{"../../../../service/UI/UIEvents":113,"../../toolbars/ToolbarToggler":31,"../../util/NicknameHandler":34,"../../util/UIUtil":35,"../SidePanelToggler":22,"./Commands":24,"./Replacement":25,"./smileys.json":26}],24:[function(require,module,exports){
  5507. /* global APP, require */
  5508. var UIUtil = require("../../util/UIUtil");
  5509. /**
  5510. * List with supported commands. The keys are the names of the commands and
  5511. * the value is the function that processes the message.
  5512. * @type {{String: function}}
  5513. */
  5514. var commands = {
  5515. "topic" : processTopic
  5516. };
  5517. /**
  5518. * Extracts the command from the message.
  5519. * @param message the received message
  5520. * @returns {string} the command
  5521. */
  5522. function getCommand(message) {
  5523. if(message) {
  5524. for(var command in commands) {
  5525. if(message.indexOf("/" + command) == 0)
  5526. return command;
  5527. }
  5528. }
  5529. return "";
  5530. }
  5531. /**
  5532. * Processes the data for topic command.
  5533. * @param commandArguments the arguments of the topic command.
  5534. */
  5535. function processTopic(commandArguments) {
  5536. var topic = UIUtil.escapeHtml(commandArguments);
  5537. APP.xmpp.setSubject(topic);
  5538. }
  5539. /**
  5540. * Constructs a new CommandProccessor instance from a message that
  5541. * handles commands received via chat messages.
  5542. * @param message the message
  5543. * @constructor
  5544. */
  5545. function CommandsProcessor(message) {
  5546. var command = getCommand(message);
  5547. /**
  5548. * Returns the name of the command.
  5549. * @returns {String} the command
  5550. */
  5551. this.getCommand = function() {
  5552. return command;
  5553. };
  5554. var messageArgument = message.substr(command.length + 2);
  5555. /**
  5556. * Returns the arguments of the command.
  5557. * @returns {string}
  5558. */
  5559. this.getArgument = function() {
  5560. return messageArgument;
  5561. };
  5562. }
  5563. /**
  5564. * Checks whether this instance is valid command or not.
  5565. * @returns {boolean}
  5566. */
  5567. CommandsProcessor.prototype.isCommand = function() {
  5568. if (this.getCommand())
  5569. return true;
  5570. return false;
  5571. };
  5572. /**
  5573. * Processes the command.
  5574. */
  5575. CommandsProcessor.prototype.processCommand = function() {
  5576. if(!this.isCommand())
  5577. return;
  5578. commands[this.getCommand()](this.getArgument());
  5579. };
  5580. module.exports = CommandsProcessor;
  5581. },{"../../util/UIUtil":35}],25:[function(require,module,exports){
  5582. var Smileys = require("./smileys.json");
  5583. /**
  5584. * Processes links and smileys in "body"
  5585. */
  5586. function processReplacements(body)
  5587. {
  5588. //make links clickable
  5589. body = linkify(body);
  5590. //add smileys
  5591. body = smilify(body);
  5592. return body;
  5593. }
  5594. /**
  5595. * Finds and replaces all links in the links in "body"
  5596. * with their <a href=""></a>
  5597. */
  5598. function linkify(inputText)
  5599. {
  5600. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  5601. //URLs starting with http://, https://, or ftp://
  5602. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  5603. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  5604. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  5605. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  5606. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  5607. //Change email addresses to mailto:: links.
  5608. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  5609. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  5610. return replacedText;
  5611. }
  5612. /**
  5613. * Replaces common smiley strings with images
  5614. */
  5615. function smilify(body)
  5616. {
  5617. if(!body) {
  5618. return body;
  5619. }
  5620. var regexs = Smileys["regexs"];
  5621. for(var smiley in regexs) {
  5622. if(regexs.hasOwnProperty(smiley)) {
  5623. body = body.replace(regexs[smiley],
  5624. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  5625. }
  5626. }
  5627. return body;
  5628. }
  5629. module.exports = {
  5630. processReplacements: processReplacements,
  5631. linkify: linkify
  5632. };
  5633. },{"./smileys.json":26}],26:[function(require,module,exports){
  5634. module.exports={
  5635. "smileys": {
  5636. "smiley1": ":)",
  5637. "smiley2": ":(",
  5638. "smiley3": ":D",
  5639. "smiley4": "(y)",
  5640. "smiley5": " :P",
  5641. "smiley6": "(wave)",
  5642. "smiley7": "(blush)",
  5643. "smiley8": "(chuckle)",
  5644. "smiley9": "(shocked)",
  5645. "smiley10": ":*",
  5646. "smiley11": "(n)",
  5647. "smiley12": "(search)",
  5648. "smiley13": " <3",
  5649. "smiley14": "(oops)",
  5650. "smiley15": "(angry)",
  5651. "smiley16": "(angel)",
  5652. "smiley17": "(sick)",
  5653. "smiley18": ";(",
  5654. "smiley19": "(bomb)",
  5655. "smiley20": "(clap)",
  5656. "smiley21": " ;)"
  5657. },
  5658. "regexs": {
  5659. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  5660. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  5661. "smiley1": /(:-\)|:\))/gi,
  5662. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  5663. "smiley5": /(:-P|:P|:-p|:p)/gi,
  5664. "smiley6": /(\(wave\))/gi,
  5665. "smiley7": /(\(blush\))/gi,
  5666. "smiley8": /(\(chuckle\))/gi,
  5667. "smiley9": /(:-0|\(shocked\))/gi,
  5668. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  5669. "smiley11": /(\(n\))/gi,
  5670. "smiley12": /(\(search\))/g,
  5671. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  5672. "smiley14": /(\(oops\))/gi,
  5673. "smiley15": /(\(angry\))/gi,
  5674. "smiley16": /(\(angel\))/gi,
  5675. "smiley17": /(\(sick\))/gi,
  5676. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  5677. "smiley19": /(\(bomb\))/gi,
  5678. "smiley20": /(\(clap\))/gi,
  5679. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  5680. }
  5681. }
  5682. },{}],27:[function(require,module,exports){
  5683. /* global $, APP, Strophe */
  5684. var Avatar = require('../../avatar/Avatar');
  5685. var numberOfContacts = 0;
  5686. var notificationInterval;
  5687. /**
  5688. * Updates the number of participants in the contact list button and sets
  5689. * the glow
  5690. * @param delta indicates whether a new user has joined (1) or someone has
  5691. * left(-1)
  5692. */
  5693. function updateNumberOfParticipants(delta) {
  5694. numberOfContacts += delta;
  5695. if (numberOfContacts === 1) {
  5696. // when the user is alone we don't show the number of participants
  5697. $("#numberOfParticipants").text('');
  5698. ContactList.setVisualNotification(false);
  5699. } else if (numberOfContacts > 1) {
  5700. ContactList.setVisualNotification(!ContactList.isVisible());
  5701. $("#numberOfParticipants").text(numberOfContacts);
  5702. } else {
  5703. console.error("Invalid number of participants: " + numberOfContacts);
  5704. }
  5705. }
  5706. /**
  5707. * Creates the avatar element.
  5708. *
  5709. * @return {object} the newly created avatar element
  5710. */
  5711. function createAvatar(jid) {
  5712. var avatar = document.createElement('img');
  5713. avatar.className = "icon-avatar avatar";
  5714. avatar.src = Avatar.getContactListUrl(jid);
  5715. return avatar;
  5716. }
  5717. /**
  5718. * Creates the display name paragraph.
  5719. *
  5720. * @param displayName the display name to set
  5721. */
  5722. function createDisplayNameParagraph(key, displayName) {
  5723. var p = document.createElement('p');
  5724. if(displayName)
  5725. p.innerText = displayName;
  5726. else if(key) {
  5727. p.setAttribute("data-i18n",key);
  5728. p.innerText = APP.translation.translateString(key);
  5729. }
  5730. return p;
  5731. }
  5732. function stopGlowing(glower) {
  5733. window.clearInterval(notificationInterval);
  5734. notificationInterval = false;
  5735. glower.removeClass('glowing');
  5736. if (!ContactList.isVisible()) {
  5737. glower.removeClass('active');
  5738. }
  5739. }
  5740. /**
  5741. * Contact list.
  5742. */
  5743. var ContactList = {
  5744. /**
  5745. * Indicates if the chat is currently visible.
  5746. *
  5747. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  5748. * otherwise
  5749. */
  5750. isVisible: function () {
  5751. return $('#contactlist').is(":visible");
  5752. },
  5753. /**
  5754. * Adds a contact for the given peerJid if such doesn't yet exist.
  5755. *
  5756. * @param peerJid the peerJid corresponding to the contact
  5757. */
  5758. ensureAddContact: function (peerJid) {
  5759. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5760. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5761. if (!contact || contact.length <= 0)
  5762. ContactList.addContact(peerJid);
  5763. },
  5764. /**
  5765. * Adds a contact for the given peer jid.
  5766. *
  5767. * @param peerJid the jid of the contact to add
  5768. */
  5769. addContact: function (peerJid) {
  5770. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5771. var contactlist = $('#contacts');
  5772. var newContact = document.createElement('li');
  5773. newContact.id = resourceJid;
  5774. newContact.className = "clickable";
  5775. newContact.onclick = function (event) {
  5776. if (event.currentTarget.className === "clickable") {
  5777. $(ContactList).trigger('contactclicked', [peerJid]);
  5778. }
  5779. };
  5780. newContact.appendChild(createAvatar(peerJid));
  5781. newContact.appendChild(createDisplayNameParagraph("participant"));
  5782. if (resourceJid === APP.xmpp.myResource()) {
  5783. contactlist.prepend(newContact);
  5784. }
  5785. else {
  5786. contactlist.append(newContact);
  5787. }
  5788. updateNumberOfParticipants(1);
  5789. },
  5790. /**
  5791. * Removes a contact for the given peer jid.
  5792. *
  5793. * @param peerJid the peerJid corresponding to the contact to remove
  5794. */
  5795. removeContact: function (peerJid) {
  5796. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5797. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5798. if (contact && contact.length > 0) {
  5799. var contactlist = $('#contactlist>ul');
  5800. contactlist.get(0).removeChild(contact.get(0));
  5801. updateNumberOfParticipants(-1);
  5802. }
  5803. },
  5804. setVisualNotification: function (show, stopGlowingIn) {
  5805. var glower = $('#contactListButton');
  5806. if (show && !notificationInterval) {
  5807. notificationInterval = window.setInterval(function () {
  5808. glower.toggleClass('active glowing');
  5809. }, 800);
  5810. }
  5811. else if (!show && notificationInterval) {
  5812. stopGlowing(glower);
  5813. }
  5814. if (stopGlowingIn) {
  5815. setTimeout(function () {
  5816. stopGlowing(glower);
  5817. }, stopGlowingIn);
  5818. }
  5819. },
  5820. setClickable: function (resourceJid, isClickable) {
  5821. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5822. if (isClickable) {
  5823. contact.addClass('clickable');
  5824. } else {
  5825. contact.removeClass('clickable');
  5826. }
  5827. },
  5828. onDisplayNameChange: function (peerJid, displayName) {
  5829. if (peerJid === 'localVideoContainer')
  5830. peerJid = APP.xmpp.myJid();
  5831. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5832. var contactName = $('#contacts #' + resourceJid + '>p');
  5833. if (contactName && displayName && displayName.length > 0)
  5834. contactName.html(displayName);
  5835. },
  5836. userAvatarChanged: function (resourceJid, contactListUrl) {
  5837. // set the avatar in the contact list
  5838. var contact = $('#' + resourceJid + '>img');
  5839. if (contact && contact.length > 0) {
  5840. contact.get(0).src = contactListUrl;
  5841. }
  5842. }
  5843. };
  5844. module.exports = ContactList;
  5845. },{"../../avatar/Avatar":18}],28:[function(require,module,exports){
  5846. /* global APP, $ */
  5847. var Avatar = require("../../avatar/Avatar");
  5848. var Settings = require("./../../../settings/Settings");
  5849. var UIUtil = require("../../util/UIUtil");
  5850. var languages = require("../../../../service/translation/languages");
  5851. function generateLanguagesSelectBox() {
  5852. var currentLang = APP.translation.getCurrentLanguage();
  5853. var html = "<select id=\"languages_selectbox\">";
  5854. var langArray = languages.getLanguages();
  5855. for(var i = 0; i < langArray.length; i++) {
  5856. var lang = langArray[i];
  5857. html += "<option ";
  5858. if(lang === currentLang)
  5859. html += "selected ";
  5860. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  5861. html += "</option>";
  5862. }
  5863. return html + "</select>";
  5864. }
  5865. var SettingsMenu = {
  5866. init: function () {
  5867. var startMutedSelector = $("#startMutedOptions");
  5868. startMutedSelector.before(generateLanguagesSelectBox());
  5869. APP.translation.translateElement($("#languages_selectbox"));
  5870. $('#settingsmenu>input').keyup(function(event){
  5871. if(event.keyCode === 13) {//enter
  5872. SettingsMenu.update();
  5873. }
  5874. });
  5875. if (APP.xmpp.isModerator()) {
  5876. startMutedSelector.css("display", "block");
  5877. }
  5878. else {
  5879. startMutedSelector.css("display", "none");
  5880. }
  5881. $("#updateSettings").click(function () {
  5882. SettingsMenu.update();
  5883. });
  5884. },
  5885. onRoleChanged: function () {
  5886. if(APP.xmpp.isModerator()) {
  5887. $("#startMutedOptions").css("display", "block");
  5888. }
  5889. else {
  5890. $("#startMutedOptions").css("display", "none");
  5891. }
  5892. },
  5893. setStartMuted: function (audio, video) {
  5894. $("#startAudioMuted").attr("checked", audio);
  5895. $("#startVideoMuted").attr("checked", video);
  5896. },
  5897. update: function() {
  5898. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  5899. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  5900. if(newDisplayName) {
  5901. var displayName = Settings.setDisplayName(newDisplayName);
  5902. APP.xmpp.addToPresence("displayName", displayName, true);
  5903. }
  5904. var language = $("#languages_selectbox").val();
  5905. APP.translation.setLanguage(language);
  5906. Settings.setLanguage(language);
  5907. APP.xmpp.addToPresence("email", newEmail);
  5908. var email = Settings.setEmail(newEmail);
  5909. var startAudioMuted = ($("#startAudioMuted").is(":checked"));
  5910. var startVideoMuted = ($("#startVideoMuted").is(":checked"));
  5911. APP.xmpp.addToPresence("startMuted",
  5912. [startAudioMuted, startVideoMuted]);
  5913. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  5914. },
  5915. isVisible: function() {
  5916. return $('#settingsmenu').is(':visible');
  5917. },
  5918. setDisplayName: function(newDisplayName) {
  5919. var displayName = Settings.setDisplayName(newDisplayName);
  5920. $('#setDisplayName').get(0).value = displayName;
  5921. },
  5922. onDisplayNameChange: function(peerJid, newDisplayName) {
  5923. if(peerJid === 'localVideoContainer' ||
  5924. peerJid === APP.xmpp.myJid()) {
  5925. this.setDisplayName(newDisplayName);
  5926. }
  5927. },
  5928. changeAvatar: function (thumbUrl) {
  5929. $('#avatar').get(0).src = thumbUrl;
  5930. }
  5931. };
  5932. module.exports = SettingsMenu;
  5933. },{"../../../../service/translation/languages":118,"../../avatar/Avatar":18,"../../util/UIUtil":35,"./../../../settings/Settings":49}],29:[function(require,module,exports){
  5934. /* global $ */
  5935. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5936. var buttonHandlers = {
  5937. "bottom_toolbar_contact_list": function () {
  5938. BottomToolbar.toggleContactList();
  5939. },
  5940. "bottom_toolbar_film_strip": function () {
  5941. BottomToolbar.toggleFilmStrip();
  5942. },
  5943. "bottom_toolbar_chat": function () {
  5944. BottomToolbar.toggleChat();
  5945. }
  5946. };
  5947. var BottomToolbar = (function (my) {
  5948. my.init = function () {
  5949. for(var k in buttonHandlers)
  5950. $("#" + k).click(buttonHandlers[k]);
  5951. };
  5952. my.toggleChat = function() {
  5953. PanelToggler.toggleChat();
  5954. };
  5955. my.toggleContactList = function() {
  5956. PanelToggler.toggleContactList();
  5957. };
  5958. my.toggleFilmStrip = function() {
  5959. var filmstrip = $("#remoteVideos");
  5960. filmstrip.toggleClass("hidden");
  5961. };
  5962. $(document).bind("remotevideo.resized", function (event, width, height) {
  5963. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  5964. $('#bottomToolbar').css({bottom: bottom + 'px'});
  5965. });
  5966. return my;
  5967. }(BottomToolbar || {}));
  5968. module.exports = BottomToolbar;
  5969. },{"../side_pannels/SidePanelToggler":22}],30:[function(require,module,exports){
  5970. /* global APP, $, buttonClick, config, lockRoom, interfaceConfig, setSharedKey,
  5971. Util */
  5972. var messageHandler = require("../util/MessageHandler");
  5973. var BottomToolbar = require("./BottomToolbar");
  5974. var Prezi = require("../prezi/Prezi");
  5975. var Etherpad = require("../etherpad/Etherpad");
  5976. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5977. var Authentication = require("../authentication/Authentication");
  5978. var UIUtil = require("../util/UIUtil");
  5979. var AuthenticationEvents
  5980. = require("../../../service/authentication/AuthenticationEvents");
  5981. var roomUrl = null;
  5982. var sharedKey = '';
  5983. var UI = null;
  5984. var buttonHandlers = {
  5985. "toolbar_button_mute": function () {
  5986. return APP.UI.toggleAudio();
  5987. },
  5988. "toolbar_button_camera": function () {
  5989. return APP.UI.toggleVideo();
  5990. },
  5991. /*"toolbar_button_authentication": function () {
  5992. return Toolbar.authenticateClicked();
  5993. },*/
  5994. "toolbar_button_record": function () {
  5995. return toggleRecording();
  5996. },
  5997. "toolbar_button_security": function () {
  5998. return Toolbar.openLockDialog();
  5999. },
  6000. "toolbar_button_link": function () {
  6001. return Toolbar.openLinkDialog();
  6002. },
  6003. "toolbar_button_chat": function () {
  6004. return BottomToolbar.toggleChat();
  6005. },
  6006. "toolbar_button_prezi": function () {
  6007. return Prezi.openPreziDialog();
  6008. },
  6009. "toolbar_button_etherpad": function () {
  6010. return Etherpad.toggleEtherpad(0);
  6011. },
  6012. "toolbar_button_desktopsharing": function () {
  6013. return APP.desktopsharing.toggleScreenSharing();
  6014. },
  6015. "toolbar_button_fullScreen": function() {
  6016. UIUtil.buttonClick("#toolbar_button_fullScreen", "icon-full-screen icon-exit-full-screen");
  6017. return Toolbar.toggleFullScreen();
  6018. },
  6019. "toolbar_button_sip": function () {
  6020. return callSipButtonClicked();
  6021. },
  6022. "toolbar_button_dialpad": function () {
  6023. return dialpadButtonClicked();
  6024. },
  6025. "toolbar_button_settings": function () {
  6026. PanelToggler.toggleSettingsMenu();
  6027. },
  6028. "toolbar_button_hangup": function () {
  6029. return hangup();
  6030. },
  6031. "toolbar_button_login": function () {
  6032. Toolbar.authenticateClicked();
  6033. },
  6034. "toolbar_button_logout": function () {
  6035. // Ask for confirmation
  6036. messageHandler.openTwoButtonDialog(
  6037. "dialog.logoutTitle",
  6038. null,
  6039. "dialog.logoutQuestion",
  6040. null,
  6041. false,
  6042. "dialog.Yes",
  6043. function (evt, yes) {
  6044. if (yes) {
  6045. APP.xmpp.logout(function (url) {
  6046. if (url) {
  6047. window.location.href = url;
  6048. } else {
  6049. hangup();
  6050. }
  6051. });
  6052. }
  6053. });
  6054. }
  6055. };
  6056. function hangup() {
  6057. APP.xmpp.disposeConference();
  6058. if(config.enableWelcomePage) {
  6059. setTimeout(function() {
  6060. window.localStorage.welcomePageDisabled = false;
  6061. window.location.pathname = "/";
  6062. }, 10000);
  6063. }
  6064. var title = APP.translation.generateTranslationHTML(
  6065. "dialog.sessTerminated");
  6066. var msg = APP.translation.generateTranslationHTML(
  6067. "dialog.hungUp");
  6068. var button = APP.translation.generateTranslationHTML(
  6069. "dialog.joinAgain");
  6070. var buttons = [];
  6071. buttons.push({title: button, value: true});
  6072. UI.messageHandler.openDialog(
  6073. title,
  6074. msg,
  6075. true,
  6076. buttons,
  6077. function(event, value, message, formVals) {
  6078. window.location.reload();
  6079. return false;
  6080. }
  6081. );
  6082. }
  6083. /**
  6084. * Starts or stops the recording for the conference.
  6085. */
  6086. function toggleRecording() {
  6087. APP.xmpp.toggleRecording(function (callback) {
  6088. var msg = APP.translation.generateTranslationHTML(
  6089. "dialog.recordingToken");
  6090. var token = APP.translation.translateString("dialog.token");
  6091. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  6092. '<h2>' + msg + '</h2>' +
  6093. '<input name="recordingToken" type="text" ' +
  6094. ' data-i18n="[placeholder]dialog.token" ' +
  6095. 'placeholder="' + token + '" autofocus>',
  6096. false,
  6097. "dialog.Save",
  6098. function (e, v, m, f) {
  6099. if (v) {
  6100. var token = f.recordingToken;
  6101. if (token) {
  6102. callback(UIUtil.escapeHtml(token));
  6103. }
  6104. }
  6105. },
  6106. null,
  6107. function () { },
  6108. ':input:first'
  6109. );
  6110. }, Toolbar.setRecordingButtonState, Toolbar.setRecordingButtonState);
  6111. }
  6112. /**
  6113. * Locks / unlocks the room.
  6114. */
  6115. function lockRoom(lock) {
  6116. var currentSharedKey = '';
  6117. if (lock)
  6118. currentSharedKey = sharedKey;
  6119. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  6120. // password is required
  6121. if (sharedKey) {
  6122. console.log('set room password');
  6123. Toolbar.lockLockButton();
  6124. }
  6125. else {
  6126. console.log('removed room password');
  6127. Toolbar.unlockLockButton();
  6128. }
  6129. }, function (err) {
  6130. console.warn('setting password failed', err);
  6131. messageHandler.showError("dialog.lockTitle",
  6132. "dialog.lockMessage");
  6133. Toolbar.setSharedKey('');
  6134. }, function () {
  6135. console.warn('room passwords not supported');
  6136. messageHandler.showError("dialog.warning",
  6137. "dialog.passwordNotSupported");
  6138. Toolbar.setSharedKey('');
  6139. });
  6140. }
  6141. /**
  6142. * Invite participants to conference.
  6143. */
  6144. function inviteParticipants() {
  6145. if (roomUrl === null)
  6146. return;
  6147. var sharedKeyText = "";
  6148. if (sharedKey && sharedKey.length > 0) {
  6149. sharedKeyText =
  6150. APP.translation.translateString("email.sharedKey",
  6151. {sharedKey: sharedKey});
  6152. sharedKeyText = sharedKeyText.replace(/\n/g, "%0D%0A");
  6153. }
  6154. var supportedBrowsers = "Chromium, Google Chrome " +
  6155. APP.translation.translateString("email.and") + " Opera";
  6156. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  6157. var subject = APP.translation.translateString("email.subject",
  6158. {appName:interfaceConfig.APP_NAME, conferenceName: conferenceName});
  6159. var body = APP.translation.translateString("email.body",
  6160. {appName:interfaceConfig.APP_NAME, sharedKeyText: sharedKeyText,
  6161. roomUrl: roomUrl, supportedBrowsers: supportedBrowsers});
  6162. body = body.replace(/\n/g, "%0D%0A");
  6163. if (window.localStorage.displayname) {
  6164. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  6165. }
  6166. if (interfaceConfig.INVITATION_POWERED_BY) {
  6167. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  6168. }
  6169. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  6170. }
  6171. function dialpadButtonClicked() {
  6172. //TODO show the dialpad box
  6173. }
  6174. function callSipButtonClicked() {
  6175. var defaultNumber
  6176. = config.defaultSipNumber ? config.defaultSipNumber : '';
  6177. var sipMsg = APP.translation.generateTranslationHTML(
  6178. "dialog.sipMsg");
  6179. messageHandler.openTwoButtonDialog(null, null, null,
  6180. '<h2>' + sipMsg + '</h2>' +
  6181. '<input name="sipNumber" type="text"' +
  6182. ' value="' + defaultNumber + '" autofocus>',
  6183. false,
  6184. "dialog.Dial",
  6185. function (e, v, m, f) {
  6186. if (v) {
  6187. var numberInput = f.sipNumber;
  6188. if (numberInput) {
  6189. APP.xmpp.dial(
  6190. numberInput, 'fromnumber', UI.getRoomName(), sharedKey);
  6191. }
  6192. }
  6193. },
  6194. null, null, ':input:first'
  6195. );
  6196. }
  6197. var Toolbar = (function (my) {
  6198. my.init = function (ui) {
  6199. for(var k in buttonHandlers)
  6200. $("#" + k).click(buttonHandlers[k]);
  6201. UI = ui;
  6202. // Update login info
  6203. APP.xmpp.addListener(
  6204. AuthenticationEvents.IDENTITY_UPDATED,
  6205. function (authenticationEnabled, userIdentity) {
  6206. var loggedIn = false;
  6207. if (userIdentity) {
  6208. loggedIn = true;
  6209. }
  6210. Toolbar.showAuthenticateButton(authenticationEnabled);
  6211. if (authenticationEnabled) {
  6212. Toolbar.setAuthenticatedIdentity(userIdentity);
  6213. Toolbar.showLoginButton(!loggedIn);
  6214. Toolbar.showLogoutButton(loggedIn);
  6215. }
  6216. }
  6217. );
  6218. };
  6219. /**
  6220. * Sets shared key
  6221. * @param sKey the shared key
  6222. */
  6223. my.setSharedKey = function (sKey) {
  6224. sharedKey = sKey;
  6225. };
  6226. my.authenticateClicked = function () {
  6227. Authentication.focusAuthenticationWindow();
  6228. if (!APP.xmpp.isExternalAuthEnabled()) {
  6229. Authentication.xmppAuthenticate();
  6230. return;
  6231. }
  6232. // Get authentication URL
  6233. if (!APP.xmpp.isMUCJoined()) {
  6234. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  6235. // If conference has not been started yet - redirect to login page
  6236. window.location.href = url;
  6237. });
  6238. } else {
  6239. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  6240. // Otherwise - open popup with authentication URL
  6241. var authenticationWindow = Authentication.createAuthenticationWindow(
  6242. function () {
  6243. // On popup closed - retry room allocation
  6244. APP.xmpp.allocateConferenceFocus(
  6245. APP.UI.getRoomName(),
  6246. function () { console.info("AUTH DONE"); }
  6247. );
  6248. }, url);
  6249. if (!authenticationWindow) {
  6250. messageHandler.openMessageDialog(
  6251. null, "dialog.popupError");
  6252. }
  6253. });
  6254. }
  6255. };
  6256. /**
  6257. * Updates the room invite url.
  6258. */
  6259. my.updateRoomUrl = function (newRoomUrl) {
  6260. roomUrl = newRoomUrl;
  6261. // If the invite dialog has been already opened we update the information.
  6262. var inviteLink = document.getElementById('inviteLinkRef');
  6263. if (inviteLink) {
  6264. inviteLink.value = roomUrl;
  6265. inviteLink.select();
  6266. $('#inviteLinkRef').parent()
  6267. .find('button[value=true]').prop('disabled', false);
  6268. }
  6269. };
  6270. /**
  6271. * Disables and enables some of the buttons.
  6272. */
  6273. my.setupButtonsFromConfig = function () {
  6274. if (config.disablePrezi) {
  6275. $("#toolbar_button_prezi").css({display: "none"});
  6276. }
  6277. };
  6278. /**
  6279. * Opens the lock room dialog.
  6280. */
  6281. my.openLockDialog = function () {
  6282. // Only the focus is able to set a shared key.
  6283. if (!APP.xmpp.isModerator()) {
  6284. if (sharedKey) {
  6285. messageHandler.openMessageDialog(null,
  6286. "dialog.passwordError");
  6287. } else {
  6288. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  6289. }
  6290. } else {
  6291. if (sharedKey) {
  6292. messageHandler.openTwoButtonDialog(null, null,
  6293. "dialog.passwordCheck",
  6294. null,
  6295. false,
  6296. "dialog.Remove",
  6297. function (e, v) {
  6298. if (v) {
  6299. Toolbar.setSharedKey('');
  6300. lockRoom(false);
  6301. }
  6302. });
  6303. } else {
  6304. var msg = APP.translation.generateTranslationHTML(
  6305. "dialog.passwordMsg");
  6306. var yourPassword = APP.translation.translateString(
  6307. "dialog.yourPassword");
  6308. messageHandler.openTwoButtonDialog(null, null, null,
  6309. '<h2>' + msg + '</h2>' +
  6310. '<input name="lockKey" type="text"' +
  6311. ' data-i18n="[placeholder]dialog.yourPassword" ' +
  6312. 'placeholder="' + yourPassword + '" autofocus>',
  6313. false,
  6314. "dialog.Save",
  6315. function (e, v, m, f) {
  6316. if (v) {
  6317. var lockKey = f.lockKey;
  6318. if (lockKey) {
  6319. Toolbar.setSharedKey(
  6320. UIUtil.escapeHtml(lockKey));
  6321. lockRoom(true);
  6322. }
  6323. }
  6324. },
  6325. null, null, 'input:first'
  6326. );
  6327. }
  6328. }
  6329. };
  6330. /**
  6331. * Opens the invite link dialog.
  6332. */
  6333. my.openLinkDialog = function () {
  6334. var inviteAttreibutes;
  6335. if (roomUrl === null) {
  6336. inviteAttreibutes = 'data-i18n="[value]roomUrlDefaultMsg" value="' +
  6337. APP.translation.translateString("roomUrlDefaultMsg") + '"';
  6338. } else {
  6339. inviteAttreibutes = "value=\"" + encodeURI(roomUrl) + "\"";
  6340. }
  6341. messageHandler.openTwoButtonDialog("dialog.shareLink",
  6342. null, null,
  6343. '<input id="inviteLinkRef" type="text" ' +
  6344. inviteAttreibutes + ' onclick="this.select();" readonly>',
  6345. false,
  6346. "dialog.Invite",
  6347. function (e, v) {
  6348. if (v) {
  6349. if (roomUrl) {
  6350. inviteParticipants();
  6351. }
  6352. }
  6353. },
  6354. function (event) {
  6355. if (roomUrl) {
  6356. document.getElementById('inviteLinkRef').select();
  6357. } else {
  6358. if (event && event.target)
  6359. $(event.target)
  6360. .find('button[value=true]').prop('disabled', true);
  6361. }
  6362. }
  6363. );
  6364. };
  6365. /**
  6366. * Opens the settings dialog.
  6367. * FIXME: not used ?
  6368. */
  6369. my.openSettingsDialog = function () {
  6370. var settings1 = APP.translation.generateTranslationHTML(
  6371. "dialog.settings1");
  6372. var settings2 = APP.translation.generateTranslationHTML(
  6373. "dialog.settings2");
  6374. var settings3 = APP.translation.generateTranslationHTML(
  6375. "dialog.settings3");
  6376. var yourPassword = APP.translation.translateString(
  6377. "dialog.yourPassword");
  6378. messageHandler.openTwoButtonDialog(null,
  6379. '<h2>' + settings1 + '</h2>' +
  6380. '<input type="checkbox" id="initMuted">' +
  6381. settings2 + '<br/>' +
  6382. '<input type="checkbox" id="requireNicknames">' +
  6383. settings3 +
  6384. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  6385. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  6386. null,
  6387. null,
  6388. false,
  6389. "dialog.Save",
  6390. function () {
  6391. document.getElementById('lockKey').focus();
  6392. },
  6393. function (e, v) {
  6394. if (v) {
  6395. if ($('#initMuted').is(":checked")) {
  6396. // it is checked
  6397. }
  6398. if ($('#requireNicknames').is(":checked")) {
  6399. // it is checked
  6400. }
  6401. /*
  6402. var lockKey = document.getElementById('lockKey');
  6403. if (lockKey.value) {
  6404. setSharedKey(lockKey.value);
  6405. lockRoom(true);
  6406. }
  6407. */
  6408. }
  6409. }
  6410. );
  6411. };
  6412. /**
  6413. * Toggles the application in and out of full screen mode
  6414. * (a.k.a. presentation mode in Chrome).
  6415. */
  6416. my.toggleFullScreen = function () {
  6417. var fsElement = document.documentElement;
  6418. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  6419. //Enter Full Screen
  6420. if (fsElement.mozRequestFullScreen) {
  6421. fsElement.mozRequestFullScreen();
  6422. }
  6423. else {
  6424. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  6425. }
  6426. } else {
  6427. //Exit Full Screen
  6428. if (document.mozCancelFullScreen) {
  6429. document.mozCancelFullScreen();
  6430. } else {
  6431. document.webkitCancelFullScreen();
  6432. }
  6433. }
  6434. };
  6435. /**
  6436. * Unlocks the lock button state.
  6437. */
  6438. my.unlockLockButton = function () {
  6439. if ($("#toolbar_button_security").hasClass("icon-security-locked"))
  6440. UIUtil.buttonClick("#toolbar_button_security", "icon-security icon-security-locked");
  6441. };
  6442. /**
  6443. * Updates the lock button state to locked.
  6444. */
  6445. my.lockLockButton = function () {
  6446. if ($("#toolbar_button_security").hasClass("icon-security"))
  6447. UIUtil.buttonClick("#toolbar_button_security", "icon-security icon-security-locked");
  6448. };
  6449. /**
  6450. * Shows or hides authentication button
  6451. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  6452. */
  6453. my.showAuthenticateButton = function (show) {
  6454. if (show) {
  6455. $('#authentication').css({display: "inline"});
  6456. }
  6457. else {
  6458. $('#authentication').css({display: "none"});
  6459. }
  6460. };
  6461. // Shows or hides the 'recording' button.
  6462. my.showRecordingButton = function (show) {
  6463. if (!config.enableRecording) {
  6464. return;
  6465. }
  6466. if (show) {
  6467. $('#toolbar_button_record').css({display: "inline"});
  6468. }
  6469. else {
  6470. $('#toolbar_button_record').css({display: "none"});
  6471. }
  6472. };
  6473. // Sets the state of the recording button
  6474. my.setRecordingButtonState = function (isRecording) {
  6475. var selector = $('#toolbar_button_record');
  6476. if (isRecording) {
  6477. selector.removeClass("icon-recEnable");
  6478. selector.addClass("icon-recEnable active");
  6479. } else {
  6480. selector.removeClass("icon-recEnable active");
  6481. selector.addClass("icon-recEnable");
  6482. }
  6483. };
  6484. // Shows or hides SIP calls button
  6485. my.showSipCallButton = function (show) {
  6486. if (APP.xmpp.isSipGatewayEnabled() && show) {
  6487. $('#toolbar_button_sip').css({display: "inline-block"});
  6488. } else {
  6489. $('#toolbar_button_sip').css({display: "none"});
  6490. }
  6491. };
  6492. // Shows or hides the dialpad button
  6493. my.showDialPadButton = function (show) {
  6494. if (show) {
  6495. $('#toolbar_button_dialpad').css({display: "inline-block"});
  6496. } else {
  6497. $('#toolbar_button_dialpad').css({display: "none"});
  6498. }
  6499. };
  6500. /**
  6501. * Displays user authenticated identity name(login).
  6502. * @param authIdentity identity name to be displayed.
  6503. */
  6504. my.setAuthenticatedIdentity = function (authIdentity) {
  6505. if (authIdentity) {
  6506. var selector = $('#toolbar_auth_identity');
  6507. selector.css({display: "list-item"});
  6508. selector.text(authIdentity);
  6509. } else {
  6510. $('#toolbar_auth_identity').css({display: "none"});
  6511. }
  6512. };
  6513. /**
  6514. * Shows/hides login button.
  6515. * @param show <tt>true</tt> to show
  6516. */
  6517. my.showLoginButton = function (show) {
  6518. if (show) {
  6519. $('#toolbar_button_login').css({display: "list-item"});
  6520. } else {
  6521. $('#toolbar_button_login').css({display: "none"});
  6522. }
  6523. };
  6524. /**
  6525. * Shows/hides logout button.
  6526. * @param show <tt>true</tt> to show
  6527. */
  6528. my.showLogoutButton = function (show) {
  6529. if (show) {
  6530. $('#toolbar_button_logout').css({display: "list-item"});
  6531. } else {
  6532. $('#toolbar_button_logout').css({display: "none"});
  6533. }
  6534. };
  6535. /**
  6536. * Sets the state of the button. The button has blue glow if desktop
  6537. * streaming is active.
  6538. * @param active the state of the desktop streaming.
  6539. */
  6540. my.changeDesktopSharingButtonState = function (active) {
  6541. var button = $("#toolbar_button_desktopsharing");
  6542. if (active) {
  6543. button.addClass("glow");
  6544. } else {
  6545. button.removeClass("glow");
  6546. }
  6547. };
  6548. return my;
  6549. }(Toolbar || {}));
  6550. module.exports = Toolbar;
  6551. },{"../../../service/authentication/AuthenticationEvents":114,"../authentication/Authentication":16,"../etherpad/Etherpad":19,"../prezi/Prezi":20,"../side_pannels/SidePanelToggler":22,"../util/MessageHandler":33,"../util/UIUtil":35,"./BottomToolbar":29}],31:[function(require,module,exports){
  6552. /* global APP, config, $, interfaceConfig, Moderator,
  6553. DesktopStreaming.showDesktopSharingButton */
  6554. var toolbarTimeoutObject,
  6555. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  6556. function showDesktopSharingButton() {
  6557. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  6558. $('#toolbar_button_desktopsharing').css({display: "inline"});
  6559. } else {
  6560. $('#toolbar_button_desktopsharing').css({display: "none"});
  6561. }
  6562. }
  6563. /**
  6564. * Hides the toolbar.
  6565. */
  6566. function hideToolbar() {
  6567. if(config.alwaysVisibleToolbar)
  6568. return;
  6569. var header = $("#header"),
  6570. bottomToolbar = $("#bottomToolbar");
  6571. var isToolbarHover = false;
  6572. header.find('*').each(function () {
  6573. var id = $(this).attr('id');
  6574. if ($("#" + id + ":hover").length > 0) {
  6575. isToolbarHover = true;
  6576. }
  6577. });
  6578. if ($("#bottomToolbar:hover").length > 0) {
  6579. isToolbarHover = true;
  6580. }
  6581. clearTimeout(toolbarTimeoutObject);
  6582. toolbarTimeoutObject = null;
  6583. if (!isToolbarHover) {
  6584. header.hide("slide", { direction: "up", duration: 300});
  6585. $('#subject').animate({top: "-=40"}, 300);
  6586. if ($("#remoteVideos").hasClass("hidden")) {
  6587. bottomToolbar.hide(
  6588. "slide", {direction: "right", duration: 300});
  6589. }
  6590. }
  6591. else {
  6592. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6593. }
  6594. }
  6595. var ToolbarToggler = {
  6596. /**
  6597. * Shows the main toolbar.
  6598. */
  6599. showToolbar: function () {
  6600. var header = $("#header"),
  6601. bottomToolbar = $("#bottomToolbar");
  6602. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  6603. header.show("slide", { direction: "up", duration: 300});
  6604. $('#subject').animate({top: "+=40"}, 300);
  6605. if (!bottomToolbar.is(":visible")) {
  6606. bottomToolbar.show(
  6607. "slide", {direction: "right", duration: 300});
  6608. }
  6609. if (toolbarTimeoutObject) {
  6610. clearTimeout(toolbarTimeoutObject);
  6611. toolbarTimeoutObject = null;
  6612. }
  6613. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6614. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  6615. }
  6616. if (APP.xmpp.isModerator())
  6617. {
  6618. // TODO: Enable settings functionality.
  6619. // Need to uncomment the settings button in index.html.
  6620. // $('#settingsButton').css({visibility:"visible"});
  6621. }
  6622. // Show/hide desktop sharing button
  6623. showDesktopSharingButton();
  6624. },
  6625. /**
  6626. * Docks/undocks the toolbar.
  6627. *
  6628. * @param isDock indicates what operation to perform
  6629. */
  6630. dockToolbar: function (isDock) {
  6631. if (isDock) {
  6632. // First make sure the toolbar is shown.
  6633. if (!$('#header').is(':visible')) {
  6634. this.showToolbar();
  6635. }
  6636. // Then clear the time out, to dock the toolbar.
  6637. if (toolbarTimeoutObject) {
  6638. clearTimeout(toolbarTimeoutObject);
  6639. toolbarTimeoutObject = null;
  6640. }
  6641. }
  6642. else {
  6643. if (!$('#header').is(':visible')) {
  6644. this.showToolbar();
  6645. }
  6646. else {
  6647. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6648. }
  6649. }
  6650. },
  6651. showDesktopSharingButton: showDesktopSharingButton
  6652. };
  6653. module.exports = ToolbarToggler;
  6654. },{}],32:[function(require,module,exports){
  6655. /* global $ */
  6656. var JitsiPopover = (function () {
  6657. /**
  6658. * Constructs new JitsiPopover and attaches it to the element
  6659. * @param element jquery selector
  6660. * @param options the options for the popover.
  6661. * @constructor
  6662. */
  6663. function JitsiPopover(element, options)
  6664. {
  6665. this.options = {
  6666. skin: "white",
  6667. content: ""
  6668. };
  6669. if(options)
  6670. {
  6671. if(options.skin)
  6672. this.options.skin = options.skin;
  6673. if(options.content)
  6674. this.options.content = options.content;
  6675. }
  6676. this.elementIsHovered = false;
  6677. this.popoverIsHovered = false;
  6678. this.popoverShown = false;
  6679. element.data("jitsi_popover", this);
  6680. this.element = element;
  6681. this.template = ' <div class="jitsipopover ' + this.options.skin +
  6682. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  6683. '<div class="jitsiPopupmenuPadding"></div></div>';
  6684. var self = this;
  6685. this.element.on("mouseenter", function () {
  6686. self.elementIsHovered = true;
  6687. self.show();
  6688. }).on("mouseleave", function () {
  6689. self.elementIsHovered = false;
  6690. setTimeout(function () {
  6691. self.hide();
  6692. }, 10);
  6693. });
  6694. }
  6695. /**
  6696. * Shows the popover
  6697. */
  6698. JitsiPopover.prototype.show = function () {
  6699. this.createPopover();
  6700. this.popoverShown = true;
  6701. };
  6702. /**
  6703. * Hides the popover
  6704. */
  6705. JitsiPopover.prototype.hide = function () {
  6706. if(!this.elementIsHovered && !this.popoverIsHovered &&
  6707. this.popoverShown) {
  6708. this.forceHide();
  6709. }
  6710. };
  6711. /**
  6712. * Hides the popover.
  6713. */
  6714. JitsiPopover.prototype.forceHide = function () {
  6715. $(".jitsipopover").remove();
  6716. this.popoverShown = false;
  6717. };
  6718. /**
  6719. * Creates the popover html.
  6720. */
  6721. JitsiPopover.prototype.createPopover = function () {
  6722. $("body").append(this.template);
  6723. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  6724. var self = this;
  6725. $(".jitsipopover").on("mouseenter", function () {
  6726. self.popoverIsHovered = true;
  6727. }).on("mouseleave", function () {
  6728. self.popoverIsHovered = false;
  6729. self.hide();
  6730. });
  6731. this.refreshPosition();
  6732. };
  6733. /**
  6734. * Refreshes the position of the popover.
  6735. */
  6736. JitsiPopover.prototype.refreshPosition = function () {
  6737. $(".jitsipopover").position({
  6738. my: "bottom",
  6739. at: "top",
  6740. collision: "fit",
  6741. of: this.element,
  6742. using: function (position, elements) {
  6743. var calcLeft = elements.target.left - elements.element.left +
  6744. elements.target.width/2;
  6745. $(".jitsipopover").css(
  6746. {top: position.top, left: position.left, display: "table"});
  6747. $(".jitsipopover > .arrow").css({left: calcLeft});
  6748. $(".jitsipopover > .jitsiPopupmenuPadding").css(
  6749. {left: calcLeft - 50});
  6750. }
  6751. });
  6752. };
  6753. /**
  6754. * Updates the content of popover.
  6755. * @param content new content
  6756. */
  6757. JitsiPopover.prototype.updateContent = function (content) {
  6758. this.options.content = content;
  6759. if(!this.popoverShown)
  6760. return;
  6761. $(".jitsipopover").remove();
  6762. this.createPopover();
  6763. };
  6764. return JitsiPopover;
  6765. })();
  6766. module.exports = JitsiPopover;
  6767. },{}],33:[function(require,module,exports){
  6768. /* global $, APP, jQuery, toastr */
  6769. var messageHandler = (function(my) {
  6770. /**
  6771. * Shows a message to the user.
  6772. *
  6773. * @param titleKey the title of the message
  6774. * @param messageKey the text of the message
  6775. */
  6776. my.openMessageDialog = function(titleKey, messageKey) {
  6777. var title = null;
  6778. if(titleKey) {
  6779. title = APP.translation.generateTranslationHTML(titleKey);
  6780. }
  6781. var message = APP.translation.generateTranslationHTML(messageKey);
  6782. $.prompt(message,
  6783. {title: title, persistent: false}
  6784. );
  6785. };
  6786. /**
  6787. * Shows a message to the user with two buttons: first is given as a
  6788. * parameter and the second is Cancel.
  6789. *
  6790. * @param titleString the title of the message
  6791. * @param msgString the text of the message
  6792. * @param persistent boolean value which determines whether the message is
  6793. * persistent or not
  6794. * @param leftButton the fist button's text
  6795. * @param submitFunction function to be called on submit
  6796. * @param loadedFunction function to be called after the prompt is fully
  6797. * loaded
  6798. * @param closeFunction function to be called after the prompt is closed
  6799. * @param focus optional focus selector or button index to be focused after
  6800. * the dialog is opened
  6801. * @param defaultButton index of default button which will be activated when
  6802. * the user press 'enter'. Indexed from 0.
  6803. */
  6804. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  6805. persistent, leftButtonKey, submitFunction, loadedFunction,
  6806. closeFunction, focus, defaultButton) {
  6807. var buttons = [];
  6808. var leftButton = APP.translation.generateTranslationHTML(leftButtonKey);
  6809. buttons.push({ title: leftButton, value: true});
  6810. var cancelButton
  6811. = APP.translation.generateTranslationHTML("dialog.Cancel");
  6812. buttons.push({title: cancelButton, value: false});
  6813. var message = msgString, title = titleString;
  6814. if (titleKey) {
  6815. title = APP.translation.generateTranslationHTML(titleKey);
  6816. }
  6817. if (msgKey) {
  6818. message = APP.translation.generateTranslationHTML(msgKey);
  6819. }
  6820. $.prompt(message, {
  6821. title: title,
  6822. persistent: false,
  6823. buttons: buttons,
  6824. defaultButton: defaultButton,
  6825. focus: focus,
  6826. loaded: loadedFunction,
  6827. submit: submitFunction,
  6828. close: closeFunction
  6829. });
  6830. };
  6831. /**
  6832. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  6833. *
  6834. * @param titleString the title of the message
  6835. * @param msgString the text of the message
  6836. * @param persistent boolean value which determines whether the message is
  6837. * persistent or not
  6838. * @param buttons object with the buttons. The keys must be the name of the
  6839. * button and value is the value that will be passed to
  6840. * submitFunction
  6841. * @param submitFunction function to be called on submit
  6842. * @param loadedFunction function to be called after the prompt is fully
  6843. * loaded
  6844. */
  6845. my.openDialog = function (titleString, msgString, persistent, buttons,
  6846. submitFunction, loadedFunction) {
  6847. var args = {
  6848. title: titleString,
  6849. persistent: persistent,
  6850. buttons: buttons,
  6851. defaultButton: 1,
  6852. loaded: loadedFunction,
  6853. submit: submitFunction
  6854. };
  6855. if (persistent) {
  6856. args.closeText = '';
  6857. }
  6858. return new Impromptu(msgString, args);
  6859. };
  6860. /**
  6861. * Closes currently opened dialog.
  6862. */
  6863. my.closeDialog = function () {
  6864. $.prompt.close();
  6865. };
  6866. /**
  6867. * Shows a dialog with different states to the user.
  6868. *
  6869. * @param statesObject object containing all the states of the dialog.
  6870. */
  6871. my.openDialogWithStates = function (statesObject, options) {
  6872. return new Impromptu(statesObject, options);
  6873. };
  6874. /**
  6875. * Opens new popup window for given <tt>url</tt> centered over current
  6876. * window.
  6877. *
  6878. * @param url the URL to be displayed in the popup window
  6879. * @param w the width of the popup window
  6880. * @param h the height of the popup window
  6881. * @param onPopupClosed optional callback function called when popup window
  6882. * has been closed.
  6883. *
  6884. * @returns {object} popup window object if opened successfully or undefined
  6885. * in case we failed to open it(popup blocked)
  6886. */
  6887. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  6888. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  6889. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  6890. var popup = window.open(
  6891. url, '_blank',
  6892. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  6893. if (popup && onPopupClosed) {
  6894. var pollTimer = window.setInterval(function () {
  6895. if (popup.closed !== false) {
  6896. window.clearInterval(pollTimer);
  6897. onPopupClosed();
  6898. }
  6899. }, 200);
  6900. }
  6901. return popup;
  6902. };
  6903. /**
  6904. * Shows a dialog prompting the user to send an error report.
  6905. *
  6906. * @param titleKey the title of the message
  6907. * @param msgKey the text of the message
  6908. * @param error the error that is being reported
  6909. */
  6910. my.openReportDialog = function(titleKey, msgKey, error) {
  6911. my.openMessageDialog(titleKey, msgKey);
  6912. console.log(error);
  6913. //FIXME send the error to the server
  6914. };
  6915. /**
  6916. * Shows an error dialog to the user.
  6917. * @param titleKey the title of the message.
  6918. * @param msgKey the text of the message.
  6919. */
  6920. my.showError = function(titleKey, msgKey) {
  6921. if (!titleKey) {
  6922. titleKey = "dialog.oops";
  6923. }
  6924. if (!msgKey) {
  6925. msgKey = "dialog.defaultError";
  6926. }
  6927. messageHandler.openMessageDialog(titleKey, msgKey);
  6928. };
  6929. my.notify = function(displayName, displayNameKey,
  6930. cls, messageKey, messageArguments, options) {
  6931. var displayNameSpan = '<span class="nickname" ';
  6932. if (displayName) {
  6933. displayNameSpan += ">" + displayName;
  6934. } else {
  6935. displayNameSpan += "data-i18n='" + displayNameKey +
  6936. "'>" + APP.translation.translateString(displayNameKey);
  6937. }
  6938. displayNameSpan += "</span>";
  6939. toastr.info(
  6940. displayNameSpan + '<br>' +
  6941. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  6942. (messageArguments?
  6943. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  6944. : "") + ">" +
  6945. APP.translation.translateString(messageKey,
  6946. messageArguments) +
  6947. '</span>', null, options);
  6948. };
  6949. return my;
  6950. }(messageHandler || {}));
  6951. module.exports = messageHandler;
  6952. },{}],34:[function(require,module,exports){
  6953. var UIEvents = require("../../../service/UI/UIEvents");
  6954. var nickname = null;
  6955. var eventEmitter = null;
  6956. var NicknameHandler = {
  6957. init: function (emitter) {
  6958. eventEmitter = emitter;
  6959. var storedDisplayName = window.localStorage.displayname;
  6960. if (storedDisplayName) {
  6961. nickname = storedDisplayName;
  6962. }
  6963. },
  6964. setNickname: function (newNickname) {
  6965. if (!newNickname || nickname === newNickname)
  6966. return;
  6967. nickname = newNickname;
  6968. window.localStorage.displayname = nickname;
  6969. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  6970. },
  6971. getNickname: function () {
  6972. return nickname;
  6973. },
  6974. addListener: function (type, listener) {
  6975. eventEmitter.on(type, listener);
  6976. }
  6977. };
  6978. module.exports = NicknameHandler;
  6979. },{"../../../service/UI/UIEvents":113}],35:[function(require,module,exports){
  6980. /* global $ */
  6981. /**
  6982. * Created by hristo on 12/22/14.
  6983. */
  6984. module.exports = {
  6985. /**
  6986. * Returns the available video width.
  6987. */
  6988. getAvailableVideoWidth: function (isVisible) {
  6989. var PanelToggler = require("../side_pannels/SidePanelToggler");
  6990. if(typeof isVisible === "undefined" || isVisible === null)
  6991. isVisible = PanelToggler.isVisible();
  6992. var rightPanelWidth
  6993. = isVisible ? PanelToggler.getPanelSize()[0] : 0;
  6994. return window.innerWidth - rightPanelWidth;
  6995. },
  6996. /**
  6997. * Changes the style class of the element given by id.
  6998. */
  6999. buttonClick: function(id, classname) {
  7000. $(id).toggleClass(classname); // add the class to the clicked element
  7001. },
  7002. /**
  7003. * Returns the text width for the given element.
  7004. *
  7005. * @param el the element
  7006. */
  7007. getTextWidth: function (el) {
  7008. return (el.clientWidth + 1);
  7009. },
  7010. /**
  7011. * Returns the text height for the given element.
  7012. *
  7013. * @param el the element
  7014. */
  7015. getTextHeight: function (el) {
  7016. return (el.clientHeight + 1);
  7017. },
  7018. /**
  7019. * Plays the sound given by id.
  7020. *
  7021. * @param id the identifier of the audio element.
  7022. */
  7023. playSoundNotification: function (id) {
  7024. document.getElementById(id).play();
  7025. },
  7026. /**
  7027. * Escapes the given text.
  7028. */
  7029. escapeHtml: function (unsafeText) {
  7030. return $('<div/>').text(unsafeText).html();
  7031. },
  7032. imageToGrayScale: function (canvas) {
  7033. var context = canvas.getContext('2d');
  7034. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  7035. var pixels = imgData.data;
  7036. for (var i = 0, n = pixels.length; i < n; i += 4) {
  7037. var grayscale
  7038. = pixels[i] * 0.3 + pixels[i+1] * 0.59 + pixels[i+2] * 0.11;
  7039. pixels[i ] = grayscale; // red
  7040. pixels[i+1] = grayscale; // green
  7041. pixels[i+2] = grayscale; // blue
  7042. // pixels[i+3] is alpha
  7043. }
  7044. // redraw the image in black & white
  7045. context.putImageData(imgData, 0, 0);
  7046. },
  7047. setTooltip: function (element, key, position) {
  7048. element.setAttribute("data-i18n", "[data-content]" + key);
  7049. element.setAttribute("data-toggle", "popover");
  7050. element.setAttribute("data-placement", position);
  7051. element.setAttribute("data-html", true);
  7052. element.setAttribute("data-container", "body");
  7053. }
  7054. };
  7055. },{"../side_pannels/SidePanelToggler":22}],36:[function(require,module,exports){
  7056. /* global APP, $ */
  7057. var JitsiPopover = require("../util/JitsiPopover");
  7058. /**
  7059. * Constructs new connection indicator.
  7060. * @param videoContainer the video container associated with the indicator.
  7061. * @constructor
  7062. */
  7063. function ConnectionIndicator(videoContainer, jid) {
  7064. this.videoContainer = videoContainer;
  7065. this.bandwidth = null;
  7066. this.packetLoss = null;
  7067. this.bitrate = null;
  7068. this.showMoreValue = false;
  7069. this.resolution = null;
  7070. this.transport = [];
  7071. this.popover = null;
  7072. this.jid = jid;
  7073. this.create();
  7074. }
  7075. /**
  7076. * Values for the connection quality
  7077. * @type {{98: string,
  7078. * 81: string,
  7079. * 64: string,
  7080. * 47: string,
  7081. * 30: string,
  7082. * 0: string}}
  7083. */
  7084. ConnectionIndicator.connectionQualityValues = {
  7085. 98: "18px", //full
  7086. 81: "15px",//4 bars
  7087. 64: "11px",//3 bars
  7088. 47: "7px",//2 bars
  7089. 30: "3px",//1 bar
  7090. 0: "0px"//empty
  7091. };
  7092. ConnectionIndicator.getIP = function(value) {
  7093. return value.substring(0, value.lastIndexOf(":"));
  7094. };
  7095. ConnectionIndicator.getPort = function(value) {
  7096. return value.substring(value.lastIndexOf(":") + 1, value.length);
  7097. };
  7098. ConnectionIndicator.getStringFromArray = function (array) {
  7099. var res = "";
  7100. for(var i = 0; i < array.length; i++) {
  7101. res += (i === 0? "" : ", ") + array[i];
  7102. }
  7103. return res;
  7104. };
  7105. /**
  7106. * Generates the html content.
  7107. * @returns {string} the html content.
  7108. */
  7109. ConnectionIndicator.prototype.generateText = function () {
  7110. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  7111. var translate = APP.translation.translateString;
  7112. if(this.bitrate === null) {
  7113. downloadBitrate = "N/A";
  7114. uploadBitrate = "N/A";
  7115. }
  7116. else {
  7117. downloadBitrate =
  7118. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  7119. uploadBitrate =
  7120. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  7121. }
  7122. if(this.packetLoss === null) {
  7123. packetLoss = "N/A";
  7124. } else {
  7125. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  7126. (this.packetLoss.download !== null ?
  7127. this.packetLoss.download : "N/A") +
  7128. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  7129. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") +
  7130. "%";
  7131. }
  7132. var resolutionValue = null;
  7133. if(this.resolution && this.jid != null) {
  7134. var keys = Object.keys(this.resolution);
  7135. for(var ssrc in this.resolution) {
  7136. resolutionValue = this.resolution[ssrc];
  7137. }
  7138. }
  7139. if(this.jid === null) {
  7140. resolution = "";
  7141. if(this.resolution === null || !Object.keys(this.resolution) ||
  7142. Object.keys(this.resolution).length === 0) {
  7143. resolution = "N/A";
  7144. } else {
  7145. for (i in this.resolution) {
  7146. resolutionValue = this.resolution[i];
  7147. if (resolutionValue) {
  7148. if (resolutionValue.height &&
  7149. resolutionValue.width) {
  7150. resolution += (resolution === "" ? "" : ", ") +
  7151. resolutionValue.width + "x" +
  7152. resolutionValue.height;
  7153. }
  7154. }
  7155. }
  7156. }
  7157. } else if(!resolutionValue ||
  7158. !resolutionValue.height ||
  7159. !resolutionValue.width) {
  7160. resolution = "N/A";
  7161. } else {
  7162. resolution = resolutionValue.width + "x" + resolutionValue.height;
  7163. }
  7164. var result = "<table style='width:100%'>" +
  7165. "<tr>" +
  7166. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  7167. translate("connectionindicator.bitrate") + "</span></td>" +
  7168. "<td><span class='jitsipopover_green'>&darr;</span>" +
  7169. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  7170. uploadBitrate + "</td>" +
  7171. "</tr><tr>" +
  7172. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  7173. translate("connectionindicator.packetloss") + "</span></td>" +
  7174. "<td>" + packetLoss + "</td>" +
  7175. "</tr><tr>" +
  7176. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  7177. translate("connectionindicator.resolution") + "</span></td>" +
  7178. "<td>" + resolution + "</td></tr></table>";
  7179. if(this.videoContainer.videoSpanId == "localVideoContainer") {
  7180. result += "<div class=\"jitsipopover_showmore\" " +
  7181. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  7182. // FIXME: we do not know local jid when this text is generated
  7183. //this.jid + "')\" data-i18n='connectionindicator." +
  7184. "local')\" data-i18n='connectionindicator." +
  7185. (this.showMoreValue ? "less" : "more") + "'>" +
  7186. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  7187. "</div><br />";
  7188. }
  7189. if (this.showMoreValue) {
  7190. var downloadBandwidth, uploadBandwidth, transport;
  7191. if (this.bandwidth === null) {
  7192. downloadBandwidth = "N/A";
  7193. uploadBandwidth = "N/A";
  7194. } else {
  7195. downloadBandwidth = this.bandwidth.download?
  7196. this.bandwidth.download + " Kbps" :
  7197. "N/A";
  7198. uploadBandwidth = this.bandwidth.upload?
  7199. this.bandwidth.upload + " Kbps" :
  7200. "N/A";
  7201. }
  7202. if (!this.transport || this.transport.length === 0) {
  7203. transport = "<tr>" +
  7204. "<td><span class='jitsipopover_blue' " +
  7205. "data-i18n='connectionindicator.address'>" +
  7206. translate("connectionindicator.address") + "</span></td>" +
  7207. "<td> N/A</td></tr>";
  7208. } else {
  7209. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  7210. for(i = 0; i < this.transport.length; i++) {
  7211. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  7212. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  7213. var localIP =
  7214. ConnectionIndicator.getIP(this.transport[i].localip);
  7215. var localPort =
  7216. ConnectionIndicator.getPort(this.transport[i].localip);
  7217. if(data.remoteIP.indexOf(ip) == -1) {
  7218. data.remoteIP.push(ip);
  7219. }
  7220. if(data.remotePort.indexOf(port) == -1) {
  7221. data.remotePort.push(port);
  7222. }
  7223. if(data.localIP.indexOf(localIP) == -1) {
  7224. data.localIP.push(localIP);
  7225. }
  7226. if(data.localPort.indexOf(localPort) == -1) {
  7227. data.localPort.push(localPort);
  7228. }
  7229. }
  7230. var local_address_key = "connectionindicator.localaddress";
  7231. var remote_address_key = "connectionindicator.remoteaddress";
  7232. var localTransport =
  7233. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  7234. local_address_key +"' data-i18n-options='" +
  7235. JSON.stringify({count: data.localIP.length}) + "'>" +
  7236. translate(local_address_key, {count: data.localIP.length}) +
  7237. "</span></td><td> " +
  7238. ConnectionIndicator.getStringFromArray(data.localIP) +
  7239. "</td></tr>";
  7240. transport =
  7241. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  7242. remote_address_key + "' data-i18n-options='" +
  7243. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  7244. translate(remote_address_key,
  7245. {count: data.remoteIP.length}) +
  7246. "</span></td><td> " +
  7247. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  7248. "</td></tr>";
  7249. var key_remote = "connectionindicator.remoteport",
  7250. key_local = "connectionindicator.localport";
  7251. transport += "<tr>" +
  7252. "<td>" +
  7253. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  7254. "' data-i18n-options='" +
  7255. JSON.stringify({count: this.transport.length}) + "'>" +
  7256. translate(key_remote, {count: this.transport.length}) +
  7257. "</span></td><td>";
  7258. localTransport += "<tr>" +
  7259. "<td>" +
  7260. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  7261. "' data-i18n-options='" +
  7262. JSON.stringify({count: this.transport.length}) + "'>" +
  7263. translate(key_local, {count: this.transport.length}) +
  7264. "</span></td><td>";
  7265. transport +=
  7266. ConnectionIndicator.getStringFromArray(data.remotePort);
  7267. localTransport +=
  7268. ConnectionIndicator.getStringFromArray(data.localPort);
  7269. transport += "</td></tr>";
  7270. transport += localTransport + "</td></tr>";
  7271. transport +="<tr>" +
  7272. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  7273. translate("connectionindicator.transport") + "</span></td>" +
  7274. "<td>" + this.transport[0].type + "</td></tr>";
  7275. }
  7276. result += "<table style='width:100%'>" +
  7277. "<tr>" +
  7278. "<td>" +
  7279. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  7280. translate("connectionindicator.bandwidth") + "</span>" +
  7281. "</td><td>" +
  7282. "<span class='jitsipopover_green'>&darr;</span>" +
  7283. downloadBandwidth +
  7284. " <span class='jitsipopover_orange'>&uarr;</span>" +
  7285. uploadBandwidth + "</td></tr>";
  7286. result += transport + "</table>";
  7287. }
  7288. return result;
  7289. };
  7290. /**
  7291. * Shows or hide the additional information.
  7292. */
  7293. ConnectionIndicator.prototype.showMore = function () {
  7294. this.showMoreValue = !this.showMoreValue;
  7295. this.updatePopoverData();
  7296. };
  7297. function createIcon(classes) {
  7298. var icon = document.createElement("span");
  7299. for(var i in classes) {
  7300. icon.classList.add(classes[i]);
  7301. }
  7302. icon.appendChild(
  7303. document.createElement("i")).classList.add("icon-connection");
  7304. return icon;
  7305. }
  7306. /**
  7307. * Creates the indicator
  7308. */
  7309. ConnectionIndicator.prototype.create = function () {
  7310. this.connectionIndicatorContainer = document.createElement("div");
  7311. this.connectionIndicatorContainer.className = "connectionindicator";
  7312. this.connectionIndicatorContainer.style.display = "none";
  7313. this.videoContainer.container.appendChild(
  7314. this.connectionIndicatorContainer);
  7315. this.popover = new JitsiPopover(
  7316. $("#" + this.videoContainer.videoSpanId + " > .connectionindicator"),
  7317. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  7318. APP.translation.translateString("connectionindicator.na") + "</div>",
  7319. skin: "black"});
  7320. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  7321. createIcon(["connection", "connection_empty"]));
  7322. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  7323. createIcon(["connection", "connection_full"]));
  7324. };
  7325. /**
  7326. * Removes the indicator
  7327. */
  7328. ConnectionIndicator.prototype.remove = function() {
  7329. if (this.connectionIndicatorContainer.parentNode) {
  7330. this.connectionIndicatorContainer.parentNode.removeChild(
  7331. this.connectionIndicatorContainer);
  7332. }
  7333. this.popover.forceHide();
  7334. };
  7335. /**
  7336. * Updates the data of the indicator
  7337. * @param percent the percent of connection quality
  7338. * @param object the statistics data.
  7339. */
  7340. ConnectionIndicator.prototype.updateConnectionQuality =
  7341. function (percent, object) {
  7342. if (percent === null) {
  7343. this.connectionIndicatorContainer.style.display = "none";
  7344. this.popover.forceHide();
  7345. return;
  7346. } else {
  7347. if(this.connectionIndicatorContainer.style.display == "none") {
  7348. this.connectionIndicatorContainer.style.display = "block";
  7349. this.videoContainer.updateIconPositions();
  7350. }
  7351. }
  7352. this.bandwidth = object.bandwidth;
  7353. this.bitrate = object.bitrate;
  7354. this.packetLoss = object.packetLoss;
  7355. this.transport = object.transport;
  7356. if (object.resolution) {
  7357. this.resolution = object.resolution;
  7358. }
  7359. for (var quality in ConnectionIndicator.connectionQualityValues) {
  7360. if (percent >= quality) {
  7361. this.fullIcon.style.width =
  7362. ConnectionIndicator.connectionQualityValues[quality];
  7363. }
  7364. }
  7365. this.updatePopoverData();
  7366. };
  7367. /**
  7368. * Updates the resolution
  7369. * @param resolution the new resolution
  7370. */
  7371. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  7372. this.resolution = resolution;
  7373. this.updatePopoverData();
  7374. };
  7375. /**
  7376. * Updates the content of the popover
  7377. */
  7378. ConnectionIndicator.prototype.updatePopoverData = function () {
  7379. this.popover.updateContent(
  7380. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  7381. APP.translation.translateElement($(".connection_info"));
  7382. };
  7383. /**
  7384. * Hides the popover
  7385. */
  7386. ConnectionIndicator.prototype.hide = function () {
  7387. this.popover.forceHide();
  7388. };
  7389. /**
  7390. * Hides the indicator
  7391. */
  7392. ConnectionIndicator.prototype.hideIndicator = function () {
  7393. this.connectionIndicatorContainer.style.display = "none";
  7394. if(this.popover)
  7395. this.popover.forceHide();
  7396. };
  7397. module.exports = ConnectionIndicator;
  7398. },{"../util/JitsiPopover":32}],37:[function(require,module,exports){
  7399. /* global $, APP, Strophe, interfaceConfig */
  7400. var Avatar = require("../avatar/Avatar");
  7401. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7402. var UIUtil = require("../util/UIUtil");
  7403. var UIEvents = require("../../../service/UI/UIEvents");
  7404. var xmpp = require("../../xmpp/xmpp");
  7405. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  7406. // FIXME: With Temasys we have to re-select everytime
  7407. //var video = $('#largeVideo');
  7408. var currentVideoWidth = null;
  7409. var currentVideoHeight = null;
  7410. // By default we use camera
  7411. var getVideoSize = getCameraVideoSize;
  7412. var getVideoPosition = getCameraVideoPosition;
  7413. /**
  7414. * The small video instance that is displayed in the large video
  7415. * @type {SmallVideo}
  7416. */
  7417. var currentSmallVideo = null;
  7418. /**
  7419. * Indicates whether the large video is enabled.
  7420. * @type {boolean}
  7421. */
  7422. var isEnabled = true;
  7423. /**
  7424. * Current large video state.
  7425. * Possible values - video, prezi or etherpad.
  7426. * @type {string}
  7427. */
  7428. var state = "video";
  7429. /**
  7430. * Returns the html element associated with the passed state of large video
  7431. * @param state the state.
  7432. * @returns {JQuery|*|jQuery|HTMLElement} the container.
  7433. */
  7434. function getContainerByState(state)
  7435. {
  7436. var selector = null;
  7437. switch (state)
  7438. {
  7439. case "video":
  7440. selector = "#largeVideo";
  7441. break;
  7442. case "etherpad":
  7443. selector = "#etherpad>iframe";
  7444. break;
  7445. case "prezi":
  7446. selector = "#presentation>iframe";
  7447. break;
  7448. }
  7449. return (selector !== null)? $(selector) : null;
  7450. }
  7451. /**
  7452. * Sets the size and position of the given video element.
  7453. *
  7454. * @param video the video element to position
  7455. * @param width the desired video width
  7456. * @param height the desired video height
  7457. * @param horizontalIndent the left and right indent
  7458. * @param verticalIndent the top and bottom indent
  7459. */
  7460. function positionVideo(video,
  7461. width,
  7462. height,
  7463. horizontalIndent,
  7464. verticalIndent,
  7465. animate) {
  7466. if (animate) {
  7467. video.animate({
  7468. width: width,
  7469. height: height,
  7470. top: verticalIndent,
  7471. bottom: verticalIndent,
  7472. left: horizontalIndent,
  7473. right: horizontalIndent
  7474. },
  7475. {
  7476. queue: false,
  7477. duration: 500
  7478. });
  7479. } else {
  7480. video.width(width);
  7481. video.height(height);
  7482. video.css({ top: verticalIndent + 'px',
  7483. bottom: verticalIndent + 'px',
  7484. left: horizontalIndent + 'px',
  7485. right: horizontalIndent + 'px'});
  7486. }
  7487. }
  7488. /**
  7489. * Returns an array of the video dimensions, so that it keeps it's aspect
  7490. * ratio and fits available area with it's larger dimension. This method
  7491. * ensures that whole video will be visible and can leave empty areas.
  7492. *
  7493. * @return an array with 2 elements, the video width and the video height
  7494. */
  7495. function getDesktopVideoSize(videoWidth,
  7496. videoHeight,
  7497. videoSpaceWidth,
  7498. videoSpaceHeight) {
  7499. if (!videoWidth)
  7500. videoWidth = currentVideoWidth;
  7501. if (!videoHeight)
  7502. videoHeight = currentVideoHeight;
  7503. var aspectRatio = videoWidth / videoHeight;
  7504. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7505. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7506. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  7507. if (availableWidth / aspectRatio >= videoSpaceHeight)
  7508. {
  7509. availableHeight = videoSpaceHeight;
  7510. availableWidth = availableHeight * aspectRatio;
  7511. }
  7512. if (availableHeight * aspectRatio >= videoSpaceWidth)
  7513. {
  7514. availableWidth = videoSpaceWidth;
  7515. availableHeight = availableWidth / aspectRatio;
  7516. }
  7517. return [availableWidth, availableHeight];
  7518. }
  7519. /**
  7520. * Returns an array of the video horizontal and vertical indents,
  7521. * so that if fits its parent.
  7522. *
  7523. * @return an array with 2 elements, the horizontal indent and the vertical
  7524. * indent
  7525. */
  7526. function getCameraVideoPosition(videoWidth,
  7527. videoHeight,
  7528. videoSpaceWidth,
  7529. videoSpaceHeight) {
  7530. // Parent height isn't completely calculated when we position the video in
  7531. // full screen mode and this is why we use the screen height in this case.
  7532. // Need to think it further at some point and implement it properly.
  7533. var isFullScreen = document.fullScreen ||
  7534. document.mozFullScreen ||
  7535. document.webkitIsFullScreen;
  7536. if (isFullScreen)
  7537. videoSpaceHeight = window.innerHeight;
  7538. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7539. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  7540. return [horizontalIndent, verticalIndent];
  7541. }
  7542. /**
  7543. * Returns an array of the video horizontal and vertical indents.
  7544. * Centers horizontally and top aligns vertically.
  7545. *
  7546. * @return an array with 2 elements, the horizontal indent and the vertical
  7547. * indent
  7548. */
  7549. function getDesktopVideoPosition(videoWidth,
  7550. videoHeight,
  7551. videoSpaceWidth,
  7552. videoSpaceHeight) {
  7553. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7554. var verticalIndent = 0;// Top aligned
  7555. return [horizontalIndent, verticalIndent];
  7556. }
  7557. /**
  7558. * Returns an array of the video dimensions, so that it covers the screen.
  7559. * It leaves no empty areas, but some parts of the video might not be visible.
  7560. *
  7561. * @return an array with 2 elements, the video width and the video height
  7562. */
  7563. function getCameraVideoSize(videoWidth,
  7564. videoHeight,
  7565. videoSpaceWidth,
  7566. videoSpaceHeight) {
  7567. if (!videoWidth)
  7568. videoWidth = currentVideoWidth;
  7569. if (!videoHeight)
  7570. videoHeight = currentVideoHeight;
  7571. var aspectRatio = videoWidth / videoHeight;
  7572. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7573. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7574. if (availableWidth / aspectRatio < videoSpaceHeight) {
  7575. availableHeight = videoSpaceHeight;
  7576. availableWidth = availableHeight * aspectRatio;
  7577. }
  7578. if (availableHeight * aspectRatio < videoSpaceWidth) {
  7579. availableWidth = videoSpaceWidth;
  7580. availableHeight = availableWidth / aspectRatio;
  7581. }
  7582. return [availableWidth, availableHeight];
  7583. }
  7584. /**
  7585. * Updates the src of the active speaker avatar
  7586. * @param jid of the current active speaker
  7587. */
  7588. function updateActiveSpeakerAvatarSrc() {
  7589. var avatar = $("#activeSpeakerAvatar")[0];
  7590. var jid = currentSmallVideo.peerJid;
  7591. var url = Avatar.getActiveSpeakerUrl(jid);
  7592. if (avatar.src === url)
  7593. return;
  7594. if (jid) {
  7595. avatar.src = url;
  7596. currentSmallVideo.showAvatar();
  7597. }
  7598. }
  7599. /**
  7600. * Change the video source of the large video.
  7601. * @param isVisible
  7602. */
  7603. function changeVideo(isVisible) {
  7604. if (!currentSmallVideo) {
  7605. console.error("Unable to change large video - no 'currentSmallVideo'");
  7606. return;
  7607. }
  7608. updateActiveSpeakerAvatarSrc();
  7609. APP.RTC.setVideoSrc($('#largeVideo')[0], currentSmallVideo.getSrc());
  7610. var videoTransform = document.getElementById('largeVideo')
  7611. .style.webkitTransform;
  7612. var flipX = currentSmallVideo.flipX;
  7613. if (flipX && videoTransform !== 'scaleX(-1)') {
  7614. document.getElementById('largeVideo').style.webkitTransform =
  7615. "scaleX(-1)";
  7616. } else if (!flipX && videoTransform === 'scaleX(-1)') {
  7617. document.getElementById('largeVideo').style.webkitTransform =
  7618. "none";
  7619. }
  7620. var isDesktop = currentSmallVideo.getVideoType() === 'screen';
  7621. // Change the way we'll be measuring and positioning large video
  7622. getVideoSize = isDesktop ? getDesktopVideoSize : getCameraVideoSize;
  7623. getVideoPosition = isDesktop ? getDesktopVideoPosition :
  7624. getCameraVideoPosition;
  7625. // Only if the large video is currently visible.
  7626. if (isVisible) {
  7627. LargeVideo.VideoLayout.largeVideoUpdated(currentSmallVideo);
  7628. $('#largeVideo').fadeIn(300);
  7629. }
  7630. }
  7631. /**
  7632. * Creates the html elements for the large video.
  7633. */
  7634. function createLargeVideoHTML()
  7635. {
  7636. var html = '<div id="largeVideoContainer" class="videocontainer">';
  7637. html += '<div id="presentation"></div>' +
  7638. '<div id="etherpad"></div>' +
  7639. '<a target="_new"><div class="watermark leftwatermark"></div></a>' +
  7640. '<a target="_new"><div class="watermark rightwatermark"></div></a>' +
  7641. '<a class="poweredby" href="http://jitsi.org" target="_new" >' +
  7642. '<span data-i18n="poweredby"></span> jitsi.org' +
  7643. '</a>'+
  7644. '<div id="activeSpeaker">' +
  7645. '<img id="activeSpeakerAvatar" src=""/>' +
  7646. '<canvas id="activeSpeakerAudioLevel"></canvas>' +
  7647. '</div>' +
  7648. '<video id="largeVideo" autoplay oncontextmenu="return false;"></video>' +
  7649. '<span id="videoConnectionMessage"></span>';
  7650. html += '</div>';
  7651. $(html).prependTo("#videospace");
  7652. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  7653. var leftWatermarkDiv
  7654. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  7655. leftWatermarkDiv.css({display: 'block'});
  7656. leftWatermarkDiv.parent().get(0).href
  7657. = interfaceConfig.JITSI_WATERMARK_LINK;
  7658. }
  7659. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  7660. var rightWatermarkDiv
  7661. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  7662. rightWatermarkDiv.css({display: 'block'});
  7663. rightWatermarkDiv.parent().get(0).href
  7664. = interfaceConfig.BRAND_WATERMARK_LINK;
  7665. rightWatermarkDiv.get(0).style.backgroundImage
  7666. = "url(images/rightwatermark.png)";
  7667. }
  7668. if (interfaceConfig.SHOW_POWERED_BY) {
  7669. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  7670. }
  7671. if (!RTCBrowserType.isIExplorer()) {
  7672. $('#largeVideo').volume = 0;
  7673. }
  7674. }
  7675. var LargeVideo = {
  7676. init: function (VideoLayout, emitter) {
  7677. if(!isEnabled)
  7678. return;
  7679. createLargeVideoHTML();
  7680. this.VideoLayout = VideoLayout;
  7681. this.eventEmitter = emitter;
  7682. this.eventEmitter.emit(UIEvents.LARGEVIDEO_INIT);
  7683. var self = this;
  7684. // Listen for large video size updates
  7685. var largeVideo = $('#largeVideo')[0];
  7686. var onplaying = function (arg1, arg2, arg3) {
  7687. // re-select
  7688. if (RTCBrowserType.isTemasysPluginUsed())
  7689. largeVideo = $('#largeVideo')[0];
  7690. currentVideoWidth = largeVideo.videoWidth;
  7691. currentVideoHeight = largeVideo.videoHeight;
  7692. self.position(currentVideoWidth, currentVideoHeight);
  7693. };
  7694. largeVideo.onplaying = onplaying;
  7695. },
  7696. /**
  7697. * Indicates if the large video is currently visible.
  7698. *
  7699. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  7700. */
  7701. isLargeVideoVisible: function() {
  7702. return $('#largeVideo').is(':visible');
  7703. },
  7704. /**
  7705. * Returns <tt>true</tt> if the user is currently displayed on large video.
  7706. */
  7707. isCurrentlyOnLarge: function (resourceJid) {
  7708. return currentSmallVideo && resourceJid &&
  7709. currentSmallVideo.getResourceJid() === resourceJid;
  7710. },
  7711. /**
  7712. * Updates the large video with the given new video source.
  7713. */
  7714. updateLargeVideo: function (resourceJid, forceUpdate) {
  7715. if(!isEnabled)
  7716. return;
  7717. var newSmallVideo = this.VideoLayout.getSmallVideo(resourceJid);
  7718. console.log('hover in ' + resourceJid + ', video: ', newSmallVideo);
  7719. if (!LargeVideo.isCurrentlyOnLarge(resourceJid) || forceUpdate) {
  7720. $('#activeSpeaker').css('visibility', 'hidden');
  7721. var oldSmallVideo = null;
  7722. if (currentSmallVideo) {
  7723. oldSmallVideo = currentSmallVideo;
  7724. }
  7725. currentSmallVideo = newSmallVideo;
  7726. var oldJid = null;
  7727. if (oldSmallVideo)
  7728. oldJid = oldSmallVideo.peerJid;
  7729. if (oldJid !== resourceJid) {
  7730. // we want the notification to trigger even if userJid is undefined,
  7731. // or null.
  7732. this.eventEmitter.emit(UIEvents.SELECTED_ENDPOINT, resourceJid);
  7733. }
  7734. if (RTCBrowserType.isSafari()) {
  7735. // FIXME In Safari fadeOut works only for the first time
  7736. changeVideo(this.isLargeVideoVisible());
  7737. } else {
  7738. $('#largeVideo').fadeOut(300,
  7739. changeVideo.bind($('#largeVideo'), this.isLargeVideoVisible()));
  7740. }
  7741. } else {
  7742. if (currentSmallVideo) {
  7743. currentSmallVideo.showAvatar();
  7744. }
  7745. }
  7746. },
  7747. /**
  7748. * Shows/hides the large video.
  7749. */
  7750. setLargeVideoVisible: function(isVisible) {
  7751. if(!isEnabled)
  7752. return;
  7753. if (isVisible) {
  7754. $('#largeVideo').css({visibility: 'visible'});
  7755. $('.watermark').css({visibility: 'visible'});
  7756. if(currentSmallVideo)
  7757. currentSmallVideo.enableDominantSpeaker(true);
  7758. }
  7759. else {
  7760. $('#largeVideo').css({visibility: 'hidden'});
  7761. $('#activeSpeaker').css('visibility', 'hidden');
  7762. $('.watermark').css({visibility: 'hidden'});
  7763. if(currentSmallVideo)
  7764. currentSmallVideo.enableDominantSpeaker(false);
  7765. }
  7766. },
  7767. onVideoTypeChanged: function (resourceJid, newVideoType) {
  7768. if (!isEnabled)
  7769. return;
  7770. if (LargeVideo.isCurrentlyOnLarge(resourceJid))
  7771. {
  7772. var isDesktop = newVideoType === 'screen';
  7773. getVideoSize = isDesktop ? getDesktopVideoSize : getCameraVideoSize;
  7774. getVideoPosition = isDesktop ? getDesktopVideoPosition
  7775. : getCameraVideoPosition;
  7776. this.position(null, null);
  7777. }
  7778. },
  7779. /**
  7780. * Positions the large video.
  7781. *
  7782. * @param videoWidth the stream video width
  7783. * @param videoHeight the stream video height
  7784. */
  7785. position: function (videoWidth, videoHeight,
  7786. videoSpaceWidth, videoSpaceHeight, animate) {
  7787. if(!isEnabled)
  7788. return;
  7789. if(!videoSpaceWidth)
  7790. videoSpaceWidth = $('#videospace').width();
  7791. if(!videoSpaceHeight)
  7792. videoSpaceHeight = window.innerHeight;
  7793. var videoSize = getVideoSize(videoWidth,
  7794. videoHeight,
  7795. videoSpaceWidth,
  7796. videoSpaceHeight);
  7797. var largeVideoWidth = videoSize[0];
  7798. var largeVideoHeight = videoSize[1];
  7799. var videoPosition = getVideoPosition(largeVideoWidth,
  7800. largeVideoHeight,
  7801. videoSpaceWidth,
  7802. videoSpaceHeight);
  7803. var horizontalIndent = videoPosition[0];
  7804. var verticalIndent = videoPosition[1];
  7805. positionVideo($('#largeVideo'),
  7806. largeVideoWidth,
  7807. largeVideoHeight,
  7808. horizontalIndent, verticalIndent, animate);
  7809. },
  7810. resize: function (animate, isVisible, completeFunction) {
  7811. if(!isEnabled)
  7812. return;
  7813. var availableHeight = window.innerHeight;
  7814. var availableWidth = UIUtil.getAvailableVideoWidth(isVisible);
  7815. if (availableWidth < 0 || availableHeight < 0) return;
  7816. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  7817. var top = availableHeight / 2 - avatarSize / 4 * 3;
  7818. $('#activeSpeaker').css('top', top);
  7819. if(animate) {
  7820. $('#videospace').animate({
  7821. right: window.innerWidth - availableWidth,
  7822. width: availableWidth,
  7823. height: availableHeight
  7824. },
  7825. {
  7826. queue: false,
  7827. duration: 500,
  7828. complete: completeFunction
  7829. });
  7830. $('#largeVideoContainer').animate({
  7831. width: availableWidth,
  7832. height: availableHeight
  7833. },
  7834. {
  7835. queue: false,
  7836. duration: 500
  7837. });
  7838. } else {
  7839. $('#videospace').width(availableWidth);
  7840. $('#videospace').height(availableHeight);
  7841. $('#largeVideoContainer').width(availableWidth);
  7842. $('#largeVideoContainer').height(availableHeight);
  7843. }
  7844. return [availableWidth, availableHeight];
  7845. },
  7846. resizeVideoAreaAnimated: function (isVisible, completeFunction) {
  7847. if(!isEnabled)
  7848. return;
  7849. var size = this.resize(true, isVisible, completeFunction);
  7850. this.position(null, null, size[0], size[1], true);
  7851. },
  7852. getResourceJid: function () {
  7853. return currentSmallVideo ? currentSmallVideo.getResourceJid() : null;
  7854. },
  7855. updateAvatar: function (resourceJid) {
  7856. if(!isEnabled)
  7857. return;
  7858. if (resourceJid === this.getResourceJid()) {
  7859. updateActiveSpeakerAvatarSrc();
  7860. }
  7861. },
  7862. showAvatar: function (resourceJid, show) {
  7863. if(!isEnabled)
  7864. return;
  7865. if(this.getResourceJid() === resourceJid && state === "video") {
  7866. $("#largeVideo").css("visibility", show ? "hidden" : "visible");
  7867. $('#activeSpeaker').css("visibility", show ? "visible" : "hidden");
  7868. return true;
  7869. }
  7870. return false;
  7871. },
  7872. /**
  7873. * Disables the large video
  7874. */
  7875. disable: function () {
  7876. isEnabled = false;
  7877. },
  7878. /**
  7879. * Enables the large video
  7880. */
  7881. enable: function () {
  7882. isEnabled = true;
  7883. },
  7884. /**
  7885. * Returns true if the video is enabled.
  7886. */
  7887. isEnabled: function () {
  7888. return isEnabled;
  7889. },
  7890. /**
  7891. * Creates the iframe used by the etherpad
  7892. * @param src the value for src attribute
  7893. * @param onloadHandler handler executed when the iframe loads it content
  7894. * @returns {HTMLElement} the iframe
  7895. */
  7896. createEtherpadIframe: function (src, onloadHandler) {
  7897. if(!isEnabled)
  7898. return;
  7899. var etherpadIFrame = document.createElement('iframe');
  7900. etherpadIFrame.src = src;
  7901. etherpadIFrame.frameBorder = 0;
  7902. etherpadIFrame.scrolling = "no";
  7903. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  7904. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  7905. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  7906. document.getElementById('etherpad').appendChild(etherpadIFrame);
  7907. etherpadIFrame.onload = onloadHandler;
  7908. return etherpadIFrame;
  7909. },
  7910. /**
  7911. * Changes the state of the large video.
  7912. * Possible values - video, prezi, etherpad.
  7913. * @param newState - the new state
  7914. */
  7915. setState: function (newState) {
  7916. if(state === newState)
  7917. return;
  7918. var currentContainer = getContainerByState(state);
  7919. if(!currentContainer)
  7920. return;
  7921. var self = this;
  7922. var oldState = state;
  7923. switch (newState)
  7924. {
  7925. case "etherpad":
  7926. $('#activeSpeaker').css('visibility', 'hidden');
  7927. currentContainer.fadeOut(300, function () {
  7928. if (oldState === "prezi") {
  7929. currentContainer.css({opacity: '0'});
  7930. $('#reloadPresentation').css({display: 'none'});
  7931. }
  7932. else {
  7933. self.setLargeVideoVisible(false);
  7934. }
  7935. });
  7936. $('#etherpad>iframe').fadeIn(300, function () {
  7937. document.body.style.background = '#eeeeee';
  7938. $('#etherpad>iframe').css({visibility: 'visible'});
  7939. $('#etherpad').css({zIndex: 2});
  7940. });
  7941. break;
  7942. case "prezi":
  7943. var prezi = $('#presentation>iframe');
  7944. currentContainer.fadeOut(300, function() {
  7945. document.body.style.background = 'black';
  7946. });
  7947. prezi.fadeIn(300, function() {
  7948. prezi.css({opacity:'1'});
  7949. ToolbarToggler.dockToolbar(true);//fix that
  7950. self.setLargeVideoVisible(false);
  7951. $('#etherpad>iframe').css({visibility: 'hidden'});
  7952. $('#etherpad').css({zIndex: 0});
  7953. });
  7954. $('#activeSpeaker').css('visibility', 'hidden');
  7955. break;
  7956. case "video":
  7957. currentContainer.fadeOut(300, function () {
  7958. $('#presentation>iframe').css({opacity:'0'});
  7959. $('#reloadPresentation').css({display:'none'});
  7960. $('#etherpad>iframe').css({visibility: 'hidden'});
  7961. $('#etherpad').css({zIndex: 0});
  7962. document.body.style.background = 'black';
  7963. ToolbarToggler.dockToolbar(false);//fix that
  7964. });
  7965. $('#largeVideo').fadeIn(300, function () {
  7966. self.setLargeVideoVisible(true);
  7967. });
  7968. break;
  7969. }
  7970. state = newState;
  7971. },
  7972. /**
  7973. * Returns the current state of the large video.
  7974. * @returns {string} the current state - video, prezi or etherpad.
  7975. */
  7976. getState: function () {
  7977. return state;
  7978. },
  7979. /**
  7980. * Sets hover handlers for the large video container div.
  7981. *
  7982. * @param inHandler
  7983. * @param outHandler
  7984. */
  7985. setHover: function(inHandler, outHandler)
  7986. {
  7987. $('#largeVideoContainer').hover(inHandler, outHandler);
  7988. },
  7989. /**
  7990. * Enables/disables the filter indicating a video problem to the user.
  7991. *
  7992. * @param enable <tt>true</tt> to enable, <tt>false</tt> to disable
  7993. */
  7994. enableVideoProblemFilter: function (enable) {
  7995. $("#largeVideo").toggleClass("videoProblemFilter", enable);
  7996. }
  7997. };
  7998. module.exports = LargeVideo;
  7999. },{"../../../service/UI/UIEvents":113,"../../RTC/RTCBrowserType":10,"../../xmpp/xmpp":69,"../avatar/Avatar":18,"../toolbars/ToolbarToggler":31,"../util/UIUtil":35}],38:[function(require,module,exports){
  8000. /* global $, interfaceConfig, APP */
  8001. var SmallVideo = require("./SmallVideo");
  8002. var ConnectionIndicator = require("./ConnectionIndicator");
  8003. var NicknameHandler = require("../util/NicknameHandler");
  8004. var UIUtil = require("../util/UIUtil");
  8005. var LargeVideo = require("./LargeVideo");
  8006. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  8007. function LocalVideo(VideoLayout) {
  8008. this.videoSpanId = "localVideoContainer";
  8009. this.container = $("#localVideoContainer").get(0);
  8010. this.VideoLayout = VideoLayout;
  8011. this.flipX = true;
  8012. this.isLocal = true;
  8013. this.peerJid = null;
  8014. }
  8015. LocalVideo.prototype = Object.create(SmallVideo.prototype);
  8016. LocalVideo.prototype.constructor = LocalVideo;
  8017. /**
  8018. * Creates the edit display name button.
  8019. *
  8020. * @returns {object} the edit button
  8021. */
  8022. function createEditDisplayNameButton() {
  8023. var editButton = document.createElement('a');
  8024. editButton.className = 'displayname';
  8025. UIUtil.setTooltip(editButton,
  8026. "videothumbnail.editnickname",
  8027. "top");
  8028. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  8029. return editButton;
  8030. }
  8031. /**
  8032. * Sets the display name for the given video span id.
  8033. */
  8034. LocalVideo.prototype.setDisplayName = function(displayName, key) {
  8035. if (!this.container) {
  8036. console.warn(
  8037. "Unable to set displayName - " + this.videoSpanId +
  8038. " does not exist");
  8039. return;
  8040. }
  8041. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8042. var defaultLocalDisplayName = APP.translation.generateTranslationHTML(
  8043. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  8044. var meHTML;
  8045. // If we already have a display name for this video.
  8046. if (nameSpan.length > 0) {
  8047. if (nameSpan.text() !== displayName) {
  8048. if (displayName && displayName.length > 0) {
  8049. meHTML = APP.translation.generateTranslationHTML("me");
  8050. $('#localDisplayName').html(displayName + ' (' + meHTML + ')');
  8051. } else {
  8052. $('#localDisplayName').html(defaultLocalDisplayName);
  8053. }
  8054. }
  8055. } else {
  8056. var editButton = createEditDisplayNameButton();
  8057. nameSpan = document.createElement('span');
  8058. nameSpan.className = 'displayname';
  8059. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  8060. if (displayName && displayName.length > 0) {
  8061. meHTML = APP.translation.generateTranslationHTML("me");
  8062. nameSpan.innerHTML = displayName + meHTML;
  8063. }
  8064. else {
  8065. nameSpan.innerHTML = defaultLocalDisplayName;
  8066. }
  8067. nameSpan.id = 'localDisplayName';
  8068. this.container.appendChild(editButton);
  8069. //translates popover of edit button
  8070. APP.translation.translateElement($("a.displayname"));
  8071. var editableText = document.createElement('input');
  8072. editableText.className = 'displayname';
  8073. editableText.type = 'text';
  8074. editableText.id = 'editDisplayName';
  8075. if (displayName && displayName.length) {
  8076. editableText.value = displayName;
  8077. }
  8078. var defaultNickname = APP.translation.translateString(
  8079. "defaultNickname", {name: "Jane Pink"});
  8080. editableText.setAttribute('style', 'display:none;');
  8081. editableText.setAttribute('data-18n',
  8082. '[placeholder]defaultNickname');
  8083. editableText.setAttribute("data-i18n-options",
  8084. JSON.stringify({name: "Jane Pink"}));
  8085. editableText.setAttribute("placeholder", defaultNickname);
  8086. this.container.appendChild(editableText);
  8087. var self = this;
  8088. $('#localVideoContainer .displayname')
  8089. .bind("click", function (e) {
  8090. var editDisplayName = $('#editDisplayName');
  8091. e.preventDefault();
  8092. e.stopPropagation();
  8093. $('#localDisplayName').hide();
  8094. editDisplayName.show();
  8095. editDisplayName.focus();
  8096. editDisplayName.select();
  8097. editDisplayName.one("focusout", function (e) {
  8098. self.VideoLayout.inputDisplayNameHandler(this.value);
  8099. });
  8100. editDisplayName.on('keydown', function (e) {
  8101. if (e.keyCode === 13) {
  8102. e.preventDefault();
  8103. self.VideoLayout.inputDisplayNameHandler(this.value);
  8104. }
  8105. });
  8106. });
  8107. }
  8108. };
  8109. LocalVideo.prototype.inputDisplayNameHandler = function (name) {
  8110. NicknameHandler.setNickname(name);
  8111. var localDisplayName = $('#localDisplayName');
  8112. if (!localDisplayName.is(":visible")) {
  8113. if (NicknameHandler.getNickname()) {
  8114. var meHTML = APP.translation.generateTranslationHTML("me");
  8115. localDisplayName.html(NicknameHandler.getNickname() + " (" +
  8116. meHTML + ")");
  8117. } else {
  8118. var defaultHTML = APP.translation.generateTranslationHTML(
  8119. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  8120. localDisplayName .html(defaultHTML);
  8121. }
  8122. localDisplayName.show();
  8123. }
  8124. $('#editDisplayName').hide();
  8125. };
  8126. LocalVideo.prototype.createConnectionIndicator = function() {
  8127. if(this.connectionIndicator)
  8128. return;
  8129. this.connectionIndicator = new ConnectionIndicator(this, null);
  8130. };
  8131. LocalVideo.prototype.changeVideo = function (stream, isMuted) {
  8132. var self = this;
  8133. function localVideoClick(event) {
  8134. // FIXME: with Temasys plugin event arg is not an event, but
  8135. // the clicked object itself, so we have to skip this call
  8136. if (event.stopPropagation) {
  8137. event.stopPropagation();
  8138. }
  8139. self.VideoLayout.handleVideoThumbClicked(
  8140. false,
  8141. APP.xmpp.myResource());
  8142. }
  8143. var localVideoContainerSelector = $('#localVideoContainer');
  8144. localVideoContainerSelector.off('click');
  8145. localVideoContainerSelector.on('click', localVideoClick);
  8146. // Add hover handler
  8147. localVideoContainerSelector.hover(
  8148. function() {
  8149. self.showDisplayName(true);
  8150. },
  8151. function() {
  8152. if (!LargeVideo.isLargeVideoVisible() ||
  8153. !LargeVideo.isCurrentlyOnLarge(self.getResourceJid())) {
  8154. self.showDisplayName(false);
  8155. }
  8156. }
  8157. );
  8158. if(isMuted) {
  8159. APP.UI.setVideoMute(true);
  8160. return;
  8161. }
  8162. this.flipX = stream.videoType != "screen";
  8163. var localVideo = document.createElement('video');
  8164. localVideo.id = 'localVideo_' +
  8165. APP.RTC.getStreamID(stream.getOriginalStream());
  8166. if (!RTCBrowserType.isIExplorer()) {
  8167. localVideo.autoplay = true;
  8168. localVideo.volume = 0; // is it required if audio is separated ?
  8169. }
  8170. localVideo.oncontextmenu = function () { return false; };
  8171. var localVideoContainer = document.getElementById('localVideoWrapper');
  8172. localVideoContainer.appendChild(localVideo);
  8173. var localVideoSelector = $('#' + localVideo.id);
  8174. // Add click handler to both video and video wrapper elements in case
  8175. // there's no video.
  8176. // onclick has to be used with Temasys plugin
  8177. localVideo.onclick = localVideoClick;
  8178. if (this.flipX) {
  8179. localVideoSelector.addClass("flipVideoX");
  8180. }
  8181. // Attach WebRTC stream
  8182. APP.RTC.attachMediaStream(localVideoSelector, stream.getOriginalStream());
  8183. // Add stream ended handler
  8184. stream.getOriginalStream().onended = function () {
  8185. // We have to re-select after attach when Temasys plugin is used,
  8186. // because <video> element is replaced with <object>
  8187. localVideo = $('#' + localVideo.id)[0];
  8188. localVideoContainer.removeChild(localVideo);
  8189. self.VideoLayout.updateRemovedVideo(APP.xmpp.myResource());
  8190. };
  8191. };
  8192. LocalVideo.prototype.joined = function (jid) {
  8193. this.peerJid = jid;
  8194. };
  8195. LocalVideo.prototype.getResourceJid = function () {
  8196. var myResource = APP.xmpp.myResource();
  8197. if (!myResource) {
  8198. console.error("Requested local resource before we're in the MUC");
  8199. }
  8200. return myResource;
  8201. };
  8202. module.exports = LocalVideo;
  8203. },{"../../RTC/RTCBrowserType":10,"../util/NicknameHandler":34,"../util/UIUtil":35,"./ConnectionIndicator":36,"./LargeVideo":37,"./SmallVideo":40}],39:[function(require,module,exports){
  8204. /* global $, APP, require, Strophe, interfaceConfig */
  8205. var ConnectionIndicator = require("./ConnectionIndicator");
  8206. var SmallVideo = require("./SmallVideo");
  8207. var AudioLevels = require("../audio_levels/AudioLevels");
  8208. var LargeVideo = require("./LargeVideo");
  8209. var Avatar = require("../avatar/Avatar");
  8210. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  8211. function RemoteVideo(peerJid, VideoLayout) {
  8212. this.peerJid = peerJid;
  8213. this.resourceJid = Strophe.getResourceFromJid(peerJid);
  8214. this.videoSpanId = 'participant_' + this.resourceJid;
  8215. this.VideoLayout = VideoLayout;
  8216. this.addRemoteVideoContainer();
  8217. this.connectionIndicator = new ConnectionIndicator(
  8218. this, this.peerJid);
  8219. this.setDisplayName();
  8220. var nickfield = document.createElement('span');
  8221. nickfield.className = "nick";
  8222. nickfield.appendChild(document.createTextNode(this.resourceJid));
  8223. this.container.appendChild(nickfield);
  8224. this.flipX = false;
  8225. this.isLocal = false;
  8226. }
  8227. RemoteVideo.prototype = Object.create(SmallVideo.prototype);
  8228. RemoteVideo.prototype.constructor = RemoteVideo;
  8229. RemoteVideo.prototype.addRemoteVideoContainer = function() {
  8230. this.container = RemoteVideo.createContainer(this.videoSpanId);
  8231. if (APP.xmpp.isModerator())
  8232. this.addRemoteVideoMenu();
  8233. AudioLevels.updateAudioLevelCanvas(this.peerJid, this.VideoLayout);
  8234. return this.container;
  8235. };
  8236. /**
  8237. * Adds the remote video menu element for the given <tt>jid</tt> in the
  8238. * given <tt>parentElement</tt>.
  8239. *
  8240. * @param jid the jid indicating the video for which we're adding a menu.
  8241. * @param parentElement the parent element where this menu will be added
  8242. */
  8243. RemoteVideo.prototype.addRemoteVideoMenu = function () {
  8244. var spanElement = document.createElement('span');
  8245. spanElement.className = 'remotevideomenu';
  8246. this.container.appendChild(spanElement);
  8247. var menuElement = document.createElement('i');
  8248. menuElement.className = 'fa fa-angle-down';
  8249. menuElement.title = 'Remote user controls';
  8250. spanElement.appendChild(menuElement);
  8251. var popupmenuElement = document.createElement('ul');
  8252. popupmenuElement.className = 'popupmenu';
  8253. popupmenuElement.id = 'remote_popupmenu_' + this.getResourceJid();
  8254. spanElement.appendChild(popupmenuElement);
  8255. var muteMenuItem = document.createElement('li');
  8256. var muteLinkItem = document.createElement('a');
  8257. var mutedIndicator = "<i style='float:left;' class='icon-mic-disabled'></i>";
  8258. if (!this.isMuted) {
  8259. muteLinkItem.innerHTML = mutedIndicator +
  8260. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  8261. muteLinkItem.className = 'mutelink';
  8262. }
  8263. else {
  8264. muteLinkItem.innerHTML = mutedIndicator +
  8265. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  8266. muteLinkItem.className = 'mutelink disabled';
  8267. }
  8268. var self = this;
  8269. muteLinkItem.onclick = function(){
  8270. if ($(this).attr('disabled') != undefined) {
  8271. event.preventDefault();
  8272. }
  8273. var isMute = self.isMuted == true;
  8274. APP.xmpp.setMute(self.peerJid, !isMute);
  8275. popupmenuElement.setAttribute('style', 'display:none;');
  8276. if (isMute) {
  8277. this.innerHTML = mutedIndicator +
  8278. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  8279. this.className = 'mutelink disabled';
  8280. }
  8281. else {
  8282. this.innerHTML = mutedIndicator +
  8283. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  8284. this.className = 'mutelink';
  8285. }
  8286. };
  8287. muteMenuItem.appendChild(muteLinkItem);
  8288. popupmenuElement.appendChild(muteMenuItem);
  8289. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  8290. var ejectMenuItem = document.createElement('li');
  8291. var ejectLinkItem = document.createElement('a');
  8292. var ejectText = "<div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.kick'>&nbsp;</div>";
  8293. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  8294. ejectLinkItem.onclick = function(){
  8295. APP.xmpp.eject(self.peerJid);
  8296. popupmenuElement.setAttribute('style', 'display:none;');
  8297. };
  8298. ejectMenuItem.appendChild(ejectLinkItem);
  8299. popupmenuElement.appendChild(ejectMenuItem);
  8300. var paddingSpan = document.createElement('span');
  8301. paddingSpan.className = 'popupmenuPadding';
  8302. popupmenuElement.appendChild(paddingSpan);
  8303. APP.translation.translateElement(
  8304. $("#" + popupmenuElement.id + " > li > a > div"));
  8305. };
  8306. /**
  8307. * Removes the remote stream element corresponding to the given stream and
  8308. * parent container.
  8309. *
  8310. * @param stream the stream
  8311. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  8312. */
  8313. RemoteVideo.prototype.removeRemoteStreamElement =
  8314. function (stream, isVideo, id) {
  8315. if (!this.container)
  8316. return false;
  8317. var select = null;
  8318. if (isVideo) {
  8319. select = $('#' + id);
  8320. }
  8321. else
  8322. select = $('#' + this.videoSpanId + '>audio');
  8323. select.remove();
  8324. console.info((isVideo ? "Video" : "Audio") +
  8325. " removed " + this.getResourceJid(), select);
  8326. if (isVideo)
  8327. this.VideoLayout.updateRemovedVideo(this.getResourceJid());
  8328. };
  8329. /**
  8330. * Removes RemoteVideo from the page.
  8331. */
  8332. RemoteVideo.prototype.remove = function () {
  8333. console.log("Remove thumbnail", this.peerJid);
  8334. this.removeConnectionIndicator();
  8335. // Remove whole container
  8336. if (this.container.parentNode)
  8337. this.container.parentNode.removeChild(this.container);
  8338. };
  8339. RemoteVideo.prototype.waitForPlayback = function (sel, stream) {
  8340. var isVideo = stream.getVideoTracks().length > 0;
  8341. if (!isVideo || stream.id === 'mixedmslabel') {
  8342. return;
  8343. }
  8344. var self = this;
  8345. var resourceJid = this.getResourceJid();
  8346. // Register 'onplaying' listener to trigger 'videoactive' on VideoLayout
  8347. // when video playback starts
  8348. var onPlayingHandler = function () {
  8349. // FIXME: why do i have to do this for FF?
  8350. if (RTCBrowserType.isFirefox()) {
  8351. APP.RTC.attachMediaStream(sel, stream);
  8352. }
  8353. if (RTCBrowserType.isTemasysPluginUsed()) {
  8354. sel = self.VideoLayout.getPeerVideoSel(resourceJid);
  8355. }
  8356. self.VideoLayout.videoactive(sel, resourceJid);
  8357. sel[0].onplaying = null;
  8358. if (RTCBrowserType.isTemasysPluginUsed()) {
  8359. // 'currentTime' is used to check if the video has started
  8360. // and the value is not set by the plugin, so we do it
  8361. sel[0].currentTime = 1;
  8362. }
  8363. };
  8364. sel[0].onplaying = onPlayingHandler;
  8365. };
  8366. RemoteVideo.prototype.addRemoteStreamElement = function (sid, stream, thessrc) {
  8367. if (!this.container)
  8368. return;
  8369. var self = this;
  8370. var isVideo = stream.getVideoTracks().length > 0;
  8371. var streamElement = SmallVideo.createStreamElement(sid, stream);
  8372. var newElementId = streamElement.id;
  8373. this.container.appendChild(streamElement);
  8374. var sel = $('#' + newElementId);
  8375. sel.hide();
  8376. // If the container is currently visible we attach the stream.
  8377. if (!isVideo || (this.container.offsetParent !== null && isVideo)) {
  8378. this.waitForPlayback(sel, stream);
  8379. APP.RTC.attachMediaStream(sel, stream);
  8380. }
  8381. stream.onended = function () {
  8382. console.log('stream ended', this);
  8383. self.removeRemoteStreamElement(stream, isVideo, newElementId);
  8384. };
  8385. // Name of video element name is different for IE/Safari
  8386. var videoElem = APP.RTC.getVideoElementName();
  8387. // Add click handler.
  8388. var onClickHandler = function (event) {
  8389. self.VideoLayout.handleVideoThumbClicked(false, self.getResourceJid());
  8390. // On IE we need to populate this handler on video <object>
  8391. // and it does not give event instance as an argument,
  8392. // so we check here for methods.
  8393. if (event.stopPropagation && event.preventDefault) {
  8394. event.stopPropagation();
  8395. event.preventDefault();
  8396. }
  8397. return false;
  8398. };
  8399. this.container.onclick = onClickHandler;
  8400. // reselect
  8401. if (RTCBrowserType.isTemasysPluginUsed())
  8402. sel = $('#' + newElementId);
  8403. sel[0].onclick = onClickHandler;
  8404. //FIXME
  8405. // Add hover handler
  8406. $(this.container).hover(
  8407. function() {
  8408. self.showDisplayName(true);
  8409. },
  8410. function() {
  8411. // If the video has been "pinned" by the user we want to
  8412. // keep the display name on place.
  8413. if (!LargeVideo.isLargeVideoVisible() ||
  8414. !LargeVideo.isCurrentlyOnLarge(self.getResourceJid()))
  8415. self.showDisplayName(false);
  8416. }
  8417. );
  8418. },
  8419. /**
  8420. * Show/hide peer container for the given resourceJid.
  8421. */
  8422. RemoteVideo.prototype.showPeerContainer = function (state) {
  8423. if (!this.container)
  8424. return;
  8425. var isHide = state === 'hide';
  8426. var resizeThumbnails = false;
  8427. if (!isHide) {
  8428. if (!$(this.container).is(':visible')) {
  8429. resizeThumbnails = true;
  8430. $(this.container).show();
  8431. }
  8432. this.showAvatar(state !== 'show');
  8433. }
  8434. else if ($(this.container).is(':visible') && isHide)
  8435. {
  8436. resizeThumbnails = true;
  8437. $(this.container).hide();
  8438. if(this.connectionIndicator)
  8439. this.connectionIndicator.hide();
  8440. }
  8441. if (resizeThumbnails) {
  8442. this.VideoLayout.resizeThumbnails();
  8443. }
  8444. // We want to be able to pin a participant from the contact list, even
  8445. // if he's not in the lastN set!
  8446. // ContactList.setClickable(resourceJid, !isHide);
  8447. };
  8448. RemoteVideo.prototype.removeConnectionIndicator = function () {
  8449. if (this.connectionIndicator)
  8450. this.connectionIndicator.remove();
  8451. };
  8452. RemoteVideo.prototype.hideConnectionIndicator = function () {
  8453. if (this.connectionIndicator)
  8454. this.connectionIndicator.hide();
  8455. };
  8456. /**
  8457. * Updates the remote video menu.
  8458. *
  8459. * @param jid the jid indicating the video for which we're adding a menu.
  8460. * @param isMuted indicates the current mute state
  8461. */
  8462. RemoteVideo.prototype.updateRemoteVideoMenu = function (isMuted) {
  8463. var muteMenuItem
  8464. = $('#remote_popupmenu_' + this.getResourceJid() + '>li>a.mutelink');
  8465. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  8466. if (muteMenuItem.length) {
  8467. var muteLink = muteMenuItem.get(0);
  8468. if (isMuted === 'true') {
  8469. muteLink.innerHTML = mutedIndicator + ' Muted';
  8470. muteLink.className = 'mutelink disabled';
  8471. }
  8472. else {
  8473. muteLink.innerHTML = mutedIndicator + ' Mute';
  8474. muteLink.className = 'mutelink';
  8475. }
  8476. }
  8477. };
  8478. /**
  8479. * Sets the display name for the given video span id.
  8480. */
  8481. RemoteVideo.prototype.setDisplayName = function(displayName, key) {
  8482. if (!this.container) {
  8483. console.warn( "Unable to set displayName - " + this.videoSpanId +
  8484. " does not exist");
  8485. return;
  8486. }
  8487. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8488. // If we already have a display name for this video.
  8489. if (nameSpan.length > 0) {
  8490. if (displayName && displayName.length > 0) {
  8491. $('#' + this.videoSpanId + '_name').html(displayName);
  8492. }
  8493. else if (key && key.length > 0) {
  8494. var nameHtml = APP.translation.generateTranslationHTML(key);
  8495. $('#' + this.videoSpanId + '_name').html(nameHtml);
  8496. }
  8497. else
  8498. $('#' + this.videoSpanId + '_name').text(
  8499. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  8500. } else {
  8501. nameSpan = document.createElement('span');
  8502. nameSpan.className = 'displayname';
  8503. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  8504. if (displayName && displayName.length > 0) {
  8505. nameSpan.innerText = displayName;
  8506. }
  8507. else
  8508. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  8509. nameSpan.id = this.videoSpanId + '_name';
  8510. }
  8511. };
  8512. /**
  8513. * Removes remote video menu element from video element identified by
  8514. * given <tt>videoElementId</tt>.
  8515. *
  8516. * @param videoElementId the id of local or remote video element.
  8517. */
  8518. RemoteVideo.prototype.removeRemoteVideoMenu = function() {
  8519. var menuSpan = $('#' + this.videoSpanId + '>span.remotevideomenu');
  8520. if (menuSpan.length) {
  8521. menuSpan.remove();
  8522. }
  8523. };
  8524. RemoteVideo.prototype.getResourceJid = function () {
  8525. if (!this.resourceJid) {
  8526. console.error("Undefined resource jid");
  8527. }
  8528. return this.resourceJid;
  8529. };
  8530. RemoteVideo.createContainer = function (spanId) {
  8531. var container = document.createElement('span');
  8532. container.id = spanId;
  8533. container.className = 'videocontainer';
  8534. var remotes = document.getElementById('remoteVideos');
  8535. return remotes.appendChild(container);
  8536. };
  8537. module.exports = RemoteVideo;
  8538. },{"../../RTC/RTCBrowserType":10,"../audio_levels/AudioLevels":14,"../avatar/Avatar":18,"./ConnectionIndicator":36,"./LargeVideo":37,"./SmallVideo":40}],40:[function(require,module,exports){
  8539. /* global $, APP, require */
  8540. var Avatar = require("../avatar/Avatar");
  8541. var UIUtil = require("../util/UIUtil");
  8542. var LargeVideo = require("./LargeVideo");
  8543. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  8544. function SmallVideo() {
  8545. this.isMuted = false;
  8546. this.hasAvatar = false;
  8547. }
  8548. function setVisibility(selector, show) {
  8549. if (selector && selector.length > 0) {
  8550. selector.css("visibility", show ? "visible" : "hidden");
  8551. }
  8552. }
  8553. SmallVideo.prototype.showDisplayName = function(isShow) {
  8554. var nameSpan = $('#' + this.videoSpanId + '>span.displayname').get(0);
  8555. if (isShow) {
  8556. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  8557. nameSpan.setAttribute("style", "display:inline-block;");
  8558. }
  8559. else {
  8560. if (nameSpan)
  8561. nameSpan.setAttribute("style", "display:none;");
  8562. }
  8563. };
  8564. SmallVideo.prototype.setDeviceAvailabilityIcons = function (devices) {
  8565. if(!this.container)
  8566. return;
  8567. var noMic = $("#" + this.videoSpanId + " > .noMic");
  8568. var noVideo = $("#" + this.videoSpanId + " > .noVideo");
  8569. noMic.remove();
  8570. noVideo.remove();
  8571. if (!devices.audio) {
  8572. this.container.appendChild(
  8573. document.createElement("div")).setAttribute("class", "noMic");
  8574. }
  8575. if (!devices.video) {
  8576. this.container.appendChild(
  8577. document.createElement("div")).setAttribute("class", "noVideo");
  8578. }
  8579. if (!devices.audio && !devices.video) {
  8580. noMic.css("background-position", "75%");
  8581. noVideo.css("background-position", "25%");
  8582. noVideo.css("background-color", "transparent");
  8583. }
  8584. };
  8585. /**
  8586. * Sets the type of the video displayed by this instance.
  8587. * @param videoType 'camera' or 'screen'
  8588. */
  8589. SmallVideo.prototype.setVideoType = function (videoType) {
  8590. this.videoType = videoType;
  8591. };
  8592. /**
  8593. * Returns the type of the video displayed by this instance.
  8594. * @returns {String} 'camera', 'screen' or undefined.
  8595. */
  8596. SmallVideo.prototype.getVideoType = function () {
  8597. return this.videoType;
  8598. };
  8599. /**
  8600. * Shows the presence status message for the given video.
  8601. */
  8602. SmallVideo.prototype.setPresenceStatus = function (statusMsg) {
  8603. if (!this.container) {
  8604. // No container
  8605. return;
  8606. }
  8607. var statusSpan = $('#' + this.videoSpanId + '>span.status');
  8608. if (!statusSpan.length) {
  8609. //Add status span
  8610. statusSpan = document.createElement('span');
  8611. statusSpan.className = 'status';
  8612. statusSpan.id = this.videoSpanId + '_status';
  8613. $('#' + this.videoSpanId)[0].appendChild(statusSpan);
  8614. statusSpan = $('#' + this.videoSpanId + '>span.status');
  8615. }
  8616. // Display status
  8617. if (statusMsg && statusMsg.length) {
  8618. $('#' + this.videoSpanId + '_status').text(statusMsg);
  8619. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  8620. }
  8621. else {
  8622. // Hide
  8623. statusSpan.get(0).setAttribute("style", "display:none;");
  8624. }
  8625. };
  8626. /**
  8627. * Creates an audio or video stream element.
  8628. */
  8629. SmallVideo.createStreamElement = function (sid, stream) {
  8630. var isVideo = stream.getVideoTracks().length > 0;
  8631. var element = isVideo ? document.createElement('video')
  8632. : document.createElement('audio');
  8633. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_') + sid + '_' +
  8634. APP.RTC.getStreamID(stream);
  8635. element.id = id;
  8636. if (!RTCBrowserType.isIExplorer()) {
  8637. element.autoplay = true;
  8638. }
  8639. element.oncontextmenu = function () { return false; };
  8640. return element;
  8641. };
  8642. /**
  8643. * Updates the data for the indicator
  8644. * @param id the id of the indicator
  8645. * @param percent the percent for connection quality
  8646. * @param object the data
  8647. */
  8648. SmallVideo.prototype.updateStatsIndicator = function (percent, object) {
  8649. if(this.connectionIndicator)
  8650. this.connectionIndicator.updateConnectionQuality(percent, object);
  8651. };
  8652. SmallVideo.prototype.hideIndicator = function () {
  8653. if(this.connectionIndicator)
  8654. this.connectionIndicator.hideIndicator();
  8655. };
  8656. /**
  8657. * Shows audio muted indicator over small videos.
  8658. * @param {string} isMuted
  8659. */
  8660. SmallVideo.prototype.showAudioIndicator = function(isMuted) {
  8661. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8662. if (!isMuted) {
  8663. if (audioMutedSpan.length > 0) {
  8664. audioMutedSpan.popover('hide');
  8665. audioMutedSpan.remove();
  8666. }
  8667. }
  8668. else {
  8669. if(audioMutedSpan.length == 0 ) {
  8670. audioMutedSpan = document.createElement('span');
  8671. audioMutedSpan.className = 'audioMuted';
  8672. UIUtil.setTooltip(audioMutedSpan,
  8673. "videothumbnail.mute",
  8674. "top");
  8675. this.container.appendChild(audioMutedSpan);
  8676. APP.translation.translateElement($('#' + this.videoSpanId + " > span"));
  8677. var mutedIndicator = document.createElement('i');
  8678. mutedIndicator.className = 'icon-mic-disabled';
  8679. audioMutedSpan.appendChild(mutedIndicator);
  8680. }
  8681. this.updateIconPositions();
  8682. }
  8683. this.isMuted = isMuted;
  8684. };
  8685. /**
  8686. * Shows video muted indicator over small videos.
  8687. */
  8688. SmallVideo.prototype.showVideoIndicator = function(isMuted) {
  8689. this.showAvatar(isMuted);
  8690. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8691. if (isMuted === false) {
  8692. if (videoMutedSpan.length > 0) {
  8693. videoMutedSpan.remove();
  8694. }
  8695. }
  8696. else {
  8697. if(videoMutedSpan.length == 0) {
  8698. videoMutedSpan = document.createElement('span');
  8699. videoMutedSpan.className = 'videoMuted';
  8700. this.container.appendChild(videoMutedSpan);
  8701. var mutedIndicator = document.createElement('i');
  8702. mutedIndicator.className = 'icon-camera-disabled';
  8703. UIUtil.setTooltip(mutedIndicator,
  8704. "videothumbnail.videomute",
  8705. "top");
  8706. videoMutedSpan.appendChild(mutedIndicator);
  8707. //translate texts for muted indicator
  8708. APP.translation.translateElement($('#' + this.videoSpanId + " > span > i"));
  8709. }
  8710. this.updateIconPositions();
  8711. }
  8712. };
  8713. SmallVideo.prototype.enableDominantSpeaker = function (isEnable) {
  8714. var resourceJid = this.getResourceJid();
  8715. var displayName = resourceJid;
  8716. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8717. if (nameSpan.length > 0)
  8718. displayName = nameSpan.html();
  8719. console.log("UI enable dominant speaker",
  8720. displayName,
  8721. resourceJid,
  8722. isEnable);
  8723. if (!this.container) {
  8724. return;
  8725. }
  8726. if (isEnable) {
  8727. this.showDisplayName(LargeVideo.getState() === "video");
  8728. if (!this.container.classList.contains("dominantspeaker"))
  8729. this.container.classList.add("dominantspeaker");
  8730. }
  8731. else {
  8732. this.showDisplayName(false);
  8733. if (this.container.classList.contains("dominantspeaker"))
  8734. this.container.classList.remove("dominantspeaker");
  8735. }
  8736. this.showAvatar();
  8737. };
  8738. SmallVideo.prototype.updateIconPositions = function () {
  8739. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8740. var connectionIndicator = $('#' + this.videoSpanId + '>div.connectionindicator');
  8741. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8742. if(connectionIndicator.length > 0 &&
  8743. connectionIndicator[0].style.display != "none") {
  8744. audioMutedSpan.css({right: "23px"});
  8745. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  8746. } else {
  8747. audioMutedSpan.css({right: "0px"});
  8748. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  8749. }
  8750. };
  8751. /**
  8752. * Creates the element indicating the moderator(owner) of the conference.
  8753. *
  8754. * @param parentElement the parent element where the owner indicator will
  8755. * be added
  8756. */
  8757. SmallVideo.prototype.createModeratorIndicatorElement = function () {
  8758. // Show moderator indicator
  8759. var indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8760. if (!indicatorSpan || indicatorSpan.length === 0) {
  8761. indicatorSpan = document.createElement('span');
  8762. indicatorSpan.className = 'focusindicator';
  8763. this.container.appendChild(indicatorSpan);
  8764. indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8765. }
  8766. if (indicatorSpan.children().length !== 0)
  8767. return;
  8768. var moderatorIndicator = document.createElement('i');
  8769. moderatorIndicator.className = 'fa fa-star';
  8770. indicatorSpan[0].appendChild(moderatorIndicator);
  8771. UIUtil.setTooltip(indicatorSpan[0],
  8772. "videothumbnail.moderator",
  8773. "top");
  8774. //translates text in focus indicators
  8775. APP.translation.translateElement($('#' + this.videoSpanId + ' .focusindicator'));
  8776. };
  8777. SmallVideo.prototype.getSrc = function () {
  8778. var videoElement = APP.RTC.getVideoElementName();
  8779. return APP.RTC.getVideoSrc(
  8780. $('#' + this.videoSpanId).find(videoElement).get(0));
  8781. };
  8782. SmallVideo.prototype.focus = function(isFocused) {
  8783. if(!isFocused) {
  8784. this.container.classList.remove("videoContainerFocused");
  8785. } else {
  8786. this.container.classList.add("videoContainerFocused");
  8787. }
  8788. };
  8789. SmallVideo.prototype.hasVideo = function () {
  8790. return $("#" + this.videoSpanId).find(
  8791. APP.RTC.getVideoElementName()).length !== 0;
  8792. };
  8793. /**
  8794. * Hides or shows the user's avatar
  8795. * @param show whether we should show the avatar or not
  8796. * video because there is no dominant speaker and no focused speaker
  8797. */
  8798. SmallVideo.prototype.showAvatar = function (show) {
  8799. if (!this.hasAvatar) {
  8800. if (this.peerJid) {
  8801. // Init avatar
  8802. this.avatarChanged(Avatar.getThumbUrl(this.peerJid));
  8803. } else {
  8804. console.error("Unable to init avatar - no peerjid", this);
  8805. return;
  8806. }
  8807. }
  8808. var resourceJid = this.getResourceJid();
  8809. var videoElem = APP.RTC.getVideoElementName();
  8810. var video = $('#' + this.videoSpanId).find(videoElem);
  8811. var avatar = $('#avatar_' + resourceJid);
  8812. if (show === undefined || show === null) {
  8813. if (!this.isLocal &&
  8814. !this.VideoLayout.isInLastN(resourceJid)) {
  8815. show = true;
  8816. } else {
  8817. // We want to show the avatar when the video is muted or not exists
  8818. // that is when 'true' or 'null' is returned
  8819. show = APP.RTC.isVideoMuted(this.peerJid) !== false;
  8820. }
  8821. }
  8822. if (LargeVideo.showAvatar(resourceJid, show)) {
  8823. setVisibility(avatar, false);
  8824. setVisibility(video, false);
  8825. } else {
  8826. if (video && video.length > 0) {
  8827. setVisibility(video, !show);
  8828. }
  8829. setVisibility(avatar, show);
  8830. }
  8831. };
  8832. SmallVideo.prototype.avatarChanged = function (thumbUrl) {
  8833. var thumbnail = $('#' + this.videoSpanId);
  8834. var resourceJid = this.getResourceJid();
  8835. var avatar = $('#avatar_' + resourceJid);
  8836. this.hasAvatar = true;
  8837. // set the avatar in the thumbnail
  8838. if (avatar && avatar.length > 0) {
  8839. avatar[0].src = thumbUrl;
  8840. } else {
  8841. if (thumbnail && thumbnail.length > 0) {
  8842. avatar = document.createElement('img');
  8843. avatar.id = 'avatar_' + resourceJid;
  8844. avatar.className = 'userAvatar';
  8845. avatar.src = thumbUrl;
  8846. thumbnail.append(avatar);
  8847. }
  8848. }
  8849. };
  8850. module.exports = SmallVideo;
  8851. },{"../../RTC/RTCBrowserType":10,"../avatar/Avatar":18,"../util/UIUtil":35,"./LargeVideo":37}],41:[function(require,module,exports){
  8852. /* global config, APP, $, Strophe, require, interfaceConfig */
  8853. var AudioLevels = require("../audio_levels/AudioLevels");
  8854. var ContactList = require("../side_pannels/contactlist/ContactList");
  8855. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  8856. var UIEvents = require("../../../service/UI/UIEvents");
  8857. var RTC = require("../../RTC/RTC");
  8858. var RTCBrowserType = require('../../RTC/RTCBrowserType');
  8859. var RemoteVideo = require("./RemoteVideo");
  8860. var LargeVideo = require("./LargeVideo");
  8861. var LocalVideo = require("./LocalVideo");
  8862. var remoteVideos = {};
  8863. var remoteVideoTypes = {};
  8864. var localVideoThumbnail = null;
  8865. var currentDominantSpeaker = null;
  8866. var lastNCount = config.channelLastN;
  8867. var localLastNCount = config.channelLastN;
  8868. var localLastNSet = [];
  8869. var lastNEndpointsCache = [];
  8870. var lastNPickupJid = null;
  8871. var eventEmitter = null;
  8872. /**
  8873. * Currently focused video jid
  8874. * @type {String}
  8875. */
  8876. var focusedVideoResourceJid = null;
  8877. var VideoLayout = (function (my) {
  8878. my.init = function (emitter) {
  8879. eventEmitter = emitter;
  8880. localVideoThumbnail = new LocalVideo(VideoLayout);
  8881. LargeVideo.init(VideoLayout, emitter);
  8882. VideoLayout.resizeLargeVideoContainer();
  8883. };
  8884. my.isInLastN = function(resource) {
  8885. return lastNCount < 0 || // lastN is disabled
  8886. // lastNEndpoints cache not built yet
  8887. (lastNCount > 0 && lastNEndpointsCache.length == 0) ||
  8888. (lastNEndpointsCache &&
  8889. lastNEndpointsCache.indexOf(resource) !== -1);
  8890. };
  8891. my.changeLocalStream = function (stream, isMuted) {
  8892. VideoLayout.changeLocalVideo(stream, isMuted);
  8893. };
  8894. my.changeLocalAudio = function(stream, isMuted) {
  8895. if (isMuted)
  8896. APP.UI.setAudioMuted(true, true);
  8897. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  8898. var localAudio = document.getElementById('localAudio');
  8899. // Writing volume not allowed in IE
  8900. if (!RTCBrowserType.isIExplorer()) {
  8901. localAudio.autoplay = true;
  8902. localAudio.volume = 0;
  8903. }
  8904. };
  8905. my.changeLocalVideo = function(stream, isMuted) {
  8906. // Set default display name.
  8907. localVideoThumbnail.setDisplayName();
  8908. localVideoThumbnail.createConnectionIndicator();
  8909. this.onVideoTypeChanged(APP.xmpp.myResource(), stream.videoType);
  8910. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  8911. localVideoThumbnail.changeVideo(stream, isMuted);
  8912. /* force update if we're currently being displayed */
  8913. if (LargeVideo.isCurrentlyOnLarge(APP.xmpp.myResource())) {
  8914. LargeVideo.updateLargeVideo(APP.xmpp.myResource(), true);
  8915. }
  8916. };
  8917. my.mucJoined = function () {
  8918. var myResourceJid = APP.xmpp.myResource();
  8919. localVideoThumbnail.joined(APP.xmpp.myJid());
  8920. if (!LargeVideo.getResourceJid())
  8921. LargeVideo.updateLargeVideo(myResourceJid, true);
  8922. };
  8923. /**
  8924. * Adds or removes icons for not available camera and microphone.
  8925. * @param resourceJid the jid of user
  8926. * @param devices available devices
  8927. */
  8928. my.setDeviceAvailabilityIcons = function (resourceJid, devices) {
  8929. if(!devices)
  8930. return;
  8931. if(!resourceJid) {
  8932. localVideoThumbnail.setDeviceAvailabilityIcons(devices);
  8933. } else {
  8934. if(remoteVideos[resourceJid])
  8935. remoteVideos[resourceJid].setDeviceAvailabilityIcons(devices);
  8936. }
  8937. };
  8938. /**
  8939. * Checks if removed video is currently displayed and tries to display
  8940. * another one instead.
  8941. * @param removedVideoSrc src stream identifier of the video.
  8942. */
  8943. my.updateRemovedVideo = function(resourceJid) {
  8944. if (resourceJid === LargeVideo.getResourceJid()) {
  8945. var newResourceJid;
  8946. // We'll show user's avatar if he is the dominant speaker or if
  8947. // his video thumbnail is pinned
  8948. if (remoteVideos[resourceJid] &&
  8949. resourceJid === focusedVideoResourceJid ||
  8950. resourceJid === currentDominantSpeaker) {
  8951. newResourceJid = resourceJid;
  8952. } else {
  8953. // Otherwise select last visible video
  8954. newResourceJid = this.electLastVisibleVideo();
  8955. }
  8956. LargeVideo.updateLargeVideo(newResourceJid);
  8957. }
  8958. };
  8959. my.electLastVisibleVideo = function() {
  8960. // pick the last visible video in the row
  8961. // if nobody else is left, this picks the local video
  8962. var jid;
  8963. var videoElem = RTC.getVideoElementName();
  8964. var pick = $('#remoteVideos>span[id!="mixedstream"]:visible:last>' + videoElem);
  8965. if (pick.length && APP.RTC.getVideoSrc(pick[0])) {
  8966. jid = VideoLayout.getPeerContainerResourceJid(pick[0].parentNode);
  8967. } else {
  8968. console.info("Last visible video no longer exists");
  8969. pick = $('#remoteVideos>span[id!="mixedstream"]>' + videoElem);
  8970. if (pick.length && APP.RTC.getVideoSrc(pick[0])) {
  8971. jid = VideoLayout.getPeerContainerResourceJid(pick[0].parentNode);
  8972. } else {
  8973. // Try local video
  8974. console.info("Fallback to local video...");
  8975. jid = APP.xmpp.myResource();
  8976. }
  8977. }
  8978. console.info("electLastVisibleVideo: " + jid);
  8979. return jid;
  8980. };
  8981. my.onRemoteStreamAdded = function (stream) {
  8982. if (stream.peerjid) {
  8983. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  8984. var resourceJid = Strophe.getResourceFromJid(stream.peerjid);
  8985. remoteVideos[resourceJid].addRemoteStreamElement(
  8986. stream.sid,
  8987. stream.getOriginalStream(),
  8988. stream.ssrc);
  8989. }
  8990. };
  8991. my.getLargeVideoJid = function () {
  8992. return LargeVideo.getResourceJid();
  8993. };
  8994. /**
  8995. * Called when large video update is finished
  8996. * @param currentSmallVideo small video currently displayed on large video
  8997. */
  8998. my.largeVideoUpdated = function (currentSmallVideo) {
  8999. // Makes sure that dominant speaker UI
  9000. // is enabled only on current small video
  9001. localVideoThumbnail.enableDominantSpeaker(
  9002. localVideoThumbnail === currentSmallVideo);
  9003. Object.keys(remoteVideos).forEach(
  9004. function (resourceJid) {
  9005. var remoteVideo = remoteVideos[resourceJid];
  9006. if (remoteVideo) {
  9007. remoteVideo.enableDominantSpeaker(
  9008. remoteVideo === currentSmallVideo);
  9009. }
  9010. }
  9011. );
  9012. };
  9013. my.handleVideoThumbClicked = function(noPinnedEndpointChangedEvent,
  9014. resourceJid) {
  9015. if(focusedVideoResourceJid) {
  9016. var oldSmallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  9017. if(oldSmallVideo)
  9018. oldSmallVideo.focus(false);
  9019. }
  9020. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  9021. // Unlock current focused.
  9022. if (focusedVideoResourceJid === resourceJid)
  9023. {
  9024. focusedVideoResourceJid = null;
  9025. // Enable the currently set dominant speaker.
  9026. if (currentDominantSpeaker) {
  9027. if(smallVideo && smallVideo.hasVideo()) {
  9028. LargeVideo.updateLargeVideo(currentDominantSpeaker);
  9029. }
  9030. }
  9031. if (!noPinnedEndpointChangedEvent) {
  9032. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  9033. }
  9034. return;
  9035. }
  9036. // Lock new video
  9037. focusedVideoResourceJid = resourceJid;
  9038. // Update focused/pinned interface.
  9039. if (resourceJid) {
  9040. if(smallVideo)
  9041. smallVideo.focus(true);
  9042. if (!noPinnedEndpointChangedEvent) {
  9043. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  9044. }
  9045. }
  9046. LargeVideo.setState("video");
  9047. LargeVideo.updateLargeVideo(resourceJid);
  9048. // Writing volume not allowed in IE
  9049. if (!RTCBrowserType.isIExplorer()) {
  9050. $('audio').each(function (idx, el) {
  9051. el.volume = 0;
  9052. el.volume = 1;
  9053. });
  9054. }
  9055. };
  9056. /**
  9057. * Checks if container for participant identified by given peerJid exists
  9058. * in the document and creates it eventually.
  9059. *
  9060. * @param peerJid peer Jid to check.
  9061. *
  9062. * @return Returns <tt>true</tt> if the peer container exists,
  9063. * <tt>false</tt> - otherwise
  9064. */
  9065. my.ensurePeerContainerExists = function(peerJid) {
  9066. ContactList.ensureAddContact(peerJid);
  9067. var resourceJid = Strophe.getResourceFromJid(peerJid);
  9068. if (!remoteVideos[resourceJid]) {
  9069. var remoteVideo = new RemoteVideo(peerJid, VideoLayout);
  9070. remoteVideos[resourceJid] = remoteVideo;
  9071. var videoType = remoteVideoTypes[resourceJid];
  9072. if (videoType) {
  9073. remoteVideo.setVideoType(videoType);
  9074. }
  9075. // In case this is not currently in the last n we don't show it.
  9076. if (localLastNCount &&
  9077. localLastNCount > 0 &&
  9078. $('#remoteVideos>span').length >= localLastNCount + 2) {
  9079. remoteVideo.showPeerContainer('hide');
  9080. }
  9081. else
  9082. VideoLayout.resizeThumbnails();
  9083. }
  9084. };
  9085. my.inputDisplayNameHandler = function (name) {
  9086. localVideoThumbnail.inputDisplayNameHandler(name);
  9087. };
  9088. my.videoactive = function (videoelem, resourceJid) {
  9089. console.info(resourceJid + " video is now active");
  9090. videoelem.show();
  9091. VideoLayout.resizeThumbnails();
  9092. // Update the large video to the last added video only if there's no
  9093. // current dominant, focused speaker or prezi playing or update it to
  9094. // the current dominant speaker.
  9095. if ((!focusedVideoResourceJid &&
  9096. !currentDominantSpeaker &&
  9097. !require("../prezi/Prezi").isPresentationVisible()) ||
  9098. focusedVideoResourceJid === resourceJid ||
  9099. (resourceJid &&
  9100. currentDominantSpeaker === resourceJid)) {
  9101. LargeVideo.updateLargeVideo(resourceJid, true);
  9102. }
  9103. };
  9104. /**
  9105. * Shows the presence status message for the given video.
  9106. */
  9107. my.setPresenceStatus = function (resourceJid, statusMsg) {
  9108. remoteVideos[resourceJid].setPresenceStatus(statusMsg);
  9109. };
  9110. /**
  9111. * Shows a visual indicator for the moderator of the conference.
  9112. */
  9113. my.showModeratorIndicator = function () {
  9114. var isModerator = APP.xmpp.isModerator();
  9115. if (isModerator) {
  9116. localVideoThumbnail.createModeratorIndicatorElement();
  9117. }
  9118. var members = APP.xmpp.getMembers();
  9119. Object.keys(members).forEach(function (jid) {
  9120. if (Strophe.getResourceFromJid(jid) === 'focus') {
  9121. // Skip server side focus
  9122. return;
  9123. }
  9124. var resourceJid = Strophe.getResourceFromJid(jid);
  9125. var member = members[jid];
  9126. if (member.role === 'moderator') {
  9127. remoteVideos[resourceJid].removeRemoteVideoMenu();
  9128. remoteVideos[resourceJid].createModeratorIndicatorElement();
  9129. } else if (isModerator) {
  9130. // We are moderator, but user is not - add menu
  9131. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  9132. remoteVideos[resourceJid].addRemoteVideoMenu();
  9133. }
  9134. }
  9135. });
  9136. };
  9137. /*
  9138. * Shows or hides the audio muted indicator over the local thumbnail video.
  9139. * @param {boolean} isMuted
  9140. */
  9141. my.showLocalAudioIndicator = function(isMuted) {
  9142. localVideoThumbnail.showAudioIndicator(isMuted);
  9143. };
  9144. /**
  9145. * Resizes the large video container.
  9146. */
  9147. my.resizeLargeVideoContainer = function () {
  9148. LargeVideo.resize();
  9149. VideoLayout.resizeThumbnails();
  9150. LargeVideo.position();
  9151. };
  9152. /**
  9153. * Resizes thumbnails.
  9154. */
  9155. my.resizeThumbnails = function(animate) {
  9156. var videoSpaceWidth = $('#remoteVideos').width();
  9157. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  9158. var width = thumbnailSize[0];
  9159. var height = thumbnailSize[1];
  9160. $('.userAvatar').css('left', (width - height) / 2);
  9161. if(animate) {
  9162. $('#remoteVideos').animate({
  9163. height: height
  9164. },
  9165. {
  9166. queue: false,
  9167. duration: 500
  9168. });
  9169. $('#remoteVideos>span').animate({
  9170. height: height,
  9171. width: width
  9172. },
  9173. {
  9174. queue: false,
  9175. duration: 500,
  9176. complete: function () {
  9177. $(document).trigger(
  9178. "remotevideo.resized",
  9179. [width,
  9180. height]);
  9181. }
  9182. });
  9183. } else {
  9184. // size videos so that while keeping AR and max height, we have a
  9185. // nice fit
  9186. $('#remoteVideos').height(height);
  9187. $('#remoteVideos>span').width(width);
  9188. $('#remoteVideos>span').height(height);
  9189. $(document).trigger("remotevideo.resized", [width, height]);
  9190. }
  9191. };
  9192. /**
  9193. * Calculates the thumbnail size.
  9194. *
  9195. * @param videoSpaceWidth the width of the video space
  9196. */
  9197. my.calculateThumbnailSize = function (videoSpaceWidth) {
  9198. // Calculate the available height, which is the inner window height minus
  9199. // 39px for the header minus 2px for the delimiter lines on the top and
  9200. // bottom of the large video, minus the 36px space inside the remoteVideos
  9201. // container used for highlighting shadow.
  9202. var availableHeight = 100;
  9203. var numvids = $('#remoteVideos>span:visible').length;
  9204. if (localLastNCount && localLastNCount > 0) {
  9205. numvids = Math.min(localLastNCount + 1, numvids);
  9206. }
  9207. // Remove the 3px borders arround videos and border around the remote
  9208. // videos area and the 4 pixels between the local video and the others
  9209. //TODO: Find out where the 4 pixels come from and remove them
  9210. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  9211. var availableWidth = availableWinWidth / numvids;
  9212. var aspectRatio = 16.0 / 9.0;
  9213. var maxHeight = Math.min(160, availableHeight);
  9214. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  9215. if (availableHeight < availableWidth / aspectRatio) {
  9216. availableWidth = Math.floor(availableHeight * aspectRatio);
  9217. }
  9218. return [availableWidth, availableHeight];
  9219. };
  9220. /**
  9221. * Returns the corresponding resource jid to the given peer container
  9222. * DOM element.
  9223. *
  9224. * @return the corresponding resource jid to the given peer container
  9225. * DOM element
  9226. */
  9227. my.getPeerContainerResourceJid = function (containerElement) {
  9228. var i = containerElement.id.indexOf('participant_');
  9229. if (i >= 0)
  9230. return containerElement.id.substring(i + 12);
  9231. };
  9232. my.getPeerVideoSel = function (peerResourceJid) {
  9233. return $('#participant_' + peerResourceJid +
  9234. '>' + APP.RTC.getVideoElementName());
  9235. };
  9236. /**
  9237. * On contact list item clicked.
  9238. */
  9239. $(ContactList).bind('contactclicked', function(event, jid) {
  9240. if (!jid) {
  9241. return;
  9242. }
  9243. if (jid === APP.xmpp.myJid()) {
  9244. $("#localVideoContainer").click();
  9245. return;
  9246. }
  9247. var resource = Strophe.getResourceFromJid(jid);
  9248. var videoSel = VideoLayout.getPeerVideoSel(resource);
  9249. if (videoSel.length > 0) {
  9250. var videoThumb = videoSel[0];
  9251. // It is not always the case that a videoThumb exists (if there is
  9252. // no actual video).
  9253. if (RTC.getVideoSrc(videoThumb)) {
  9254. // We have a video src, great! Let's update the large video
  9255. // now.
  9256. VideoLayout.handleVideoThumbClicked(
  9257. false,
  9258. Strophe.getResourceFromJid(jid));
  9259. } else {
  9260. // If we don't have a video src for jid, there's absolutely
  9261. // no point in calling handleVideoThumbClicked; Quite
  9262. // simply, it won't work because it needs an src to attach
  9263. // to the large video.
  9264. //
  9265. // Instead, we trigger the pinned endpoint changed event to
  9266. // let the bridge adjust its lastN set for myjid and store
  9267. // the pinned user in the lastNPickupJid variable to be
  9268. // picked up later by the lastN changed event handler.
  9269. lastNPickupJid = jid;
  9270. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  9271. Strophe.getResourceFromJid(jid));
  9272. }
  9273. }
  9274. });
  9275. /**
  9276. * On audio muted event.
  9277. */
  9278. my.onAudioMute = function (jid, isMuted) {
  9279. var resourceJid = Strophe.getResourceFromJid(jid);
  9280. if (resourceJid === APP.xmpp.myResource()) {
  9281. localVideoThumbnail.showAudioIndicator(isMuted);
  9282. } else {
  9283. VideoLayout.ensurePeerContainerExists(jid);
  9284. remoteVideos[resourceJid].showAudioIndicator(isMuted);
  9285. if (APP.xmpp.isModerator()) {
  9286. remoteVideos[resourceJid].updateRemoteVideoMenu(isMuted);
  9287. }
  9288. }
  9289. };
  9290. /**
  9291. * On video muted event.
  9292. */
  9293. my.onVideoMute = function (jid, value) {
  9294. if (jid !== APP.xmpp.myJid() &&
  9295. !APP.RTC.muteRemoteVideoStream(jid, value))
  9296. return;
  9297. if (jid === APP.xmpp.myJid()) {
  9298. localVideoThumbnail.showVideoIndicator(value);
  9299. } else {
  9300. var resource = Strophe.getResourceFromJid(jid);
  9301. VideoLayout.ensurePeerContainerExists(jid);
  9302. remoteVideos[resource].showVideoIndicator(value);
  9303. var el = VideoLayout.getPeerVideoSel(resource);
  9304. if (!value)
  9305. el.show();
  9306. else
  9307. el.hide();
  9308. }
  9309. };
  9310. /**
  9311. * Display name changed.
  9312. */
  9313. my.onDisplayNameChanged =
  9314. function (jid, displayName, status) {
  9315. if (jid === 'localVideoContainer' ||
  9316. jid === APP.xmpp.myJid()) {
  9317. localVideoThumbnail.setDisplayName(displayName);
  9318. } else {
  9319. VideoLayout.ensurePeerContainerExists(jid);
  9320. remoteVideos[Strophe.getResourceFromJid(jid)].setDisplayName(
  9321. displayName,
  9322. status);
  9323. }
  9324. };
  9325. /**
  9326. * On dominant speaker changed event.
  9327. */
  9328. my.onDominantSpeakerChanged = function (resourceJid) {
  9329. // We ignore local user events.
  9330. if (resourceJid === APP.xmpp.myResource())
  9331. return;
  9332. var members = APP.xmpp.getMembers();
  9333. // Update the current dominant speaker.
  9334. if (resourceJid !== currentDominantSpeaker) {
  9335. var currentJID = APP.xmpp.findJidFromResource(currentDominantSpeaker);
  9336. var newJID = APP.xmpp.findJidFromResource(resourceJid);
  9337. if(currentDominantSpeaker && (!members || !members[currentJID] ||
  9338. !members[currentJID].displayName) && remoteVideos[resourceJid]) {
  9339. remoteVideos[resourceJid].setDisplayName(null);
  9340. }
  9341. if(resourceJid && (!members || !members[newJID] ||
  9342. !members[newJID].displayName) && remoteVideos[resourceJid]) {
  9343. remoteVideos[resourceJid].setDisplayName(null,
  9344. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  9345. }
  9346. currentDominantSpeaker = resourceJid;
  9347. } else {
  9348. return;
  9349. }
  9350. // Obtain container for new dominant speaker.
  9351. var videoSel = VideoLayout.getPeerVideoSel(resourceJid);
  9352. // Local video will not have container found, but that's ok
  9353. // since we don't want to switch to local video.
  9354. if (!focusedVideoResourceJid && videoSel.length) {
  9355. // Update the large video if the video source is already available,
  9356. // otherwise wait for the "videoactive.jingle" event.
  9357. if (videoSel[0].currentTime > 0) {
  9358. LargeVideo.updateLargeVideo(resourceJid);
  9359. }
  9360. }
  9361. };
  9362. /**
  9363. * On last N change event.
  9364. *
  9365. * @param lastNEndpoints the list of last N endpoints
  9366. * @param endpointsEnteringLastN the list currently entering last N
  9367. * endpoints
  9368. */
  9369. my.onLastNEndpointsChanged = function (lastNEndpoints,
  9370. endpointsEnteringLastN,
  9371. stream) {
  9372. if (lastNCount !== lastNEndpoints.length)
  9373. lastNCount = lastNEndpoints.length;
  9374. lastNEndpointsCache = lastNEndpoints;
  9375. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  9376. //
  9377. // If LastN drops to, say, 2, because of adaptivity, then E should see
  9378. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  9379. // so E sees them. C is only in E's local LastN set.
  9380. //
  9381. // If F starts talking and LastN = 3, then E should see thumbnails for
  9382. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  9383. // enters E's local LastN ejecting C.
  9384. // Increase the local LastN set size, if necessary.
  9385. if (lastNCount > localLastNCount) {
  9386. localLastNCount = lastNCount;
  9387. }
  9388. // Update the local LastN set preserving the order in which the
  9389. // endpoints appeared in the LastN/local LastN set.
  9390. var nextLocalLastNSet = lastNEndpoints.slice(0);
  9391. for (var i = 0; i < localLastNSet.length; i++) {
  9392. if (nextLocalLastNSet.length >= localLastNCount) {
  9393. break;
  9394. }
  9395. var resourceJid = localLastNSet[i];
  9396. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  9397. nextLocalLastNSet.push(resourceJid);
  9398. }
  9399. }
  9400. localLastNSet = nextLocalLastNSet;
  9401. var updateLargeVideo = false;
  9402. // Handle LastN/local LastN changes.
  9403. $('#remoteVideos>span').each(function( index, element ) {
  9404. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  9405. var isReceived = true;
  9406. if (resourceJid &&
  9407. lastNEndpoints.indexOf(resourceJid) < 0 &&
  9408. localLastNSet.indexOf(resourceJid) < 0) {
  9409. console.log("Remove from last N", resourceJid);
  9410. remoteVideos[resourceJid].showPeerContainer('hide');
  9411. isReceived = false;
  9412. } else if (resourceJid &&
  9413. $('#participant_' + resourceJid).is(':visible') &&
  9414. lastNEndpoints.indexOf(resourceJid) < 0 &&
  9415. localLastNSet.indexOf(resourceJid) >= 0) {
  9416. remoteVideos[resourceJid].showPeerContainer('avatar');
  9417. isReceived = false;
  9418. }
  9419. if (!isReceived) {
  9420. // resourceJid has dropped out of the server side lastN set, so
  9421. // it is no longer being received. If resourceJid was being
  9422. // displayed in the large video we have to switch to another
  9423. // user.
  9424. if (!updateLargeVideo &&
  9425. resourceJid === LargeVideo.getResourceJid()) {
  9426. updateLargeVideo = true;
  9427. }
  9428. }
  9429. });
  9430. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  9431. endpointsEnteringLastN = lastNEndpoints;
  9432. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  9433. endpointsEnteringLastN.forEach(function (resourceJid) {
  9434. var isVisible = $('#participant_' + resourceJid).is(':visible');
  9435. remoteVideos[resourceJid].showPeerContainer('show');
  9436. if (!isVisible) {
  9437. console.log("Add to last N", resourceJid);
  9438. var jid = APP.xmpp.findJidFromResource(resourceJid);
  9439. var mediaStream =
  9440. APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  9441. var sel = VideoLayout.getPeerVideoSel(resourceJid);
  9442. APP.RTC.attachMediaStream(sel, mediaStream.stream);
  9443. if (lastNPickupJid == mediaStream.peerjid) {
  9444. // Clean up the lastN pickup jid.
  9445. lastNPickupJid = null;
  9446. // Don't fire the events again, they've already
  9447. // been fired in the contact list click handler.
  9448. VideoLayout.handleVideoThumbClicked(
  9449. false,
  9450. Strophe.getResourceFromJid(mediaStream.peerjid));
  9451. updateLargeVideo = false;
  9452. }
  9453. remoteVideos[resourceJid].
  9454. waitForPlayback(sel, mediaStream.stream);
  9455. }
  9456. });
  9457. }
  9458. // The endpoint that was being shown in the large video has dropped out
  9459. // of the lastN set and there was no lastN pickup jid. We need to update
  9460. // the large video now.
  9461. if (updateLargeVideo) {
  9462. var resource;
  9463. var myResource
  9464. = APP.xmpp.myResource();
  9465. // Find out which endpoint to show in the large video.
  9466. for (i = 0; i < lastNEndpoints.length; i++) {
  9467. resource = lastNEndpoints[i];
  9468. if (!resource || resource === myResource)
  9469. continue;
  9470. // videoSrcToSsrc needs to be update for this call to succeed.
  9471. LargeVideo.updateLargeVideo(resource);
  9472. break;
  9473. }
  9474. }
  9475. };
  9476. /**
  9477. * Updates local stats
  9478. * @param percent
  9479. * @param object
  9480. */
  9481. my.updateLocalConnectionStats = function (percent, object) {
  9482. var resolution = null;
  9483. if (object.resolution !== null) {
  9484. resolution = object.resolution;
  9485. object.resolution = resolution[APP.xmpp.myJid()];
  9486. delete resolution[APP.xmpp.myJid()];
  9487. }
  9488. localVideoThumbnail.updateStatsIndicator(percent, object);
  9489. for (var jid in resolution) {
  9490. if (resolution[jid] === null)
  9491. continue;
  9492. var resourceJid = Strophe.getResourceFromJid(jid);
  9493. if (remoteVideos[resourceJid] &&
  9494. remoteVideos[resourceJid].connectionIndicator) {
  9495. remoteVideos[resourceJid].connectionIndicator.
  9496. updateResolution(resolution[jid]);
  9497. }
  9498. }
  9499. };
  9500. /**
  9501. * Updates remote stats.
  9502. * @param jid the jid associated with the stats
  9503. * @param percent the connection quality percent
  9504. * @param object the stats data
  9505. */
  9506. my.updateConnectionStats = function (jid, percent, object) {
  9507. var resourceJid = Strophe.getResourceFromJid(jid);
  9508. if (remoteVideos[resourceJid])
  9509. remoteVideos[resourceJid].updateStatsIndicator(percent, object);
  9510. };
  9511. /**
  9512. * Hides the connection indicator
  9513. * @param jid
  9514. */
  9515. my.hideConnectionIndicator = function (jid) {
  9516. remoteVideos[Strophe.getResourceFromJid(jid)].hideConnectionIndicator();
  9517. };
  9518. /**
  9519. * Hides all the indicators
  9520. */
  9521. my.onStatsStop = function () {
  9522. for(var video in remoteVideos) {
  9523. remoteVideos[video].hideIndicator();
  9524. }
  9525. localVideoThumbnail.hideIndicator();
  9526. };
  9527. my.participantLeft = function (jid) {
  9528. // Unlock large video
  9529. var resourceJid = Strophe.getResourceFromJid(jid);
  9530. if (focusedVideoResourceJid === resourceJid) {
  9531. console.info("Focused video owner has left the conference");
  9532. focusedVideoResourceJid = null;
  9533. }
  9534. if (currentDominantSpeaker === resourceJid)
  9535. {
  9536. console.info("Dominant speaker has left the conference");
  9537. currentDominantSpeaker = null;
  9538. }
  9539. var remoteVideo = remoteVideos[resourceJid];
  9540. if (remoteVideo) {
  9541. // Remove remote video
  9542. console.info("Removing remote video: " + resourceJid);
  9543. remoteVideo.remove();
  9544. delete remoteVideos[resourceJid];
  9545. } else {
  9546. console.warn("No remote video for " + resourceJid);
  9547. }
  9548. VideoLayout.resizeThumbnails();
  9549. };
  9550. my.onVideoTypeChanged = function (resourceJid, newVideoType) {
  9551. if (remoteVideoTypes[resourceJid] === newVideoType) {
  9552. return;
  9553. }
  9554. console.info("Peer video type changed: ", resourceJid, newVideoType);
  9555. remoteVideoTypes[resourceJid] = newVideoType;
  9556. var smallVideo;
  9557. if (resourceJid === APP.xmpp.myResource()) {
  9558. if (!localVideoThumbnail) {
  9559. console.warn("Local video not ready yet");
  9560. return;
  9561. }
  9562. smallVideo = localVideoThumbnail;
  9563. } else if (remoteVideos[resourceJid]) {
  9564. smallVideo = remoteVideos[resourceJid];
  9565. } else {
  9566. return;
  9567. }
  9568. smallVideo.setVideoType(newVideoType);
  9569. LargeVideo.onVideoTypeChanged(resourceJid, newVideoType);
  9570. };
  9571. my.showMore = function (jid) {
  9572. if (jid === 'local') {
  9573. localVideoThumbnail.connectionIndicator.showMore();
  9574. } else {
  9575. var remoteVideo = remoteVideos[Strophe.getResourceFromJid(jid)];
  9576. if (remoteVideo) {
  9577. remoteVideo.connectionIndicator.showMore();
  9578. } else {
  9579. console.info("Error - no remote video for jid: " + jid);
  9580. }
  9581. }
  9582. };
  9583. my.addPreziContainer = function (id) {
  9584. var container = RemoteVideo.createContainer(id);
  9585. VideoLayout.resizeThumbnails();
  9586. return container;
  9587. };
  9588. my.setLargeVideoVisible = function (isVisible) {
  9589. LargeVideo.setLargeVideoVisible(isVisible);
  9590. if(!isVisible && focusedVideoResourceJid) {
  9591. var smallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  9592. if(smallVideo) {
  9593. smallVideo.focus(false);
  9594. smallVideo.showAvatar();
  9595. }
  9596. focusedVideoResourceJid = null;
  9597. }
  9598. };
  9599. /**
  9600. * Resizes the video area
  9601. * @param callback a function to be called when the video space is
  9602. * resized.
  9603. */
  9604. my.resizeVideoArea = function(isVisible, callback) {
  9605. LargeVideo.resizeVideoAreaAnimated(isVisible, callback);
  9606. VideoLayout.resizeThumbnails(true);
  9607. };
  9608. my.getSmallVideo = function (resourceJid) {
  9609. if(resourceJid == APP.xmpp.myResource()) {
  9610. return localVideoThumbnail;
  9611. } else {
  9612. if(!remoteVideos[resourceJid])
  9613. return null;
  9614. return remoteVideos[resourceJid];
  9615. }
  9616. };
  9617. my.userAvatarChanged = function(resourceJid, thumbUrl) {
  9618. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  9619. if(smallVideo)
  9620. smallVideo.avatarChanged(thumbUrl);
  9621. else
  9622. console.warn(
  9623. "Missed avatar update - no small video yet for " + resourceJid);
  9624. LargeVideo.updateAvatar(resourceJid, thumbUrl);
  9625. };
  9626. my.createEtherpadIframe = function(src, onloadHandler)
  9627. {
  9628. return LargeVideo.createEtherpadIframe(src, onloadHandler);
  9629. };
  9630. my.setLargeVideoState = function (state) {
  9631. LargeVideo.setState(state);
  9632. };
  9633. my.getLargeVideoState = function () {
  9634. return LargeVideo.getState();
  9635. };
  9636. my.setLargeVideoHover = function (inHandler, outHandler) {
  9637. LargeVideo.setHover(inHandler, outHandler);
  9638. };
  9639. /**
  9640. * Indicates that the video has been interrupted.
  9641. */
  9642. my.onVideoInterrupted = function () {
  9643. LargeVideo.enableVideoProblemFilter(true);
  9644. var reconnectingKey = "connection.RECONNECTING";
  9645. $('#videoConnectionMessage').attr("data-i18n", reconnectingKey);
  9646. $('#videoConnectionMessage').text(APP.translation.translateString(reconnectingKey));
  9647. $('#videoConnectionMessage').css({display: "block"});
  9648. };
  9649. /**
  9650. * Indicates that the video has been restored.
  9651. */
  9652. my.onVideoRestored = function () {
  9653. LargeVideo.enableVideoProblemFilter(false);
  9654. $('#videoConnectionMessage').css({display: "none"});
  9655. };
  9656. return my;
  9657. }(VideoLayout || {}));
  9658. module.exports = VideoLayout;
  9659. },{"../../../service/RTC/MediaStreamTypes":109,"../../../service/UI/UIEvents":113,"../../RTC/RTC":9,"../../RTC/RTCBrowserType":10,"../audio_levels/AudioLevels":14,"../prezi/Prezi":20,"../side_pannels/contactlist/ContactList":27,"./LargeVideo":37,"./LocalVideo":38,"./RemoteVideo":39}],42:[function(require,module,exports){
  9660. //var nouns = [
  9661. //];
  9662. var pluralNouns = [
  9663. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  9664. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  9665. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  9666. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  9667. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  9668. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  9669. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  9670. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  9671. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  9672. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  9673. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  9674. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  9675. ];
  9676. //var places = [
  9677. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  9678. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  9679. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  9680. // "Bridge"
  9681. //];
  9682. var verbs = [
  9683. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  9684. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  9685. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  9686. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  9687. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  9688. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  9689. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  9690. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  9691. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  9692. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  9693. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  9694. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  9695. ];
  9696. var adverbs = [
  9697. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  9698. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  9699. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  9700. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  9701. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  9702. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  9703. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  9704. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  9705. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  9706. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  9707. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  9708. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  9709. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  9710. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  9711. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly",
  9712. "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  9713. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  9714. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  9715. ];
  9716. var adjectives = [
  9717. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  9718. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  9719. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  9720. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  9721. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  9722. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  9723. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  9724. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  9725. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  9726. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  9727. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  9728. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  9729. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  9730. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  9731. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  9732. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  9733. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  9734. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  9735. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  9736. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  9737. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  9738. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  9739. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  9740. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  9741. "Zealous"
  9742. ];
  9743. //var pronouns = [
  9744. //];
  9745. //var conjunctions = [
  9746. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  9747. //];
  9748. /*
  9749. * Maps a string (category name) to the array of words from that category.
  9750. */
  9751. var CATEGORIES =
  9752. {
  9753. //"_NOUN_": nouns,
  9754. "_PLURALNOUN_": pluralNouns,
  9755. //"_PLACE_": places,
  9756. "_VERB_": verbs,
  9757. "_ADVERB_": adverbs,
  9758. "_ADJECTIVE_": adjectives
  9759. //"_PRONOUN_": pronouns,
  9760. //"_CONJUNCTION_": conjunctions,
  9761. };
  9762. var PATTERNS = [
  9763. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  9764. // BeautifulFungiOrSpaghetti
  9765. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  9766. // AmazinglyScaryToy
  9767. //"_ADVERB__ADJECTIVE__NOUN_",
  9768. // NeitherTrashNorRifle
  9769. //"Neither_NOUN_Nor_NOUN_",
  9770. //"Either_NOUN_Or_NOUN_",
  9771. // EitherCopulateOrInvestigate
  9772. //"Either_VERB_Or_VERB_",
  9773. //"Neither_VERB_Nor_VERB_",
  9774. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  9775. //"The_ADVERB__ADJECTIVE__NOUN_",
  9776. //"The_ADVERB__ADJECTIVE__NOUN_s",
  9777. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  9778. // WolvesComputeBadly
  9779. //"_PLURALNOUN__VERB__ADVERB_",
  9780. // UniteFacilitateAndMerge
  9781. //"_VERB__VERB_And_VERB_",
  9782. //NastyWitchesAtThePub
  9783. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  9784. ];
  9785. /*
  9786. * Returns a random element from the array 'arr'
  9787. */
  9788. function randomElement(arr) {
  9789. return arr[Math.floor(Math.random() * arr.length)];
  9790. }
  9791. /*
  9792. * Returns true if the string 's' contains one of the
  9793. * template strings.
  9794. */
  9795. function hasTemplate(s) {
  9796. for (var template in CATEGORIES){
  9797. if (s.indexOf(template) >= 0){
  9798. return true;
  9799. }
  9800. }
  9801. }
  9802. /**
  9803. * Generates new room name.
  9804. */
  9805. var RoomNameGenerator = {
  9806. generateRoomWithoutSeparator: function() {
  9807. // Note that if more than one pattern is available, the choice of
  9808. // 'name' won't have a uniform distribution amongst all patterns (names
  9809. // from patterns with fewer options will have higher probability of
  9810. // being chosen that names from patterns with more options).
  9811. var name = randomElement(PATTERNS);
  9812. var word;
  9813. while (hasTemplate(name)) {
  9814. for (var template in CATEGORIES) {
  9815. word = randomElement(CATEGORIES[template]);
  9816. name = name.replace(template, word);
  9817. }
  9818. }
  9819. return name;
  9820. }
  9821. };
  9822. module.exports = RoomNameGenerator;
  9823. },{}],43:[function(require,module,exports){
  9824. /* global $, interfaceConfig */
  9825. var animateTimeout, updateTimeout;
  9826. var RoomNameGenerator = require("./RoomnameGenerator");
  9827. function enter_room() {
  9828. var val = $("#enter_room_field").val();
  9829. if(!val) {
  9830. val = $("#enter_room_field").attr("room_name");
  9831. }
  9832. if (val) {
  9833. window.location.pathname = "/" + val;
  9834. }
  9835. }
  9836. function animate(word) {
  9837. var currentVal = $("#enter_room_field").attr("placeholder");
  9838. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  9839. animateTimeout = setTimeout(function() {
  9840. animate(word.substring(1, word.length))
  9841. }, 70);
  9842. }
  9843. function update_roomname() {
  9844. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  9845. $("#enter_room_field").attr("room_name", word);
  9846. $("#enter_room_field").attr("placeholder", "");
  9847. clearTimeout(animateTimeout);
  9848. animate(word);
  9849. updateTimeout = setTimeout(update_roomname, 10000);
  9850. }
  9851. function setupWelcomePage() {
  9852. $("#videoconference_page").hide();
  9853. $("#domain_name").text(
  9854. window.location.protocol + "//" + window.location.host + "/");
  9855. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  9856. var leftWatermarkDiv =
  9857. $("#welcome_page_header div[class='watermark leftwatermark']");
  9858. if(leftWatermarkDiv && leftWatermarkDiv.length > 0) {
  9859. leftWatermarkDiv.css({display: 'block'});
  9860. leftWatermarkDiv.parent().get(0).href =
  9861. interfaceConfig.JITSI_WATERMARK_LINK;
  9862. }
  9863. }
  9864. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  9865. var rightWatermarkDiv =
  9866. $("#welcome_page_header div[class='watermark rightwatermark']");
  9867. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  9868. rightWatermarkDiv.css({display: 'block'});
  9869. rightWatermarkDiv.parent().get(0).href =
  9870. interfaceConfig.BRAND_WATERMARK_LINK;
  9871. rightWatermarkDiv.get(0).style.backgroundImage =
  9872. "url(images/rightwatermark.png)";
  9873. }
  9874. }
  9875. if (interfaceConfig.SHOW_POWERED_BY) {
  9876. $("#welcome_page_header>a[class='poweredby']")
  9877. .css({display: 'block'});
  9878. }
  9879. $("#enter_room_button").click(function() {
  9880. enter_room();
  9881. });
  9882. $("#enter_room_field").keydown(function (event) {
  9883. if (event.keyCode === 13 /* enter */) {
  9884. enter_room();
  9885. }
  9886. });
  9887. if (interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE !== false) {
  9888. var updateTimeout;
  9889. var animateTimeout;
  9890. var selector = $("#reload_roomname");
  9891. selector.click(function () {
  9892. clearTimeout(updateTimeout);
  9893. clearTimeout(animateTimeout);
  9894. update_roomname();
  9895. });
  9896. selector.show();
  9897. update_roomname();
  9898. }
  9899. $("#disable_welcome").click(function () {
  9900. window.localStorage.welcomePageDisabled =
  9901. $("#disable_welcome").is(":checked");
  9902. });
  9903. }
  9904. module.exports = setupWelcomePage;
  9905. },{"./RoomnameGenerator":42}],44:[function(require,module,exports){
  9906. /* global $, $iq, config */
  9907. var params = {};
  9908. function getConfigParamsFromUrl() {
  9909. if(!location.hash)
  9910. return {};
  9911. var hash = location.hash.substr(1);
  9912. var result = {};
  9913. hash.split("&").forEach(function(part) {
  9914. var item = part.split("=");
  9915. result[item[0]] = JSON.parse(
  9916. decodeURIComponent(item[1]).replace(/\\&/, "&"));
  9917. });
  9918. return result;
  9919. }
  9920. params = getConfigParamsFromUrl();
  9921. var URLProcessor = {
  9922. setConfigParametersFromUrl: function () {
  9923. for(var k in params)
  9924. {
  9925. if(typeof k !== "string" || k.indexOf("config.") === -1)
  9926. continue;
  9927. var v = params[k];
  9928. var confKey = k.substr(7);
  9929. if(config[confKey] && typeof config[confKey] !== typeof v)
  9930. {
  9931. console.warn("The type of " + k +
  9932. " is wrong. That parameter won't be updated in config.js.");
  9933. continue;
  9934. }
  9935. config[confKey] = v;
  9936. }
  9937. }
  9938. };
  9939. module.exports = URLProcessor;
  9940. },{}],45:[function(require,module,exports){
  9941. /* global APP, require */
  9942. var EventEmitter = require("events");
  9943. var eventEmitter = new EventEmitter();
  9944. var CQEvents = require("../../service/connectionquality/CQEvents");
  9945. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9946. /**
  9947. * local stats
  9948. * @type {{}}
  9949. */
  9950. var stats = {};
  9951. /**
  9952. * remote stats
  9953. * @type {{}}
  9954. */
  9955. var remoteStats = {};
  9956. /**
  9957. * Interval for sending statistics to other participants
  9958. * @type {null}
  9959. */
  9960. var sendIntervalId = null;
  9961. /**
  9962. * Start statistics sending.
  9963. */
  9964. function startSendingStats() {
  9965. sendStats();
  9966. sendIntervalId = setInterval(sendStats, 10000);
  9967. }
  9968. /**
  9969. * Sends statistics to other participants
  9970. */
  9971. function sendStats() {
  9972. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  9973. }
  9974. /**
  9975. * Converts statistics to format for sending through XMPP
  9976. * @param stats the statistics
  9977. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  9978. */
  9979. function convertToMUCStats(stats) {
  9980. return {
  9981. "bitrate_download": stats.bitrate.download,
  9982. "bitrate_upload": stats.bitrate.upload,
  9983. "packetLoss_total": stats.packetLoss.total,
  9984. "packetLoss_download": stats.packetLoss.download,
  9985. "packetLoss_upload": stats.packetLoss.upload
  9986. };
  9987. }
  9988. /**
  9989. * Converts statistics to format used by VideoLayout
  9990. * @param stats
  9991. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  9992. */
  9993. function parseMUCStats(stats) {
  9994. return {
  9995. bitrate: {
  9996. download: stats.bitrate_download,
  9997. upload: stats.bitrate_upload
  9998. },
  9999. packetLoss: {
  10000. total: stats.packetLoss_total,
  10001. download: stats.packetLoss_download,
  10002. upload: stats.packetLoss_upload
  10003. }
  10004. };
  10005. }
  10006. var ConnectionQuality = {
  10007. init: function () {
  10008. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  10009. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  10010. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  10011. },
  10012. /**
  10013. * Updates the local statistics
  10014. * @param data new statistics
  10015. */
  10016. updateLocalStats: function (data) {
  10017. stats = data;
  10018. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  10019. if (sendIntervalId == null) {
  10020. startSendingStats();
  10021. }
  10022. },
  10023. /**
  10024. * Updates remote statistics
  10025. * @param jid the jid associated with the statistics
  10026. * @param data the statistics
  10027. */
  10028. updateRemoteStats: function (jid, data) {
  10029. if (data == null || data.packetLoss_total == null) {
  10030. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  10031. return;
  10032. }
  10033. remoteStats[jid] = parseMUCStats(data);
  10034. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  10035. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  10036. },
  10037. /**
  10038. * Stops statistics sending.
  10039. */
  10040. stopSendingStats: function () {
  10041. clearInterval(sendIntervalId);
  10042. sendIntervalId = null;
  10043. //notify UI about stopping statistics gathering
  10044. eventEmitter.emit(CQEvents.STOP);
  10045. },
  10046. /**
  10047. * Returns the local statistics.
  10048. */
  10049. getStats: function () {
  10050. return stats;
  10051. },
  10052. addListener: function (type, listener) {
  10053. eventEmitter.on(type, listener);
  10054. }
  10055. };
  10056. module.exports = ConnectionQuality;
  10057. },{"../../service/connectionquality/CQEvents":115,"../../service/xmpp/XMPPEvents":119,"events":1}],46:[function(require,module,exports){
  10058. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  10059. getUserMediaWithConstraints */
  10060. /**
  10061. * Indicates that desktop stream is currently in use(for toggle purpose).
  10062. * @type {boolean}
  10063. */
  10064. var isUsingScreenStream = false;
  10065. /**
  10066. * Indicates that switch stream operation is in progress and prevent from
  10067. * triggering new events.
  10068. * @type {boolean}
  10069. */
  10070. var switchInProgress = false;
  10071. /**
  10072. * Method used to get screen sharing stream.
  10073. *
  10074. * @type {function (stream_callback, failure_callback}
  10075. */
  10076. var obtainDesktopStream = null;
  10077. /**
  10078. * Indicates whether desktop sharing extension is installed.
  10079. * @type {boolean}
  10080. */
  10081. var extInstalled = false;
  10082. /**
  10083. * Indicates whether update of desktop sharing extension is required.
  10084. * @type {boolean}
  10085. */
  10086. var extUpdateRequired = false;
  10087. var AdapterJS = require("../RTC/adapter.screenshare");
  10088. var EventEmitter = require("events");
  10089. var eventEmitter = new EventEmitter();
  10090. var DesktopSharingEventTypes
  10091. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  10092. var RTCBrowserType = require("../RTC/RTCBrowserType");
  10093. var RTCEvents = require("../../service/RTC/RTCEvents");
  10094. /**
  10095. * Method obtains desktop stream from WebRTC 'screen' source.
  10096. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  10097. */
  10098. function obtainWebRTCScreen(streamCallback, failCallback) {
  10099. APP.RTC.getUserMediaWithConstraints(
  10100. ['screen'],
  10101. streamCallback,
  10102. failCallback
  10103. );
  10104. }
  10105. /**
  10106. * Constructs inline install URL for Chrome desktop streaming extension.
  10107. * The 'chromeExtensionId' must be defined in config.js.
  10108. * @returns {string}
  10109. */
  10110. function getWebStoreInstallUrl()
  10111. {
  10112. return "https://chrome.google.com/webstore/detail/" +
  10113. config.chromeExtensionId;
  10114. }
  10115. /**
  10116. * Checks whether extension update is required.
  10117. * @param minVersion minimal required version
  10118. * @param extVersion current extension version
  10119. * @returns {boolean}
  10120. */
  10121. function isUpdateRequired(minVersion, extVersion)
  10122. {
  10123. try
  10124. {
  10125. var s1 = minVersion.split('.');
  10126. var s2 = extVersion.split('.');
  10127. var len = Math.max(s1.length, s2.length);
  10128. for (var i = 0; i < len; i++)
  10129. {
  10130. var n1 = 0,
  10131. n2 = 0;
  10132. if (i < s1.length)
  10133. n1 = parseInt(s1[i]);
  10134. if (i < s2.length)
  10135. n2 = parseInt(s2[i]);
  10136. if (isNaN(n1) || isNaN(n2))
  10137. {
  10138. return true;
  10139. }
  10140. else if (n1 !== n2)
  10141. {
  10142. return n1 > n2;
  10143. }
  10144. }
  10145. // will happen if boths version has identical numbers in
  10146. // their components (even if one of them is longer, has more components)
  10147. return false;
  10148. }
  10149. catch (e)
  10150. {
  10151. console.error("Failed to parse extension version", e);
  10152. APP.UI.messageHandler.showError("dialog.error",
  10153. "dialog.detectext");
  10154. return true;
  10155. }
  10156. }
  10157. function checkChromeExtInstalled(callback) {
  10158. if (!chrome.runtime) {
  10159. // No API, so no extension for sure
  10160. callback(false, false);
  10161. return;
  10162. }
  10163. chrome.runtime.sendMessage(
  10164. config.chromeExtensionId,
  10165. { getVersion: true },
  10166. function (response) {
  10167. if (!response || !response.version) {
  10168. // Communication failure - assume that no endpoint exists
  10169. console.warn(
  10170. "Extension not installed?: ", chrome.runtime.lastError);
  10171. callback(false, false);
  10172. return;
  10173. }
  10174. // Check installed extension version
  10175. var extVersion = response.version;
  10176. console.log('Extension version is: ' + extVersion);
  10177. var updateRequired
  10178. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  10179. callback(!updateRequired, updateRequired);
  10180. }
  10181. );
  10182. }
  10183. function doGetStreamFromExtension(streamCallback, failCallback) {
  10184. // Sends 'getStream' msg to the extension.
  10185. // Extension id must be defined in the config.
  10186. chrome.runtime.sendMessage(
  10187. config.chromeExtensionId,
  10188. { getStream: true, sources: config.desktopSharingSources },
  10189. function (response) {
  10190. if (!response) {
  10191. failCallback(chrome.runtime.lastError);
  10192. return;
  10193. }
  10194. console.log("Response from extension: " + response);
  10195. if (response.streamId) {
  10196. APP.RTC.getUserMediaWithConstraints(
  10197. ['desktop'],
  10198. function (stream) {
  10199. streamCallback(stream);
  10200. },
  10201. failCallback,
  10202. null, null, null,
  10203. response.streamId);
  10204. } else {
  10205. failCallback("Extension failed to get the stream");
  10206. }
  10207. }
  10208. );
  10209. }
  10210. /**
  10211. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  10212. * stream for returned stream token.
  10213. */
  10214. function obtainScreenFromExtension(streamCallback, failCallback) {
  10215. if (extInstalled) {
  10216. doGetStreamFromExtension(streamCallback, failCallback);
  10217. } else {
  10218. if (extUpdateRequired) {
  10219. alert(
  10220. 'Jitsi Desktop Streamer requires update. ' +
  10221. 'Changes will take effect after next Chrome restart.');
  10222. }
  10223. chrome.webstore.install(
  10224. getWebStoreInstallUrl(),
  10225. function (arg) {
  10226. console.log("Extension installed successfully", arg);
  10227. extInstalled = true;
  10228. // We need to give a moment for the endpoint to become available
  10229. window.setTimeout(function () {
  10230. doGetStreamFromExtension(streamCallback, failCallback);
  10231. }, 500);
  10232. },
  10233. function (arg) {
  10234. console.log("Failed to install the extension", arg);
  10235. failCallback(arg);
  10236. APP.UI.messageHandler.showError("dialog.error",
  10237. "dialog.failtoinstall");
  10238. }
  10239. );
  10240. }
  10241. }
  10242. /**
  10243. * Call this method to toggle desktop sharing feature.
  10244. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  10245. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  10246. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  10247. * enabled), pass any other string or nothing in order to disable this
  10248. * feature completely.
  10249. */
  10250. function setDesktopSharing(method) {
  10251. obtainDesktopStream = null;
  10252. // When TemasysWebRTC plugin is used we always use getUserMedia, so we don't
  10253. // care about 'method' parameter
  10254. if (RTCBrowserType.isTemasysPluginUsed()) {
  10255. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  10256. console.info("Screensharing not supported by this plugin version");
  10257. } else if (!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  10258. console.info(
  10259. "Screensharing not available with Temasys plugin on this site");
  10260. } else {
  10261. obtainDesktopStream = obtainWebRTCScreen;
  10262. console.info("Using Temasys plugin for desktop sharing");
  10263. }
  10264. } else if (RTCBrowserType.isChrome()) {
  10265. if (method == "ext") {
  10266. if (RTCBrowserType.getChromeVersion() >= 34) {
  10267. obtainDesktopStream = obtainScreenFromExtension;
  10268. console.info("Using Chrome extension for desktop sharing");
  10269. initChromeExtension();
  10270. } else {
  10271. console.info("Chrome extension not supported until ver 34");
  10272. }
  10273. } else if (method == "webrtc") {
  10274. obtainDesktopStream = obtainWebRTCScreen;
  10275. console.info("Using Chrome WebRTC for desktop sharing");
  10276. }
  10277. }
  10278. if (!obtainDesktopStream) {
  10279. console.info("Desktop sharing disabled");
  10280. }
  10281. }
  10282. /**
  10283. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  10284. * config.js to support inline installs. Host site must be selected as main
  10285. * website of published extension.
  10286. */
  10287. function initInlineInstalls()
  10288. {
  10289. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  10290. }
  10291. function initChromeExtension() {
  10292. // Initialize Chrome extension inline installs
  10293. initInlineInstalls();
  10294. // Check if extension is installed
  10295. checkChromeExtInstalled(function (installed, updateRequired) {
  10296. extInstalled = installed;
  10297. extUpdateRequired = updateRequired;
  10298. console.info(
  10299. "Chrome extension installed: " + extInstalled +
  10300. " updateRequired: " + extUpdateRequired);
  10301. });
  10302. }
  10303. function getVideoStreamFailed(error) {
  10304. console.error("Failed to obtain the stream to switch to", error);
  10305. switchInProgress = false;
  10306. isUsingScreenStream = false;
  10307. newStreamCreated(null);
  10308. }
  10309. function getDesktopStreamFailed(error) {
  10310. console.error("Failed to obtain the stream to switch to", error);
  10311. switchInProgress = false;
  10312. }
  10313. function streamSwitchDone() {
  10314. switchInProgress = false;
  10315. eventEmitter.emit(
  10316. DesktopSharingEventTypes.SWITCHING_DONE,
  10317. isUsingScreenStream);
  10318. }
  10319. function newStreamCreated(stream)
  10320. {
  10321. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  10322. stream, isUsingScreenStream, streamSwitchDone);
  10323. }
  10324. function onEndedHandler(stream) {
  10325. if (!switchInProgress && isUsingScreenStream) {
  10326. APP.desktopsharing.toggleScreenSharing();
  10327. }
  10328. //FIXME: to be verified
  10329. if (stream.removeEventListener) {
  10330. stream.removeEventListener('ended', onEndedHandler);
  10331. } else {
  10332. stream.detachEvent('ended', onEndedHandler);
  10333. }
  10334. }
  10335. // Called when RTC finishes initialization
  10336. function onWebRtcReady() {
  10337. setDesktopSharing(config.desktopSharing);
  10338. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  10339. }
  10340. module.exports = {
  10341. isUsingScreenStream: function () {
  10342. return isUsingScreenStream;
  10343. },
  10344. /**
  10345. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  10346. * and enabled.
  10347. */
  10348. isDesktopSharingEnabled: function () { return !!obtainDesktopStream; },
  10349. init: function () {
  10350. APP.RTC.addListener(RTCEvents.RTC_READY, onWebRtcReady);
  10351. },
  10352. addListener: function (listener, type)
  10353. {
  10354. eventEmitter.on(type, listener);
  10355. },
  10356. removeListener: function (listener, type) {
  10357. eventEmitter.removeListener(type, listener);
  10358. },
  10359. /*
  10360. * Toggles screen sharing.
  10361. */
  10362. toggleScreenSharing: function () {
  10363. if (switchInProgress || !obtainDesktopStream) {
  10364. console.warn("Switch in progress or no method defined");
  10365. return;
  10366. }
  10367. switchInProgress = true;
  10368. if (!isUsingScreenStream)
  10369. {
  10370. // Switch to desktop stream
  10371. obtainDesktopStream(
  10372. function (stream) {
  10373. // We now use screen stream
  10374. isUsingScreenStream = true;
  10375. // Hook 'ended' event to restore camera
  10376. // when screen stream stops
  10377. //FIXME: to be verified
  10378. if (stream.addEventListener) {
  10379. stream.addEventListener('ended', function () {
  10380. onEndedHandler(stream);
  10381. });
  10382. } else {
  10383. stream.attachEvent('ended', function () {
  10384. onEndedHandler(stream);
  10385. });
  10386. }
  10387. newStreamCreated(stream);
  10388. },
  10389. getDesktopStreamFailed);
  10390. } else {
  10391. // Disable screen stream
  10392. APP.RTC.getUserMediaWithConstraints(
  10393. ['video'],
  10394. function (stream) {
  10395. // We are now using camera stream
  10396. isUsingScreenStream = false;
  10397. newStreamCreated(stream);
  10398. },
  10399. getVideoStreamFailed, config.resolution || '360'
  10400. );
  10401. }
  10402. }
  10403. };
  10404. },{"../../service/RTC/RTCEvents":110,"../../service/desktopsharing/DesktopSharingEventTypes":116,"../RTC/RTCBrowserType":10,"../RTC/adapter.screenshare":12,"events":1}],47:[function(require,module,exports){
  10405. /* global APP, $ */
  10406. //maps keycode to character, id of popover for given function and function
  10407. var shortcuts = {};
  10408. function initShortcutHandlers() {
  10409. shortcuts = {
  10410. 67: {
  10411. character: "C",
  10412. id: "toggleChatPopover",
  10413. function: APP.UI.toggleChat
  10414. },
  10415. 70: {
  10416. character: "F",
  10417. id: "filmstripPopover",
  10418. function: APP.UI.toggleFilmStrip
  10419. },
  10420. 77: {
  10421. character: "M",
  10422. id: "mutePopover",
  10423. function: APP.UI.toggleAudio
  10424. },
  10425. 84: {
  10426. character: "T",
  10427. function: function() {
  10428. if(!APP.RTC.localAudio.isMuted()) {
  10429. APP.UI.toggleAudio();
  10430. }
  10431. }
  10432. },
  10433. 86: {
  10434. character: "V",
  10435. id: "toggleVideoPopover",
  10436. function: APP.UI.toggleVideo
  10437. }
  10438. };
  10439. }
  10440. var KeyboardShortcut = {
  10441. init: function () {
  10442. initShortcutHandlers();
  10443. window.onkeyup = function(e) {
  10444. var keycode = e.which;
  10445. if(!($(":focus").is("input[type=text]") ||
  10446. $(":focus").is("input[type=password]") ||
  10447. $(":focus").is("textarea"))) {
  10448. if (typeof shortcuts[keycode] === "object") {
  10449. shortcuts[keycode].function();
  10450. }
  10451. else if (keycode >= "0".charCodeAt(0) &&
  10452. keycode <= "9".charCodeAt(0)) {
  10453. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  10454. }
  10455. //esc while the smileys are visible hides them
  10456. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  10457. APP.UI.toggleSmileys();
  10458. }
  10459. };
  10460. window.onkeydown = function(e) {
  10461. if(!($(":focus").is("input[type=text]") ||
  10462. $(":focus").is("input[type=password]") ||
  10463. $(":focus").is("textarea"))) {
  10464. if(e.which === "T".charCodeAt(0)) {
  10465. if(APP.RTC.localAudio.isMuted()) {
  10466. APP.UI.toggleAudio();
  10467. }
  10468. }
  10469. }
  10470. };
  10471. var self = this;
  10472. $('body').popover({ selector: '[data-toggle=popover]',
  10473. trigger: 'click hover',
  10474. content: function() {
  10475. return this.getAttribute("content") +
  10476. self.getShortcut(this.getAttribute("shortcut"));
  10477. }
  10478. });
  10479. },
  10480. /**
  10481. *
  10482. * @param id indicates the popover associated with the shortcut
  10483. * @returns {string} the keyboard shortcut used for the id given
  10484. */
  10485. getShortcut: function (id) {
  10486. for (var keycode in shortcuts) {
  10487. if (shortcuts.hasOwnProperty(keycode)) {
  10488. if (shortcuts[keycode].id === id) {
  10489. return " (" + shortcuts[keycode].character + ")";
  10490. }
  10491. }
  10492. }
  10493. return "";
  10494. }
  10495. };
  10496. module.exports = KeyboardShortcut;
  10497. },{}],48:[function(require,module,exports){
  10498. /* global APP, require, $ */
  10499. /**
  10500. * This module is meant to (eventually) contain and manage all information
  10501. * about members/participants of the conference, so that other modules don't
  10502. * have to do it on their own, and so that other modules can access members'
  10503. * information from a single place.
  10504. *
  10505. * Currently this module only manages information about the support of jingle
  10506. * DTMF of the members. Other fields, as well as accessor methods are meant to
  10507. * be added as needed.
  10508. */
  10509. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10510. var Events = require("../../service/members/Events");
  10511. var EventEmitter = require("events");
  10512. var eventEmitter = new EventEmitter();
  10513. /**
  10514. * The actual container.
  10515. */
  10516. var members = {};
  10517. /**
  10518. * There is at least one member that supports DTMF (i.e. is jigasi).
  10519. */
  10520. var atLeastOneDtmf = false;
  10521. function registerListeners() {
  10522. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  10523. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  10524. }
  10525. /**
  10526. * Handles a new member joining the MUC.
  10527. */
  10528. function onMucMemberJoined(jid, id, displayName) {
  10529. var member = {
  10530. displayName: displayName
  10531. };
  10532. APP.xmpp.getConnection().disco.info(
  10533. jid, "" /* node */, function(iq) { onDiscoInfoReceived(jid, iq); });
  10534. members[jid] = member;
  10535. }
  10536. /**
  10537. * Handles a member leaving the MUC.
  10538. */
  10539. function onMucMemberLeft(jid) {
  10540. delete members[jid];
  10541. updateAtLeastOneDtmf();
  10542. }
  10543. /**
  10544. * Handles the reception of a disco#info packet from a particular JID.
  10545. * @param jid the JID sending the packet.
  10546. * @param iq the packet.
  10547. */
  10548. function onDiscoInfoReceived(jid, iq) {
  10549. if (!members[jid])
  10550. return;
  10551. var supportsDtmf
  10552. = $(iq).find('>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  10553. updateDtmf(jid, supportsDtmf);
  10554. }
  10555. /**
  10556. * Updates the 'supportsDtmf' field for a member.
  10557. * @param jid the jid of the member.
  10558. * @param newValue the new value for the 'supportsDtmf' field.
  10559. */
  10560. function updateDtmf(jid, newValue) {
  10561. var oldValue = members[jid].supportsDtmf;
  10562. members[jid].supportsDtmf = newValue;
  10563. if (newValue != oldValue) {
  10564. updateAtLeastOneDtmf();
  10565. }
  10566. }
  10567. /**
  10568. * Checks each member's 'supportsDtmf' field and updates
  10569. * 'atLastOneSupportsDtmf'.
  10570. */
  10571. function updateAtLeastOneDtmf() {
  10572. var newAtLeastOneDtmf = false;
  10573. for (var key in members) {
  10574. if (typeof members[key].supportsDtmf !== 'undefined'
  10575. && members[key].supportsDtmf) {
  10576. newAtLeastOneDtmf= true;
  10577. break;
  10578. }
  10579. }
  10580. if (atLeastOneDtmf != newAtLeastOneDtmf) {
  10581. atLeastOneDtmf = newAtLeastOneDtmf;
  10582. eventEmitter.emit(Events.DTMF_SUPPORT_CHANGED, atLeastOneDtmf);
  10583. }
  10584. }
  10585. /**
  10586. * Exported interface.
  10587. */
  10588. var Members = {
  10589. start: function() {
  10590. registerListeners();
  10591. },
  10592. addListener: function(type, listener) {
  10593. eventEmitter.on(type, listener);
  10594. },
  10595. removeListener: function (type, listener) {
  10596. eventEmitter.removeListener(type, listener);
  10597. },
  10598. size: function () {
  10599. return Object.keys(members).length;
  10600. },
  10601. getMembers: function () {
  10602. return members;
  10603. }
  10604. };
  10605. module.exports = Members;
  10606. },{"../../service/members/Events":117,"../../service/xmpp/XMPPEvents":119,"events":1}],49:[function(require,module,exports){
  10607. var email = '';
  10608. var displayName = '';
  10609. var userId;
  10610. var language = null;
  10611. function supportsLocalStorage() {
  10612. try {
  10613. return 'localStorage' in window && window.localStorage !== null;
  10614. } catch (e) {
  10615. console.log("localstorage is not supported");
  10616. return false;
  10617. }
  10618. }
  10619. function generateUniqueId() {
  10620. function _p8() {
  10621. return (Math.random().toString(16) + "000000000").substr(2, 8);
  10622. }
  10623. return _p8() + _p8() + _p8() + _p8();
  10624. }
  10625. if (supportsLocalStorage()) {
  10626. if (!window.localStorage.jitsiMeetId) {
  10627. window.localStorage.jitsiMeetId = generateUniqueId();
  10628. console.log("generated id", window.localStorage.jitsiMeetId);
  10629. }
  10630. userId = window.localStorage.jitsiMeetId || '';
  10631. email = window.localStorage.email || '';
  10632. displayName = window.localStorage.displayname || '';
  10633. language = window.localStorage.language;
  10634. } else {
  10635. console.log("local storage is not supported");
  10636. userId = generateUniqueId();
  10637. }
  10638. var Settings = {
  10639. setDisplayName: function (newDisplayName) {
  10640. displayName = newDisplayName;
  10641. window.localStorage.displayname = displayName;
  10642. return displayName;
  10643. },
  10644. setEmail: function (newEmail) {
  10645. email = newEmail;
  10646. window.localStorage.email = newEmail;
  10647. return email;
  10648. },
  10649. getSettings: function () {
  10650. return {
  10651. email: email,
  10652. displayName: displayName,
  10653. uid: userId,
  10654. language: language
  10655. };
  10656. },
  10657. setLanguage: function (lang) {
  10658. language = lang;
  10659. window.localStorage.language = lang;
  10660. }
  10661. };
  10662. module.exports = Settings;
  10663. },{}],50:[function(require,module,exports){
  10664. /* global config, $, APP, Strophe, callstats */
  10665. var callStats = null;
  10666. function initCallback (err, msg) {
  10667. console.log("Initializing Status: err="+err+" msg="+msg);
  10668. }
  10669. var CallStats = {
  10670. init: function (jingleSession) {
  10671. if(!config.callStatsID || !config.callStatsSecret || callStats !== null)
  10672. return;
  10673. callStats = new callstats($,io,jsSHA);
  10674. this.session = jingleSession;
  10675. this.peerconnection = jingleSession.peerconnection.peerconnection;
  10676. this.userID = APP.xmpp.myResource();
  10677. var location = window.location;
  10678. this.confID = location.protocol + "//" +
  10679. location.hostname + location.pathname;
  10680. //userID is generated or given by the origin server
  10681. callStats.initialize(config.callStatsID,
  10682. config.callStatsSecret,
  10683. this.userID,
  10684. initCallback);
  10685. var usage = callStats.fabricUsage.multiplex;
  10686. callStats.addNewFabric(this.peerconnection,
  10687. Strophe.getResourceFromJid(jingleSession.peerjid),
  10688. usage,
  10689. this.confID,
  10690. this.pcCallback.bind(this));
  10691. },
  10692. pcCallback: function (err, msg) {
  10693. if (!callStats)
  10694. return;
  10695. console.log("Monitoring status: "+ err + " msg: " + msg);
  10696. callStats.sendFabricEvent(this.peerconnection,
  10697. callStats.fabricEvent.fabricSetup, this.confID);
  10698. },
  10699. sendMuteEvent: function (mute, type) {
  10700. if (!callStats)
  10701. return;
  10702. var event = null;
  10703. if (type === "video") {
  10704. event = (mute? callStats.fabricEvent.videoPause :
  10705. callStats.fabricEvent.videoResume);
  10706. }
  10707. else {
  10708. event = (mute? callStats.fabricEvent.audioMute :
  10709. callStats.fabricEvent.audioUnmute);
  10710. }
  10711. callStats.sendFabricEvent(this.peerconnection, event, this.confID);
  10712. },
  10713. sendTerminateEvent: function () {
  10714. if(!callStats) {
  10715. return;
  10716. }
  10717. callStats.sendFabricEvent(this.peerconnection,
  10718. callStats.fabricEvent.fabricTerminated, this.confID);
  10719. },
  10720. sendSetupFailedEvent: function () {
  10721. if(!callStats) {
  10722. return;
  10723. }
  10724. callStats.sendFabricEvent(this.peerconnection,
  10725. callStats.fabricEvent.fabricSetupFailed, this.confID);
  10726. }
  10727. };
  10728. module.exports = CallStats;
  10729. },{}],51:[function(require,module,exports){
  10730. /* global config */
  10731. /**
  10732. * Provides statistics for the local stream.
  10733. */
  10734. var RTCBrowserType = require('../RTC/RTCBrowserType');
  10735. /**
  10736. * Size of the webaudio analyzer buffer.
  10737. * @type {number}
  10738. */
  10739. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  10740. /**
  10741. * Value of the webaudio analyzer smoothing time parameter.
  10742. * @type {number}
  10743. */
  10744. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  10745. /**
  10746. * Converts time domain data array to audio level.
  10747. * @param samples the time domain data array.
  10748. * @returns {number} the audio level
  10749. */
  10750. function timeDomainDataToAudioLevel(samples) {
  10751. var maxVolume = 0;
  10752. var length = samples.length;
  10753. for (var i = 0; i < length; i++) {
  10754. if (maxVolume < samples[i])
  10755. maxVolume = samples[i];
  10756. }
  10757. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  10758. }
  10759. /**
  10760. * Animates audio level change
  10761. * @param newLevel the new audio level
  10762. * @param lastLevel the last audio level
  10763. * @returns {Number} the audio level to be set
  10764. */
  10765. function animateLevel(newLevel, lastLevel) {
  10766. var value = 0;
  10767. var diff = lastLevel - newLevel;
  10768. if(diff > 0.2) {
  10769. value = lastLevel - 0.2;
  10770. }
  10771. else if(diff < -0.4) {
  10772. value = lastLevel + 0.4;
  10773. }
  10774. else {
  10775. value = newLevel;
  10776. }
  10777. return parseFloat(value.toFixed(3));
  10778. }
  10779. /**
  10780. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  10781. *
  10782. * @param stream the local stream
  10783. * @param interval stats refresh interval given in ms.
  10784. * @constructor
  10785. */
  10786. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  10787. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  10788. this.stream = stream;
  10789. this.intervalId = null;
  10790. this.intervalMilis = interval;
  10791. this.eventEmitter = eventEmitter;
  10792. this.audioLevel = 0;
  10793. this.statisticsService = statisticsService;
  10794. }
  10795. /**
  10796. * Starts the collecting the statistics.
  10797. */
  10798. LocalStatsCollector.prototype.start = function () {
  10799. if (config.disableAudioLevels || !window.AudioContext ||
  10800. RTCBrowserType.isTemasysPluginUsed())
  10801. return;
  10802. var context = new AudioContext();
  10803. var analyser = context.createAnalyser();
  10804. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  10805. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  10806. var source = context.createMediaStreamSource(this.stream);
  10807. source.connect(analyser);
  10808. var self = this;
  10809. this.intervalId = setInterval(
  10810. function () {
  10811. var array = new Uint8Array(analyser.frequencyBinCount);
  10812. analyser.getByteTimeDomainData(array);
  10813. var audioLevel = timeDomainDataToAudioLevel(array);
  10814. if (audioLevel != self.audioLevel) {
  10815. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  10816. self.eventEmitter.emit(
  10817. "statistics.audioLevel",
  10818. self.statisticsService.LOCAL_JID,
  10819. self.audioLevel);
  10820. }
  10821. },
  10822. this.intervalMilis
  10823. );
  10824. };
  10825. /**
  10826. * Stops collecting the statistics.
  10827. */
  10828. LocalStatsCollector.prototype.stop = function () {
  10829. if (this.intervalId) {
  10830. clearInterval(this.intervalId);
  10831. this.intervalId = null;
  10832. }
  10833. };
  10834. module.exports = LocalStatsCollector;
  10835. },{"../RTC/RTCBrowserType":10}],52:[function(require,module,exports){
  10836. /* global require, ssrc2jid */
  10837. /* jshint -W117 */
  10838. var RTCBrowserType = require("../RTC/RTCBrowserType");
  10839. /* Whether we support the browser we are running into for logging statistics */
  10840. var browserSupported = RTCBrowserType.isChrome() ||
  10841. RTCBrowserType.isOpera();
  10842. /**
  10843. * Calculates packet lost percent using the number of lost packets and the
  10844. * number of all packet.
  10845. * @param lostPackets the number of lost packets
  10846. * @param totalPackets the number of all packets.
  10847. * @returns {number} packet loss percent
  10848. */
  10849. function calculatePacketLoss(lostPackets, totalPackets) {
  10850. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  10851. return 0;
  10852. return Math.round((lostPackets/totalPackets)*100);
  10853. }
  10854. function getStatValue(item, name) {
  10855. var browserType = RTCBrowserType.getBrowserType();
  10856. if (!keyMap[browserType][name])
  10857. throw "The property isn't supported!";
  10858. var key = keyMap[browserType][name];
  10859. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  10860. item.stat(key) : item[key];
  10861. }
  10862. /**
  10863. * Peer statistics data holder.
  10864. * @constructor
  10865. */
  10866. function PeerStats()
  10867. {
  10868. this.ssrc2Loss = {};
  10869. this.ssrc2AudioLevel = {};
  10870. this.ssrc2bitrate = {};
  10871. this.ssrc2resolution = {};
  10872. }
  10873. /**
  10874. * The bandwidth
  10875. * @type {{}}
  10876. */
  10877. PeerStats.bandwidth = {};
  10878. /**
  10879. * The bit rate
  10880. * @type {{}}
  10881. */
  10882. PeerStats.bitrate = {};
  10883. /**
  10884. * The packet loss rate
  10885. * @type {{}}
  10886. */
  10887. PeerStats.packetLoss = null;
  10888. /**
  10889. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  10890. * represented by this instance.
  10891. * @param ssrc audio or video RTP stream SSRC.
  10892. * @param lossRate new packet loss rate value to be set.
  10893. */
  10894. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  10895. {
  10896. this.ssrc2Loss[ssrc] = lossRate;
  10897. };
  10898. /**
  10899. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  10900. * represented by this instance.
  10901. * @param ssrc audio or video RTP stream SSRC.
  10902. * @param resolution new resolution value to be set.
  10903. */
  10904. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  10905. {
  10906. if(resolution === null && this.ssrc2resolution[ssrc])
  10907. {
  10908. delete this.ssrc2resolution[ssrc];
  10909. }
  10910. else if(resolution !== null)
  10911. this.ssrc2resolution[ssrc] = resolution;
  10912. };
  10913. /**
  10914. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  10915. * represented by this instance.
  10916. * @param ssrc audio or video RTP stream SSRC.
  10917. * @param bitrate new bitrate value to be set.
  10918. */
  10919. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  10920. {
  10921. if(this.ssrc2bitrate[ssrc])
  10922. {
  10923. this.ssrc2bitrate[ssrc].download += bitrate.download;
  10924. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  10925. }
  10926. else {
  10927. this.ssrc2bitrate[ssrc] = bitrate;
  10928. }
  10929. };
  10930. /**
  10931. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  10932. * the stream which belongs to the peer represented by this instance.
  10933. * @param ssrc RTP stream SSRC for which current audio level value will be
  10934. * updated.
  10935. * @param audioLevel the new audio level value to be set. Value is truncated to
  10936. * fit the range from 0 to 1.
  10937. */
  10938. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  10939. {
  10940. // Range limit 0 - 1
  10941. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  10942. };
  10943. function formatAudioLevel(audioLevel) {
  10944. return Math.min(Math.max(audioLevel, 0), 1);
  10945. }
  10946. /**
  10947. * Array with the transport information.
  10948. * @type {Array}
  10949. */
  10950. PeerStats.transport = [];
  10951. /**
  10952. * <tt>StatsCollector</tt> registers for stats updates of given
  10953. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  10954. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  10955. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  10956. * instance as an event source.
  10957. *
  10958. * @param peerconnection webRTC peer connection object.
  10959. * @param interval stats refresh interval given in ms.
  10960. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  10961. * called on stats update.
  10962. * @constructor
  10963. */
  10964. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  10965. {
  10966. this.peerconnection = peerconnection;
  10967. this.baselineAudioLevelsReport = null;
  10968. this.currentAudioLevelsReport = null;
  10969. this.currentStatsReport = null;
  10970. this.baselineStatsReport = null;
  10971. this.audioLevelsIntervalId = null;
  10972. this.eventEmitter = eventEmitter;
  10973. /**
  10974. * Gather PeerConnection stats once every this many milliseconds.
  10975. */
  10976. this.GATHER_INTERVAL = 15000;
  10977. /**
  10978. * Log stats via the focus once every this many milliseconds.
  10979. */
  10980. this.LOG_INTERVAL = 60000;
  10981. /**
  10982. * Gather stats and store them in this.statsToBeLogged.
  10983. */
  10984. this.gatherStatsIntervalId = null;
  10985. /**
  10986. * Send the stats already saved in this.statsToBeLogged to be logged via
  10987. * the focus.
  10988. */
  10989. this.logStatsIntervalId = null;
  10990. /**
  10991. * Stores the statistics which will be send to the focus to be logged.
  10992. */
  10993. this.statsToBeLogged =
  10994. {
  10995. timestamps: [],
  10996. stats: {}
  10997. };
  10998. // Updates stats interval
  10999. this.audioLevelsIntervalMilis = audioLevelsInterval;
  11000. this.statsIntervalId = null;
  11001. this.statsIntervalMilis = statsInterval;
  11002. // Map of jids to PeerStats
  11003. this.jid2stats = {};
  11004. }
  11005. module.exports = StatsCollector;
  11006. /**
  11007. * Stops stats updates.
  11008. */
  11009. StatsCollector.prototype.stop = function () {
  11010. if (this.audioLevelsIntervalId) {
  11011. clearInterval(this.audioLevelsIntervalId);
  11012. this.audioLevelsIntervalId = null;
  11013. }
  11014. if (this.statsIntervalId)
  11015. {
  11016. clearInterval(this.statsIntervalId);
  11017. this.statsIntervalId = null;
  11018. }
  11019. if(this.logStatsIntervalId)
  11020. {
  11021. clearInterval(this.logStatsIntervalId);
  11022. this.logStatsIntervalId = null;
  11023. }
  11024. if(this.gatherStatsIntervalId)
  11025. {
  11026. clearInterval(this.gatherStatsIntervalId);
  11027. this.gatherStatsIntervalId = null;
  11028. }
  11029. };
  11030. /**
  11031. * Callback passed to <tt>getStats</tt> method.
  11032. * @param error an error that occurred on <tt>getStats</tt> call.
  11033. */
  11034. StatsCollector.prototype.errorCallback = function (error)
  11035. {
  11036. console.error("Get stats error", error);
  11037. this.stop();
  11038. };
  11039. /**
  11040. * Starts stats updates.
  11041. */
  11042. StatsCollector.prototype.start = function ()
  11043. {
  11044. var self = this;
  11045. if (!config.disableAudioLevels) {
  11046. this.audioLevelsIntervalId = setInterval(
  11047. function () {
  11048. // Interval updates
  11049. self.peerconnection.getStats(
  11050. function (report) {
  11051. var results = null;
  11052. if (!report || !report.result ||
  11053. typeof report.result != 'function') {
  11054. results = report;
  11055. }
  11056. else {
  11057. results = report.result();
  11058. }
  11059. //console.error("Got interval report", results);
  11060. self.currentAudioLevelsReport = results;
  11061. self.processAudioLevelReport();
  11062. self.baselineAudioLevelsReport =
  11063. self.currentAudioLevelsReport;
  11064. },
  11065. self.errorCallback
  11066. );
  11067. },
  11068. self.audioLevelsIntervalMilis
  11069. );
  11070. }
  11071. if (!config.disableStats && browserSupported) {
  11072. this.statsIntervalId = setInterval(
  11073. function () {
  11074. // Interval updates
  11075. self.peerconnection.getStats(
  11076. function (report) {
  11077. var results = null;
  11078. if (!report || !report.result ||
  11079. typeof report.result != 'function') {
  11080. //firefox
  11081. results = report;
  11082. }
  11083. else {
  11084. //chrome
  11085. results = report.result();
  11086. }
  11087. //console.error("Got interval report", results);
  11088. self.currentStatsReport = results;
  11089. try {
  11090. self.processStatsReport();
  11091. }
  11092. catch (e) {
  11093. console.error("Unsupported key:" + e, e);
  11094. }
  11095. self.baselineStatsReport = self.currentStatsReport;
  11096. },
  11097. self.errorCallback
  11098. );
  11099. },
  11100. self.statsIntervalMilis
  11101. );
  11102. }
  11103. if (config.logStats && browserSupported) {
  11104. this.gatherStatsIntervalId = setInterval(
  11105. function () {
  11106. self.peerconnection.getStats(
  11107. function (report) {
  11108. self.addStatsToBeLogged(report.result());
  11109. },
  11110. function () {
  11111. }
  11112. );
  11113. },
  11114. this.GATHER_INTERVAL
  11115. );
  11116. this.logStatsIntervalId = setInterval(
  11117. function() { self.logStats(); },
  11118. this.LOG_INTERVAL);
  11119. }
  11120. };
  11121. /**
  11122. * Checks whether a certain record should be included in the logged statistics.
  11123. */
  11124. function acceptStat(reportId, reportType, statName) {
  11125. if (reportType == "googCandidatePair" && statName == "googChannelId")
  11126. return false;
  11127. if (reportType == "ssrc") {
  11128. if (statName == "googTrackId" ||
  11129. statName == "transportId" ||
  11130. statName == "ssrc")
  11131. return false;
  11132. }
  11133. return true;
  11134. }
  11135. /**
  11136. * Checks whether a certain record should be included in the logged statistics.
  11137. */
  11138. function acceptReport(id, type) {
  11139. if (id.substring(0, 15) == "googCertificate" ||
  11140. id.substring(0, 9) == "googTrack" ||
  11141. id.substring(0, 20) == "googLibjingleSession")
  11142. return false;
  11143. if (type == "googComponent")
  11144. return false;
  11145. return true;
  11146. }
  11147. /**
  11148. * Converts the stats to the format used for logging, and saves the data in
  11149. * this.statsToBeLogged.
  11150. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  11151. */
  11152. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  11153. var self = this;
  11154. var num_records = this.statsToBeLogged.timestamps.length;
  11155. this.statsToBeLogged.timestamps.push(new Date().getTime());
  11156. reports.map(function (report) {
  11157. if (!acceptReport(report.id, report.type))
  11158. return;
  11159. var stat = self.statsToBeLogged.stats[report.id];
  11160. if (!stat) {
  11161. stat = self.statsToBeLogged.stats[report.id] = {};
  11162. }
  11163. stat.type = report.type;
  11164. report.names().map(function (name) {
  11165. if (!acceptStat(report.id, report.type, name))
  11166. return;
  11167. var values = stat[name];
  11168. if (!values) {
  11169. values = stat[name] = [];
  11170. }
  11171. while (values.length < num_records) {
  11172. values.push(null);
  11173. }
  11174. values.push(report.stat(name));
  11175. });
  11176. });
  11177. };
  11178. StatsCollector.prototype.logStats = function () {
  11179. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  11180. return;
  11181. // Reset the stats
  11182. this.statsToBeLogged.stats = {};
  11183. this.statsToBeLogged.timestamps = [];
  11184. };
  11185. var keyMap = {};
  11186. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  11187. "ssrc": "ssrc",
  11188. "packetsReceived": "packetsReceived",
  11189. "packetsLost": "packetsLost",
  11190. "packetsSent": "packetsSent",
  11191. "bytesReceived": "bytesReceived",
  11192. "bytesSent": "bytesSent"
  11193. };
  11194. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  11195. "receiveBandwidth": "googAvailableReceiveBandwidth",
  11196. "sendBandwidth": "googAvailableSendBandwidth",
  11197. "remoteAddress": "googRemoteAddress",
  11198. "transportType": "googTransportType",
  11199. "localAddress": "googLocalAddress",
  11200. "activeConnection": "googActiveConnection",
  11201. "ssrc": "ssrc",
  11202. "packetsReceived": "packetsReceived",
  11203. "packetsSent": "packetsSent",
  11204. "packetsLost": "packetsLost",
  11205. "bytesReceived": "bytesReceived",
  11206. "bytesSent": "bytesSent",
  11207. "googFrameHeightReceived": "googFrameHeightReceived",
  11208. "googFrameWidthReceived": "googFrameWidthReceived",
  11209. "googFrameHeightSent": "googFrameHeightSent",
  11210. "googFrameWidthSent": "googFrameWidthSent",
  11211. "audioInputLevel": "audioInputLevel",
  11212. "audioOutputLevel": "audioOutputLevel"
  11213. };
  11214. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  11215. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  11216. /**
  11217. * Stats processing logic.
  11218. */
  11219. StatsCollector.prototype.processStatsReport = function () {
  11220. if (!this.baselineStatsReport) {
  11221. return;
  11222. }
  11223. for (var idx in this.currentStatsReport) {
  11224. var now = this.currentStatsReport[idx];
  11225. try {
  11226. if (getStatValue(now, 'receiveBandwidth') ||
  11227. getStatValue(now, 'sendBandwidth')) {
  11228. PeerStats.bandwidth = {
  11229. "download": Math.round(
  11230. (getStatValue(now, 'receiveBandwidth')) / 1000),
  11231. "upload": Math.round(
  11232. (getStatValue(now, 'sendBandwidth')) / 1000)
  11233. };
  11234. }
  11235. }
  11236. catch(e){/*not supported*/}
  11237. if(now.type == 'googCandidatePair')
  11238. {
  11239. var ip, type, localIP, active;
  11240. try {
  11241. ip = getStatValue(now, 'remoteAddress');
  11242. type = getStatValue(now, "transportType");
  11243. localIP = getStatValue(now, "localAddress");
  11244. active = getStatValue(now, "activeConnection");
  11245. }
  11246. catch(e){/*not supported*/}
  11247. if(!ip || !type || !localIP || active != "true")
  11248. continue;
  11249. var addressSaved = false;
  11250. for(var i = 0; i < PeerStats.transport.length; i++)
  11251. {
  11252. if(PeerStats.transport[i].ip == ip &&
  11253. PeerStats.transport[i].type == type &&
  11254. PeerStats.transport[i].localip == localIP)
  11255. {
  11256. addressSaved = true;
  11257. }
  11258. }
  11259. if(addressSaved)
  11260. continue;
  11261. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  11262. continue;
  11263. }
  11264. if(now.type == "candidatepair")
  11265. {
  11266. if(now.state == "succeeded")
  11267. continue;
  11268. var local = this.currentStatsReport[now.localCandidateId];
  11269. var remote = this.currentStatsReport[now.remoteCandidateId];
  11270. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  11271. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  11272. }
  11273. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  11274. now.type != "inboundrtp") {
  11275. continue;
  11276. }
  11277. var before = this.baselineStatsReport[idx];
  11278. if (!before) {
  11279. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  11280. continue;
  11281. }
  11282. var ssrc = getStatValue(now, 'ssrc');
  11283. if(!ssrc)
  11284. continue;
  11285. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  11286. if (!jid && (Date.now() - now.timestamp) < 3000) {
  11287. console.warn("No jid for ssrc: " + ssrc);
  11288. continue;
  11289. }
  11290. var jidStats = this.jid2stats[jid];
  11291. if (!jidStats) {
  11292. jidStats = new PeerStats();
  11293. this.jid2stats[jid] = jidStats;
  11294. }
  11295. var isDownloadStream = true;
  11296. var key = 'packetsReceived';
  11297. if (!getStatValue(now, key))
  11298. {
  11299. isDownloadStream = false;
  11300. key = 'packetsSent';
  11301. if (!getStatValue(now, key))
  11302. {
  11303. console.warn("No packetsReceived nor packetSent stat found");
  11304. continue;
  11305. }
  11306. }
  11307. var packetsNow = getStatValue(now, key);
  11308. if(!packetsNow || packetsNow < 0)
  11309. packetsNow = 0;
  11310. var packetsBefore = getStatValue(before, key);
  11311. if(!packetsBefore || packetsBefore < 0)
  11312. packetsBefore = 0;
  11313. var packetRate = packetsNow - packetsBefore;
  11314. if(!packetRate || packetRate < 0)
  11315. packetRate = 0;
  11316. var currentLoss = getStatValue(now, 'packetsLost');
  11317. if(!currentLoss || currentLoss < 0)
  11318. currentLoss = 0;
  11319. var previousLoss = getStatValue(before, 'packetsLost');
  11320. if(!previousLoss || previousLoss < 0)
  11321. previousLoss = 0;
  11322. var lossRate = currentLoss - previousLoss;
  11323. if(!lossRate || lossRate < 0)
  11324. lossRate = 0;
  11325. var packetsTotal = (packetRate + lossRate);
  11326. jidStats.setSsrcLoss(ssrc,
  11327. {"packetsTotal": packetsTotal,
  11328. "packetsLost": lossRate,
  11329. "isDownloadStream": isDownloadStream});
  11330. var bytesReceived = 0, bytesSent = 0;
  11331. if(getStatValue(now, "bytesReceived"))
  11332. {
  11333. bytesReceived = getStatValue(now, "bytesReceived") -
  11334. getStatValue(before, "bytesReceived");
  11335. }
  11336. if(getStatValue(now, "bytesSent"))
  11337. {
  11338. bytesSent = getStatValue(now, "bytesSent") -
  11339. getStatValue(before, "bytesSent");
  11340. }
  11341. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  11342. if(bytesReceived <= 0 || time <= 0)
  11343. {
  11344. bytesReceived = 0;
  11345. }
  11346. else
  11347. {
  11348. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  11349. }
  11350. if(bytesSent <= 0 || time <= 0)
  11351. {
  11352. bytesSent = 0;
  11353. }
  11354. else
  11355. {
  11356. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  11357. }
  11358. jidStats.setSsrcBitrate(ssrc, {
  11359. "download": bytesReceived,
  11360. "upload": bytesSent});
  11361. var resolution = {height: null, width: null};
  11362. try {
  11363. if (getStatValue(now, "googFrameHeightReceived") &&
  11364. getStatValue(now, "googFrameWidthReceived")) {
  11365. resolution.height = getStatValue(now, "googFrameHeightReceived");
  11366. resolution.width = getStatValue(now, "googFrameWidthReceived");
  11367. }
  11368. else if (getStatValue(now, "googFrameHeightSent") &&
  11369. getStatValue(now, "googFrameWidthSent")) {
  11370. resolution.height = getStatValue(now, "googFrameHeightSent");
  11371. resolution.width = getStatValue(now, "googFrameWidthSent");
  11372. }
  11373. }
  11374. catch(e){/*not supported*/}
  11375. if(resolution.height && resolution.width)
  11376. {
  11377. jidStats.setSsrcResolution(ssrc, resolution);
  11378. }
  11379. else
  11380. {
  11381. jidStats.setSsrcResolution(ssrc, null);
  11382. }
  11383. }
  11384. var self = this;
  11385. // Jid stats
  11386. var totalPackets = {download: 0, upload: 0};
  11387. var lostPackets = {download: 0, upload: 0};
  11388. var bitrateDownload = 0;
  11389. var bitrateUpload = 0;
  11390. var resolutions = {};
  11391. Object.keys(this.jid2stats).forEach(
  11392. function (jid)
  11393. {
  11394. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  11395. function (ssrc)
  11396. {
  11397. var type = "upload";
  11398. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  11399. type = "download";
  11400. totalPackets[type] +=
  11401. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  11402. lostPackets[type] +=
  11403. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  11404. }
  11405. );
  11406. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  11407. function (ssrc) {
  11408. bitrateDownload +=
  11409. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  11410. bitrateUpload +=
  11411. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  11412. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  11413. }
  11414. );
  11415. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  11416. }
  11417. );
  11418. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  11419. PeerStats.packetLoss = {
  11420. total:
  11421. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  11422. totalPackets.download + totalPackets.upload),
  11423. download:
  11424. calculatePacketLoss(lostPackets.download, totalPackets.download),
  11425. upload:
  11426. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  11427. };
  11428. this.eventEmitter.emit("statistics.connectionstats",
  11429. {
  11430. "bitrate": PeerStats.bitrate,
  11431. "packetLoss": PeerStats.packetLoss,
  11432. "bandwidth": PeerStats.bandwidth,
  11433. "resolution": resolutions,
  11434. "transport": PeerStats.transport
  11435. });
  11436. PeerStats.transport = [];
  11437. };
  11438. /**
  11439. * Stats processing logic.
  11440. */
  11441. StatsCollector.prototype.processAudioLevelReport = function () {
  11442. if (!this.baselineAudioLevelsReport) {
  11443. return;
  11444. }
  11445. for (var idx in this.currentAudioLevelsReport) {
  11446. var now = this.currentAudioLevelsReport[idx];
  11447. if (now.type != 'ssrc') {
  11448. continue;
  11449. }
  11450. var before = this.baselineAudioLevelsReport[idx];
  11451. if (!before) {
  11452. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  11453. continue;
  11454. }
  11455. var ssrc = getStatValue(now, 'ssrc');
  11456. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  11457. if (!jid) {
  11458. if((Date.now() - now.timestamp) < 3000)
  11459. console.warn("No jid for ssrc: " + ssrc);
  11460. continue;
  11461. }
  11462. var jidStats = this.jid2stats[jid];
  11463. if (!jidStats) {
  11464. jidStats = new PeerStats();
  11465. this.jid2stats[jid] = jidStats;
  11466. }
  11467. // Audio level
  11468. var audioLevel = null;
  11469. try {
  11470. audioLevel = getStatValue(now, 'audioInputLevel');
  11471. if (!audioLevel)
  11472. audioLevel = getStatValue(now, 'audioOutputLevel');
  11473. }
  11474. catch(e) {/*not supported*/
  11475. console.warn("Audio Levels are not available in the statistics.");
  11476. clearInterval(this.audioLevelsIntervalId);
  11477. return;
  11478. }
  11479. if (audioLevel) {
  11480. // TODO: can't find specs about what this value really is,
  11481. // but it seems to vary between 0 and around 32k.
  11482. audioLevel = audioLevel / 32767;
  11483. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  11484. if(jid != APP.xmpp.myJid())
  11485. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  11486. }
  11487. }
  11488. };
  11489. },{"../RTC/RTCBrowserType":10}],53:[function(require,module,exports){
  11490. /* global require, APP */
  11491. /**
  11492. * Created by hristo on 8/4/14.
  11493. */
  11494. var LocalStats = require("./LocalStatsCollector.js");
  11495. var RTPStats = require("./RTPStatsCollector.js");
  11496. var EventEmitter = require("events");
  11497. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  11498. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11499. var CallStats = require("./CallStats");
  11500. var RTCEvents = require("../../service/RTC/RTCEvents");
  11501. var eventEmitter = new EventEmitter();
  11502. var localStats = null;
  11503. var rtpStats = null;
  11504. function stopLocal() {
  11505. if (localStats) {
  11506. localStats.stop();
  11507. localStats = null;
  11508. }
  11509. }
  11510. function stopRemote() {
  11511. if (rtpStats) {
  11512. rtpStats.stop();
  11513. eventEmitter.emit("statistics.stop");
  11514. rtpStats = null;
  11515. }
  11516. }
  11517. function startRemoteStats (peerconnection) {
  11518. if (rtpStats) {
  11519. rtpStats.stop();
  11520. }
  11521. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  11522. rtpStats.start();
  11523. }
  11524. function onStreamCreated(stream) {
  11525. if(stream.getOriginalStream().getAudioTracks().length === 0) {
  11526. return;
  11527. }
  11528. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  11529. eventEmitter);
  11530. localStats.start();
  11531. }
  11532. function onDisposeConference(onUnload) {
  11533. CallStats.sendTerminateEvent();
  11534. stopRemote();
  11535. if(onUnload) {
  11536. stopLocal();
  11537. eventEmitter.removeAllListeners();
  11538. }
  11539. }
  11540. var statistics = {
  11541. /**
  11542. * Indicates that this audio level is for local jid.
  11543. * @type {string}
  11544. */
  11545. LOCAL_JID: 'local',
  11546. addAudioLevelListener: function(listener)
  11547. {
  11548. eventEmitter.on("statistics.audioLevel", listener);
  11549. },
  11550. removeAudioLevelListener: function(listener)
  11551. {
  11552. eventEmitter.removeListener("statistics.audioLevel", listener);
  11553. },
  11554. addConnectionStatsListener: function(listener)
  11555. {
  11556. eventEmitter.on("statistics.connectionstats", listener);
  11557. },
  11558. removeConnectionStatsListener: function(listener)
  11559. {
  11560. eventEmitter.removeListener("statistics.connectionstats", listener);
  11561. },
  11562. addRemoteStatsStopListener: function(listener)
  11563. {
  11564. eventEmitter.on("statistics.stop", listener);
  11565. },
  11566. removeRemoteStatsStopListener: function(listener)
  11567. {
  11568. eventEmitter.removeListener("statistics.stop", listener);
  11569. },
  11570. stop: function () {
  11571. stopLocal();
  11572. stopRemote();
  11573. if(eventEmitter)
  11574. {
  11575. eventEmitter.removeAllListeners();
  11576. }
  11577. },
  11578. stopRemoteStatistics: function()
  11579. {
  11580. stopRemote();
  11581. },
  11582. start: function () {
  11583. APP.RTC.addStreamListener(onStreamCreated,
  11584. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  11585. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  11586. //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  11587. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  11588. startRemoteStats(event.peerconnection);
  11589. // CallStats.init(event);
  11590. });
  11591. APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  11592. CallStats.init(session);
  11593. });
  11594. APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  11595. CallStats.sendMuteEvent(mute, "audio");
  11596. });
  11597. APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  11598. CallStats.sendSetupFailedEvent();
  11599. });
  11600. APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  11601. CallStats.sendMuteEvent(mute, "video");
  11602. });
  11603. }
  11604. };
  11605. module.exports = statistics;
  11606. },{"../../service/RTC/RTCEvents":110,"../../service/RTC/StreamEventTypes.js":112,"../../service/xmpp/XMPPEvents":119,"./CallStats":50,"./LocalStatsCollector.js":51,"./RTPStatsCollector.js":52,"events":1}],54:[function(require,module,exports){
  11607. /* global $, require, config, interfaceConfig */
  11608. var i18n = require("i18next-client");
  11609. var languages = require("../../service/translation/languages");
  11610. var Settings = require("../settings/Settings");
  11611. var DEFAULT_LANG = languages.EN;
  11612. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  11613. return value.replace("__app__", interfaceConfig.APP_NAME);
  11614. });
  11615. var defaultOptions = {
  11616. detectLngQS: "lang",
  11617. useCookie: false,
  11618. fallbackLng: DEFAULT_LANG,
  11619. load: "unspecific",
  11620. resGetPath: 'lang/__ns__-__lng__.json',
  11621. ns: {
  11622. namespaces: ['main', 'languages'],
  11623. defaultNs: 'main'
  11624. },
  11625. lngWhitelist : languages.getLanguages(),
  11626. fallbackOnNull: true,
  11627. fallbackOnEmpty: true,
  11628. useDataAttrOptions: true,
  11629. app: interfaceConfig.APP_NAME,
  11630. getAsync: false,
  11631. defaultValueFromContent: false,
  11632. customLoad: function(lng, ns, options, done) {
  11633. var resPath = "lang/__ns__-__lng__.json";
  11634. if(lng === languages.EN)
  11635. resPath = "lang/__ns__.json";
  11636. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  11637. i18n.functions.ajax({
  11638. url: url,
  11639. success: function(data, status, xhr) {
  11640. i18n.functions.log('loaded: ' + url);
  11641. done(null, data);
  11642. },
  11643. error : function(xhr, status, error) {
  11644. if ((status && status == 200) ||
  11645. (xhr && xhr.status && xhr.status == 200)) {
  11646. // file loaded but invalid json, stop waste time !
  11647. i18n.functions.error('There is a typo in: ' + url);
  11648. } else if ((status && status == 404) ||
  11649. (xhr && xhr.status && xhr.status == 404)) {
  11650. i18n.functions.log('Does not exist: ' + url);
  11651. } else {
  11652. var theStatus = status ? status :
  11653. ((xhr && xhr.status) ? xhr.status : null);
  11654. i18n.functions.log(theStatus + ' when loading ' + url);
  11655. }
  11656. done(error, {});
  11657. },
  11658. dataType: "json",
  11659. async : options.getAsync
  11660. });
  11661. }
  11662. // options for caching
  11663. // useLocalStorage: true,
  11664. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  11665. };
  11666. function initCompleted(t) {
  11667. $("[data-i18n]").i18n();
  11668. }
  11669. function checkForParameter() {
  11670. var query = window.location.search.substring(1);
  11671. var vars = query.split("&");
  11672. for (var i=0;i<vars.length;i++) {
  11673. var pair = vars[i].split("=");
  11674. if(pair[0] == "lang")
  11675. {
  11676. return pair[1];
  11677. }
  11678. }
  11679. return null;
  11680. }
  11681. module.exports = {
  11682. init: function (lang) {
  11683. var options = defaultOptions;
  11684. if(!lang)
  11685. {
  11686. lang = checkForParameter();
  11687. if(!lang)
  11688. {
  11689. var settings = Settings.getSettings();
  11690. if(settings)
  11691. lang = settings.language;
  11692. if(!lang && config.defaultLanguage)
  11693. {
  11694. lang = config.defaultLanguage;
  11695. }
  11696. }
  11697. }
  11698. if(lang) {
  11699. options.lng = lang;
  11700. }
  11701. i18n.init(options, initCompleted);
  11702. },
  11703. translateString: function (key, options) {
  11704. return i18n.t(key, options);
  11705. },
  11706. setLanguage: function (lang) {
  11707. if(!lang)
  11708. lang = DEFAULT_LANG;
  11709. i18n.setLng(lang, defaultOptions, initCompleted);
  11710. },
  11711. getCurrentLanguage: function () {
  11712. return i18n.lng();
  11713. },
  11714. translateElement: function (selector) {
  11715. selector.i18n();
  11716. },
  11717. generateTranslationHTML: function (key, options) {
  11718. var str = "<span data-i18n=\"" + key + "\"";
  11719. if(options)
  11720. {
  11721. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  11722. }
  11723. str += ">";
  11724. str += this.translateString(key, options);
  11725. str += "</span>";
  11726. return str;
  11727. }
  11728. };
  11729. },{"../../service/translation/languages":118,"../settings/Settings":49,"i18next-client":71}],55:[function(require,module,exports){
  11730. /* jshint -W117 */
  11731. var TraceablePeerConnection = require("./TraceablePeerConnection");
  11732. var SDPDiffer = require("./SDPDiffer");
  11733. var SDPUtil = require("./SDPUtil");
  11734. var SDP = require("./SDP");
  11735. var async = require("async");
  11736. var transform = require("sdp-transform");
  11737. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11738. var RTCBrowserType = require("../RTC/RTCBrowserType");
  11739. var VideoSSRCHack = require("./VideoSSRCHack");
  11740. // Jingle stuff
  11741. function JingleSession(me, sid, connection, service, eventEmitter) {
  11742. this.me = me;
  11743. this.sid = sid;
  11744. this.connection = connection;
  11745. this.initiator = null;
  11746. this.responder = null;
  11747. this.isInitiator = null;
  11748. this.peerjid = null;
  11749. this.state = null;
  11750. this.localSDP = null;
  11751. this.remoteSDP = null;
  11752. this.relayedStreams = [];
  11753. this.startTime = null;
  11754. this.stopTime = null;
  11755. this.media_constraints = null;
  11756. this.pc_constraints = null;
  11757. this.ice_config = {};
  11758. this.drip_container = [];
  11759. this.service = service;
  11760. this.eventEmitter = eventEmitter;
  11761. this.usetrickle = true;
  11762. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  11763. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  11764. this.hadstuncandidate = false;
  11765. this.hadturncandidate = false;
  11766. this.lasticecandidate = false;
  11767. this.statsinterval = null;
  11768. this.reason = null;
  11769. this.addssrc = [];
  11770. this.removessrc = [];
  11771. this.pendingop = null;
  11772. this.switchstreams = false;
  11773. this.wait = true;
  11774. this.localStreamsSSRC = null;
  11775. this.ssrcOwners = {};
  11776. this.ssrcVideoTypes = {};
  11777. this.eventEmitter = eventEmitter;
  11778. /**
  11779. * The indicator which determines whether the (local) video has been muted
  11780. * in response to a user command in contrast to an automatic decision made
  11781. * by the application logic.
  11782. */
  11783. this.videoMuteByUser = false;
  11784. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  11785. // We start with the queue paused. We resume it when the signaling state is
  11786. // stable and the ice connection state is connected.
  11787. this.modifySourcesQueue.pause();
  11788. }
  11789. JingleSession.prototype.updateModifySourcesQueue = function() {
  11790. var signalingState = this.peerconnection.signalingState;
  11791. var iceConnectionState = this.peerconnection.iceConnectionState;
  11792. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  11793. this.modifySourcesQueue.resume();
  11794. } else {
  11795. this.modifySourcesQueue.pause();
  11796. }
  11797. };
  11798. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  11799. var self = this;
  11800. if (this.state !== null) {
  11801. console.error('attempt to initiate on session ' + this.sid +
  11802. 'in state ' + this.state);
  11803. return;
  11804. }
  11805. this.isInitiator = isInitiator;
  11806. this.state = 'pending';
  11807. this.initiator = isInitiator ? this.me : peerjid;
  11808. this.responder = !isInitiator ? this.me : peerjid;
  11809. this.peerjid = peerjid;
  11810. this.hadstuncandidate = false;
  11811. this.hadturncandidate = false;
  11812. this.lasticecandidate = false;
  11813. this.isreconnect = false;
  11814. this.peerconnection
  11815. = new TraceablePeerConnection(
  11816. this.connection.jingle.ice_config,
  11817. this.connection.jingle.pc_constraints,
  11818. this);
  11819. this.peerconnection.onicecandidate = function (event) {
  11820. self.sendIceCandidate(event.candidate);
  11821. };
  11822. this.peerconnection.onaddstream = function (event) {
  11823. if (event.stream.id !== 'default') {
  11824. console.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  11825. self.remoteStreamAdded(event);
  11826. } else {
  11827. // This is a recvonly stream. Clients that implement Unified Plan,
  11828. // such as Firefox use recvonly "streams/channels/tracks" for
  11829. // receiving remote stream/tracks, as opposed to Plan B where there
  11830. // are only 3 channels: audio, video and data.
  11831. console.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  11832. }
  11833. };
  11834. this.peerconnection.onremovestream = function (event) {
  11835. // Remove the stream from remoteStreams
  11836. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  11837. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  11838. };
  11839. this.peerconnection.onsignalingstatechange = function (event) {
  11840. if (!(self && self.peerconnection)) return;
  11841. self.updateModifySourcesQueue();
  11842. };
  11843. /**
  11844. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  11845. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  11846. * RTCPeerConnection.iceConnectionState changes.
  11847. *
  11848. * @param event the event containing information about the change
  11849. */
  11850. this.peerconnection.oniceconnectionstatechange = function (event) {
  11851. if (!(self && self.peerconnection)) return;
  11852. self.updateModifySourcesQueue();
  11853. switch (self.peerconnection.iceConnectionState) {
  11854. case 'connected':
  11855. self.startTime = new Date();
  11856. // Informs interested parties that the connection has been restored.
  11857. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  11858. self.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  11859. self.isreconnect = false;
  11860. break;
  11861. case 'disconnected':
  11862. self.isreconnect = true;
  11863. self.stopTime = new Date();
  11864. // Informs interested parties that the connection has been interrupted.
  11865. if (self.peerconnection.signalingState === 'stable')
  11866. self.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  11867. break;
  11868. case 'failed':
  11869. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11870. break;
  11871. }
  11872. onIceConnectionStateChange(self.sid, self);
  11873. };
  11874. this.peerconnection.onnegotiationneeded = function (event) {
  11875. self.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  11876. };
  11877. // add any local and relayed stream
  11878. APP.RTC.localStreams.forEach(function(stream) {
  11879. self.peerconnection.addStream(stream.getOriginalStream());
  11880. });
  11881. this.relayedStreams.forEach(function(stream) {
  11882. self.peerconnection.addStream(stream);
  11883. });
  11884. };
  11885. function onIceConnectionStateChange(sid, session) {
  11886. switch (session.peerconnection.iceConnectionState) {
  11887. case 'checking':
  11888. session.timeChecking = (new Date()).getTime();
  11889. session.firstconnect = true;
  11890. break;
  11891. case 'completed': // on caller side
  11892. case 'connected':
  11893. if (session.firstconnect) {
  11894. session.firstconnect = false;
  11895. var metadata = {};
  11896. metadata.setupTime
  11897. = (new Date()).getTime() - session.timeChecking;
  11898. session.peerconnection.getStats(function (res) {
  11899. if(res && res.result) {
  11900. res.result().forEach(function (report) {
  11901. if (report.type == 'googCandidatePair' &&
  11902. report.stat('googActiveConnection') == 'true') {
  11903. metadata.localCandidateType
  11904. = report.stat('googLocalCandidateType');
  11905. metadata.remoteCandidateType
  11906. = report.stat('googRemoteCandidateType');
  11907. // log pair as well so we can get nice pie
  11908. // charts
  11909. metadata.candidatePair
  11910. = report.stat('googLocalCandidateType') +
  11911. ';' +
  11912. report.stat('googRemoteCandidateType');
  11913. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  11914. {
  11915. metadata.ipv6 = true;
  11916. }
  11917. }
  11918. });
  11919. }
  11920. });
  11921. }
  11922. break;
  11923. }
  11924. }
  11925. JingleSession.prototype.accept = function () {
  11926. this.state = 'active';
  11927. var pranswer = this.peerconnection.localDescription;
  11928. if (!pranswer || pranswer.type != 'pranswer') {
  11929. return;
  11930. }
  11931. console.log('going from pranswer to answer');
  11932. if (this.usetrickle) {
  11933. // remove candidates already sent from session-accept
  11934. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  11935. for (var i = 0; i < lines.length; i++) {
  11936. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  11937. }
  11938. }
  11939. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  11940. // FIXME: change any inactive to sendrecv or whatever they were originally
  11941. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  11942. }
  11943. var prsdp = new SDP(pranswer.sdp);
  11944. var accept = $iq({to: this.peerjid,
  11945. type: 'set'})
  11946. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11947. action: 'session-accept',
  11948. initiator: this.initiator,
  11949. responder: this.responder,
  11950. sid: this.sid });
  11951. // FIXME why do we generate session-accept in 3 different places ?
  11952. prsdp.toJingle(
  11953. accept,
  11954. this.initiator == this.me ? 'initiator' : 'responder',
  11955. this.localStreamsSSRC);
  11956. var sdp = this.peerconnection.localDescription.sdp;
  11957. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  11958. // FIXME: change any inactive to sendrecv or whatever they were originally
  11959. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  11960. }
  11961. var self = this;
  11962. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  11963. function () {
  11964. //console.log('setLocalDescription success');
  11965. self.setLocalDescription();
  11966. VideoSSRCHack.processSessionInit(accept);
  11967. self.connection.sendIQ(accept,
  11968. function () {
  11969. var ack = {};
  11970. ack.source = 'answer';
  11971. $(document).trigger('ack.jingle', [self.sid, ack]);
  11972. },
  11973. function (stanza) {
  11974. var error = ($(stanza).find('error').length) ? {
  11975. code: $(stanza).find('error').attr('code'),
  11976. reason: $(stanza).find('error :first')[0].tagName
  11977. }:{};
  11978. error.source = 'answer';
  11979. JingleSession.onJingleError(self.sid, error);
  11980. },
  11981. 10000);
  11982. },
  11983. function (e) {
  11984. console.error('setLocalDescription failed', e);
  11985. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11986. }
  11987. );
  11988. };
  11989. JingleSession.prototype.terminate = function (reason) {
  11990. this.state = 'ended';
  11991. this.reason = reason;
  11992. this.peerconnection.close();
  11993. if (this.statsinterval !== null) {
  11994. window.clearInterval(this.statsinterval);
  11995. this.statsinterval = null;
  11996. }
  11997. };
  11998. JingleSession.prototype.active = function () {
  11999. return this.state == 'active';
  12000. };
  12001. JingleSession.prototype.sendIceCandidate = function (candidate) {
  12002. var self = this;
  12003. if (candidate && !this.lasticecandidate) {
  12004. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  12005. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  12006. if (!(ice && jcand)) {
  12007. console.error('failed to get ice && jcand');
  12008. return;
  12009. }
  12010. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  12011. if (jcand.type === 'srflx') {
  12012. this.hadstuncandidate = true;
  12013. } else if (jcand.type === 'relay') {
  12014. this.hadturncandidate = true;
  12015. }
  12016. if (this.usetrickle) {
  12017. if (this.usedrip) {
  12018. if (this.drip_container.length === 0) {
  12019. // start 20ms callout
  12020. window.setTimeout(function () {
  12021. if (self.drip_container.length === 0) return;
  12022. self.sendIceCandidates(self.drip_container);
  12023. self.drip_container = [];
  12024. }, 20);
  12025. }
  12026. this.drip_container.push(candidate);
  12027. return;
  12028. } else {
  12029. self.sendIceCandidate([candidate]);
  12030. }
  12031. }
  12032. } else {
  12033. //console.log('sendIceCandidate: last candidate.');
  12034. if (!this.usetrickle) {
  12035. //console.log('should send full offer now...');
  12036. //FIXME why do we generate session-accept in 3 different places ?
  12037. var init = $iq({to: this.peerjid,
  12038. type: 'set'})
  12039. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12040. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  12041. initiator: this.initiator,
  12042. sid: this.sid});
  12043. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  12044. var self = this;
  12045. var sendJingle = function (ssrc) {
  12046. if(!ssrc)
  12047. ssrc = {};
  12048. self.localSDP.toJingle(
  12049. init,
  12050. self.initiator == self.me ? 'initiator' : 'responder',
  12051. ssrc);
  12052. VideoSSRCHack.processSessionInit(init);
  12053. self.connection.sendIQ(init,
  12054. function () {
  12055. //console.log('session initiate ack');
  12056. var ack = {};
  12057. ack.source = 'offer';
  12058. $(document).trigger('ack.jingle', [self.sid, ack]);
  12059. },
  12060. function (stanza) {
  12061. self.state = 'error';
  12062. self.peerconnection.close();
  12063. var error = ($(stanza).find('error').length) ? {
  12064. code: $(stanza).find('error').attr('code'),
  12065. reason: $(stanza).find('error :first')[0].tagName,
  12066. }:{};
  12067. error.source = 'offer';
  12068. JingleSession.onJingleError(self.sid, error);
  12069. },
  12070. 10000);
  12071. }
  12072. sendJingle();
  12073. }
  12074. this.lasticecandidate = true;
  12075. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  12076. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  12077. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  12078. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  12079. }
  12080. }
  12081. };
  12082. JingleSession.prototype.sendIceCandidates = function (candidates) {
  12083. console.log('sendIceCandidates', candidates);
  12084. var cand = $iq({to: this.peerjid, type: 'set'})
  12085. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12086. action: 'transport-info',
  12087. initiator: this.initiator,
  12088. sid: this.sid});
  12089. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  12090. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  12091. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  12092. if (cands.length > 0) {
  12093. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  12094. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  12095. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  12096. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  12097. }).c('transport', ice);
  12098. for (var i = 0; i < cands.length; i++) {
  12099. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  12100. }
  12101. // add fingerprint
  12102. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  12103. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  12104. tmp.required = true;
  12105. cand.c(
  12106. 'fingerprint',
  12107. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  12108. .t(tmp.fingerprint);
  12109. delete tmp.fingerprint;
  12110. cand.attrs(tmp);
  12111. cand.up();
  12112. }
  12113. cand.up(); // transport
  12114. cand.up(); // content
  12115. }
  12116. }
  12117. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  12118. //console.log('was this the last candidate', this.lasticecandidate);
  12119. this.connection.sendIQ(cand,
  12120. function () {
  12121. var ack = {};
  12122. ack.source = 'transportinfo';
  12123. $(document).trigger('ack.jingle', [this.sid, ack]);
  12124. },
  12125. function (stanza) {
  12126. var error = ($(stanza).find('error').length) ? {
  12127. code: $(stanza).find('error').attr('code'),
  12128. reason: $(stanza).find('error :first')[0].tagName,
  12129. }:{};
  12130. error.source = 'transportinfo';
  12131. JingleSession.onJingleError(this.sid, error);
  12132. },
  12133. 10000);
  12134. };
  12135. JingleSession.prototype.sendOffer = function () {
  12136. //console.log('sendOffer...');
  12137. var self = this;
  12138. this.peerconnection.createOffer(function (sdp) {
  12139. self.createdOffer(sdp);
  12140. },
  12141. function (e) {
  12142. console.error('createOffer failed', e);
  12143. },
  12144. this.media_constraints
  12145. );
  12146. };
  12147. // FIXME createdOffer is never used in jitsi-meet
  12148. JingleSession.prototype.createdOffer = function (sdp) {
  12149. //console.log('createdOffer', sdp);
  12150. var self = this;
  12151. this.localSDP = new SDP(sdp.sdp);
  12152. //this.localSDP.mangle();
  12153. var sendJingle = function () {
  12154. var init = $iq({to: this.peerjid,
  12155. type: 'set'})
  12156. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12157. action: 'session-initiate',
  12158. initiator: this.initiator,
  12159. sid: this.sid});
  12160. self.localSDP.toJingle(
  12161. init,
  12162. this.initiator == this.me ? 'initiator' : 'responder',
  12163. this.localStreamsSSRC);
  12164. VideoSSRCHack.processSessionInit(init);
  12165. self.connection.sendIQ(init,
  12166. function () {
  12167. var ack = {};
  12168. ack.source = 'offer';
  12169. $(document).trigger('ack.jingle', [self.sid, ack]);
  12170. },
  12171. function (stanza) {
  12172. self.state = 'error';
  12173. self.peerconnection.close();
  12174. var error = ($(stanza).find('error').length) ? {
  12175. code: $(stanza).find('error').attr('code'),
  12176. reason: $(stanza).find('error :first')[0].tagName,
  12177. }:{};
  12178. error.source = 'offer';
  12179. JingleSession.onJingleError(self.sid, error);
  12180. },
  12181. 10000);
  12182. }
  12183. sdp.sdp = this.localSDP.raw;
  12184. this.peerconnection.setLocalDescription(sdp,
  12185. function () {
  12186. if(self.usetrickle)
  12187. {
  12188. sendJingle();
  12189. }
  12190. self.setLocalDescription();
  12191. //console.log('setLocalDescription success');
  12192. },
  12193. function (e) {
  12194. console.error('setLocalDescription failed', e);
  12195. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12196. }
  12197. );
  12198. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  12199. for (var i = 0; i < cands.length; i++) {
  12200. var cand = SDPUtil.parse_icecandidate(cands[i]);
  12201. if (cand.type == 'srflx') {
  12202. this.hadstuncandidate = true;
  12203. } else if (cand.type == 'relay') {
  12204. this.hadturncandidate = true;
  12205. }
  12206. }
  12207. };
  12208. JingleSession.prototype.readSsrcInfo = function (contents) {
  12209. var self = this;
  12210. $(contents).each(function (idx, content) {
  12211. var name = $(content).attr('name');
  12212. var mediaType = this.getAttribute('name');
  12213. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  12214. ssrcs.each(function () {
  12215. var ssrc = this.getAttribute('ssrc');
  12216. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  12217. function () {
  12218. var owner = this.getAttribute('owner');
  12219. self.ssrcOwners[ssrc] = owner;
  12220. }
  12221. );
  12222. });
  12223. });
  12224. };
  12225. JingleSession.prototype.getSsrcOwner = function (ssrc) {
  12226. return this.ssrcOwners[ssrc];
  12227. };
  12228. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  12229. //console.log('setting remote description... ', desctype);
  12230. this.remoteSDP = new SDP('');
  12231. this.remoteSDP.fromJingle(elem);
  12232. this.readSsrcInfo($(elem).find(">content"));
  12233. if (this.peerconnection.remoteDescription !== null) {
  12234. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  12235. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  12236. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  12237. for (var i = 0; i < pranswer.media.length; i++) {
  12238. // make sure we have ice ufrag and pwd
  12239. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  12240. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  12241. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  12242. } else {
  12243. console.warn('no ice ufrag?');
  12244. }
  12245. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  12246. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  12247. } else {
  12248. console.warn('no ice pwd?');
  12249. }
  12250. }
  12251. // copy over candidates
  12252. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  12253. for (var j = 0; j < lines.length; j++) {
  12254. this.remoteSDP.media[i] += lines[j] + '\r\n';
  12255. }
  12256. }
  12257. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  12258. }
  12259. }
  12260. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  12261. this.peerconnection.setRemoteDescription(remotedesc,
  12262. function () {
  12263. //console.log('setRemoteDescription success');
  12264. },
  12265. function (e) {
  12266. console.error('setRemoteDescription error', e);
  12267. JingleSession.onJingleFatalError(self, e);
  12268. }
  12269. );
  12270. };
  12271. JingleSession.prototype.addIceCandidate = function (elem) {
  12272. var self = this;
  12273. if (this.peerconnection.signalingState == 'closed') {
  12274. return;
  12275. }
  12276. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  12277. console.log('trickle ice candidate arriving before session accept...');
  12278. // create a PRANSWER for setRemoteDescription
  12279. if (!this.remoteSDP) {
  12280. var cobbled = 'v=0\r\n' +
  12281. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  12282. 's=-\r\n' +
  12283. 't=0 0\r\n';
  12284. // first, take some things from the local description
  12285. for (var i = 0; i < this.localSDP.media.length; i++) {
  12286. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  12287. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  12288. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  12289. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  12290. }
  12291. cobbled += 'a=inactive\r\n';
  12292. }
  12293. this.remoteSDP = new SDP(cobbled);
  12294. }
  12295. // then add things like ice and dtls from remote candidate
  12296. elem.each(function () {
  12297. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  12298. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12299. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12300. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  12301. var tmp = $(this).find('transport');
  12302. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  12303. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  12304. tmp = $(this).find('transport>fingerprint');
  12305. if (tmp.length) {
  12306. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  12307. } else {
  12308. console.log('no dtls fingerprint (webrtc issue #1718?)');
  12309. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  12310. }
  12311. break;
  12312. }
  12313. }
  12314. }
  12315. });
  12316. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  12317. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  12318. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  12319. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  12320. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  12321. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  12322. }).length == this.remoteSDP.media.length;
  12323. if (iscomplete) {
  12324. console.log('setting pranswer');
  12325. try {
  12326. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  12327. function() {
  12328. },
  12329. function(e) {
  12330. console.log('setRemoteDescription pranswer failed', e.toString());
  12331. });
  12332. } catch (e) {
  12333. console.error('setting pranswer failed', e);
  12334. }
  12335. } else {
  12336. //console.log('not yet setting pranswer');
  12337. }
  12338. }
  12339. // operate on each content element
  12340. elem.each(function () {
  12341. // would love to deactivate this, but firefox still requires it
  12342. var idx = -1;
  12343. var i;
  12344. for (i = 0; i < self.remoteSDP.media.length; i++) {
  12345. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12346. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12347. idx = i;
  12348. break;
  12349. }
  12350. }
  12351. if (idx == -1) { // fall back to localdescription
  12352. for (i = 0; i < self.localSDP.media.length; i++) {
  12353. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12354. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12355. idx = i;
  12356. break;
  12357. }
  12358. }
  12359. }
  12360. var name = $(this).attr('name');
  12361. // TODO: check ice-pwd and ice-ufrag?
  12362. $(this).find('transport>candidate').each(function () {
  12363. var line, candidate;
  12364. line = SDPUtil.candidateFromJingle(this);
  12365. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  12366. sdpMid: name,
  12367. candidate: line});
  12368. try {
  12369. self.peerconnection.addIceCandidate(candidate);
  12370. } catch (e) {
  12371. console.error('addIceCandidate failed', e.toString(), line);
  12372. }
  12373. });
  12374. });
  12375. };
  12376. JingleSession.prototype.sendAnswer = function (provisional) {
  12377. //console.log('createAnswer', provisional);
  12378. var self = this;
  12379. this.peerconnection.createAnswer(
  12380. function (sdp) {
  12381. self.createdAnswer(sdp, provisional);
  12382. },
  12383. function (e) {
  12384. console.error('createAnswer failed', e);
  12385. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12386. },
  12387. this.media_constraints
  12388. );
  12389. };
  12390. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  12391. //console.log('createAnswer callback');
  12392. var self = this;
  12393. this.localSDP = new SDP(sdp.sdp);
  12394. //this.localSDP.mangle();
  12395. this.usepranswer = provisional === true;
  12396. if (this.usetrickle) {
  12397. if (this.usepranswer) {
  12398. sdp.type = 'pranswer';
  12399. for (var i = 0; i < this.localSDP.media.length; i++) {
  12400. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  12401. }
  12402. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  12403. }
  12404. }
  12405. var self = this;
  12406. var sendJingle = function (ssrcs) {
  12407. // FIXME why do we generate session-accept in 3 different places ?
  12408. var accept = $iq({to: self.peerjid,
  12409. type: 'set'})
  12410. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12411. action: 'session-accept',
  12412. initiator: self.initiator,
  12413. responder: self.responder,
  12414. sid: self.sid });
  12415. self.localSDP.toJingle(
  12416. accept,
  12417. self.initiator == self.me ? 'initiator' : 'responder',
  12418. ssrcs);
  12419. VideoSSRCHack.processSessionInit(accept);
  12420. self.connection.sendIQ(accept,
  12421. function () {
  12422. var ack = {};
  12423. ack.source = 'answer';
  12424. $(document).trigger('ack.jingle', [self.sid, ack]);
  12425. },
  12426. function (stanza) {
  12427. var error = ($(stanza).find('error').length) ? {
  12428. code: $(stanza).find('error').attr('code'),
  12429. reason: $(stanza).find('error :first')[0].tagName,
  12430. }:{};
  12431. error.source = 'answer';
  12432. JingleSession.onJingleError(self.sid, error);
  12433. },
  12434. 10000);
  12435. }
  12436. sdp.sdp = this.localSDP.raw;
  12437. this.peerconnection.setLocalDescription(sdp,
  12438. function () {
  12439. //console.log('setLocalDescription success');
  12440. if (self.usetrickle && !self.usepranswer) {
  12441. sendJingle();
  12442. }
  12443. self.setLocalDescription();
  12444. },
  12445. function (e) {
  12446. console.error('setLocalDescription failed', e);
  12447. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12448. }
  12449. );
  12450. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  12451. for (var j = 0; j < cands.length; j++) {
  12452. var cand = SDPUtil.parse_icecandidate(cands[j]);
  12453. if (cand.type == 'srflx') {
  12454. this.hadstuncandidate = true;
  12455. } else if (cand.type == 'relay') {
  12456. this.hadturncandidate = true;
  12457. }
  12458. }
  12459. };
  12460. JingleSession.prototype.sendTerminate = function (reason, text) {
  12461. var self = this,
  12462. term = $iq({to: this.peerjid,
  12463. type: 'set'})
  12464. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12465. action: 'session-terminate',
  12466. initiator: this.initiator,
  12467. sid: this.sid})
  12468. .c('reason')
  12469. .c(reason || 'success');
  12470. if (text) {
  12471. term.up().c('text').t(text);
  12472. }
  12473. this.connection.sendIQ(term,
  12474. function () {
  12475. self.peerconnection.close();
  12476. self.peerconnection = null;
  12477. self.terminate();
  12478. var ack = {};
  12479. ack.source = 'terminate';
  12480. $(document).trigger('ack.jingle', [self.sid, ack]);
  12481. },
  12482. function (stanza) {
  12483. var error = ($(stanza).find('error').length) ? {
  12484. code: $(stanza).find('error').attr('code'),
  12485. reason: $(stanza).find('error :first')[0].tagName,
  12486. }:{};
  12487. $(document).trigger('ack.jingle', [self.sid, error]);
  12488. },
  12489. 10000);
  12490. if (this.statsinterval !== null) {
  12491. window.clearInterval(this.statsinterval);
  12492. this.statsinterval = null;
  12493. }
  12494. };
  12495. JingleSession.prototype.addSource = function (elem, fromJid) {
  12496. var self = this;
  12497. // FIXME: dirty waiting
  12498. if (!this.peerconnection.localDescription)
  12499. {
  12500. console.warn("addSource - localDescription not ready yet")
  12501. setTimeout(function()
  12502. {
  12503. self.addSource(elem, fromJid);
  12504. },
  12505. 200
  12506. );
  12507. return;
  12508. }
  12509. console.log('addssrc', new Date().getTime());
  12510. console.log('ice', this.peerconnection.iceConnectionState);
  12511. this.readSsrcInfo(elem);
  12512. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12513. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12514. $(elem).each(function (idx, content) {
  12515. var name = $(content).attr('name');
  12516. var lines = '';
  12517. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12518. var semantics = this.getAttribute('semantics');
  12519. var ssrcs = $(this).find('>source').map(function () {
  12520. return this.getAttribute('ssrc');
  12521. }).get();
  12522. if (ssrcs.length != 0) {
  12523. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12524. }
  12525. });
  12526. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12527. tmp.each(function () {
  12528. var ssrc = $(this).attr('ssrc');
  12529. if(mySdp.containsSSRC(ssrc)){
  12530. /**
  12531. * This happens when multiple participants change their streams at the same time and
  12532. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  12533. * addssrc are scheduled for update IQ. See
  12534. */
  12535. console.warn("Got add stream request for my own ssrc: "+ssrc);
  12536. return;
  12537. }
  12538. if (sdp.containsSSRC(ssrc)) {
  12539. console.warn("Source-add request for existing SSRC: " + ssrc);
  12540. return;
  12541. }
  12542. $(this).find('>parameter').each(function () {
  12543. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12544. if ($(this).attr('value') && $(this).attr('value').length)
  12545. lines += ':' + $(this).attr('value');
  12546. lines += '\r\n';
  12547. });
  12548. });
  12549. sdp.media.forEach(function(media, idx) {
  12550. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12551. return;
  12552. sdp.media[idx] += lines;
  12553. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  12554. self.addssrc[idx] += lines;
  12555. });
  12556. sdp.raw = sdp.session + sdp.media.join('');
  12557. });
  12558. this.modifySourcesQueue.push(function() {
  12559. // When a source is added and if this is FF, a new channel is allocated
  12560. // for receiving the added source. We need to diffuse the SSRC of this
  12561. // new recvonly channel to the rest of the peers.
  12562. console.log('modify sources done');
  12563. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12564. console.log("SDPs", mySdp, newSdp);
  12565. self.notifyMySSRCUpdate(mySdp, newSdp);
  12566. });
  12567. };
  12568. JingleSession.prototype.removeSource = function (elem, fromJid) {
  12569. var self = this;
  12570. // FIXME: dirty waiting
  12571. if (!this.peerconnection.localDescription)
  12572. {
  12573. console.warn("removeSource - localDescription not ready yet")
  12574. setTimeout(function()
  12575. {
  12576. self.removeSource(elem, fromJid);
  12577. },
  12578. 200
  12579. );
  12580. return;
  12581. }
  12582. console.log('removessrc', new Date().getTime());
  12583. console.log('ice', this.peerconnection.iceConnectionState);
  12584. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12585. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12586. $(elem).each(function (idx, content) {
  12587. var name = $(content).attr('name');
  12588. var lines = '';
  12589. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12590. var semantics = this.getAttribute('semantics');
  12591. var ssrcs = $(this).find('>source').map(function () {
  12592. return this.getAttribute('ssrc');
  12593. }).get();
  12594. if (ssrcs.length != 0) {
  12595. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12596. }
  12597. });
  12598. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12599. tmp.each(function () {
  12600. var ssrc = $(this).attr('ssrc');
  12601. // This should never happen, but can be useful for bug detection
  12602. if(mySdp.containsSSRC(ssrc)){
  12603. console.error("Got remove stream request for my own ssrc: "+ssrc);
  12604. return;
  12605. }
  12606. $(this).find('>parameter').each(function () {
  12607. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12608. if ($(this).attr('value') && $(this).attr('value').length)
  12609. lines += ':' + $(this).attr('value');
  12610. lines += '\r\n';
  12611. });
  12612. });
  12613. sdp.media.forEach(function(media, idx) {
  12614. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12615. return;
  12616. sdp.media[idx] += lines;
  12617. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  12618. self.removessrc[idx] += lines;
  12619. });
  12620. sdp.raw = sdp.session + sdp.media.join('');
  12621. });
  12622. this.modifySourcesQueue.push(function() {
  12623. // When a source is removed and if this is FF, the recvonly channel that
  12624. // receives the remote stream is deactivated . We need to diffuse the
  12625. // recvonly SSRC removal to the rest of the peers.
  12626. console.log('modify sources done');
  12627. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12628. console.log("SDPs", mySdp, newSdp);
  12629. self.notifyMySSRCUpdate(mySdp, newSdp);
  12630. });
  12631. };
  12632. JingleSession.prototype._modifySources = function (successCallback, queueCallback) {
  12633. var self = this;
  12634. if (this.peerconnection.signalingState == 'closed') return;
  12635. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  12636. // There is nothing to do since scheduled job might have been executed by another succeeding call
  12637. this.setLocalDescription();
  12638. if(successCallback){
  12639. successCallback();
  12640. }
  12641. queueCallback();
  12642. return;
  12643. }
  12644. // Reset switch streams flag
  12645. this.switchstreams = false;
  12646. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12647. // add sources
  12648. this.addssrc.forEach(function(lines, idx) {
  12649. sdp.media[idx] += lines;
  12650. });
  12651. this.addssrc = [];
  12652. // remove sources
  12653. this.removessrc.forEach(function(lines, idx) {
  12654. lines = lines.split('\r\n');
  12655. lines.pop(); // remove empty last element;
  12656. lines.forEach(function(line) {
  12657. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  12658. });
  12659. });
  12660. this.removessrc = [];
  12661. sdp.raw = sdp.session + sdp.media.join('');
  12662. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  12663. function() {
  12664. if(self.signalingState == 'closed') {
  12665. console.error("createAnswer attempt on closed state");
  12666. queueCallback("createAnswer attempt on closed state");
  12667. return;
  12668. }
  12669. self.peerconnection.createAnswer(
  12670. function(modifiedAnswer) {
  12671. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  12672. if (self.pendingop !== null) {
  12673. var sdp = new SDP(modifiedAnswer.sdp);
  12674. if (sdp.media.length > 1) {
  12675. switch(self.pendingop) {
  12676. case 'mute':
  12677. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  12678. break;
  12679. case 'unmute':
  12680. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  12681. break;
  12682. }
  12683. sdp.raw = sdp.session + sdp.media.join('');
  12684. modifiedAnswer.sdp = sdp.raw;
  12685. }
  12686. self.pendingop = null;
  12687. }
  12688. // FIXME: pushing down an answer while ice connection state
  12689. // is still checking is bad...
  12690. //console.log(self.peerconnection.iceConnectionState);
  12691. // trying to work around another chrome bug
  12692. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  12693. self.peerconnection.setLocalDescription(modifiedAnswer,
  12694. function() {
  12695. //console.log('modified setLocalDescription ok');
  12696. self.setLocalDescription();
  12697. if(successCallback){
  12698. successCallback();
  12699. }
  12700. queueCallback();
  12701. },
  12702. function(error) {
  12703. console.error('modified setLocalDescription failed', error);
  12704. queueCallback(error);
  12705. }
  12706. );
  12707. },
  12708. function(error) {
  12709. console.error('modified answer failed', error);
  12710. queueCallback(error);
  12711. }
  12712. );
  12713. },
  12714. function(error) {
  12715. console.error('modify failed', error);
  12716. queueCallback(error);
  12717. }
  12718. );
  12719. };
  12720. /**
  12721. * Switches video streams.
  12722. * @param new_stream new stream that will be used as video of this session.
  12723. * @param oldStream old video stream of this session.
  12724. * @param success_callback callback executed after successful stream switch.
  12725. */
  12726. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback, isAudio) {
  12727. var self = this;
  12728. // Remember SDP to figure out added/removed SSRCs
  12729. var oldSdp = null;
  12730. if(self.peerconnection) {
  12731. if(self.peerconnection.localDescription) {
  12732. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  12733. }
  12734. self.peerconnection.removeStream(oldStream, true);
  12735. if(new_stream)
  12736. self.peerconnection.addStream(new_stream);
  12737. }
  12738. // Conference is not active
  12739. if(!oldSdp || !self.peerconnection) {
  12740. success_callback();
  12741. return;
  12742. }
  12743. self.switchstreams = true;
  12744. self.modifySourcesQueue.push(function() {
  12745. console.log('modify sources done');
  12746. success_callback();
  12747. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12748. console.log("SDPs", oldSdp, newSdp);
  12749. self.notifyMySSRCUpdate(oldSdp, newSdp);
  12750. });
  12751. };
  12752. /**
  12753. * Figures out added/removed ssrcs and send update IQs.
  12754. * @param old_sdp SDP object for old description.
  12755. * @param new_sdp SDP object for new description.
  12756. */
  12757. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  12758. if (!(this.peerconnection.signalingState == 'stable' &&
  12759. this.peerconnection.iceConnectionState == 'connected')){
  12760. console.log("Too early to send updates");
  12761. return;
  12762. }
  12763. // send source-remove IQ.
  12764. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  12765. var remove = $iq({to: this.peerjid, type: 'set'})
  12766. .c('jingle', {
  12767. xmlns: 'urn:xmpp:jingle:1',
  12768. action: 'source-remove',
  12769. initiator: this.initiator,
  12770. sid: this.sid
  12771. }
  12772. );
  12773. var removed = sdpDiffer.toJingle(remove);
  12774. // Let 'source-remove' IQ through the hack and see if we're allowed to send
  12775. // it in the current form
  12776. if (removed)
  12777. remove = VideoSSRCHack.processSourceRemove(remove);
  12778. if (removed && remove) {
  12779. this.connection.sendIQ(remove,
  12780. function (res) {
  12781. console.info('got remove result', res);
  12782. },
  12783. function (err) {
  12784. console.error('got remove error', err);
  12785. }
  12786. );
  12787. } else {
  12788. console.log('removal not necessary');
  12789. }
  12790. // send source-add IQ.
  12791. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  12792. var add = $iq({to: this.peerjid, type: 'set'})
  12793. .c('jingle', {
  12794. xmlns: 'urn:xmpp:jingle:1',
  12795. action: 'source-add',
  12796. initiator: this.initiator,
  12797. sid: this.sid
  12798. }
  12799. );
  12800. var added = sdpDiffer.toJingle(add);
  12801. // Let 'source-add' IQ through the hack and see if we're allowed to send
  12802. // it in the current form
  12803. if (added)
  12804. add = VideoSSRCHack.processSourceAdd(add);
  12805. if (added & add) {
  12806. this.connection.sendIQ(add,
  12807. function (res) {
  12808. console.info('got add result', res);
  12809. },
  12810. function (err) {
  12811. console.error('got add error', err);
  12812. }
  12813. );
  12814. } else {
  12815. console.log('addition not necessary');
  12816. }
  12817. };
  12818. /**
  12819. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  12820. *
  12821. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  12822. * tracks; otherwise, <tt>false</tt>
  12823. * @param callback a function to be invoked with <tt>mute</tt> after all video
  12824. * tracks have been enabled/disabled. The function may, optionally, return
  12825. * another function which is to be invoked after the whole mute/unmute operation
  12826. * has completed successfully.
  12827. * @param options an object which specifies optional arguments such as the
  12828. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  12829. * specifies whether the method was initiated in response to a user command (in
  12830. * contrast to an automatic decision made by the application logic)
  12831. */
  12832. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  12833. var byUser;
  12834. if (options) {
  12835. byUser = options.byUser;
  12836. if (typeof byUser === 'undefined') {
  12837. byUser = true;
  12838. }
  12839. } else {
  12840. byUser = true;
  12841. }
  12842. // The user's command to mute the (local) video takes precedence over any
  12843. // automatic decision made by the application logic.
  12844. if (byUser) {
  12845. this.videoMuteByUser = mute;
  12846. } else if (this.videoMuteByUser) {
  12847. return;
  12848. }
  12849. this.hardMuteVideo(mute);
  12850. var self = this;
  12851. var oldSdp = null;
  12852. if(self.peerconnection) {
  12853. if(self.peerconnection.localDescription) {
  12854. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  12855. }
  12856. }
  12857. this.modifySourcesQueue.push(function() {
  12858. console.log('modify sources done');
  12859. callback(mute);
  12860. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12861. console.log("SDPs", oldSdp, newSdp);
  12862. self.notifyMySSRCUpdate(oldSdp, newSdp);
  12863. });
  12864. };
  12865. JingleSession.prototype.hardMuteVideo = function (muted) {
  12866. this.pendingop = muted ? 'mute' : 'unmute';
  12867. };
  12868. JingleSession.prototype.sendMute = function (muted, content) {
  12869. var info = $iq({to: this.peerjid,
  12870. type: 'set'})
  12871. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12872. action: 'session-info',
  12873. initiator: this.initiator,
  12874. sid: this.sid });
  12875. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  12876. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  12877. if (content) {
  12878. info.attrs({'name': content});
  12879. }
  12880. this.connection.send(info);
  12881. };
  12882. JingleSession.prototype.sendRinging = function () {
  12883. var info = $iq({to: this.peerjid,
  12884. type: 'set'})
  12885. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12886. action: 'session-info',
  12887. initiator: this.initiator,
  12888. sid: this.sid });
  12889. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  12890. this.connection.send(info);
  12891. };
  12892. JingleSession.prototype.getStats = function (interval) {
  12893. var self = this;
  12894. var recv = {audio: 0, video: 0};
  12895. var lost = {audio: 0, video: 0};
  12896. var lastrecv = {audio: 0, video: 0};
  12897. var lastlost = {audio: 0, video: 0};
  12898. var loss = {audio: 0, video: 0};
  12899. var delta = {audio: 0, video: 0};
  12900. this.statsinterval = window.setInterval(function () {
  12901. if (self && self.peerconnection && self.peerconnection.getStats) {
  12902. self.peerconnection.getStats(function (stats) {
  12903. var results = stats.result();
  12904. // TODO: there are so much statistics you can get from this..
  12905. for (var i = 0; i < results.length; ++i) {
  12906. if (results[i].type == 'ssrc') {
  12907. var packetsrecv = results[i].stat('packetsReceived');
  12908. var packetslost = results[i].stat('packetsLost');
  12909. if (packetsrecv && packetslost) {
  12910. packetsrecv = parseInt(packetsrecv, 10);
  12911. packetslost = parseInt(packetslost, 10);
  12912. if (results[i].stat('googFrameRateReceived')) {
  12913. lastlost.video = lost.video;
  12914. lastrecv.video = recv.video;
  12915. recv.video = packetsrecv;
  12916. lost.video = packetslost;
  12917. } else {
  12918. lastlost.audio = lost.audio;
  12919. lastrecv.audio = recv.audio;
  12920. recv.audio = packetsrecv;
  12921. lost.audio = packetslost;
  12922. }
  12923. }
  12924. }
  12925. }
  12926. delta.audio = recv.audio - lastrecv.audio;
  12927. delta.video = recv.video - lastrecv.video;
  12928. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  12929. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  12930. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  12931. });
  12932. }
  12933. }, interval || 3000);
  12934. return this.statsinterval;
  12935. };
  12936. JingleSession.onJingleError = function (session, error)
  12937. {
  12938. console.error("Jingle error", error);
  12939. }
  12940. JingleSession.onJingleFatalError = function (session, error)
  12941. {
  12942. this.service.sessionTerminated = true;
  12943. this.connection.emuc.doLeave();
  12944. this.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12945. this.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  12946. }
  12947. JingleSession.prototype.setLocalDescription = function () {
  12948. var self = this;
  12949. var newssrcs = [];
  12950. var session = transform.parse(this.peerconnection.localDescription.sdp);
  12951. session.media.forEach(function (media) {
  12952. if (media.ssrcs != null && media.ssrcs.length > 0) {
  12953. // TODO(gp) maybe exclude FID streams?
  12954. media.ssrcs.forEach(function (ssrc) {
  12955. if (ssrc.attribute !== 'cname') {
  12956. return;
  12957. }
  12958. newssrcs.push({
  12959. 'ssrc': ssrc.id,
  12960. 'type': media.type
  12961. });
  12962. });
  12963. }
  12964. else if(self.localStreamsSSRC && self.localStreamsSSRC[media.type])
  12965. {
  12966. newssrcs.push({
  12967. 'ssrc': self.localStreamsSSRC[media.type],
  12968. 'type': media.type
  12969. });
  12970. }
  12971. });
  12972. console.log('new ssrcs', newssrcs);
  12973. // Bind us as local SSRCs owner
  12974. if (newssrcs.length > 0) {
  12975. for (var i = 1; i <= newssrcs.length; i ++) {
  12976. var ssrc = newssrcs[i-1].ssrc;
  12977. var myJid = self.connection.emuc.myroomjid;
  12978. self.ssrcOwners[ssrc] = myJid;
  12979. }
  12980. }
  12981. }
  12982. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  12983. function sendKeyframe(pc) {
  12984. console.log('sendkeyframe', pc.iceConnectionState);
  12985. if (pc.iceConnectionState !== 'connected') return; // safe...
  12986. var self = this;
  12987. pc.setRemoteDescription(
  12988. pc.remoteDescription,
  12989. function () {
  12990. pc.createAnswer(
  12991. function (modifiedAnswer) {
  12992. pc.setLocalDescription(
  12993. modifiedAnswer,
  12994. function () {
  12995. // noop
  12996. },
  12997. function (error) {
  12998. console.log('triggerKeyframe setLocalDescription failed', error);
  12999. eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  13000. }
  13001. );
  13002. },
  13003. function (error) {
  13004. console.log('triggerKeyframe createAnswer failed', error);
  13005. eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  13006. }
  13007. );
  13008. },
  13009. function (error) {
  13010. console.log('triggerKeyframe setRemoteDescription failed', error);
  13011. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  13012. }
  13013. );
  13014. }
  13015. JingleSession.prototype.remoteStreamAdded = function (data, times) {
  13016. var self = this;
  13017. var thessrc;
  13018. var streamId = APP.RTC.getStreamID(data.stream);
  13019. // look up an associated JID for a stream id
  13020. if (!streamId) {
  13021. console.error("No stream ID for", data.stream);
  13022. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  13023. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  13024. var ssrclines
  13025. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  13026. ssrclines = ssrclines.filter(function (line) {
  13027. // NOTE(gp) previously we filtered on the mslabel, but that property
  13028. // is not always present.
  13029. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  13030. if (RTCBrowserType.isTemasysPluginUsed()) {
  13031. return ((line.indexOf('mslabel:' + streamId) !== -1));
  13032. } else {
  13033. return ((line.indexOf('msid:' + streamId) !== -1));
  13034. }
  13035. });
  13036. if (ssrclines.length) {
  13037. thessrc = ssrclines[0].substring(7).split(' ')[0];
  13038. if (!self.ssrcOwners[thessrc]) {
  13039. console.error("No SSRC owner known for: " + thessrc);
  13040. return;
  13041. }
  13042. data.peerjid = self.ssrcOwners[thessrc];
  13043. console.log('associated jid', self.ssrcOwners[thessrc]);
  13044. } else {
  13045. console.error("No SSRC lines for ", streamId);
  13046. }
  13047. }
  13048. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  13049. var isVideo = data.stream.getVideoTracks().length > 0;
  13050. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  13051. if (isVideo &&
  13052. data.peerjid && this.peerjid === data.peerjid &&
  13053. data.stream.getVideoTracks().length === 0 &&
  13054. APP.RTC.localVideo.getTracks().length > 0) {
  13055. window.setTimeout(function () {
  13056. sendKeyframe(self.peerconnection);
  13057. }, 3000);
  13058. }
  13059. }
  13060. module.exports = JingleSession;
  13061. },{"../../service/xmpp/XMPPEvents":119,"../RTC/RTCBrowserType":10,"./SDP":56,"./SDPDiffer":57,"./SDPUtil":58,"./TraceablePeerConnection":59,"./VideoSSRCHack":60,"async":70,"sdp-transform":106}],56:[function(require,module,exports){
  13062. /* jshint -W117 */
  13063. var SDPUtil = require("./SDPUtil");
  13064. // SDP STUFF
  13065. function SDP(sdp) {
  13066. this.media = sdp.split('\r\nm=');
  13067. for (var i = 1; i < this.media.length; i++) {
  13068. this.media[i] = 'm=' + this.media[i];
  13069. if (i != this.media.length - 1) {
  13070. this.media[i] += '\r\n';
  13071. }
  13072. }
  13073. this.session = this.media.shift() + '\r\n';
  13074. this.raw = this.session + this.media.join('');
  13075. }
  13076. /**
  13077. * Returns map of MediaChannel mapped per channel idx.
  13078. */
  13079. SDP.prototype.getMediaSsrcMap = function() {
  13080. var self = this;
  13081. var media_ssrcs = {};
  13082. var tmp;
  13083. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  13084. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  13085. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  13086. var media = {
  13087. mediaindex: mediaindex,
  13088. mid: mid,
  13089. ssrcs: {},
  13090. ssrcGroups: []
  13091. };
  13092. media_ssrcs[mediaindex] = media;
  13093. tmp.forEach(function (line) {
  13094. var linessrc = line.substring(7).split(' ')[0];
  13095. // allocate new ChannelSsrc
  13096. if(!media.ssrcs[linessrc]) {
  13097. media.ssrcs[linessrc] = {
  13098. ssrc: linessrc,
  13099. lines: []
  13100. };
  13101. }
  13102. media.ssrcs[linessrc].lines.push(line);
  13103. });
  13104. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  13105. tmp.forEach(function(line){
  13106. var semantics = line.substr(0, idx).substr(13);
  13107. var ssrcs = line.substr(14 + semantics.length).split(' ');
  13108. if (ssrcs.length != 0) {
  13109. media.ssrcGroups.push({
  13110. semantics: semantics,
  13111. ssrcs: ssrcs
  13112. });
  13113. }
  13114. });
  13115. }
  13116. return media_ssrcs;
  13117. };
  13118. /**
  13119. * Returns <tt>true</tt> if this SDP contains given SSRC.
  13120. * @param ssrc the ssrc to check.
  13121. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  13122. */
  13123. SDP.prototype.containsSSRC = function(ssrc) {
  13124. var medias = this.getMediaSsrcMap();
  13125. var contains = false;
  13126. Object.keys(medias).forEach(function(mediaindex){
  13127. var media = medias[mediaindex];
  13128. //console.log("Check", channel, ssrc);
  13129. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  13130. contains = true;
  13131. }
  13132. });
  13133. return contains;
  13134. };
  13135. // remove iSAC and CN from SDP
  13136. SDP.prototype.mangle = function () {
  13137. var i, j, mline, lines, rtpmap, newdesc;
  13138. for (i = 0; i < this.media.length; i++) {
  13139. lines = this.media[i].split('\r\n');
  13140. lines.pop(); // remove empty last element
  13141. mline = SDPUtil.parse_mline(lines.shift());
  13142. if (mline.media != 'audio')
  13143. continue;
  13144. newdesc = '';
  13145. mline.fmt.length = 0;
  13146. for (j = 0; j < lines.length; j++) {
  13147. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  13148. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  13149. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  13150. continue;
  13151. mline.fmt.push(rtpmap.id);
  13152. newdesc += lines[j] + '\r\n';
  13153. } else {
  13154. newdesc += lines[j] + '\r\n';
  13155. }
  13156. }
  13157. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  13158. this.media[i] += newdesc;
  13159. }
  13160. this.raw = this.session + this.media.join('');
  13161. };
  13162. // remove lines matching prefix from session section
  13163. SDP.prototype.removeSessionLines = function(prefix) {
  13164. var self = this;
  13165. var lines = SDPUtil.find_lines(this.session, prefix);
  13166. lines.forEach(function(line) {
  13167. self.session = self.session.replace(line + '\r\n', '');
  13168. });
  13169. this.raw = this.session + this.media.join('');
  13170. return lines;
  13171. }
  13172. // remove lines matching prefix from a media section specified by mediaindex
  13173. // TODO: non-numeric mediaindex could match mid
  13174. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  13175. var self = this;
  13176. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  13177. lines.forEach(function(line) {
  13178. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  13179. });
  13180. this.raw = this.session + this.media.join('');
  13181. return lines;
  13182. }
  13183. // add content's to a jingle element
  13184. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  13185. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  13186. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  13187. var self = this;
  13188. // new bundle plan
  13189. if (SDPUtil.find_line(this.session, 'a=group:')) {
  13190. lines = SDPUtil.find_lines(this.session, 'a=group:');
  13191. for (i = 0; i < lines.length; i++) {
  13192. tmp = lines[i].split(' ');
  13193. var semantics = tmp.shift().substr(8);
  13194. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  13195. for (j = 0; j < tmp.length; j++) {
  13196. elem.c('content', {name: tmp[j]}).up();
  13197. }
  13198. elem.up();
  13199. }
  13200. }
  13201. for (i = 0; i < this.media.length; i++) {
  13202. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  13203. if (!(mline.media === 'audio' ||
  13204. mline.media === 'video' ||
  13205. mline.media === 'application'))
  13206. {
  13207. continue;
  13208. }
  13209. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  13210. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  13211. } else {
  13212. if(ssrcs && ssrcs[mline.media])
  13213. {
  13214. ssrc = ssrcs[mline.media];
  13215. }
  13216. else
  13217. ssrc = false;
  13218. }
  13219. elem.c('content', {creator: thecreator, name: mline.media});
  13220. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  13221. // prefer identifier from a=mid if present
  13222. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  13223. elem.attrs({ name: mid });
  13224. }
  13225. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  13226. {
  13227. elem.c('description',
  13228. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  13229. media: mline.media });
  13230. if (ssrc) {
  13231. elem.attrs({ssrc: ssrc});
  13232. }
  13233. for (j = 0; j < mline.fmt.length; j++) {
  13234. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  13235. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  13236. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  13237. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  13238. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  13239. for (k = 0; k < tmp.length; k++) {
  13240. elem.c('parameter', tmp[k]).up();
  13241. }
  13242. }
  13243. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  13244. elem.up();
  13245. }
  13246. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  13247. elem.c('encryption', {required: 1});
  13248. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  13249. crypto.forEach(function(line) {
  13250. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  13251. });
  13252. elem.up(); // end of encryption
  13253. }
  13254. if (ssrc) {
  13255. // new style mapping
  13256. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13257. // FIXME: group by ssrc and support multiple different ssrcs
  13258. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  13259. if(ssrclines.length > 0) {
  13260. ssrclines.forEach(function (line) {
  13261. idx = line.indexOf(' ');
  13262. var linessrc = line.substr(0, idx).substr(7);
  13263. if (linessrc != ssrc) {
  13264. elem.up();
  13265. ssrc = linessrc;
  13266. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13267. }
  13268. var kv = line.substr(idx + 1);
  13269. elem.c('parameter');
  13270. if (kv.indexOf(':') == -1) {
  13271. elem.attrs({ name: kv });
  13272. } else {
  13273. var k = kv.split(':', 2)[0];
  13274. elem.attrs({ name: k });
  13275. var v = kv.split(':', 2)[1];
  13276. v = SDPUtil.filter_special_chars(v);
  13277. elem.attrs({ value: v });
  13278. }
  13279. elem.up();
  13280. });
  13281. }
  13282. else
  13283. {
  13284. elem.up();
  13285. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13286. elem.c('parameter');
  13287. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  13288. elem.up();
  13289. var msid = null;
  13290. if(mline.media == "audio")
  13291. {
  13292. msid = APP.RTC.localAudio.getId();
  13293. }
  13294. else
  13295. {
  13296. msid = APP.RTC.localVideo.getId();
  13297. }
  13298. if(msid != null)
  13299. {
  13300. msid = SDPUtil.filter_special_chars(msid);
  13301. elem.c('parameter');
  13302. elem.attrs({name: "msid", value:msid});
  13303. elem.up();
  13304. elem.c('parameter');
  13305. elem.attrs({name: "mslabel", value:msid});
  13306. elem.up();
  13307. elem.c('parameter');
  13308. elem.attrs({name: "label", value:msid});
  13309. elem.up();
  13310. }
  13311. }
  13312. elem.up();
  13313. // XEP-0339 handle ssrc-group attributes
  13314. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  13315. ssrc_group_lines.forEach(function(line) {
  13316. idx = line.indexOf(' ');
  13317. var semantics = line.substr(0, idx).substr(13);
  13318. var ssrcs = line.substr(14 + semantics.length).split(' ');
  13319. if (ssrcs.length != 0) {
  13320. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13321. ssrcs.forEach(function(ssrc) {
  13322. elem.c('source', { ssrc: ssrc })
  13323. .up();
  13324. });
  13325. elem.up();
  13326. }
  13327. });
  13328. }
  13329. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  13330. elem.c('rtcp-mux').up();
  13331. }
  13332. // XEP-0293 -- map a=rtcp-fb:*
  13333. this.RtcpFbToJingle(i, elem, '*');
  13334. // XEP-0294
  13335. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  13336. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  13337. for (j = 0; j < lines.length; j++) {
  13338. tmp = SDPUtil.parse_extmap(lines[j]);
  13339. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  13340. uri: tmp.uri,
  13341. id: tmp.value });
  13342. if (tmp.hasOwnProperty('direction')) {
  13343. switch (tmp.direction) {
  13344. case 'sendonly':
  13345. elem.attrs({senders: 'responder'});
  13346. break;
  13347. case 'recvonly':
  13348. elem.attrs({senders: 'initiator'});
  13349. break;
  13350. case 'sendrecv':
  13351. elem.attrs({senders: 'both'});
  13352. break;
  13353. case 'inactive':
  13354. elem.attrs({senders: 'none'});
  13355. break;
  13356. }
  13357. }
  13358. // TODO: handle params
  13359. elem.up();
  13360. }
  13361. }
  13362. elem.up(); // end of description
  13363. }
  13364. // map ice-ufrag/pwd, dtls fingerprint, candidates
  13365. this.TransportToJingle(i, elem);
  13366. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  13367. elem.attrs({senders: 'both'});
  13368. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  13369. elem.attrs({senders: 'initiator'});
  13370. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  13371. elem.attrs({senders: 'responder'});
  13372. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  13373. elem.attrs({senders: 'none'});
  13374. }
  13375. if (mline.port == '0') {
  13376. // estos hack to reject an m-line
  13377. elem.attrs({senders: 'rejected'});
  13378. }
  13379. elem.up(); // end of content
  13380. }
  13381. elem.up();
  13382. return elem;
  13383. };
  13384. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  13385. var i = mediaindex;
  13386. var tmp;
  13387. var self = this;
  13388. elem.c('transport');
  13389. // XEP-0343 DTLS/SCTP
  13390. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  13391. {
  13392. var sctpmap = SDPUtil.find_line(
  13393. this.media[i], 'a=sctpmap:', self.session);
  13394. if (sctpmap)
  13395. {
  13396. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  13397. elem.c('sctpmap',
  13398. {
  13399. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  13400. number: sctpAttrs[0], /* SCTP port */
  13401. protocol: sctpAttrs[1], /* protocol */
  13402. });
  13403. // Optional stream count attribute
  13404. if (sctpAttrs.length > 2)
  13405. elem.attrs({ streams: sctpAttrs[2]});
  13406. elem.up();
  13407. }
  13408. }
  13409. // XEP-0320
  13410. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  13411. fingerprints.forEach(function(line) {
  13412. tmp = SDPUtil.parse_fingerprint(line);
  13413. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  13414. elem.c('fingerprint').t(tmp.fingerprint);
  13415. delete tmp.fingerprint;
  13416. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  13417. if (line) {
  13418. tmp.setup = line.substr(8);
  13419. }
  13420. elem.attrs(tmp);
  13421. elem.up(); // end of fingerprint
  13422. });
  13423. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  13424. if (tmp) {
  13425. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  13426. elem.attrs(tmp);
  13427. // XEP-0176
  13428. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  13429. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  13430. lines.forEach(function (line) {
  13431. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  13432. });
  13433. }
  13434. }
  13435. elem.up(); // end of transport
  13436. }
  13437. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  13438. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  13439. lines.forEach(function (line) {
  13440. var tmp = SDPUtil.parse_rtcpfb(line);
  13441. if (tmp.type == 'trr-int') {
  13442. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  13443. elem.up();
  13444. } else {
  13445. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  13446. if (tmp.params.length > 0) {
  13447. elem.attrs({'subtype': tmp.params[0]});
  13448. }
  13449. elem.up();
  13450. }
  13451. });
  13452. };
  13453. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  13454. var media = '';
  13455. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  13456. if (tmp.length) {
  13457. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  13458. if (tmp.attr('value')) {
  13459. media += tmp.attr('value');
  13460. } else {
  13461. media += '0';
  13462. }
  13463. media += '\r\n';
  13464. }
  13465. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  13466. tmp.each(function () {
  13467. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  13468. if ($(this).attr('subtype')) {
  13469. media += ' ' + $(this).attr('subtype');
  13470. }
  13471. media += '\r\n';
  13472. });
  13473. return media;
  13474. };
  13475. // construct an SDP from a jingle stanza
  13476. SDP.prototype.fromJingle = function (jingle) {
  13477. var self = this;
  13478. this.raw = 'v=0\r\n' +
  13479. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  13480. 's=-\r\n' +
  13481. 't=0 0\r\n';
  13482. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  13483. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  13484. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  13485. var contents = $(group).find('>content').map(function (idx, content) {
  13486. return content.getAttribute('name');
  13487. }).get();
  13488. if (contents.length > 0) {
  13489. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  13490. }
  13491. });
  13492. }
  13493. this.session = this.raw;
  13494. jingle.find('>content').each(function () {
  13495. var m = self.jingle2media($(this));
  13496. self.media.push(m);
  13497. });
  13498. // reconstruct msid-semantic -- apparently not necessary
  13499. /*
  13500. var msid = SDPUtil.parse_ssrc(this.raw);
  13501. if (msid.hasOwnProperty('mslabel')) {
  13502. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  13503. }
  13504. */
  13505. this.raw = this.session + this.media.join('');
  13506. };
  13507. // translate a jingle content element into an an SDP media part
  13508. SDP.prototype.jingle2media = function (content) {
  13509. var media = '',
  13510. desc = content.find('description'),
  13511. ssrc = desc.attr('ssrc'),
  13512. self = this,
  13513. tmp;
  13514. var sctp = content.find(
  13515. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  13516. tmp = { media: desc.attr('media') };
  13517. tmp.port = '1';
  13518. if (content.attr('senders') == 'rejected') {
  13519. // estos hack to reject an m-line.
  13520. tmp.port = '0';
  13521. }
  13522. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  13523. if (sctp.length)
  13524. tmp.proto = 'DTLS/SCTP';
  13525. else
  13526. tmp.proto = 'RTP/SAVPF';
  13527. } else {
  13528. tmp.proto = 'RTP/AVPF';
  13529. }
  13530. if (!sctp.length)
  13531. {
  13532. tmp.fmt = desc.find('payload-type').map(
  13533. function () { return this.getAttribute('id'); }).get();
  13534. media += SDPUtil.build_mline(tmp) + '\r\n';
  13535. }
  13536. else
  13537. {
  13538. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  13539. media += 'a=sctpmap:' + sctp.attr('number') +
  13540. ' ' + sctp.attr('protocol');
  13541. var streamCount = sctp.attr('streams');
  13542. if (streamCount)
  13543. media += ' ' + streamCount + '\r\n';
  13544. else
  13545. media += '\r\n';
  13546. }
  13547. media += 'c=IN IP4 0.0.0.0\r\n';
  13548. if (!sctp.length)
  13549. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  13550. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  13551. if (tmp.length) {
  13552. if (tmp.attr('ufrag')) {
  13553. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  13554. }
  13555. if (tmp.attr('pwd')) {
  13556. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  13557. }
  13558. tmp.find('>fingerprint').each(function () {
  13559. // FIXME: check namespace at some point
  13560. media += 'a=fingerprint:' + this.getAttribute('hash');
  13561. media += ' ' + $(this).text();
  13562. media += '\r\n';
  13563. if (this.getAttribute('setup')) {
  13564. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  13565. }
  13566. });
  13567. }
  13568. switch (content.attr('senders')) {
  13569. case 'initiator':
  13570. media += 'a=sendonly\r\n';
  13571. break;
  13572. case 'responder':
  13573. media += 'a=recvonly\r\n';
  13574. break;
  13575. case 'none':
  13576. media += 'a=inactive\r\n';
  13577. break;
  13578. case 'both':
  13579. media += 'a=sendrecv\r\n';
  13580. break;
  13581. }
  13582. media += 'a=mid:' + content.attr('name') + '\r\n';
  13583. // <description><rtcp-mux/></description>
  13584. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  13585. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  13586. if (desc.find('rtcp-mux').length) {
  13587. media += 'a=rtcp-mux\r\n';
  13588. }
  13589. if (desc.find('encryption').length) {
  13590. desc.find('encryption>crypto').each(function () {
  13591. media += 'a=crypto:' + this.getAttribute('tag');
  13592. media += ' ' + this.getAttribute('crypto-suite');
  13593. media += ' ' + this.getAttribute('key-params');
  13594. if (this.getAttribute('session-params')) {
  13595. media += ' ' + this.getAttribute('session-params');
  13596. }
  13597. media += '\r\n';
  13598. });
  13599. }
  13600. desc.find('payload-type').each(function () {
  13601. media += SDPUtil.build_rtpmap(this) + '\r\n';
  13602. if ($(this).find('>parameter').length) {
  13603. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  13604. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  13605. media += '\r\n';
  13606. }
  13607. // xep-0293
  13608. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  13609. });
  13610. // xep-0293
  13611. media += self.RtcpFbFromJingle(desc, '*');
  13612. // xep-0294
  13613. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  13614. tmp.each(function () {
  13615. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  13616. });
  13617. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  13618. media += SDPUtil.candidateFromJingle(this);
  13619. });
  13620. // XEP-0339 handle ssrc-group attributes
  13621. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  13622. var semantics = this.getAttribute('semantics');
  13623. var ssrcs = $(this).find('>source').map(function() {
  13624. return this.getAttribute('ssrc');
  13625. }).get();
  13626. if (ssrcs.length != 0) {
  13627. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  13628. }
  13629. });
  13630. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  13631. tmp.each(function () {
  13632. var ssrc = this.getAttribute('ssrc');
  13633. $(this).find('>parameter').each(function () {
  13634. var name = this.getAttribute('name');
  13635. var value = this.getAttribute('value');
  13636. value = SDPUtil.filter_special_chars(value);
  13637. media += 'a=ssrc:' + ssrc + ' ' + name;
  13638. if (value && value.length)
  13639. media += ':' + value;
  13640. media += '\r\n';
  13641. });
  13642. });
  13643. return media;
  13644. };
  13645. module.exports = SDP;
  13646. },{"./SDPUtil":58}],57:[function(require,module,exports){
  13647. var SDPUtil = require("./SDPUtil");
  13648. function SDPDiffer(mySDP, otherSDP) {
  13649. this.mySDP = mySDP;
  13650. this.otherSDP = otherSDP;
  13651. }
  13652. /**
  13653. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  13654. * @param otherSdp the other SDP to check ssrc with.
  13655. */
  13656. SDPDiffer.prototype.getNewMedia = function() {
  13657. // this could be useful in Array.prototype.
  13658. function arrayEquals(array) {
  13659. // if the other array is a falsy value, return
  13660. if (!array)
  13661. return false;
  13662. // compare lengths - can save a lot of time
  13663. if (this.length != array.length)
  13664. return false;
  13665. for (var i = 0, l=this.length; i < l; i++) {
  13666. // Check if we have nested arrays
  13667. if (this[i] instanceof Array && array[i] instanceof Array) {
  13668. // recurse into the nested arrays
  13669. if (!this[i].equals(array[i]))
  13670. return false;
  13671. }
  13672. else if (this[i] != array[i]) {
  13673. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  13674. return false;
  13675. }
  13676. }
  13677. return true;
  13678. }
  13679. var myMedias = this.mySDP.getMediaSsrcMap();
  13680. var othersMedias = this.otherSDP.getMediaSsrcMap();
  13681. var newMedia = {};
  13682. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  13683. var myMedia = myMedias[othersMediaIdx];
  13684. var othersMedia = othersMedias[othersMediaIdx];
  13685. if(!myMedia && othersMedia) {
  13686. // Add whole channel
  13687. newMedia[othersMediaIdx] = othersMedia;
  13688. return;
  13689. }
  13690. // Look for new ssrcs accross the channel
  13691. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  13692. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  13693. // Allocate channel if we've found ssrc that doesn't exist in our channel
  13694. if(!newMedia[othersMediaIdx]){
  13695. newMedia[othersMediaIdx] = {
  13696. mediaindex: othersMedia.mediaindex,
  13697. mid: othersMedia.mid,
  13698. ssrcs: {},
  13699. ssrcGroups: []
  13700. };
  13701. }
  13702. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  13703. }
  13704. });
  13705. // Look for new ssrc groups across the channels
  13706. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  13707. // try to match the other ssrc-group with an ssrc-group of ours
  13708. var matched = false;
  13709. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  13710. var mySsrcGroup = myMedia.ssrcGroups[i];
  13711. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  13712. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  13713. matched = true;
  13714. break;
  13715. }
  13716. }
  13717. if (!matched) {
  13718. // Allocate channel if we've found an ssrc-group that doesn't
  13719. // exist in our channel
  13720. if(!newMedia[othersMediaIdx]){
  13721. newMedia[othersMediaIdx] = {
  13722. mediaindex: othersMedia.mediaindex,
  13723. mid: othersMedia.mid,
  13724. ssrcs: {},
  13725. ssrcGroups: []
  13726. };
  13727. }
  13728. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  13729. }
  13730. });
  13731. });
  13732. return newMedia;
  13733. };
  13734. /**
  13735. * Sends SSRC update IQ.
  13736. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  13737. * @param sid session identifier that will be put into the IQ.
  13738. * @param initiator initiator identifier.
  13739. * @param toJid destination Jid
  13740. * @param isAdd indicates if this is remove or add operation.
  13741. */
  13742. SDPDiffer.prototype.toJingle = function(modify) {
  13743. var sdpMediaSsrcs = this.getNewMedia();
  13744. var self = this;
  13745. // FIXME: only announce video ssrcs since we mix audio and dont need
  13746. // the audio ssrcs therefore
  13747. var modified = false;
  13748. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  13749. modified = true;
  13750. var media = sdpMediaSsrcs[mediaindex];
  13751. modify.c('content', {name: media.mid});
  13752. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  13753. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  13754. // generate sources from lines
  13755. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  13756. var mediaSsrc = media.ssrcs[ssrcNum];
  13757. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13758. modify.attrs({ssrc: mediaSsrc.ssrc});
  13759. // iterate over ssrc lines
  13760. mediaSsrc.lines.forEach(function (line) {
  13761. var idx = line.indexOf(' ');
  13762. var kv = line.substr(idx + 1);
  13763. modify.c('parameter');
  13764. if (kv.indexOf(':') == -1) {
  13765. modify.attrs({ name: kv });
  13766. } else {
  13767. var nv = kv.split(':', 2);
  13768. var name = nv[0];
  13769. var value = SDPUtil.filter_special_chars(nv[1]);
  13770. modify.attrs({ name: name });
  13771. modify.attrs({ value: value });
  13772. }
  13773. modify.up(); // end of parameter
  13774. });
  13775. modify.up(); // end of source
  13776. });
  13777. // generate source groups from lines
  13778. media.ssrcGroups.forEach(function(ssrcGroup) {
  13779. if (ssrcGroup.ssrcs.length != 0) {
  13780. modify.c('ssrc-group', {
  13781. semantics: ssrcGroup.semantics,
  13782. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  13783. });
  13784. ssrcGroup.ssrcs.forEach(function (ssrc) {
  13785. modify.c('source', { ssrc: ssrc })
  13786. .up(); // end of source
  13787. });
  13788. modify.up(); // end of ssrc-group
  13789. }
  13790. });
  13791. modify.up(); // end of description
  13792. modify.up(); // end of content
  13793. });
  13794. return modified;
  13795. };
  13796. module.exports = SDPDiffer;
  13797. },{"./SDPUtil":58}],58:[function(require,module,exports){
  13798. SDPUtil = {
  13799. filter_special_chars: function (text) {
  13800. return text.replace(/[\\\/\{,\}\+]/g, "");
  13801. },
  13802. iceparams: function (mediadesc, sessiondesc) {
  13803. var data = null;
  13804. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  13805. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  13806. data = {
  13807. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  13808. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  13809. };
  13810. }
  13811. return data;
  13812. },
  13813. parse_iceufrag: function (line) {
  13814. return line.substring(12);
  13815. },
  13816. build_iceufrag: function (frag) {
  13817. return 'a=ice-ufrag:' + frag;
  13818. },
  13819. parse_icepwd: function (line) {
  13820. return line.substring(10);
  13821. },
  13822. build_icepwd: function (pwd) {
  13823. return 'a=ice-pwd:' + pwd;
  13824. },
  13825. parse_mid: function (line) {
  13826. return line.substring(6);
  13827. },
  13828. parse_mline: function (line) {
  13829. var parts = line.substring(2).split(' '),
  13830. data = {};
  13831. data.media = parts.shift();
  13832. data.port = parts.shift();
  13833. data.proto = parts.shift();
  13834. if (parts[parts.length - 1] === '') { // trailing whitespace
  13835. parts.pop();
  13836. }
  13837. data.fmt = parts;
  13838. return data;
  13839. },
  13840. build_mline: function (mline) {
  13841. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  13842. },
  13843. parse_rtpmap: function (line) {
  13844. var parts = line.substring(9).split(' '),
  13845. data = {};
  13846. data.id = parts.shift();
  13847. parts = parts[0].split('/');
  13848. data.name = parts.shift();
  13849. data.clockrate = parts.shift();
  13850. data.channels = parts.length ? parts.shift() : '1';
  13851. return data;
  13852. },
  13853. /**
  13854. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  13855. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  13856. * @returns [SCTP port number, protocol, streams]
  13857. */
  13858. parse_sctpmap: function (line)
  13859. {
  13860. var parts = line.substring(10).split(' ');
  13861. var sctpPort = parts[0];
  13862. var protocol = parts[1];
  13863. // Stream count is optional
  13864. var streamCount = parts.length > 2 ? parts[2] : null;
  13865. return [sctpPort, protocol, streamCount];// SCTP port
  13866. },
  13867. build_rtpmap: function (el) {
  13868. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  13869. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  13870. line += '/' + el.getAttribute('channels');
  13871. }
  13872. return line;
  13873. },
  13874. parse_crypto: function (line) {
  13875. var parts = line.substring(9).split(' '),
  13876. data = {};
  13877. data.tag = parts.shift();
  13878. data['crypto-suite'] = parts.shift();
  13879. data['key-params'] = parts.shift();
  13880. if (parts.length) {
  13881. data['session-params'] = parts.join(' ');
  13882. }
  13883. return data;
  13884. },
  13885. parse_fingerprint: function (line) { // RFC 4572
  13886. var parts = line.substring(14).split(' '),
  13887. data = {};
  13888. data.hash = parts.shift();
  13889. data.fingerprint = parts.shift();
  13890. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  13891. return data;
  13892. },
  13893. parse_fmtp: function (line) {
  13894. var parts = line.split(' '),
  13895. i, key, value,
  13896. data = [];
  13897. parts.shift();
  13898. parts = parts.join(' ').split(';');
  13899. for (i = 0; i < parts.length; i++) {
  13900. key = parts[i].split('=')[0];
  13901. while (key.length && key[0] == ' ') {
  13902. key = key.substring(1);
  13903. }
  13904. value = parts[i].split('=')[1];
  13905. if (key && value) {
  13906. data.push({name: key, value: value});
  13907. } else if (key) {
  13908. // rfc 4733 (DTMF) style stuff
  13909. data.push({name: '', value: key});
  13910. }
  13911. }
  13912. return data;
  13913. },
  13914. parse_icecandidate: function (line) {
  13915. var candidate = {},
  13916. elems = line.split(' ');
  13917. candidate.foundation = elems[0].substring(12);
  13918. candidate.component = elems[1];
  13919. candidate.protocol = elems[2].toLowerCase();
  13920. candidate.priority = elems[3];
  13921. candidate.ip = elems[4];
  13922. candidate.port = elems[5];
  13923. // elems[6] => "typ"
  13924. candidate.type = elems[7];
  13925. candidate.generation = 0; // default value, may be overwritten below
  13926. for (var i = 8; i < elems.length; i += 2) {
  13927. switch (elems[i]) {
  13928. case 'raddr':
  13929. candidate['rel-addr'] = elems[i + 1];
  13930. break;
  13931. case 'rport':
  13932. candidate['rel-port'] = elems[i + 1];
  13933. break;
  13934. case 'generation':
  13935. candidate.generation = elems[i + 1];
  13936. break;
  13937. case 'tcptype':
  13938. candidate.tcptype = elems[i + 1];
  13939. break;
  13940. default: // TODO
  13941. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  13942. }
  13943. }
  13944. candidate.network = '1';
  13945. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  13946. return candidate;
  13947. },
  13948. build_icecandidate: function (cand) {
  13949. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  13950. line += ' ';
  13951. switch (cand.type) {
  13952. case 'srflx':
  13953. case 'prflx':
  13954. case 'relay':
  13955. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  13956. line += 'raddr';
  13957. line += ' ';
  13958. line += cand['rel-addr'];
  13959. line += ' ';
  13960. line += 'rport';
  13961. line += ' ';
  13962. line += cand['rel-port'];
  13963. line += ' ';
  13964. }
  13965. break;
  13966. }
  13967. if (cand.hasOwnAttribute('tcptype')) {
  13968. line += 'tcptype';
  13969. line += ' ';
  13970. line += cand.tcptype;
  13971. line += ' ';
  13972. }
  13973. line += 'generation';
  13974. line += ' ';
  13975. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  13976. return line;
  13977. },
  13978. parse_ssrc: function (desc) {
  13979. // proprietary mapping of a=ssrc lines
  13980. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  13981. // and parse according to that
  13982. var lines = desc.split('\r\n'),
  13983. data = {};
  13984. for (var i = 0; i < lines.length; i++) {
  13985. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  13986. var idx = lines[i].indexOf(' ');
  13987. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  13988. }
  13989. }
  13990. return data;
  13991. },
  13992. parse_rtcpfb: function (line) {
  13993. var parts = line.substr(10).split(' ');
  13994. var data = {};
  13995. data.pt = parts.shift();
  13996. data.type = parts.shift();
  13997. data.params = parts;
  13998. return data;
  13999. },
  14000. parse_extmap: function (line) {
  14001. var parts = line.substr(9).split(' ');
  14002. var data = {};
  14003. data.value = parts.shift();
  14004. if (data.value.indexOf('/') != -1) {
  14005. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  14006. data.value = data.value.substr(0, data.value.indexOf('/'));
  14007. } else {
  14008. data.direction = 'both';
  14009. }
  14010. data.uri = parts.shift();
  14011. data.params = parts;
  14012. return data;
  14013. },
  14014. find_line: function (haystack, needle, sessionpart) {
  14015. var lines = haystack.split('\r\n');
  14016. for (var i = 0; i < lines.length; i++) {
  14017. if (lines[i].substring(0, needle.length) == needle) {
  14018. return lines[i];
  14019. }
  14020. }
  14021. if (!sessionpart) {
  14022. return false;
  14023. }
  14024. // search session part
  14025. lines = sessionpart.split('\r\n');
  14026. for (var j = 0; j < lines.length; j++) {
  14027. if (lines[j].substring(0, needle.length) == needle) {
  14028. return lines[j];
  14029. }
  14030. }
  14031. return false;
  14032. },
  14033. find_lines: function (haystack, needle, sessionpart) {
  14034. var lines = haystack.split('\r\n'),
  14035. needles = [];
  14036. for (var i = 0; i < lines.length; i++) {
  14037. if (lines[i].substring(0, needle.length) == needle)
  14038. needles.push(lines[i]);
  14039. }
  14040. if (needles.length || !sessionpart) {
  14041. return needles;
  14042. }
  14043. // search session part
  14044. lines = sessionpart.split('\r\n');
  14045. for (var j = 0; j < lines.length; j++) {
  14046. if (lines[j].substring(0, needle.length) == needle) {
  14047. needles.push(lines[j]);
  14048. }
  14049. }
  14050. return needles;
  14051. },
  14052. candidateToJingle: function (line) {
  14053. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  14054. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  14055. if (line.indexOf('candidate:') === 0) {
  14056. line = 'a=' + line;
  14057. } else if (line.substring(0, 12) != 'a=candidate:') {
  14058. console.log('parseCandidate called with a line that is not a candidate line');
  14059. console.log(line);
  14060. return null;
  14061. }
  14062. if (line.substring(line.length - 2) == '\r\n') // chomp it
  14063. line = line.substring(0, line.length - 2);
  14064. var candidate = {},
  14065. elems = line.split(' '),
  14066. i;
  14067. if (elems[6] != 'typ') {
  14068. console.log('did not find typ in the right place');
  14069. console.log(line);
  14070. return null;
  14071. }
  14072. candidate.foundation = elems[0].substring(12);
  14073. candidate.component = elems[1];
  14074. candidate.protocol = elems[2].toLowerCase();
  14075. candidate.priority = elems[3];
  14076. candidate.ip = elems[4];
  14077. candidate.port = elems[5];
  14078. // elems[6] => "typ"
  14079. candidate.type = elems[7];
  14080. candidate.generation = '0'; // default, may be overwritten below
  14081. for (i = 8; i < elems.length; i += 2) {
  14082. switch (elems[i]) {
  14083. case 'raddr':
  14084. candidate['rel-addr'] = elems[i + 1];
  14085. break;
  14086. case 'rport':
  14087. candidate['rel-port'] = elems[i + 1];
  14088. break;
  14089. case 'generation':
  14090. candidate.generation = elems[i + 1];
  14091. break;
  14092. case 'tcptype':
  14093. candidate.tcptype = elems[i + 1];
  14094. break;
  14095. default: // TODO
  14096. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  14097. }
  14098. }
  14099. candidate.network = '1';
  14100. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  14101. return candidate;
  14102. },
  14103. candidateFromJingle: function (cand) {
  14104. var line = 'a=candidate:';
  14105. line += cand.getAttribute('foundation');
  14106. line += ' ';
  14107. line += cand.getAttribute('component');
  14108. line += ' ';
  14109. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  14110. line += ' ';
  14111. line += cand.getAttribute('priority');
  14112. line += ' ';
  14113. line += cand.getAttribute('ip');
  14114. line += ' ';
  14115. line += cand.getAttribute('port');
  14116. line += ' ';
  14117. line += 'typ';
  14118. line += ' ' + cand.getAttribute('type');
  14119. line += ' ';
  14120. switch (cand.getAttribute('type')) {
  14121. case 'srflx':
  14122. case 'prflx':
  14123. case 'relay':
  14124. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  14125. line += 'raddr';
  14126. line += ' ';
  14127. line += cand.getAttribute('rel-addr');
  14128. line += ' ';
  14129. line += 'rport';
  14130. line += ' ';
  14131. line += cand.getAttribute('rel-port');
  14132. line += ' ';
  14133. }
  14134. break;
  14135. }
  14136. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  14137. line += 'tcptype';
  14138. line += ' ';
  14139. line += cand.getAttribute('tcptype');
  14140. line += ' ';
  14141. }
  14142. line += 'generation';
  14143. line += ' ';
  14144. line += cand.getAttribute('generation') || '0';
  14145. return line + '\r\n';
  14146. }
  14147. };
  14148. module.exports = SDPUtil;
  14149. },{}],59:[function(require,module,exports){
  14150. var RTC = require('../RTC/RTC');
  14151. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  14152. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14153. var VideoSSRCHack = require("./VideoSSRCHack");
  14154. function TraceablePeerConnection(ice_config, constraints, session) {
  14155. var self = this;
  14156. var RTCPeerConnectionType = null;
  14157. if (RTCBrowserType.isFirefox()) {
  14158. RTCPeerConnectionType = mozRTCPeerConnection;
  14159. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  14160. RTCPeerConnectionType = RTCPeerConnection;
  14161. } else {
  14162. RTCPeerConnectionType = webkitRTCPeerConnection;
  14163. }
  14164. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  14165. this.updateLog = [];
  14166. this.stats = {};
  14167. this.statsinterval = null;
  14168. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  14169. var Interop = require('sdp-interop').Interop;
  14170. this.interop = new Interop();
  14171. var Simulcast = require('sdp-simulcast');
  14172. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  14173. // override as desired
  14174. this.trace = function (what, info) {
  14175. /*console.warn('WTRACE', what, info);
  14176. if (info && RTCBrowserType.isIExplorer()) {
  14177. if (info.length > 1024) {
  14178. console.warn('WTRACE', what, info.substr(1024));
  14179. }
  14180. if (info.length > 2048) {
  14181. console.warn('WTRACE', what, info.substr(2048));
  14182. }
  14183. }*/
  14184. self.updateLog.push({
  14185. time: new Date(),
  14186. type: what,
  14187. value: info || ""
  14188. });
  14189. };
  14190. this.onicecandidate = null;
  14191. this.peerconnection.onicecandidate = function (event) {
  14192. // FIXME: this causes stack overflow with Temasys Plugin
  14193. if (!RTCBrowserType.isTemasysPluginUsed())
  14194. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  14195. if (self.onicecandidate !== null) {
  14196. self.onicecandidate(event);
  14197. }
  14198. };
  14199. this.onaddstream = null;
  14200. this.peerconnection.onaddstream = function (event) {
  14201. self.trace('onaddstream', event.stream.id);
  14202. if (self.onaddstream !== null) {
  14203. self.onaddstream(event);
  14204. }
  14205. };
  14206. this.onremovestream = null;
  14207. this.peerconnection.onremovestream = function (event) {
  14208. self.trace('onremovestream', event.stream.id);
  14209. if (self.onremovestream !== null) {
  14210. self.onremovestream(event);
  14211. }
  14212. };
  14213. this.onsignalingstatechange = null;
  14214. this.peerconnection.onsignalingstatechange = function (event) {
  14215. self.trace('onsignalingstatechange', self.signalingState);
  14216. if (self.onsignalingstatechange !== null) {
  14217. self.onsignalingstatechange(event);
  14218. }
  14219. };
  14220. this.oniceconnectionstatechange = null;
  14221. this.peerconnection.oniceconnectionstatechange = function (event) {
  14222. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  14223. if (self.oniceconnectionstatechange !== null) {
  14224. self.oniceconnectionstatechange(event);
  14225. }
  14226. };
  14227. this.onnegotiationneeded = null;
  14228. this.peerconnection.onnegotiationneeded = function (event) {
  14229. self.trace('onnegotiationneeded');
  14230. if (self.onnegotiationneeded !== null) {
  14231. self.onnegotiationneeded(event);
  14232. }
  14233. };
  14234. self.ondatachannel = null;
  14235. this.peerconnection.ondatachannel = function (event) {
  14236. self.trace('ondatachannel', event);
  14237. if (self.ondatachannel !== null) {
  14238. self.ondatachannel(event);
  14239. }
  14240. };
  14241. // XXX: do all non-firefox browsers which we support also support this?
  14242. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  14243. this.statsinterval = window.setInterval(function() {
  14244. self.peerconnection.getStats(function(stats) {
  14245. var results = stats.result();
  14246. var now = new Date();
  14247. for (var i = 0; i < results.length; ++i) {
  14248. results[i].names().forEach(function (name) {
  14249. var id = results[i].id + '-' + name;
  14250. if (!self.stats[id]) {
  14251. self.stats[id] = {
  14252. startTime: now,
  14253. endTime: now,
  14254. values: [],
  14255. times: []
  14256. };
  14257. }
  14258. self.stats[id].values.push(results[i].stat(name));
  14259. self.stats[id].times.push(now.getTime());
  14260. if (self.stats[id].values.length > self.maxstats) {
  14261. self.stats[id].values.shift();
  14262. self.stats[id].times.shift();
  14263. }
  14264. self.stats[id].endTime = now;
  14265. });
  14266. }
  14267. });
  14268. }, 1000);
  14269. }
  14270. }
  14271. /**
  14272. * Returns a string representation of a SessionDescription object.
  14273. */
  14274. var dumpSDP = function(description) {
  14275. if (typeof description === 'undefined' || description == null) {
  14276. return '';
  14277. }
  14278. return 'type: ' + description.type + '\r\n' + description.sdp;
  14279. };
  14280. /**
  14281. * Takes a SessionDescription object and returns a "normalized" version.
  14282. * Currently it only takes care of ordering the a=ssrc lines.
  14283. */
  14284. var normalizePlanB = function(desc) {
  14285. if (typeof desc !== 'object' || desc === null ||
  14286. typeof desc.sdp !== 'string') {
  14287. console.warn('An empty description was passed as an argument.');
  14288. return desc;
  14289. }
  14290. var transform = require('sdp-transform');
  14291. var session = transform.parse(desc.sdp);
  14292. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  14293. Array.isArray(session.media)) {
  14294. session.media.forEach(function (mLine) {
  14295. // Chrome appears to be picky about the order in which a=ssrc lines
  14296. // are listed in an m-line when rtx is enabled (and thus there are
  14297. // a=ssrc-group lines with FID semantics). Specifically if we have
  14298. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  14299. // the "a=ssrc:S1" lines, SRD fails.
  14300. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  14301. // first.
  14302. var firstSsrcs = [];
  14303. var newSsrcLines = [];
  14304. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  14305. mLine.ssrcGroups.forEach(function (group) {
  14306. if (typeof group.semantics !== 'undefined' &&
  14307. group.semantics === 'FID') {
  14308. if (typeof group.ssrcs !== 'undefined') {
  14309. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  14310. }
  14311. }
  14312. });
  14313. }
  14314. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  14315. for (var i = 0; i<mLine.ssrcs.length; i++){
  14316. if (typeof mLine.ssrcs[i] === 'object'
  14317. && typeof mLine.ssrcs[i].id !== 'undefined'
  14318. && $.inArray(mLine.ssrcs[i].id, firstSsrcs) == 0) {
  14319. newSsrcLines.push(mLine.ssrcs[i]);
  14320. delete mLine.ssrcs[i];
  14321. }
  14322. }
  14323. for (var i = 0; i<mLine.ssrcs.length; i++){
  14324. if (typeof mLine.ssrcs[i] !== 'undefined') {
  14325. newSsrcLines.push(mLine.ssrcs[i]);
  14326. }
  14327. }
  14328. mLine.ssrcs = newSsrcLines;
  14329. }
  14330. });
  14331. }
  14332. var resStr = transform.write(session);
  14333. return new RTCSessionDescription({
  14334. type: desc.type,
  14335. sdp: resStr
  14336. });
  14337. };
  14338. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  14339. TraceablePeerConnection.prototype.__defineGetter__(
  14340. 'signalingState',
  14341. function() { return this.peerconnection.signalingState; });
  14342. TraceablePeerConnection.prototype.__defineGetter__(
  14343. 'iceConnectionState',
  14344. function() { return this.peerconnection.iceConnectionState; });
  14345. TraceablePeerConnection.prototype.__defineGetter__(
  14346. 'localDescription',
  14347. function() {
  14348. var desc = this.peerconnection.localDescription;
  14349. desc = VideoSSRCHack.mungeLocalVideoSSRC(desc);
  14350. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  14351. // if we're running on FF, transform to Plan B first.
  14352. if (RTCBrowserType.usesUnifiedPlan()) {
  14353. desc = this.interop.toPlanB(desc);
  14354. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  14355. }
  14356. return desc;
  14357. });
  14358. TraceablePeerConnection.prototype.__defineGetter__(
  14359. 'remoteDescription',
  14360. function() {
  14361. var desc = this.peerconnection.remoteDescription;
  14362. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  14363. // if we're running on FF, transform to Plan B first.
  14364. if (RTCBrowserType.usesUnifiedPlan()) {
  14365. desc = this.interop.toPlanB(desc);
  14366. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  14367. }
  14368. return desc;
  14369. });
  14370. }
  14371. TraceablePeerConnection.prototype.addStream = function (stream) {
  14372. this.trace('addStream', stream.id);
  14373. try
  14374. {
  14375. this.peerconnection.addStream(stream);
  14376. }
  14377. catch (e)
  14378. {
  14379. console.error(e);
  14380. }
  14381. };
  14382. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  14383. this.trace('removeStream', stream.id);
  14384. if(stopStreams) {
  14385. stream.getAudioTracks().forEach(function (track) {
  14386. // stop() not supported with IE
  14387. if (track.stop) {
  14388. track.stop();
  14389. }
  14390. });
  14391. stream.getVideoTracks().forEach(function (track) {
  14392. // stop() not supported with IE
  14393. if (track.stop) {
  14394. track.stop();
  14395. }
  14396. });
  14397. if (stream.stop) {
  14398. stream.stop();
  14399. }
  14400. }
  14401. try {
  14402. // FF doesn't support this yet.
  14403. if (this.peerconnection.removeStream)
  14404. this.peerconnection.removeStream(stream);
  14405. } catch (e) {
  14406. console.error(e);
  14407. }
  14408. };
  14409. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  14410. this.trace('createDataChannel', label, opts);
  14411. return this.peerconnection.createDataChannel(label, opts);
  14412. };
  14413. TraceablePeerConnection.prototype.setLocalDescription
  14414. = function (description, successCallback, failureCallback) {
  14415. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  14416. // if we're running on FF, transform to Plan A first.
  14417. if (RTCBrowserType.usesUnifiedPlan()) {
  14418. description = this.interop.toUnifiedPlan(description);
  14419. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  14420. }
  14421. var self = this;
  14422. this.peerconnection.setLocalDescription(description,
  14423. function () {
  14424. self.trace('setLocalDescriptionOnSuccess');
  14425. successCallback();
  14426. },
  14427. function (err) {
  14428. self.trace('setLocalDescriptionOnFailure', err);
  14429. failureCallback(err);
  14430. }
  14431. );
  14432. /*
  14433. if (this.statsinterval === null && this.maxstats > 0) {
  14434. // start gathering stats
  14435. }
  14436. */
  14437. };
  14438. TraceablePeerConnection.prototype.setRemoteDescription
  14439. = function (description, successCallback, failureCallback) {
  14440. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  14441. // TODO the focus should squeze or explode the remote simulcast
  14442. description = this.simulcast.mungeRemoteDescription(description);
  14443. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  14444. // if we're running on FF, transform to Plan A first.
  14445. if (RTCBrowserType.usesUnifiedPlan()) {
  14446. description = this.interop.toUnifiedPlan(description);
  14447. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  14448. }
  14449. if (RTCBrowserType.usesPlanB()) {
  14450. description = normalizePlanB(description);
  14451. }
  14452. var self = this;
  14453. this.peerconnection.setRemoteDescription(description,
  14454. function () {
  14455. self.trace('setRemoteDescriptionOnSuccess');
  14456. successCallback();
  14457. },
  14458. function (err) {
  14459. self.trace('setRemoteDescriptionOnFailure', err);
  14460. failureCallback(err);
  14461. }
  14462. );
  14463. /*
  14464. if (this.statsinterval === null && this.maxstats > 0) {
  14465. // start gathering stats
  14466. }
  14467. */
  14468. };
  14469. TraceablePeerConnection.prototype.close = function () {
  14470. this.trace('stop');
  14471. if (this.statsinterval !== null) {
  14472. window.clearInterval(this.statsinterval);
  14473. this.statsinterval = null;
  14474. }
  14475. this.peerconnection.close();
  14476. };
  14477. TraceablePeerConnection.prototype.createOffer
  14478. = function (successCallback, failureCallback, constraints) {
  14479. var self = this;
  14480. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  14481. this.peerconnection.createOffer(
  14482. function (offer) {
  14483. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  14484. // NOTE this is not tested because in meet the focus generates the
  14485. // offer.
  14486. // if we're running on FF, transform to Plan B first.
  14487. if (RTCBrowserType.usesUnifiedPlan()) {
  14488. offer = self.interop.toPlanB(offer);
  14489. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  14490. }
  14491. offer = VideoSSRCHack.mungeLocalVideoSSRC(offer);
  14492. if (config.enableSimulcast && self.simulcast.isSupported()) {
  14493. offer = self.simulcast.mungeLocalDescription(offer);
  14494. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  14495. }
  14496. successCallback(offer);
  14497. },
  14498. function(err) {
  14499. self.trace('createOfferOnFailure', err);
  14500. failureCallback(err);
  14501. },
  14502. constraints
  14503. );
  14504. };
  14505. TraceablePeerConnection.prototype.createAnswer
  14506. = function (successCallback, failureCallback, constraints) {
  14507. var self = this;
  14508. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  14509. this.peerconnection.createAnswer(
  14510. function (answer) {
  14511. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  14512. // if we're running on FF, transform to Plan A first.
  14513. if (RTCBrowserType.usesUnifiedPlan()) {
  14514. answer = self.interop.toPlanB(answer);
  14515. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  14516. }
  14517. // munge local video SSRC
  14518. answer = VideoSSRCHack.mungeLocalVideoSSRC(answer);
  14519. if (config.enableSimulcast && self.simulcast.isSupported()) {
  14520. answer = self.simulcast.mungeLocalDescription(answer);
  14521. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  14522. }
  14523. successCallback(answer);
  14524. },
  14525. function(err) {
  14526. self.trace('createAnswerOnFailure', err);
  14527. failureCallback(err);
  14528. },
  14529. constraints
  14530. );
  14531. };
  14532. TraceablePeerConnection.prototype.addIceCandidate
  14533. = function (candidate, successCallback, failureCallback) {
  14534. //var self = this;
  14535. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  14536. this.peerconnection.addIceCandidate(candidate);
  14537. /* maybe later
  14538. this.peerconnection.addIceCandidate(candidate,
  14539. function () {
  14540. self.trace('addIceCandidateOnSuccess');
  14541. successCallback();
  14542. },
  14543. function (err) {
  14544. self.trace('addIceCandidateOnFailure', err);
  14545. failureCallback(err);
  14546. }
  14547. );
  14548. */
  14549. };
  14550. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  14551. // TODO: Is this the correct way to handle Opera, Temasys?
  14552. if (RTCBrowserType.isFirefox()) {
  14553. // ignore for now...
  14554. if(!errback)
  14555. errback = function () {};
  14556. this.peerconnection.getStats(null, callback, errback);
  14557. } else {
  14558. this.peerconnection.getStats(callback);
  14559. }
  14560. };
  14561. module.exports = TraceablePeerConnection;
  14562. },{"../../service/xmpp/XMPPEvents":119,"../RTC/RTC":9,"../RTC/RTCBrowserType.js":10,"./VideoSSRCHack":60,"sdp-interop":92,"sdp-simulcast":99,"sdp-transform":106}],60:[function(require,module,exports){
  14563. /* global $ */
  14564. /*
  14565. The purpose of this hack is to re-use SSRC of first video stream ever created
  14566. for any video streams created later on. In order to do that this hack:
  14567. 1. Stores the SSRC of the first video stream created by
  14568. a) scanning Jingle session-accept/session-invite for existing video SSRC
  14569. b) watching for 'source-add' for new video stream if it has not been
  14570. created in step a)
  14571. 2. Exposes method 'mungeLocalVideoSSRC' which replaces any new video SSRC with
  14572. the stored one. It is called by 'TracablePeerConnection' before local SDP is
  14573. returned to the other parts of the application.
  14574. 3. Scans 'source-remove'/'source-add' notifications for stored video SSRC and
  14575. blocks those notifications. This makes Jicofo and all participants think
  14576. that it exists all the time even if the video stream has been removed or
  14577. replaced locally. Thanks to that there is no additional signaling activity
  14578. on video mute or when switching to the desktop stream.
  14579. */
  14580. var SDP = require('./SDP');
  14581. /**
  14582. * Stored SSRC of local video stream.
  14583. */
  14584. var localVideoSSRC;
  14585. /**
  14586. * Method removes <source> element which describes <tt>localVideoSSRC</tt>
  14587. * from given Jingle IQ.
  14588. * @param modifyIq 'source-add' or 'source-remove' Jingle IQ.
  14589. * @param actionName display name of the action which will be printed in log
  14590. * messages.
  14591. * @returns {*} modified Jingle IQ, so that it does not contain <source> element
  14592. * corresponding to <tt>localVideoSSRC</tt> or <tt>null</tt> if no
  14593. * other SSRCs left to be signaled after removing it.
  14594. */
  14595. var filterOutSource = function (modifyIq, actionName) {
  14596. if (!localVideoSSRC)
  14597. return modifyIq;
  14598. var modifyIqTree = $(modifyIq.tree());
  14599. var videoSSRC = modifyIqTree.find(
  14600. '>jingle>content[name="video"]' +
  14601. '>description>source[ssrc="' + localVideoSSRC + '"]');
  14602. if (!videoSSRC.length) {
  14603. return modifyIqTree;
  14604. }
  14605. console.info(
  14606. 'Blocking ' + actionName + ' for local video SSRC: ' + localVideoSSRC);
  14607. videoSSRC.remove();
  14608. // Check if any sources still left to be added/removed
  14609. if (modifyIqTree.find('>jingle>content>description>source').length) {
  14610. return modifyIqTree;
  14611. } else {
  14612. return null;
  14613. }
  14614. };
  14615. /**
  14616. * Scans given Jingle IQ for video SSRC and stores it.
  14617. * @param jingleIq the Jingle IQ to be scanned for video SSRC.
  14618. */
  14619. var storeLocalVideoSSRC = function (jingleIq) {
  14620. var videoSSRCs =
  14621. $(jingleIq.tree())
  14622. .find('>jingle>content[name="video"]>description>source');
  14623. console.info('Video desc: ', videoSSRCs);
  14624. if (!videoSSRCs.length)
  14625. return;
  14626. var ssrc = videoSSRCs.attr('ssrc');
  14627. if (ssrc) {
  14628. localVideoSSRC = ssrc;
  14629. console.info(
  14630. 'Stored local video SSRC for future re-use: ' + localVideoSSRC);
  14631. } else {
  14632. console.error('No "ssrc" attribute present in <source> element');
  14633. }
  14634. };
  14635. var LocalVideoSSRCHack = {
  14636. /**
  14637. * Method must be called before 'session-initiate' or 'session-invite' is
  14638. * sent. Scans the IQ for local video SSRC and stores it if detected.
  14639. *
  14640. * @param sessionInit our 'session-initiate' or 'session-accept' Jingle IQ
  14641. * which will be scanned for local video SSRC.
  14642. */
  14643. processSessionInit: function (sessionInit) {
  14644. if (localVideoSSRC) {
  14645. console.error("Local SSRC stored already: " + localVideoSSRC);
  14646. return;
  14647. }
  14648. storeLocalVideoSSRC(sessionInit);
  14649. },
  14650. /**
  14651. * If we have local video SSRC stored searched given
  14652. * <tt>localDescription</tt> for video SSRC and makes sure it is replaced
  14653. * with the stored one.
  14654. * @param localDescription local description object that will have local
  14655. * video SSRC replaced with the stored one
  14656. * @returns modified <tt>localDescription</tt> object.
  14657. */
  14658. mungeLocalVideoSSRC: function (localDescription) {
  14659. // IF we have local video SSRC stored make sure it is replaced
  14660. // with old SSRC
  14661. if (localVideoSSRC) {
  14662. var newSdp = new SDP(localDescription.sdp);
  14663. if (newSdp.media[1].indexOf("a=ssrc:") !== -1 &&
  14664. !newSdp.containsSSRC(localVideoSSRC)) {
  14665. // Get new video SSRC
  14666. var map = newSdp.getMediaSsrcMap();
  14667. var videoPart = map[1];
  14668. var videoSSRCs = videoPart.ssrcs;
  14669. var newSSRC = Object.keys(videoSSRCs)[0];
  14670. console.info(
  14671. "Replacing new video SSRC: " + newSSRC +
  14672. " with " + localVideoSSRC);
  14673. localDescription.sdp =
  14674. newSdp.raw.replace(
  14675. new RegExp('a=ssrc:' + newSSRC, 'g'),
  14676. 'a=ssrc:' + localVideoSSRC);
  14677. }
  14678. }
  14679. return localDescription;
  14680. },
  14681. /**
  14682. * Method must be called before 'source-add' notification is sent. In case
  14683. * we have local video SSRC advertised already it will be removed from the
  14684. * notification. If no other SSRCs are described by given IQ null will be
  14685. * returned which means that there is no point in sending the notification.
  14686. * @param sourceAdd 'source-add' Jingle IQ to be processed
  14687. * @returns modified 'source-add' IQ which can be sent to the focus or
  14688. * <tt>null</tt> if no notification shall be sent. It is no longer
  14689. * a Strophe IQ Builder instance, but DOM element tree.
  14690. */
  14691. processSourceAdd: function (sourceAdd) {
  14692. if (!localVideoSSRC) {
  14693. // Store local SSRC if available
  14694. storeLocalVideoSSRC(sourceAdd);
  14695. return sourceAdd;
  14696. } else {
  14697. return filterOutSource(sourceAdd, 'source-add');
  14698. }
  14699. },
  14700. /**
  14701. * Method must be called before 'source-remove' notification is sent.
  14702. * Removes local video SSRC from the notification. If there are no other
  14703. * SSRCs described in the given IQ <tt>null</tt> will be returned which
  14704. * means that there is no point in sending the notification.
  14705. * @param sourceRemove 'source-remove' Jingle IQ to be processed
  14706. * @returns modified 'source-remove' IQ which can be sent to the focus or
  14707. * <tt>null</tt> if no notification shall be sent. It is no longer
  14708. * a Strophe IQ Builder instance, but DOM element tree.
  14709. */
  14710. processSourceRemove: function (sourceRemove) {
  14711. return filterOutSource(sourceRemove, 'source-remove');
  14712. }
  14713. };
  14714. module.exports = LocalVideoSSRCHack;
  14715. },{"./SDP":56}],61:[function(require,module,exports){
  14716. /* global $, $iq, APP, config, messageHandler,
  14717. roomName, sessionTerminated, Strophe, Util */
  14718. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14719. var Settings = require("../settings/Settings");
  14720. var AuthenticationEvents
  14721. = require("../../service/authentication/AuthenticationEvents");
  14722. /**
  14723. * Contains logic responsible for enabling/disabling functionality available
  14724. * only to moderator users.
  14725. */
  14726. var connection = null;
  14727. var focusUserJid;
  14728. function createExpBackoffTimer(step) {
  14729. var count = 1;
  14730. return function (reset) {
  14731. // Reset call
  14732. if (reset) {
  14733. count = 1;
  14734. return;
  14735. }
  14736. // Calculate next timeout
  14737. var timeout = Math.pow(2, count - 1);
  14738. count += 1;
  14739. return timeout * step;
  14740. };
  14741. }
  14742. var getNextTimeout = createExpBackoffTimer(1000);
  14743. var getNextErrorTimeout = createExpBackoffTimer(1000);
  14744. // External authentication stuff
  14745. var externalAuthEnabled = false;
  14746. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  14747. // it will be enabled automatically if focus detects the component through
  14748. // service discovery.
  14749. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  14750. var eventEmitter = null;
  14751. var Moderator = {
  14752. isModerator: function () {
  14753. return connection && connection.emuc.isModerator();
  14754. },
  14755. isPeerModerator: function (peerJid) {
  14756. return connection &&
  14757. connection.emuc.getMemberRole(peerJid) === 'moderator';
  14758. },
  14759. isExternalAuthEnabled: function () {
  14760. return externalAuthEnabled;
  14761. },
  14762. isSipGatewayEnabled: function () {
  14763. return sipGatewayEnabled;
  14764. },
  14765. setConnection: function (con) {
  14766. connection = con;
  14767. },
  14768. init: function (xmpp, emitter) {
  14769. this.xmppService = xmpp;
  14770. eventEmitter = emitter;
  14771. // Message listener that talks to POPUP window
  14772. function listener(event) {
  14773. if (event.data && event.data.sessionId) {
  14774. if (event.origin !== window.location.origin) {
  14775. console.warn("Ignoring sessionId from different origin: " +
  14776. event.origin);
  14777. return;
  14778. }
  14779. localStorage.setItem('sessionId', event.data.sessionId);
  14780. // After popup is closed we will authenticate
  14781. }
  14782. }
  14783. // Register
  14784. if (window.addEventListener) {
  14785. window.addEventListener("message", listener, false);
  14786. } else {
  14787. window.attachEvent("onmessage", listener);
  14788. }
  14789. },
  14790. onMucMemberLeft: function (jid) {
  14791. console.info("Someone left is it focus ? " + jid);
  14792. var resource = Strophe.getResourceFromJid(jid);
  14793. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  14794. console.info(
  14795. "Focus has left the room - leaving conference");
  14796. //hangUp();
  14797. // We'd rather reload to have everything re-initialized
  14798. // FIXME: show some message before reload
  14799. location.reload();
  14800. }
  14801. },
  14802. setFocusUserJid: function (focusJid) {
  14803. if (!focusUserJid) {
  14804. focusUserJid = focusJid;
  14805. console.info("Focus jid set to: " + focusUserJid);
  14806. }
  14807. },
  14808. getFocusUserJid: function () {
  14809. return focusUserJid;
  14810. },
  14811. getFocusComponent: function () {
  14812. // Get focus component address
  14813. var focusComponent = config.hosts.focus;
  14814. // If not specified use default: 'focus.domain'
  14815. if (!focusComponent) {
  14816. focusComponent = 'focus.' + config.hosts.domain;
  14817. }
  14818. return focusComponent;
  14819. },
  14820. createConferenceIq: function (roomName) {
  14821. // Generate create conference IQ
  14822. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  14823. // Session Id used for authentication
  14824. var sessionId = localStorage.getItem('sessionId');
  14825. var machineUID = Settings.getSettings().uid;
  14826. console.info(
  14827. "Session ID: " + sessionId + " machine UID: " + machineUID);
  14828. elem.c('conference', {
  14829. xmlns: 'http://jitsi.org/protocol/focus',
  14830. room: roomName,
  14831. 'machine-uid': machineUID
  14832. });
  14833. if (sessionId) {
  14834. elem.attrs({ 'session-id': sessionId});
  14835. }
  14836. if (config.hosts.bridge !== undefined) {
  14837. elem.c(
  14838. 'property',
  14839. { name: 'bridge', value: config.hosts.bridge})
  14840. .up();
  14841. }
  14842. // Tell the focus we have Jigasi configured
  14843. if (config.hosts.call_control !== undefined) {
  14844. elem.c(
  14845. 'property',
  14846. { name: 'call_control', value: config.hosts.call_control})
  14847. .up();
  14848. }
  14849. if (config.channelLastN !== undefined) {
  14850. elem.c(
  14851. 'property',
  14852. { name: 'channelLastN', value: config.channelLastN})
  14853. .up();
  14854. }
  14855. if (config.adaptiveLastN !== undefined) {
  14856. elem.c(
  14857. 'property',
  14858. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  14859. .up();
  14860. }
  14861. if (config.adaptiveSimulcast !== undefined) {
  14862. elem.c(
  14863. 'property',
  14864. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  14865. .up();
  14866. }
  14867. if (config.openSctp !== undefined) {
  14868. elem.c(
  14869. 'property',
  14870. { name: 'openSctp', value: config.openSctp})
  14871. .up();
  14872. }
  14873. if(config.startAudioMuted !== undefined)
  14874. {
  14875. elem.c(
  14876. 'property',
  14877. { name: 'startAudioMuted', value: config.startAudioMuted})
  14878. .up();
  14879. }
  14880. if(config.startVideoMuted !== undefined)
  14881. {
  14882. elem.c(
  14883. 'property',
  14884. { name: 'startVideoMuted', value: config.startVideoMuted})
  14885. .up();
  14886. }
  14887. elem.c(
  14888. 'property',
  14889. { name: 'simulcastMode', value: 'rewriting'})
  14890. .up();
  14891. elem.up();
  14892. return elem;
  14893. },
  14894. parseSessionId: function (resultIq) {
  14895. var sessionId = $(resultIq).find('conference').attr('session-id');
  14896. if (sessionId) {
  14897. console.info('Received sessionId: ' + sessionId);
  14898. localStorage.setItem('sessionId', sessionId);
  14899. }
  14900. },
  14901. parseConfigOptions: function (resultIq) {
  14902. Moderator.setFocusUserJid(
  14903. $(resultIq).find('conference').attr('focusjid'));
  14904. var authenticationEnabled
  14905. = $(resultIq).find(
  14906. '>conference>property' +
  14907. '[name=\'authentication\'][value=\'true\']').length > 0;
  14908. console.info("Authentication enabled: " + authenticationEnabled);
  14909. externalAuthEnabled = $(resultIq).find(
  14910. '>conference>property' +
  14911. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  14912. console.info('External authentication enabled: ' + externalAuthEnabled);
  14913. if (!externalAuthEnabled) {
  14914. // We expect to receive sessionId in 'internal' authentication mode
  14915. Moderator.parseSessionId(resultIq);
  14916. }
  14917. var authIdentity = $(resultIq).find('>conference').attr('identity');
  14918. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  14919. authenticationEnabled, authIdentity);
  14920. // Check if focus has auto-detected Jigasi component(this will be also
  14921. // included if we have passed our host from the config)
  14922. if ($(resultIq).find(
  14923. '>conference>property' +
  14924. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  14925. sipGatewayEnabled = true;
  14926. }
  14927. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  14928. },
  14929. // FIXME: we need to show the fact that we're waiting for the focus
  14930. // to the user(or that focus is not available)
  14931. allocateConferenceFocus: function (roomName, callback) {
  14932. // Try to use focus user JID from the config
  14933. Moderator.setFocusUserJid(config.focusUserJid);
  14934. // Send create conference IQ
  14935. var iq = Moderator.createConferenceIq(roomName);
  14936. var self = this;
  14937. connection.sendIQ(
  14938. iq,
  14939. function (result) {
  14940. // Setup config options
  14941. Moderator.parseConfigOptions(result);
  14942. if ('true' === $(result).find('conference').attr('ready')) {
  14943. // Reset both timers
  14944. getNextTimeout(true);
  14945. getNextErrorTimeout(true);
  14946. // Exec callback
  14947. callback();
  14948. } else {
  14949. var waitMs = getNextTimeout();
  14950. console.info("Waiting for the focus... " + waitMs);
  14951. // Reset error timeout
  14952. getNextErrorTimeout(true);
  14953. window.setTimeout(
  14954. function () {
  14955. Moderator.allocateConferenceFocus(
  14956. roomName, callback);
  14957. }, waitMs);
  14958. }
  14959. },
  14960. function (error) {
  14961. // Invalid session ? remove and try again
  14962. // without session ID to get a new one
  14963. var invalidSession
  14964. = $(error).find('>error>session-invalid').length;
  14965. if (invalidSession) {
  14966. console.info("Session expired! - removing");
  14967. localStorage.removeItem("sessionId");
  14968. }
  14969. if ($(error).find('>error>graceful-shutdown').length) {
  14970. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  14971. return;
  14972. }
  14973. // Check for error returned by the reservation system
  14974. var reservationErr = $(error).find('>error>reservation-error');
  14975. if (reservationErr.length) {
  14976. // Trigger error event
  14977. var errorCode = reservationErr.attr('error-code');
  14978. var errorMsg;
  14979. if ($(error).find('>error>text')) {
  14980. errorMsg = $(error).find('>error>text').text();
  14981. }
  14982. eventEmitter.emit(
  14983. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  14984. return;
  14985. }
  14986. // Not authorized to create new room
  14987. if ($(error).find('>error>not-authorized').length) {
  14988. console.warn("Unauthorized to start the conference", error);
  14989. var toDomain
  14990. = Strophe.getDomainFromJid(error.getAttribute('to'));
  14991. if (toDomain !== config.hosts.anonymousdomain) {
  14992. // FIXME: "is external" should come either from
  14993. // the focus or config.js
  14994. externalAuthEnabled = true;
  14995. }
  14996. eventEmitter.emit(
  14997. XMPPEvents.AUTHENTICATION_REQUIRED,
  14998. function () {
  14999. Moderator.allocateConferenceFocus(
  15000. roomName, callback);
  15001. });
  15002. return;
  15003. }
  15004. var waitMs = getNextErrorTimeout();
  15005. console.error("Focus error, retry after " + waitMs, error);
  15006. // Show message
  15007. var focusComponent = Moderator.getFocusComponent();
  15008. var retrySec = waitMs / 1000;
  15009. // FIXME: message is duplicated ?
  15010. // Do not show in case of session invalid
  15011. // which means just a retry
  15012. if (!invalidSession) {
  15013. eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  15014. focusComponent, retrySec);
  15015. }
  15016. // Reset response timeout
  15017. getNextTimeout(true);
  15018. window.setTimeout(
  15019. function () {
  15020. Moderator.allocateConferenceFocus(roomName, callback);
  15021. }, waitMs);
  15022. }
  15023. );
  15024. },
  15025. getLoginUrl: function (roomName, urlCallback) {
  15026. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  15027. iq.c('login-url', {
  15028. xmlns: 'http://jitsi.org/protocol/focus',
  15029. room: roomName,
  15030. 'machine-uid': Settings.getSettings().uid
  15031. });
  15032. connection.sendIQ(
  15033. iq,
  15034. function (result) {
  15035. var url = $(result).find('login-url').attr('url');
  15036. url = url = decodeURIComponent(url);
  15037. if (url) {
  15038. console.info("Got auth url: " + url);
  15039. urlCallback(url);
  15040. } else {
  15041. console.error(
  15042. "Failed to get auth url from the focus", result);
  15043. }
  15044. },
  15045. function (error) {
  15046. console.error("Get auth url error", error);
  15047. }
  15048. );
  15049. },
  15050. getPopupLoginUrl: function (roomName, urlCallback) {
  15051. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  15052. iq.c('login-url', {
  15053. xmlns: 'http://jitsi.org/protocol/focus',
  15054. room: roomName,
  15055. 'machine-uid': Settings.getSettings().uid,
  15056. popup: true
  15057. });
  15058. connection.sendIQ(
  15059. iq,
  15060. function (result) {
  15061. var url = $(result).find('login-url').attr('url');
  15062. url = url = decodeURIComponent(url);
  15063. if (url) {
  15064. console.info("Got POPUP auth url: " + url);
  15065. urlCallback(url);
  15066. } else {
  15067. console.error(
  15068. "Failed to get POPUP auth url from the focus", result);
  15069. }
  15070. },
  15071. function (error) {
  15072. console.error('Get POPUP auth url error', error);
  15073. }
  15074. );
  15075. },
  15076. logout: function (callback) {
  15077. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  15078. var sessionId = localStorage.getItem('sessionId');
  15079. if (!sessionId) {
  15080. callback();
  15081. return;
  15082. }
  15083. iq.c('logout', {
  15084. xmlns: 'http://jitsi.org/protocol/focus',
  15085. 'session-id': sessionId
  15086. });
  15087. connection.sendIQ(
  15088. iq,
  15089. function (result) {
  15090. var logoutUrl = $(result).find('logout').attr('logout-url');
  15091. if (logoutUrl) {
  15092. logoutUrl = decodeURIComponent(logoutUrl);
  15093. }
  15094. console.info("Log out OK, url: " + logoutUrl, result);
  15095. localStorage.removeItem('sessionId');
  15096. callback(logoutUrl);
  15097. },
  15098. function (error) {
  15099. console.error("Logout error", error);
  15100. }
  15101. );
  15102. }
  15103. };
  15104. module.exports = Moderator;
  15105. },{"../../service/authentication/AuthenticationEvents":114,"../../service/xmpp/XMPPEvents":119,"../settings/Settings":49}],62:[function(require,module,exports){
  15106. /* global $, $iq, config, connection, focusMucJid, messageHandler,
  15107. Toolbar, Util */
  15108. var Moderator = require("./moderator");
  15109. var recordingToken = null;
  15110. var recordingEnabled;
  15111. /**
  15112. * Whether to use a jirecon component for recording, or use the videobridge
  15113. * through COLIBRI.
  15114. */
  15115. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  15116. /**
  15117. * The ID of the jirecon recording session. Jirecon generates it when we
  15118. * initially start recording, and it needs to be used in subsequent requests
  15119. * to jirecon.
  15120. */
  15121. var jireconRid = null;
  15122. function setRecordingToken(token) {
  15123. recordingToken = token;
  15124. }
  15125. function setRecordingJirecon(state, token, callback, connection) {
  15126. if (state == recordingEnabled){
  15127. return;
  15128. }
  15129. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  15130. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  15131. action: state ? 'start' : 'stop',
  15132. mucjid: connection.emuc.roomjid});
  15133. if (!state){
  15134. iq.attrs({rid: jireconRid});
  15135. }
  15136. console.log('Start recording');
  15137. connection.sendIQ(
  15138. iq,
  15139. function (result) {
  15140. // TODO wait for an IQ with the real status, since this is
  15141. // provisional?
  15142. jireconRid = $(result).find('recording').attr('rid');
  15143. console.log('Recording ' + (state ? 'started' : 'stopped') +
  15144. '(jirecon)' + result);
  15145. recordingEnabled = state;
  15146. if (!state){
  15147. jireconRid = null;
  15148. }
  15149. callback(state);
  15150. },
  15151. function (error) {
  15152. console.log('Failed to start recording, error: ', error);
  15153. callback(recordingEnabled);
  15154. });
  15155. }
  15156. // Sends a COLIBRI message which enables or disables (according to 'state')
  15157. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  15158. // with the new recording state, according to the IQ.
  15159. function setRecordingColibri(state, token, callback, connection) {
  15160. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  15161. elem.c('conference', {
  15162. xmlns: 'http://jitsi.org/protocol/colibri'
  15163. });
  15164. elem.c('recording', {state: state, token: token});
  15165. connection.sendIQ(elem,
  15166. function (result) {
  15167. console.log('Set recording "', state, '". Result:', result);
  15168. var recordingElem = $(result).find('>conference>recording');
  15169. var newState = ('true' === recordingElem.attr('state'));
  15170. recordingEnabled = newState;
  15171. callback(newState);
  15172. },
  15173. function (error) {
  15174. console.warn(error);
  15175. callback(recordingEnabled);
  15176. }
  15177. );
  15178. }
  15179. function setRecording(state, token, callback, connection) {
  15180. if (useJirecon){
  15181. setRecordingJirecon(state, token, callback, connection);
  15182. } else {
  15183. setRecordingColibri(state, token, callback, connection);
  15184. }
  15185. }
  15186. var Recording = {
  15187. toggleRecording: function (tokenEmptyCallback,
  15188. startingCallback, startedCallback, connection) {
  15189. if (!Moderator.isModerator()) {
  15190. console.log(
  15191. 'non-focus, or conference not yet organized:' +
  15192. ' not enabling recording');
  15193. return;
  15194. }
  15195. var self = this;
  15196. // Jirecon does not (currently) support a token.
  15197. if (!recordingToken && !useJirecon) {
  15198. tokenEmptyCallback(function (value) {
  15199. setRecordingToken(value);
  15200. self.toggleRecording(tokenEmptyCallback,
  15201. startingCallback, startedCallback, connection);
  15202. });
  15203. return;
  15204. }
  15205. var oldState = recordingEnabled;
  15206. startingCallback(!oldState);
  15207. setRecording(!oldState,
  15208. recordingToken,
  15209. function (state) {
  15210. console.log("New recording state: ", state);
  15211. if (state === oldState) {
  15212. // FIXME: new focus:
  15213. // this will not work when moderator changes
  15214. // during active session. Then it will assume that
  15215. // recording status has changed to true, but it might have
  15216. // been already true(and we only received actual status from
  15217. // the focus).
  15218. //
  15219. // SO we start with status null, so that it is initialized
  15220. // here and will fail only after second click, so if invalid
  15221. // token was used we have to press the button twice before
  15222. // current status will be fetched and token will be reset.
  15223. //
  15224. // Reliable way would be to return authentication error.
  15225. // Or status update when moderator connects.
  15226. // Or we have to stop recording session when current
  15227. // moderator leaves the room.
  15228. // Failed to change, reset the token because it might
  15229. // have been wrong
  15230. setRecordingToken(null);
  15231. }
  15232. startedCallback(state);
  15233. },
  15234. connection
  15235. );
  15236. }
  15237. };
  15238. module.exports = Recording;
  15239. },{"./moderator":61}],63:[function(require,module,exports){
  15240. /* jshint -W117 */
  15241. /* a simple MUC connection plugin
  15242. * can only handle a single MUC room
  15243. */
  15244. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15245. var Moderator = require("./moderator");
  15246. module.exports = function(XMPP, eventEmitter) {
  15247. Strophe.addConnectionPlugin('emuc', {
  15248. connection: null,
  15249. roomjid: null,
  15250. myroomjid: null,
  15251. members: {},
  15252. list_members: [], // so we can elect a new focus
  15253. presMap: {},
  15254. preziMap: {},
  15255. joined: false,
  15256. isOwner: false,
  15257. role: null,
  15258. focusMucJid: null,
  15259. bridgeIsDown: false,
  15260. init: function (conn) {
  15261. this.connection = conn;
  15262. },
  15263. initPresenceMap: function (myroomjid) {
  15264. this.presMap['to'] = myroomjid;
  15265. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  15266. if (APP.RTC.localAudio && APP.RTC.localAudio.isMuted()) {
  15267. this.addAudioInfoToPresence(true);
  15268. }
  15269. if (APP.RTC.localVideo && APP.RTC.localVideo.isMuted()) {
  15270. this.addVideoInfoToPresence(true);
  15271. }
  15272. },
  15273. doJoin: function (jid, password) {
  15274. this.myroomjid = jid;
  15275. console.info("Joined MUC as " + this.myroomjid);
  15276. this.initPresenceMap(this.myroomjid);
  15277. if (!this.roomjid) {
  15278. this.roomjid = Strophe.getBareJidFromJid(jid);
  15279. // add handlers (just once)
  15280. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  15281. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  15282. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  15283. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  15284. }
  15285. if (password !== undefined) {
  15286. this.presMap['password'] = password;
  15287. }
  15288. this.sendPresence();
  15289. },
  15290. doLeave: function () {
  15291. console.log("do leave", this.myroomjid);
  15292. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  15293. this.presMap.length = 0;
  15294. this.connection.send(pres);
  15295. },
  15296. createNonAnonymousRoom: function () {
  15297. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  15298. var getForm = $iq({type: 'get', to: this.roomjid})
  15299. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  15300. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15301. var self = this;
  15302. this.connection.sendIQ(getForm, function (form) {
  15303. if (!$(form).find(
  15304. '>query>x[xmlns="jabber:x:data"]' +
  15305. '>field[var="muc#roomconfig_whois"]').length) {
  15306. console.error('non-anonymous rooms not supported');
  15307. return;
  15308. }
  15309. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  15310. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  15311. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15312. formSubmit.c('field', {'var': 'FORM_TYPE'})
  15313. .c('value')
  15314. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  15315. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  15316. .c('value').t('anyone').up().up();
  15317. self.connection.sendIQ(formSubmit);
  15318. }, function (error) {
  15319. console.error("Error getting room configuration form");
  15320. });
  15321. },
  15322. onPresence: function (pres) {
  15323. var from = pres.getAttribute('from');
  15324. // What is this for? A workaround for something?
  15325. if (pres.getAttribute('type')) {
  15326. return true;
  15327. }
  15328. // Parse etherpad tag.
  15329. var etherpad = $(pres).find('>etherpad');
  15330. if (etherpad.length) {
  15331. if (config.etherpad_base) {
  15332. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  15333. }
  15334. }
  15335. // Parse prezi tag.
  15336. var presentation = $(pres).find('>prezi');
  15337. if (presentation.length) {
  15338. var url = presentation.attr('url');
  15339. var current = presentation.find('>current').text();
  15340. console.log('presentation info received from', from, url);
  15341. if (this.preziMap[from] == null) {
  15342. this.preziMap[from] = url;
  15343. $(document).trigger('presentationadded.muc', [from, url, current]);
  15344. }
  15345. else {
  15346. $(document).trigger('gotoslide.muc', [from, url, current]);
  15347. }
  15348. }
  15349. else if (this.preziMap[from] != null) {
  15350. var url = this.preziMap[from];
  15351. delete this.preziMap[from];
  15352. $(document).trigger('presentationremoved.muc', [from, url]);
  15353. }
  15354. // Parse audio info tag.
  15355. var audioMuted = $(pres).find('>audiomuted');
  15356. if (audioMuted.length) {
  15357. eventEmitter.emit(XMPPEvents.AUDIO_MUTED,
  15358. from, (audioMuted.text() === "true"));
  15359. }
  15360. // Parse video info tag.
  15361. var videoMuted = $(pres).find('>videomuted');
  15362. if (videoMuted.length) {
  15363. eventEmitter.emit(XMPPEvents.VIDEO_MUTED,
  15364. from, (videoMuted.text() === "true"));
  15365. }
  15366. var startMuted = $(pres).find('>startmuted');
  15367. if (startMuted.length)
  15368. {
  15369. eventEmitter.emit(XMPPEvents.START_MUTED_SETTING_CHANGED,
  15370. startMuted.attr("audio") === "true", startMuted.attr("video") === "true");
  15371. }
  15372. var devices = $(pres).find('>devices');
  15373. if(devices.length)
  15374. {
  15375. var audio = devices.find('>audio');
  15376. var video = devices.find('>video');
  15377. var devicesValues = {audio: false, video: false};
  15378. if(audio.length && audio.text() === "true")
  15379. {
  15380. devicesValues.audio = true;
  15381. }
  15382. if(video.length && video.text() === "true")
  15383. {
  15384. devicesValues.video = true;
  15385. }
  15386. eventEmitter.emit(XMPPEvents.DEVICE_AVAILABLE,
  15387. Strophe.getResourceFromJid(from), devicesValues);
  15388. }
  15389. var videoType = $(pres).find('>videoType');
  15390. if (videoType.length)
  15391. {
  15392. if (videoType.text().length)
  15393. {
  15394. eventEmitter.emit(XMPPEvents.VIDEO_TYPE,
  15395. Strophe.getResourceFromJid(from), videoType.text());
  15396. }
  15397. }
  15398. var stats = $(pres).find('>stats');
  15399. if (stats.length) {
  15400. var statsObj = {};
  15401. Strophe.forEachChild(stats[0], "stat", function (el) {
  15402. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  15403. });
  15404. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  15405. }
  15406. // Parse status.
  15407. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  15408. this.isOwner = true;
  15409. this.createNonAnonymousRoom();
  15410. }
  15411. // Parse roles.
  15412. var member = {};
  15413. member.show = $(pres).find('>show').text();
  15414. member.status = $(pres).find('>status').text();
  15415. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  15416. member.affiliation = tmp.attr('affiliation');
  15417. member.role = tmp.attr('role');
  15418. // Focus recognition
  15419. member.jid = tmp.attr('jid');
  15420. member.isFocus = false;
  15421. if (member.jid
  15422. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  15423. member.isFocus = true;
  15424. }
  15425. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  15426. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  15427. if (from == this.myroomjid) {
  15428. if (member.affiliation == 'owner') this.isOwner = true;
  15429. if (this.role !== member.role) {
  15430. this.role = member.role;
  15431. eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  15432. from, member, pres, Moderator.isModerator());
  15433. }
  15434. if (!this.joined) {
  15435. this.joined = true;
  15436. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  15437. this.list_members.push(from);
  15438. }
  15439. } else if (this.members[from] === undefined) {
  15440. // new participant
  15441. this.members[from] = member;
  15442. this.list_members.push(from);
  15443. console.log('entered', from, member);
  15444. if (member.isFocus) {
  15445. this.focusMucJid = from;
  15446. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  15447. }
  15448. else {
  15449. var id = $(pres).find('>userId').text();
  15450. var email = $(pres).find('>email');
  15451. if (email.length > 0) {
  15452. id = email.text();
  15453. }
  15454. eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, id, member.displayName);
  15455. }
  15456. } else {
  15457. // Presence update for existing participant
  15458. // Watch role change:
  15459. if (this.members[from].role != member.role) {
  15460. this.members[from].role = member.role;
  15461. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  15462. member.role, member.displayName);
  15463. }
  15464. }
  15465. // Always trigger presence to update bindings
  15466. this.parsePresence(from, member, pres);
  15467. // Trigger status message update
  15468. if (member.status) {
  15469. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  15470. }
  15471. return true;
  15472. },
  15473. onPresenceUnavailable: function (pres) {
  15474. var from = pres.getAttribute('from');
  15475. // room destroyed ?
  15476. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  15477. '>destroy').length) {
  15478. var reason;
  15479. var reasonSelect = $(pres).find(
  15480. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  15481. '>destroy>reason');
  15482. if (reasonSelect.length) {
  15483. reason = reasonSelect.text();
  15484. }
  15485. XMPP.disposeConference(false);
  15486. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  15487. return true;
  15488. }
  15489. // Status code 110 indicates that this notification is "self-presence".
  15490. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  15491. delete this.members[from];
  15492. this.list_members.splice(this.list_members.indexOf(from), 1);
  15493. this.onParticipantLeft(from);
  15494. }
  15495. // If the status code is 110 this means we're leaving and we would like
  15496. // to remove everyone else from our view, so we trigger the event.
  15497. else if (this.list_members.length > 1) {
  15498. for (var i = 0; i < this.list_members.length; i++) {
  15499. var member = this.list_members[i];
  15500. delete this.members[i];
  15501. this.list_members.splice(i, 1);
  15502. this.onParticipantLeft(member);
  15503. }
  15504. }
  15505. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  15506. $(document).trigger('kicked.muc', [from]);
  15507. if (this.myroomjid === from) {
  15508. XMPP.disposeConference(false);
  15509. eventEmitter.emit(XMPPEvents.KICKED);
  15510. }
  15511. }
  15512. return true;
  15513. },
  15514. onPresenceError: function (pres) {
  15515. var from = pres.getAttribute('from');
  15516. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  15517. console.log('on password required', from);
  15518. var self = this;
  15519. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  15520. self.doJoin(from, value);
  15521. });
  15522. } else if ($(pres).find(
  15523. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  15524. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  15525. if (toDomain === config.hosts.anonymousdomain) {
  15526. // enter the room by replying with 'not-authorized'. This would
  15527. // result in reconnection from authorized domain.
  15528. // We're either missing Jicofo/Prosody config for anonymous
  15529. // domains or something is wrong.
  15530. // XMPP.promptLogin();
  15531. eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  15532. } else {
  15533. console.warn('onPresError ', pres);
  15534. eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  15535. }
  15536. } else {
  15537. console.warn('onPresError ', pres);
  15538. eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  15539. }
  15540. return true;
  15541. },
  15542. sendMessage: function (body, nickname) {
  15543. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  15544. msg.c('body', body).up();
  15545. if (nickname) {
  15546. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  15547. }
  15548. this.connection.send(msg);
  15549. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  15550. },
  15551. setSubject: function (subject) {
  15552. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  15553. msg.c('subject', subject);
  15554. this.connection.send(msg);
  15555. console.log("topic changed to " + subject);
  15556. },
  15557. onMessage: function (msg) {
  15558. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  15559. var from = msg.getAttribute('from');
  15560. var nick =
  15561. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  15562. .text() ||
  15563. Strophe.getResourceFromJid(from);
  15564. var txt = $(msg).find('>body').text();
  15565. var type = msg.getAttribute("type");
  15566. if (type == "error") {
  15567. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  15568. $(msg).find('>text').text(), txt);
  15569. return true;
  15570. }
  15571. var subject = $(msg).find('>subject');
  15572. if (subject.length) {
  15573. var subjectText = subject.text();
  15574. if (subjectText || subjectText == "") {
  15575. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  15576. console.log("Subject is changed to " + subjectText);
  15577. }
  15578. }
  15579. // xep-0203 delay
  15580. var stamp = $(msg).find('>delay').attr('stamp');
  15581. if (!stamp) {
  15582. // or xep-0091 delay, UTC timestamp
  15583. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  15584. if (stamp) {
  15585. // the format is CCYYMMDDThh:mm:ss
  15586. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  15587. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  15588. }
  15589. }
  15590. if (txt) {
  15591. console.log('chat', nick, txt);
  15592. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  15593. from, nick, txt, this.myroomjid, stamp);
  15594. }
  15595. return true;
  15596. },
  15597. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  15598. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  15599. var ob = this;
  15600. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  15601. function (res) {
  15602. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  15603. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  15604. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15605. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  15606. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  15607. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  15608. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  15609. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  15610. ob.connection.sendIQ(formsubmit,
  15611. onSuccess,
  15612. onError);
  15613. } else {
  15614. onNotSupported();
  15615. }
  15616. }, onError);
  15617. },
  15618. kick: function (jid) {
  15619. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  15620. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  15621. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  15622. .c('reason').t('You have been kicked.').up().up().up();
  15623. this.connection.sendIQ(
  15624. kickIQ,
  15625. function (result) {
  15626. console.log('Kick participant with jid: ', jid, result);
  15627. },
  15628. function (error) {
  15629. console.log('Kick participant error: ', error);
  15630. });
  15631. },
  15632. sendPresence: function () {
  15633. if (!this.presMap['to']) {
  15634. // Too early to send presence - not initialized
  15635. return;
  15636. }
  15637. var pres = $pres({to: this.presMap['to'] });
  15638. pres.c('x', {xmlns: this.presMap['xns']});
  15639. if (this.presMap['password']) {
  15640. pres.c('password').t(this.presMap['password']).up();
  15641. }
  15642. pres.up();
  15643. // Send XEP-0115 'c' stanza that contains our capabilities info
  15644. if (this.connection.caps) {
  15645. this.connection.caps.node = config.clientNode;
  15646. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  15647. }
  15648. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  15649. .t(navigator.userAgent).up();
  15650. if (this.presMap['bridgeIsDown']) {
  15651. pres.c('bridgeIsDown').up();
  15652. }
  15653. if (this.presMap['email']) {
  15654. pres.c('email').t(this.presMap['email']).up();
  15655. }
  15656. if (this.presMap['userId']) {
  15657. pres.c('userId').t(this.presMap['userId']).up();
  15658. }
  15659. if (this.presMap['displayName']) {
  15660. // XEP-0172
  15661. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  15662. .t(this.presMap['displayName']).up();
  15663. }
  15664. if(this.presMap["devices"])
  15665. {
  15666. pres.c('devices').c('audio').t(this.presMap['devices'].audio).up()
  15667. .c('video').t(this.presMap['devices'].video).up().up();
  15668. }
  15669. if (this.presMap['audions']) {
  15670. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  15671. .t(this.presMap['audiomuted']).up();
  15672. }
  15673. if (this.presMap['videons']) {
  15674. pres.c('videomuted', {xmlns: this.presMap['videons']})
  15675. .t(this.presMap['videomuted']).up();
  15676. }
  15677. if (this.presMap['videoTypeNs']) {
  15678. pres.c('videoType', { xmlns: this.presMap['videoTypeNs'] })
  15679. .t(this.presMap['videoType']).up();
  15680. }
  15681. if (this.presMap['statsns']) {
  15682. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  15683. for (var stat in this.presMap["stats"])
  15684. if (this.presMap["stats"][stat] != null)
  15685. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  15686. pres.up();
  15687. }
  15688. if (this.presMap['prezins']) {
  15689. pres.c('prezi',
  15690. {xmlns: this.presMap['prezins'],
  15691. 'url': this.presMap['preziurl']})
  15692. .c('current').t(this.presMap['prezicurrent']).up().up();
  15693. }
  15694. if(this.presMap["startMuted"] !== undefined)
  15695. {
  15696. pres.c("startmuted", {audio: this.presMap["startMuted"].audio,
  15697. video: this.presMap["startMuted"].video,
  15698. xmlns: "http://jitsi.org/jitmeet/start-muted"});
  15699. delete this.presMap["startMuted"];
  15700. }
  15701. pres.up();
  15702. this.connection.send(pres);
  15703. },
  15704. addDisplayNameToPresence: function (displayName) {
  15705. this.presMap['displayName'] = displayName;
  15706. },
  15707. addDevicesToPresence: function (devices) {
  15708. this.presMap['devices'] = devices;
  15709. },
  15710. /**
  15711. * Adds the info about the type of our video stream.
  15712. * @param videoType 'camera' or 'screen'
  15713. */
  15714. addVideoTypeToPresence: function (videoType) {
  15715. this.presMap['videoTypeNs'] = 'http://jitsi.org/jitmeet/video';
  15716. this.presMap['videoType'] = videoType;
  15717. },
  15718. addPreziToPresence: function (url, currentSlide) {
  15719. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  15720. this.presMap['preziurl'] = url;
  15721. this.presMap['prezicurrent'] = currentSlide;
  15722. },
  15723. removePreziFromPresence: function () {
  15724. delete this.presMap['prezins'];
  15725. delete this.presMap['preziurl'];
  15726. delete this.presMap['prezicurrent'];
  15727. },
  15728. addCurrentSlideToPresence: function (currentSlide) {
  15729. this.presMap['prezicurrent'] = currentSlide;
  15730. },
  15731. getPrezi: function (roomjid) {
  15732. return this.preziMap[roomjid];
  15733. },
  15734. addAudioInfoToPresence: function (isMuted) {
  15735. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  15736. this.presMap['audiomuted'] = isMuted.toString();
  15737. },
  15738. addVideoInfoToPresence: function (isMuted) {
  15739. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  15740. this.presMap['videomuted'] = isMuted.toString();
  15741. },
  15742. addConnectionInfoToPresence: function (stats) {
  15743. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  15744. this.presMap['stats'] = stats;
  15745. },
  15746. findJidFromResource: function (resourceJid) {
  15747. if (resourceJid &&
  15748. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  15749. return this.myroomjid;
  15750. }
  15751. var peerJid = null;
  15752. Object.keys(this.members).some(function (jid) {
  15753. peerJid = jid;
  15754. return Strophe.getResourceFromJid(jid) === resourceJid;
  15755. });
  15756. return peerJid;
  15757. },
  15758. addBridgeIsDownToPresence: function () {
  15759. this.presMap['bridgeIsDown'] = true;
  15760. },
  15761. addEmailToPresence: function (email) {
  15762. this.presMap['email'] = email;
  15763. },
  15764. addUserIdToPresence: function (userId) {
  15765. this.presMap['userId'] = userId;
  15766. },
  15767. addStartMutedToPresence: function (audio, video) {
  15768. this.presMap["startMuted"] = {audio: audio, video: video};
  15769. },
  15770. isModerator: function () {
  15771. return this.role === 'moderator';
  15772. },
  15773. getMemberRole: function (peerJid) {
  15774. if (this.members[peerJid]) {
  15775. return this.members[peerJid].role;
  15776. }
  15777. return null;
  15778. },
  15779. onParticipantLeft: function (jid) {
  15780. eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  15781. this.connection.jingle.terminateByJid(jid);
  15782. if (this.getPrezi(jid)) {
  15783. $(document).trigger('presentationremoved.muc',
  15784. [jid, this.getPrezi(jid)]);
  15785. }
  15786. Moderator.onMucMemberLeft(jid);
  15787. },
  15788. parsePresence: function (from, member, pres) {
  15789. if($(pres).find(">bridgeIsDown").length > 0 && !this.bridgeIsDown) {
  15790. this.bridgeIsDown = true;
  15791. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  15792. }
  15793. if(member.isFocus)
  15794. return;
  15795. var displayName = !config.displayJids
  15796. ? member.displayName : Strophe.getResourceFromJid(from);
  15797. if (displayName && displayName.length > 0) {
  15798. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  15799. }
  15800. var id = $(pres).find('>userID').text();
  15801. var email = $(pres).find('>email');
  15802. if (email.length > 0) {
  15803. id = email.text();
  15804. }
  15805. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  15806. }
  15807. });
  15808. };
  15809. },{"../../service/xmpp/XMPPEvents":119,"./moderator":61}],64:[function(require,module,exports){
  15810. /* jshint -W117 */
  15811. var JingleSession = require("./JingleSession");
  15812. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15813. var RTCBrowserType = require("../RTC/RTCBrowserType");
  15814. module.exports = function(XMPP, eventEmitter) {
  15815. function CallIncomingJingle(sid, connection) {
  15816. var sess = connection.jingle.sessions[sid];
  15817. // TODO: do we check activecall == null?
  15818. connection.jingle.activecall = sess;
  15819. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  15820. // TODO: check affiliation and/or role
  15821. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  15822. sess.usedrip = true; // not-so-naive trickle ice
  15823. sess.sendAnswer();
  15824. sess.accept();
  15825. }
  15826. Strophe.addConnectionPlugin('jingle', {
  15827. connection: null,
  15828. sessions: {},
  15829. jid2session: {},
  15830. ice_config: {iceServers: []},
  15831. pc_constraints: {},
  15832. activecall: null,
  15833. media_constraints: {
  15834. mandatory: {
  15835. 'OfferToReceiveAudio': true,
  15836. 'OfferToReceiveVideo': true
  15837. }
  15838. // MozDontOfferDataChannel: true when this is firefox
  15839. },
  15840. init: function (conn) {
  15841. this.connection = conn;
  15842. if (this.connection.disco) {
  15843. // http://xmpp.org/extensions/xep-0167.html#support
  15844. // http://xmpp.org/extensions/xep-0176.html#support
  15845. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  15846. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  15847. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  15848. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  15849. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  15850. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  15851. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  15852. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  15853. || RTCBrowserType.isTemasysPluginUsed()) {
  15854. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  15855. }
  15856. // this is dealt with by SDP O/A so we don't need to announce this
  15857. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  15858. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  15859. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  15860. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  15861. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  15862. }
  15863. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  15864. },
  15865. onJingle: function (iq) {
  15866. var sid = $(iq).find('jingle').attr('sid');
  15867. var action = $(iq).find('jingle').attr('action');
  15868. var fromJid = iq.getAttribute('from');
  15869. // send ack first
  15870. var ack = $iq({type: 'result',
  15871. to: fromJid,
  15872. id: iq.getAttribute('id')
  15873. });
  15874. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  15875. var sess = this.sessions[sid];
  15876. if ('session-initiate' != action) {
  15877. if (sess === null) {
  15878. ack.type = 'error';
  15879. ack.c('error', {type: 'cancel'})
  15880. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  15881. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  15882. this.connection.send(ack);
  15883. return true;
  15884. }
  15885. // local jid is not checked
  15886. if (fromJid != sess.peerjid) {
  15887. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  15888. ack.type = 'error';
  15889. ack.c('error', {type: 'cancel'})
  15890. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  15891. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  15892. this.connection.send(ack);
  15893. return true;
  15894. }
  15895. } else if (sess !== undefined) {
  15896. // existing session with same session id
  15897. // this might be out-of-order if the sess.peerjid is the same as from
  15898. ack.type = 'error';
  15899. ack.c('error', {type: 'cancel'})
  15900. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  15901. console.warn('duplicate session id', sid);
  15902. this.connection.send(ack);
  15903. return true;
  15904. }
  15905. // FIXME: check for a defined action
  15906. this.connection.send(ack);
  15907. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  15908. switch (action) {
  15909. case 'session-initiate':
  15910. var startMuted = $(iq).find('jingle>startmuted');
  15911. if (startMuted && startMuted.length > 0) {
  15912. var audioMuted = startMuted.attr("audio");
  15913. var videoMuted = startMuted.attr("video");
  15914. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  15915. audioMuted === "true", videoMuted === "true");
  15916. }
  15917. sess = new JingleSession(
  15918. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  15919. this.connection, XMPP, eventEmitter);
  15920. // configure session
  15921. sess.media_constraints = this.media_constraints;
  15922. sess.pc_constraints = this.pc_constraints;
  15923. sess.ice_config = this.ice_config;
  15924. sess.initiate(fromJid, false);
  15925. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  15926. sess.setRemoteDescription($(iq).find('>jingle'), 'offer');
  15927. this.sessions[sess.sid] = sess;
  15928. this.jid2session[sess.peerjid] = sess;
  15929. // the callback should either
  15930. // .sendAnswer and .accept
  15931. // or .sendTerminate -- not necessarily synchronus
  15932. CallIncomingJingle(sess.sid, this.connection);
  15933. break;
  15934. case 'session-accept':
  15935. sess.setRemoteDescription($(iq).find('>jingle'), 'answer');
  15936. sess.accept();
  15937. $(document).trigger('callaccepted.jingle', [sess.sid]);
  15938. break;
  15939. case 'session-terminate':
  15940. // If this is not the focus sending the terminate, we have
  15941. // nothing more to do here.
  15942. if (Object.keys(this.sessions).length < 1
  15943. || !(this.sessions[Object.keys(this.sessions)[0]]
  15944. instanceof JingleSession))
  15945. {
  15946. break;
  15947. }
  15948. console.log('terminating...', sess.sid);
  15949. sess.terminate();
  15950. this.terminate(sess.sid);
  15951. if ($(iq).find('>jingle>reason').length) {
  15952. $(document).trigger('callterminated.jingle', [
  15953. sess.sid,
  15954. sess.peerjid,
  15955. $(iq).find('>jingle>reason>:first')[0].tagName,
  15956. $(iq).find('>jingle>reason>text').text()
  15957. ]);
  15958. } else {
  15959. $(document).trigger('callterminated.jingle',
  15960. [sess.sid, sess.peerjid]);
  15961. }
  15962. break;
  15963. case 'transport-info':
  15964. sess.addIceCandidate($(iq).find('>jingle>content'));
  15965. break;
  15966. case 'session-info':
  15967. var affected;
  15968. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15969. $(document).trigger('ringing.jingle', [sess.sid]);
  15970. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15971. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  15972. $(document).trigger('mute.jingle', [sess.sid, affected]);
  15973. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15974. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  15975. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  15976. }
  15977. break;
  15978. case 'addsource': // FIXME: proprietary, un-jingleish
  15979. case 'source-add': // FIXME: proprietary
  15980. sess.addSource($(iq).find('>jingle>content'), fromJid);
  15981. break;
  15982. case 'removesource': // FIXME: proprietary, un-jingleish
  15983. case 'source-remove': // FIXME: proprietary
  15984. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  15985. break;
  15986. default:
  15987. console.warn('jingle action not implemented', action);
  15988. break;
  15989. }
  15990. return true;
  15991. },
  15992. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  15993. var sess = new JingleSession(myjid || this.connection.jid,
  15994. Math.random().toString(36).substr(2, 12), // random string
  15995. this.connection, XMPP, eventEmitter);
  15996. // configure session
  15997. sess.media_constraints = this.media_constraints;
  15998. sess.pc_constraints = this.pc_constraints;
  15999. sess.ice_config = this.ice_config;
  16000. sess.initiate(peerjid, true);
  16001. this.sessions[sess.sid] = sess;
  16002. this.jid2session[sess.peerjid] = sess;
  16003. sess.sendOffer();
  16004. return sess;
  16005. },
  16006. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  16007. if (sid === null || sid === undefined) {
  16008. for (sid in this.sessions) {
  16009. if (this.sessions[sid].state != 'ended') {
  16010. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  16011. this.sessions[sid].terminate();
  16012. }
  16013. delete this.jid2session[this.sessions[sid].peerjid];
  16014. delete this.sessions[sid];
  16015. }
  16016. } else if (this.sessions.hasOwnProperty(sid)) {
  16017. if (this.sessions[sid].state != 'ended') {
  16018. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  16019. this.sessions[sid].terminate();
  16020. }
  16021. delete this.jid2session[this.sessions[sid].peerjid];
  16022. delete this.sessions[sid];
  16023. }
  16024. },
  16025. // Used to terminate a session when an unavailable presence is received.
  16026. terminateByJid: function (jid) {
  16027. if (this.jid2session.hasOwnProperty(jid)) {
  16028. var sess = this.jid2session[jid];
  16029. if (sess) {
  16030. sess.terminate();
  16031. console.log('peer went away silently', jid);
  16032. delete this.sessions[sess.sid];
  16033. delete this.jid2session[jid];
  16034. $(document).trigger('callterminated.jingle',
  16035. [sess.sid, jid], 'gone');
  16036. }
  16037. }
  16038. },
  16039. terminateRemoteByJid: function (jid, reason) {
  16040. if (this.jid2session.hasOwnProperty(jid)) {
  16041. var sess = this.jid2session[jid];
  16042. if (sess) {
  16043. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  16044. sess.terminate();
  16045. console.log('terminate peer with jid', sess.sid, jid);
  16046. delete this.sessions[sess.sid];
  16047. delete this.jid2session[jid];
  16048. $(document).trigger('callterminated.jingle',
  16049. [sess.sid, jid, 'kicked']);
  16050. }
  16051. }
  16052. },
  16053. getStunAndTurnCredentials: function () {
  16054. // get stun and turn configuration from server via xep-0215
  16055. // uses time-limited credentials as described in
  16056. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  16057. //
  16058. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  16059. // for a prosody module which implements this
  16060. //
  16061. // currently, this doesn't work with updateIce and therefore credentials with a long
  16062. // validity have to be fetched before creating the peerconnection
  16063. // TODO: implement refresh via updateIce as described in
  16064. // https://code.google.com/p/webrtc/issues/detail?id=1650
  16065. var self = this;
  16066. this.connection.sendIQ(
  16067. $iq({type: 'get', to: this.connection.domain})
  16068. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  16069. function (res) {
  16070. var iceservers = [];
  16071. $(res).find('>services>service').each(function (idx, el) {
  16072. el = $(el);
  16073. var dict = {};
  16074. var type = el.attr('type');
  16075. switch (type) {
  16076. case 'stun':
  16077. dict.url = 'stun:' + el.attr('host');
  16078. if (el.attr('port')) {
  16079. dict.url += ':' + el.attr('port');
  16080. }
  16081. iceservers.push(dict);
  16082. break;
  16083. case 'turn':
  16084. case 'turns':
  16085. dict.url = type + ':';
  16086. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  16087. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  16088. dict.url += el.attr('username') + '@';
  16089. } else {
  16090. dict.username = el.attr('username'); // only works in M28
  16091. }
  16092. }
  16093. dict.url += el.attr('host');
  16094. if (el.attr('port') && el.attr('port') != '3478') {
  16095. dict.url += ':' + el.attr('port');
  16096. }
  16097. if (el.attr('transport') && el.attr('transport') != 'udp') {
  16098. dict.url += '?transport=' + el.attr('transport');
  16099. }
  16100. if (el.attr('password')) {
  16101. dict.credential = el.attr('password');
  16102. }
  16103. iceservers.push(dict);
  16104. break;
  16105. }
  16106. });
  16107. self.ice_config.iceServers = iceservers;
  16108. },
  16109. function (err) {
  16110. console.warn('getting turn credentials failed', err);
  16111. console.warn('is mod_turncredentials or similar installed?');
  16112. }
  16113. );
  16114. // implement push?
  16115. },
  16116. /**
  16117. * Returns the data saved in 'updateLog' in a format to be logged.
  16118. */
  16119. getLog: function () {
  16120. var data = {};
  16121. var self = this;
  16122. Object.keys(this.sessions).forEach(function (sid) {
  16123. var session = self.sessions[sid];
  16124. if (session.peerconnection && session.peerconnection.updateLog) {
  16125. // FIXME: should probably be a .dump call
  16126. data["jingle_" + session.sid] = {
  16127. updateLog: session.peerconnection.updateLog,
  16128. stats: session.peerconnection.stats,
  16129. url: window.location.href
  16130. };
  16131. }
  16132. });
  16133. return data;
  16134. }
  16135. });
  16136. };
  16137. },{"../../service/xmpp/XMPPEvents":119,"../RTC/RTCBrowserType":10,"./JingleSession":55}],65:[function(require,module,exports){
  16138. /* global Strophe */
  16139. module.exports = function () {
  16140. Strophe.addConnectionPlugin('logger', {
  16141. // logs raw stanzas and makes them available for download as JSON
  16142. connection: null,
  16143. log: [],
  16144. init: function (conn) {
  16145. this.connection = conn;
  16146. this.connection.rawInput = this.log_incoming.bind(this);
  16147. this.connection.rawOutput = this.log_outgoing.bind(this);
  16148. },
  16149. log_incoming: function (stanza) {
  16150. this.log.push([new Date().getTime(), 'incoming', stanza]);
  16151. },
  16152. log_outgoing: function (stanza) {
  16153. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  16154. }
  16155. });
  16156. };
  16157. },{}],66:[function(require,module,exports){
  16158. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  16159. setAudioMuted, Strophe */
  16160. /**
  16161. * Moderate connection plugin.
  16162. */
  16163. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  16164. module.exports = function (XMPP, eventEmitter) {
  16165. Strophe.addConnectionPlugin('moderate', {
  16166. connection: null,
  16167. init: function (conn) {
  16168. this.connection = conn;
  16169. this.connection.addHandler(this.onMute.bind(this),
  16170. 'http://jitsi.org/jitmeet/audio',
  16171. 'iq',
  16172. 'set',
  16173. null,
  16174. null);
  16175. },
  16176. setMute: function (jid, mute) {
  16177. console.info("set mute", mute);
  16178. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  16179. .c('mute', {
  16180. xmlns: 'http://jitsi.org/jitmeet/audio',
  16181. jid: jid
  16182. })
  16183. .t(mute.toString())
  16184. .up();
  16185. this.connection.sendIQ(
  16186. iqToFocus,
  16187. function (result) {
  16188. console.log('set mute', result);
  16189. },
  16190. function (error) {
  16191. console.log('set mute error', error);
  16192. });
  16193. },
  16194. onMute: function (iq) {
  16195. var from = iq.getAttribute('from');
  16196. if (from !== this.connection.emuc.focusMucJid) {
  16197. console.warn("Ignored mute from non focus peer");
  16198. return false;
  16199. }
  16200. var mute = $(iq).find('mute');
  16201. if (mute.length) {
  16202. var doMuteAudio = mute.text() === "true";
  16203. eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
  16204. XMPP.forceMuted = doMuteAudio;
  16205. }
  16206. return true;
  16207. },
  16208. eject: function (jid) {
  16209. // We're not the focus, so can't terminate
  16210. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  16211. this.connection.emuc.kick(jid);
  16212. }
  16213. });
  16214. }
  16215. },{"../../service/xmpp/XMPPEvents":119}],67:[function(require,module,exports){
  16216. /* jshint -W117 */
  16217. module.exports = function() {
  16218. Strophe.addConnectionPlugin('rayo',
  16219. {
  16220. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  16221. connection: null,
  16222. init: function (conn) {
  16223. this.connection = conn;
  16224. if (this.connection.disco) {
  16225. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  16226. }
  16227. this.connection.addHandler(
  16228. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  16229. },
  16230. onRayo: function (iq) {
  16231. console.info("Rayo IQ", iq);
  16232. },
  16233. dial: function (to, from, roomName, roomPass) {
  16234. var self = this;
  16235. var req = $iq(
  16236. {
  16237. type: 'set',
  16238. to: this.connection.emuc.focusMucJid
  16239. }
  16240. );
  16241. req.c('dial',
  16242. {
  16243. xmlns: this.RAYO_XMLNS,
  16244. to: to,
  16245. from: from
  16246. });
  16247. req.c('header',
  16248. {
  16249. name: 'JvbRoomName',
  16250. value: roomName
  16251. }).up();
  16252. if (roomPass !== null && roomPass.length) {
  16253. req.c('header',
  16254. {
  16255. name: 'JvbRoomPassword',
  16256. value: roomPass
  16257. }).up();
  16258. }
  16259. this.connection.sendIQ(
  16260. req,
  16261. function (result) {
  16262. console.info('Dial result ', result);
  16263. var resource = $(result).find('ref').attr('uri');
  16264. this.call_resource = resource.substr('xmpp:'.length);
  16265. console.info(
  16266. "Received call resource: " + this.call_resource);
  16267. },
  16268. function (error) {
  16269. console.info('Dial error ', error);
  16270. }
  16271. );
  16272. },
  16273. hang_up: function () {
  16274. if (!this.call_resource) {
  16275. console.warn("No call in progress");
  16276. return;
  16277. }
  16278. var self = this;
  16279. var req = $iq(
  16280. {
  16281. type: 'set',
  16282. to: this.call_resource
  16283. }
  16284. );
  16285. req.c('hangup',
  16286. {
  16287. xmlns: this.RAYO_XMLNS
  16288. });
  16289. this.connection.sendIQ(
  16290. req,
  16291. function (result) {
  16292. console.info('Hangup result ', result);
  16293. self.call_resource = null;
  16294. },
  16295. function (error) {
  16296. console.info('Hangup error ', error);
  16297. self.call_resource = null;
  16298. }
  16299. );
  16300. }
  16301. }
  16302. );
  16303. };
  16304. },{}],68:[function(require,module,exports){
  16305. /**
  16306. * Strophe logger implementation. Logs from level WARN and above.
  16307. */
  16308. module.exports = function () {
  16309. Strophe.log = function (level, msg) {
  16310. switch (level) {
  16311. case Strophe.LogLevel.WARN:
  16312. console.warn("Strophe: " + msg);
  16313. break;
  16314. case Strophe.LogLevel.ERROR:
  16315. case Strophe.LogLevel.FATAL:
  16316. console.error("Strophe: " + msg);
  16317. break;
  16318. }
  16319. };
  16320. Strophe.getStatusString = function (status) {
  16321. switch (status) {
  16322. case Strophe.Status.ERROR:
  16323. return "ERROR";
  16324. case Strophe.Status.CONNECTING:
  16325. return "CONNECTING";
  16326. case Strophe.Status.CONNFAIL:
  16327. return "CONNFAIL";
  16328. case Strophe.Status.AUTHENTICATING:
  16329. return "AUTHENTICATING";
  16330. case Strophe.Status.AUTHFAIL:
  16331. return "AUTHFAIL";
  16332. case Strophe.Status.CONNECTED:
  16333. return "CONNECTED";
  16334. case Strophe.Status.DISCONNECTED:
  16335. return "DISCONNECTED";
  16336. case Strophe.Status.DISCONNECTING:
  16337. return "DISCONNECTING";
  16338. case Strophe.Status.ATTACHED:
  16339. return "ATTACHED";
  16340. default:
  16341. return "unknown";
  16342. }
  16343. };
  16344. };
  16345. },{}],69:[function(require,module,exports){
  16346. /* global $, APP, config, Strophe*/
  16347. var Moderator = require("./moderator");
  16348. var EventEmitter = require("events");
  16349. var Recording = require("./recording");
  16350. var SDP = require("./SDP");
  16351. var Settings = require("../settings/Settings");
  16352. var Pako = require("pako");
  16353. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  16354. var RTCEvents = require("../../service/RTC/RTCEvents");
  16355. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  16356. var retry = require('retry');
  16357. var eventEmitter = new EventEmitter();
  16358. var connection = null;
  16359. var authenticatedUser = false;
  16360. function connect(jid, password) {
  16361. var faultTolerantConnect = retry.operation({
  16362. retries: 3
  16363. });
  16364. // fault tolerant connect
  16365. faultTolerantConnect.attempt(function () {
  16366. connection = XMPP.createConnection();
  16367. Moderator.setConnection(connection);
  16368. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  16369. if (config.useIPv6) {
  16370. // https://code.google.com/p/webrtc/issues/detail?id=2828
  16371. if (!connection.jingle.pc_constraints.optional)
  16372. connection.jingle.pc_constraints.optional = [];
  16373. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  16374. }
  16375. // Include user info in MUC presence
  16376. var settings = Settings.getSettings();
  16377. if (settings.email) {
  16378. connection.emuc.addEmailToPresence(settings.email);
  16379. }
  16380. if (settings.uid) {
  16381. connection.emuc.addUserIdToPresence(settings.uid);
  16382. }
  16383. if (settings.displayName) {
  16384. connection.emuc.addDisplayNameToPresence(settings.displayName);
  16385. }
  16386. // connection.connect() starts the connection process.
  16387. //
  16388. // As the connection process proceeds, the user supplied callback will
  16389. // be triggered multiple times with status updates. The callback should
  16390. // take two arguments - the status code and the error condition.
  16391. //
  16392. // The status code will be one of the values in the Strophe.Status
  16393. // constants. The error condition will be one of the conditions defined
  16394. // in RFC 3920 or the condition ‘strophe-parsererror’.
  16395. //
  16396. // The Parameters wait, hold and route are optional and only relevant
  16397. // for BOSH connections. Please see XEP 124 for a more detailed
  16398. // explanation of the optional parameters.
  16399. //
  16400. // Connection status constants for use by the connection handler
  16401. // callback.
  16402. //
  16403. // Status.ERROR - An error has occurred (websockets specific)
  16404. // Status.CONNECTING - The connection is currently being made
  16405. // Status.CONNFAIL - The connection attempt failed
  16406. // Status.AUTHENTICATING - The connection is authenticating
  16407. // Status.AUTHFAIL - The authentication attempt failed
  16408. // Status.CONNECTED - The connection has succeeded
  16409. // Status.DISCONNECTED - The connection has been terminated
  16410. // Status.DISCONNECTING - The connection is currently being terminated
  16411. // Status.ATTACHED - The connection has been attached
  16412. var anonymousConnectionFailed = false;
  16413. var connectionFailed = false;
  16414. var lastErrorMsg;
  16415. connection.connect(jid, password, function (status, msg) {
  16416. console.log('Strophe status changed to',
  16417. Strophe.getStatusString(status), msg);
  16418. if (status === Strophe.Status.CONNECTED) {
  16419. if (config.useStunTurn) {
  16420. connection.jingle.getStunAndTurnCredentials();
  16421. }
  16422. console.info("My Jabber ID: " + connection.jid);
  16423. if (password)
  16424. authenticatedUser = true;
  16425. maybeDoJoin();
  16426. } else if (status === Strophe.Status.CONNFAIL) {
  16427. if (msg === 'x-strophe-bad-non-anon-jid') {
  16428. anonymousConnectionFailed = true;
  16429. } else {
  16430. connectionFailed = true;
  16431. }
  16432. lastErrorMsg = msg;
  16433. } else if (status === Strophe.Status.DISCONNECTED) {
  16434. if (anonymousConnectionFailed) {
  16435. // prompt user for username and password
  16436. XMPP.promptLogin();
  16437. } else {
  16438. // Strophe already has built-in HTTP/BOSH error handling and
  16439. // request retry logic. Requests are resent automatically
  16440. // until their error count reaches 5. Strophe.js disconnects
  16441. // if the error count is > 5. We are not replicating this
  16442. // here.
  16443. //
  16444. // The "problem" is that failed HTTP/BOSH requests don't
  16445. // trigger a callback with a status update, so when a
  16446. // callback with status Strophe.Status.DISCONNECTED arrives,
  16447. // we can't be sure if it's a graceful disconnect or if it's
  16448. // triggered by some HTTP/BOSH error.
  16449. //
  16450. // But that's a minor issue in Jitsi Meet as we never
  16451. // disconnect anyway, not even when the user closes the
  16452. // browser window (which is kind of wrong, but the point is
  16453. // that we should never ever get disconnected).
  16454. //
  16455. // On the other hand, failed connections due to XMPP layer
  16456. // errors, trigger a callback with status Strophe.Status.CONNFAIL.
  16457. //
  16458. // Here we implement retry logic for failed connections due
  16459. // to XMPP layer errors and we display an error to the user
  16460. // if we get disconnected from the XMPP server permanently.
  16461. // If the connection failed, retry.
  16462. if (connectionFailed &&
  16463. faultTolerantConnect.retry("connection-failed")) {
  16464. return;
  16465. }
  16466. // If we failed to connect to the XMPP server, fire an event
  16467. // to let all the interested module now about it.
  16468. eventEmitter.emit(XMPPEvents.CONNECTION_FAILED,
  16469. msg ? msg : lastErrorMsg);
  16470. }
  16471. } else if (status === Strophe.Status.AUTHFAIL) {
  16472. // wrong password or username, prompt user
  16473. XMPP.promptLogin();
  16474. }
  16475. });
  16476. });
  16477. }
  16478. function maybeDoJoin() {
  16479. if (connection && connection.connected &&
  16480. Strophe.getResourceFromJid(connection.jid) &&
  16481. (APP.RTC.localAudio || APP.RTC.localVideo)) {
  16482. // .connected is true while connecting?
  16483. doJoin();
  16484. }
  16485. }
  16486. function doJoin() {
  16487. eventEmitter.emit(XMPPEvents.READY_TO_JOIN);
  16488. }
  16489. function initStrophePlugins()
  16490. {
  16491. require("./strophe.emuc")(XMPP, eventEmitter);
  16492. require("./strophe.jingle")(XMPP, eventEmitter);
  16493. require("./strophe.moderate")(XMPP, eventEmitter);
  16494. require("./strophe.util")();
  16495. require("./strophe.rayo")();
  16496. require("./strophe.logger")();
  16497. }
  16498. /**
  16499. * If given <tt>localStream</tt> is video one this method will advertise it's
  16500. * video type in MUC presence.
  16501. * @param localStream new or modified <tt>LocalStream</tt>.
  16502. */
  16503. function broadcastLocalVideoType(localStream) {
  16504. if (localStream.videoType)
  16505. XMPP.addToPresence('videoType', localStream.videoType);
  16506. }
  16507. function registerListeners() {
  16508. APP.RTC.addStreamListener(
  16509. function (localStream) {
  16510. maybeDoJoin();
  16511. broadcastLocalVideoType(localStream);
  16512. },
  16513. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED
  16514. );
  16515. APP.RTC.addStreamListener(
  16516. broadcastLocalVideoType,
  16517. StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  16518. );
  16519. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  16520. XMPP.addToPresence("devices", devices);
  16521. });
  16522. }
  16523. var unload = (function () {
  16524. var unloaded = false;
  16525. return function () {
  16526. if (unloaded) { return; }
  16527. unloaded = true;
  16528. if (connection && connection.connected) {
  16529. // ensure signout
  16530. $.ajax({
  16531. type: 'POST',
  16532. url: config.bosh,
  16533. async: false,
  16534. cache: false,
  16535. contentType: 'application/xml',
  16536. data: "<body rid='" +
  16537. (connection.rid || connection._proto.rid) +
  16538. "' xmlns='http://jabber.org/protocol/httpbind' sid='" +
  16539. (connection.sid || connection._proto.sid) +
  16540. "' type='terminate'>" +
  16541. "<presence xmlns='jabber:client' type='unavailable'/>" +
  16542. "</body>",
  16543. success: function (data) {
  16544. console.log('signed out');
  16545. console.log(data);
  16546. },
  16547. error: function (XMLHttpRequest, textStatus, errorThrown) {
  16548. console.log('signout error',
  16549. textStatus + ' (' + errorThrown + ')');
  16550. }
  16551. });
  16552. }
  16553. XMPP.disposeConference(true);
  16554. };
  16555. })();
  16556. function setupEvents() {
  16557. // In recent versions of FF the 'beforeunload' event is not fired when the
  16558. // window or the tab is closed. It is only fired when we leave the page
  16559. // (change URL). If this participant doesn't unload properly, then it
  16560. // becomes a ghost for the rest of the participants that stay in the
  16561. // conference. Thankfully handling the 'unload' event in addition to the
  16562. // 'beforeunload' event seems to guarantee the execution of the 'unload'
  16563. // method at least once.
  16564. //
  16565. // The 'unload' method can safely be run multiple times, it will actually do
  16566. // something only the first time that it's run, so we're don't have to worry
  16567. // about browsers that fire both events.
  16568. $(window).bind('beforeunload', unload);
  16569. $(window).bind('unload', unload);
  16570. }
  16571. var XMPP = {
  16572. getConnection: function(){ return connection; },
  16573. sessionTerminated: false,
  16574. /**
  16575. * XMPP connection status
  16576. */
  16577. Status: Strophe.Status,
  16578. /**
  16579. * Remembers if we were muted by the focus.
  16580. * @type {boolean}
  16581. */
  16582. forceMuted: false,
  16583. start: function () {
  16584. setupEvents();
  16585. initStrophePlugins();
  16586. registerListeners();
  16587. Moderator.init(this, eventEmitter);
  16588. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  16589. // Force authenticated domain if room is appended with '?login=true'
  16590. if (config.hosts.anonymousdomain &&
  16591. window.location.search.indexOf("login=true") !== -1) {
  16592. configDomain = config.hosts.domain;
  16593. }
  16594. var jid = configDomain || window.location.hostname;
  16595. connect(jid, null);
  16596. },
  16597. createConnection: function () {
  16598. var bosh = config.bosh || '/http-bind';
  16599. return new Strophe.Connection(bosh);
  16600. },
  16601. getStatusString: function (status) {
  16602. return Strophe.getStatusString(status);
  16603. },
  16604. promptLogin: function () {
  16605. eventEmitter.emit(XMPPEvents.PROMPT_FOR_LOGIN);
  16606. },
  16607. joinRoom: function(roomName, useNicks, nick) {
  16608. var roomjid = roomName;
  16609. if (useNicks) {
  16610. if (nick) {
  16611. roomjid += '/' + nick;
  16612. } else {
  16613. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  16614. }
  16615. } else {
  16616. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  16617. if(!authenticatedUser)
  16618. tmpJid = tmpJid.substr(0, 8);
  16619. roomjid += '/' + tmpJid;
  16620. }
  16621. connection.emuc.doJoin(roomjid);
  16622. },
  16623. myJid: function () {
  16624. if(!connection)
  16625. return null;
  16626. return connection.emuc.myroomjid;
  16627. },
  16628. myResource: function () {
  16629. if(!connection || ! connection.emuc.myroomjid)
  16630. return null;
  16631. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  16632. },
  16633. disposeConference: function (onUnload) {
  16634. var handler = connection.jingle.activecall;
  16635. if (handler && handler.peerconnection) {
  16636. // FIXME: probably removing streams is not required and close() should
  16637. // be enough
  16638. if (APP.RTC.localAudio) {
  16639. handler.peerconnection.removeStream(
  16640. APP.RTC.localAudio.getOriginalStream(), onUnload);
  16641. }
  16642. if (APP.RTC.localVideo) {
  16643. handler.peerconnection.removeStream(
  16644. APP.RTC.localVideo.getOriginalStream(), onUnload);
  16645. }
  16646. handler.peerconnection.close();
  16647. }
  16648. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  16649. connection.jingle.activecall = null;
  16650. if (!onUnload) {
  16651. this.sessionTerminated = true;
  16652. connection.emuc.doLeave();
  16653. }
  16654. },
  16655. addListener: function(type, listener) {
  16656. eventEmitter.on(type, listener);
  16657. },
  16658. removeListener: function (type, listener) {
  16659. eventEmitter.removeListener(type, listener);
  16660. },
  16661. allocateConferenceFocus: function(roomName, callback) {
  16662. Moderator.allocateConferenceFocus(roomName, callback);
  16663. },
  16664. getLoginUrl: function (roomName, callback) {
  16665. Moderator.getLoginUrl(roomName, callback);
  16666. },
  16667. getPopupLoginUrl: function (roomName, callback) {
  16668. Moderator.getPopupLoginUrl(roomName, callback);
  16669. },
  16670. isModerator: function () {
  16671. return Moderator.isModerator();
  16672. },
  16673. isSipGatewayEnabled: function () {
  16674. return Moderator.isSipGatewayEnabled();
  16675. },
  16676. isExternalAuthEnabled: function () {
  16677. return Moderator.isExternalAuthEnabled();
  16678. },
  16679. isConferenceInProgress: function () {
  16680. return connection && connection.jingle.activecall &&
  16681. connection.jingle.activecall.peerconnection;
  16682. },
  16683. switchStreams: function (stream, oldStream, callback, isAudio) {
  16684. if (this.isConferenceInProgress()) {
  16685. // FIXME: will block switchInProgress on true value in case of exception
  16686. connection.jingle.activecall.switchStreams(stream, oldStream, callback, isAudio);
  16687. } else {
  16688. // We are done immediately
  16689. console.warn("No conference handler or conference not started yet");
  16690. callback();
  16691. }
  16692. },
  16693. sendVideoInfoPresence: function (mute) {
  16694. if(!connection)
  16695. return;
  16696. connection.emuc.addVideoInfoToPresence(mute);
  16697. connection.emuc.sendPresence();
  16698. },
  16699. setVideoMute: function (mute, callback, options) {
  16700. if(!connection)
  16701. return;
  16702. var self = this;
  16703. var localCallback = function (mute) {
  16704. self.sendVideoInfoPresence(mute);
  16705. return callback(mute);
  16706. };
  16707. if(connection.jingle.activecall)
  16708. {
  16709. connection.jingle.activecall.setVideoMute(
  16710. mute, localCallback, options);
  16711. }
  16712. else {
  16713. localCallback(mute);
  16714. }
  16715. },
  16716. setAudioMute: function (mute, callback) {
  16717. if (!(connection && APP.RTC.localAudio)) {
  16718. return false;
  16719. }
  16720. if (this.forceMuted && !mute) {
  16721. console.info("Asking focus for unmute");
  16722. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  16723. // FIXME: wait for result before resetting muted status
  16724. this.forceMuted = false;
  16725. }
  16726. if (mute == APP.RTC.localAudio.isMuted()) {
  16727. // Nothing to do
  16728. return true;
  16729. }
  16730. APP.RTC.localAudio.setMute(mute);
  16731. this.sendAudioInfoPresence(mute, callback);
  16732. return true;
  16733. },
  16734. sendAudioInfoPresence: function(mute, callback) {
  16735. if(connection) {
  16736. connection.emuc.addAudioInfoToPresence(mute);
  16737. connection.emuc.sendPresence();
  16738. }
  16739. callback();
  16740. return true;
  16741. },
  16742. toggleRecording: function (tokenEmptyCallback,
  16743. startingCallback, startedCallback) {
  16744. Recording.toggleRecording(tokenEmptyCallback,
  16745. startingCallback, startedCallback, connection);
  16746. },
  16747. addToPresence: function (name, value, dontSend) {
  16748. switch (name) {
  16749. case "displayName":
  16750. connection.emuc.addDisplayNameToPresence(value);
  16751. break;
  16752. case "prezi":
  16753. connection.emuc.addPreziToPresence(value, 0);
  16754. break;
  16755. case "preziSlide":
  16756. connection.emuc.addCurrentSlideToPresence(value);
  16757. break;
  16758. case "connectionQuality":
  16759. connection.emuc.addConnectionInfoToPresence(value);
  16760. break;
  16761. case "email":
  16762. connection.emuc.addEmailToPresence(value);
  16763. break;
  16764. case "devices":
  16765. connection.emuc.addDevicesToPresence(value);
  16766. break;
  16767. case "videoType":
  16768. connection.emuc.addVideoTypeToPresence(value);
  16769. break;
  16770. case "startMuted":
  16771. if(!Moderator.isModerator())
  16772. return;
  16773. connection.emuc.addStartMutedToPresence(value[0],
  16774. value[1]);
  16775. break;
  16776. default :
  16777. console.log("Unknown tag for presence: " + name);
  16778. return;
  16779. }
  16780. if (!dontSend)
  16781. connection.emuc.sendPresence();
  16782. },
  16783. /**
  16784. * Sends 'data' as a log message to the focus. Returns true iff a message
  16785. * was sent.
  16786. * @param data
  16787. * @returns {boolean} true iff a message was sent.
  16788. */
  16789. sendLogs: function (data) {
  16790. if(!connection.emuc.focusMucJid)
  16791. return false;
  16792. var deflate = true;
  16793. var content = JSON.stringify(data);
  16794. if (deflate) {
  16795. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  16796. }
  16797. content = Base64.encode(content);
  16798. // XEP-0337-ish
  16799. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  16800. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  16801. id: 'PeerConnectionStats'});
  16802. message.c('message').t(content).up();
  16803. if (deflate) {
  16804. message.c('tag', {name: "deflated", value: "true"}).up();
  16805. }
  16806. message.up();
  16807. connection.send(message);
  16808. return true;
  16809. },
  16810. // Gets the logs from strophe.jingle.
  16811. getJingleLog: function () {
  16812. return connection.jingle ? connection.jingle.getLog() : {};
  16813. },
  16814. // Gets the logs from strophe.
  16815. getXmppLog: function () {
  16816. return connection.logger ? connection.logger.log : null;
  16817. },
  16818. getPrezi: function () {
  16819. return connection.emuc.getPrezi(this.myJid());
  16820. },
  16821. removePreziFromPresence: function () {
  16822. connection.emuc.removePreziFromPresence();
  16823. connection.emuc.sendPresence();
  16824. },
  16825. sendChatMessage: function (message, nickname) {
  16826. connection.emuc.sendMessage(message, nickname);
  16827. },
  16828. setSubject: function (topic) {
  16829. connection.emuc.setSubject(topic);
  16830. },
  16831. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  16832. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  16833. },
  16834. dial: function (to, from, roomName,roomPass) {
  16835. connection.rayo.dial(to, from, roomName,roomPass);
  16836. },
  16837. setMute: function (jid, mute) {
  16838. connection.moderate.setMute(jid, mute);
  16839. },
  16840. eject: function (jid) {
  16841. connection.moderate.eject(jid);
  16842. },
  16843. logout: function (callback) {
  16844. Moderator.logout(callback);
  16845. },
  16846. findJidFromResource: function (resource) {
  16847. return connection.emuc.findJidFromResource(resource);
  16848. },
  16849. getMembers: function () {
  16850. return connection.emuc.members;
  16851. },
  16852. getJidFromSSRC: function (ssrc) {
  16853. if (!this.isConferenceInProgress())
  16854. return null;
  16855. return connection.jingle.activecall.getSsrcOwner(ssrc);
  16856. },
  16857. // Returns true iff we have joined the MUC.
  16858. isMUCJoined: function () {
  16859. return connection.emuc.joined;
  16860. },
  16861. getSessions: function () {
  16862. return connection.jingle.sessions;
  16863. },
  16864. removeStream: function (stream) {
  16865. if (!this.isConferenceInProgress())
  16866. return;
  16867. connection.jingle.activecall.peerconnection.removeStream(stream);
  16868. }
  16869. };
  16870. module.exports = XMPP;
  16871. },{"../../service/RTC/RTCEvents":110,"../../service/RTC/StreamEventTypes":112,"../../service/xmpp/XMPPEvents":119,"../settings/Settings":49,"./SDP":56,"./moderator":61,"./recording":62,"./strophe.emuc":63,"./strophe.jingle":64,"./strophe.logger":65,"./strophe.moderate":66,"./strophe.rayo":67,"./strophe.util":68,"events":1,"pako":72,"retry":88}],70:[function(require,module,exports){
  16872. (function (process){
  16873. /*!
  16874. * async
  16875. * https://github.com/caolan/async
  16876. *
  16877. * Copyright 2010-2014 Caolan McMahon
  16878. * Released under the MIT license
  16879. */
  16880. /*jshint onevar: false, indent:4 */
  16881. /*global setImmediate: false, setTimeout: false, console: false */
  16882. (function () {
  16883. var async = {};
  16884. // global on the server, window in the browser
  16885. var root, previous_async;
  16886. root = this;
  16887. if (root != null) {
  16888. previous_async = root.async;
  16889. }
  16890. async.noConflict = function () {
  16891. root.async = previous_async;
  16892. return async;
  16893. };
  16894. function only_once(fn) {
  16895. var called = false;
  16896. return function() {
  16897. if (called) throw new Error("Callback was already called.");
  16898. called = true;
  16899. fn.apply(root, arguments);
  16900. }
  16901. }
  16902. //// cross-browser compatiblity functions ////
  16903. var _toString = Object.prototype.toString;
  16904. var _isArray = Array.isArray || function (obj) {
  16905. return _toString.call(obj) === '[object Array]';
  16906. };
  16907. var _each = function (arr, iterator) {
  16908. if (arr.forEach) {
  16909. return arr.forEach(iterator);
  16910. }
  16911. for (var i = 0; i < arr.length; i += 1) {
  16912. iterator(arr[i], i, arr);
  16913. }
  16914. };
  16915. var _map = function (arr, iterator) {
  16916. if (arr.map) {
  16917. return arr.map(iterator);
  16918. }
  16919. var results = [];
  16920. _each(arr, function (x, i, a) {
  16921. results.push(iterator(x, i, a));
  16922. });
  16923. return results;
  16924. };
  16925. var _reduce = function (arr, iterator, memo) {
  16926. if (arr.reduce) {
  16927. return arr.reduce(iterator, memo);
  16928. }
  16929. _each(arr, function (x, i, a) {
  16930. memo = iterator(memo, x, i, a);
  16931. });
  16932. return memo;
  16933. };
  16934. var _keys = function (obj) {
  16935. if (Object.keys) {
  16936. return Object.keys(obj);
  16937. }
  16938. var keys = [];
  16939. for (var k in obj) {
  16940. if (obj.hasOwnProperty(k)) {
  16941. keys.push(k);
  16942. }
  16943. }
  16944. return keys;
  16945. };
  16946. //// exported async module functions ////
  16947. //// nextTick implementation with browser-compatible fallback ////
  16948. if (typeof process === 'undefined' || !(process.nextTick)) {
  16949. if (typeof setImmediate === 'function') {
  16950. async.nextTick = function (fn) {
  16951. // not a direct alias for IE10 compatibility
  16952. setImmediate(fn);
  16953. };
  16954. async.setImmediate = async.nextTick;
  16955. }
  16956. else {
  16957. async.nextTick = function (fn) {
  16958. setTimeout(fn, 0);
  16959. };
  16960. async.setImmediate = async.nextTick;
  16961. }
  16962. }
  16963. else {
  16964. async.nextTick = process.nextTick;
  16965. if (typeof setImmediate !== 'undefined') {
  16966. async.setImmediate = function (fn) {
  16967. // not a direct alias for IE10 compatibility
  16968. setImmediate(fn);
  16969. };
  16970. }
  16971. else {
  16972. async.setImmediate = async.nextTick;
  16973. }
  16974. }
  16975. async.each = function (arr, iterator, callback) {
  16976. callback = callback || function () {};
  16977. if (!arr.length) {
  16978. return callback();
  16979. }
  16980. var completed = 0;
  16981. _each(arr, function (x) {
  16982. iterator(x, only_once(done) );
  16983. });
  16984. function done(err) {
  16985. if (err) {
  16986. callback(err);
  16987. callback = function () {};
  16988. }
  16989. else {
  16990. completed += 1;
  16991. if (completed >= arr.length) {
  16992. callback();
  16993. }
  16994. }
  16995. }
  16996. };
  16997. async.forEach = async.each;
  16998. async.eachSeries = function (arr, iterator, callback) {
  16999. callback = callback || function () {};
  17000. if (!arr.length) {
  17001. return callback();
  17002. }
  17003. var completed = 0;
  17004. var iterate = function () {
  17005. iterator(arr[completed], function (err) {
  17006. if (err) {
  17007. callback(err);
  17008. callback = function () {};
  17009. }
  17010. else {
  17011. completed += 1;
  17012. if (completed >= arr.length) {
  17013. callback();
  17014. }
  17015. else {
  17016. iterate();
  17017. }
  17018. }
  17019. });
  17020. };
  17021. iterate();
  17022. };
  17023. async.forEachSeries = async.eachSeries;
  17024. async.eachLimit = function (arr, limit, iterator, callback) {
  17025. var fn = _eachLimit(limit);
  17026. fn.apply(null, [arr, iterator, callback]);
  17027. };
  17028. async.forEachLimit = async.eachLimit;
  17029. var _eachLimit = function (limit) {
  17030. return function (arr, iterator, callback) {
  17031. callback = callback || function () {};
  17032. if (!arr.length || limit <= 0) {
  17033. return callback();
  17034. }
  17035. var completed = 0;
  17036. var started = 0;
  17037. var running = 0;
  17038. (function replenish () {
  17039. if (completed >= arr.length) {
  17040. return callback();
  17041. }
  17042. while (running < limit && started < arr.length) {
  17043. started += 1;
  17044. running += 1;
  17045. iterator(arr[started - 1], function (err) {
  17046. if (err) {
  17047. callback(err);
  17048. callback = function () {};
  17049. }
  17050. else {
  17051. completed += 1;
  17052. running -= 1;
  17053. if (completed >= arr.length) {
  17054. callback();
  17055. }
  17056. else {
  17057. replenish();
  17058. }
  17059. }
  17060. });
  17061. }
  17062. })();
  17063. };
  17064. };
  17065. var doParallel = function (fn) {
  17066. return function () {
  17067. var args = Array.prototype.slice.call(arguments);
  17068. return fn.apply(null, [async.each].concat(args));
  17069. };
  17070. };
  17071. var doParallelLimit = function(limit, fn) {
  17072. return function () {
  17073. var args = Array.prototype.slice.call(arguments);
  17074. return fn.apply(null, [_eachLimit(limit)].concat(args));
  17075. };
  17076. };
  17077. var doSeries = function (fn) {
  17078. return function () {
  17079. var args = Array.prototype.slice.call(arguments);
  17080. return fn.apply(null, [async.eachSeries].concat(args));
  17081. };
  17082. };
  17083. var _asyncMap = function (eachfn, arr, iterator, callback) {
  17084. arr = _map(arr, function (x, i) {
  17085. return {index: i, value: x};
  17086. });
  17087. if (!callback) {
  17088. eachfn(arr, function (x, callback) {
  17089. iterator(x.value, function (err) {
  17090. callback(err);
  17091. });
  17092. });
  17093. } else {
  17094. var results = [];
  17095. eachfn(arr, function (x, callback) {
  17096. iterator(x.value, function (err, v) {
  17097. results[x.index] = v;
  17098. callback(err);
  17099. });
  17100. }, function (err) {
  17101. callback(err, results);
  17102. });
  17103. }
  17104. };
  17105. async.map = doParallel(_asyncMap);
  17106. async.mapSeries = doSeries(_asyncMap);
  17107. async.mapLimit = function (arr, limit, iterator, callback) {
  17108. return _mapLimit(limit)(arr, iterator, callback);
  17109. };
  17110. var _mapLimit = function(limit) {
  17111. return doParallelLimit(limit, _asyncMap);
  17112. };
  17113. // reduce only has a series version, as doing reduce in parallel won't
  17114. // work in many situations.
  17115. async.reduce = function (arr, memo, iterator, callback) {
  17116. async.eachSeries(arr, function (x, callback) {
  17117. iterator(memo, x, function (err, v) {
  17118. memo = v;
  17119. callback(err);
  17120. });
  17121. }, function (err) {
  17122. callback(err, memo);
  17123. });
  17124. };
  17125. // inject alias
  17126. async.inject = async.reduce;
  17127. // foldl alias
  17128. async.foldl = async.reduce;
  17129. async.reduceRight = function (arr, memo, iterator, callback) {
  17130. var reversed = _map(arr, function (x) {
  17131. return x;
  17132. }).reverse();
  17133. async.reduce(reversed, memo, iterator, callback);
  17134. };
  17135. // foldr alias
  17136. async.foldr = async.reduceRight;
  17137. var _filter = function (eachfn, arr, iterator, callback) {
  17138. var results = [];
  17139. arr = _map(arr, function (x, i) {
  17140. return {index: i, value: x};
  17141. });
  17142. eachfn(arr, function (x, callback) {
  17143. iterator(x.value, function (v) {
  17144. if (v) {
  17145. results.push(x);
  17146. }
  17147. callback();
  17148. });
  17149. }, function (err) {
  17150. callback(_map(results.sort(function (a, b) {
  17151. return a.index - b.index;
  17152. }), function (x) {
  17153. return x.value;
  17154. }));
  17155. });
  17156. };
  17157. async.filter = doParallel(_filter);
  17158. async.filterSeries = doSeries(_filter);
  17159. // select alias
  17160. async.select = async.filter;
  17161. async.selectSeries = async.filterSeries;
  17162. var _reject = function (eachfn, arr, iterator, callback) {
  17163. var results = [];
  17164. arr = _map(arr, function (x, i) {
  17165. return {index: i, value: x};
  17166. });
  17167. eachfn(arr, function (x, callback) {
  17168. iterator(x.value, function (v) {
  17169. if (!v) {
  17170. results.push(x);
  17171. }
  17172. callback();
  17173. });
  17174. }, function (err) {
  17175. callback(_map(results.sort(function (a, b) {
  17176. return a.index - b.index;
  17177. }), function (x) {
  17178. return x.value;
  17179. }));
  17180. });
  17181. };
  17182. async.reject = doParallel(_reject);
  17183. async.rejectSeries = doSeries(_reject);
  17184. var _detect = function (eachfn, arr, iterator, main_callback) {
  17185. eachfn(arr, function (x, callback) {
  17186. iterator(x, function (result) {
  17187. if (result) {
  17188. main_callback(x);
  17189. main_callback = function () {};
  17190. }
  17191. else {
  17192. callback();
  17193. }
  17194. });
  17195. }, function (err) {
  17196. main_callback();
  17197. });
  17198. };
  17199. async.detect = doParallel(_detect);
  17200. async.detectSeries = doSeries(_detect);
  17201. async.some = function (arr, iterator, main_callback) {
  17202. async.each(arr, function (x, callback) {
  17203. iterator(x, function (v) {
  17204. if (v) {
  17205. main_callback(true);
  17206. main_callback = function () {};
  17207. }
  17208. callback();
  17209. });
  17210. }, function (err) {
  17211. main_callback(false);
  17212. });
  17213. };
  17214. // any alias
  17215. async.any = async.some;
  17216. async.every = function (arr, iterator, main_callback) {
  17217. async.each(arr, function (x, callback) {
  17218. iterator(x, function (v) {
  17219. if (!v) {
  17220. main_callback(false);
  17221. main_callback = function () {};
  17222. }
  17223. callback();
  17224. });
  17225. }, function (err) {
  17226. main_callback(true);
  17227. });
  17228. };
  17229. // all alias
  17230. async.all = async.every;
  17231. async.sortBy = function (arr, iterator, callback) {
  17232. async.map(arr, function (x, callback) {
  17233. iterator(x, function (err, criteria) {
  17234. if (err) {
  17235. callback(err);
  17236. }
  17237. else {
  17238. callback(null, {value: x, criteria: criteria});
  17239. }
  17240. });
  17241. }, function (err, results) {
  17242. if (err) {
  17243. return callback(err);
  17244. }
  17245. else {
  17246. var fn = function (left, right) {
  17247. var a = left.criteria, b = right.criteria;
  17248. return a < b ? -1 : a > b ? 1 : 0;
  17249. };
  17250. callback(null, _map(results.sort(fn), function (x) {
  17251. return x.value;
  17252. }));
  17253. }
  17254. });
  17255. };
  17256. async.auto = function (tasks, callback) {
  17257. callback = callback || function () {};
  17258. var keys = _keys(tasks);
  17259. var remainingTasks = keys.length
  17260. if (!remainingTasks) {
  17261. return callback();
  17262. }
  17263. var results = {};
  17264. var listeners = [];
  17265. var addListener = function (fn) {
  17266. listeners.unshift(fn);
  17267. };
  17268. var removeListener = function (fn) {
  17269. for (var i = 0; i < listeners.length; i += 1) {
  17270. if (listeners[i] === fn) {
  17271. listeners.splice(i, 1);
  17272. return;
  17273. }
  17274. }
  17275. };
  17276. var taskComplete = function () {
  17277. remainingTasks--
  17278. _each(listeners.slice(0), function (fn) {
  17279. fn();
  17280. });
  17281. };
  17282. addListener(function () {
  17283. if (!remainingTasks) {
  17284. var theCallback = callback;
  17285. // prevent final callback from calling itself if it errors
  17286. callback = function () {};
  17287. theCallback(null, results);
  17288. }
  17289. });
  17290. _each(keys, function (k) {
  17291. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  17292. var taskCallback = function (err) {
  17293. var args = Array.prototype.slice.call(arguments, 1);
  17294. if (args.length <= 1) {
  17295. args = args[0];
  17296. }
  17297. if (err) {
  17298. var safeResults = {};
  17299. _each(_keys(results), function(rkey) {
  17300. safeResults[rkey] = results[rkey];
  17301. });
  17302. safeResults[k] = args;
  17303. callback(err, safeResults);
  17304. // stop subsequent errors hitting callback multiple times
  17305. callback = function () {};
  17306. }
  17307. else {
  17308. results[k] = args;
  17309. async.setImmediate(taskComplete);
  17310. }
  17311. };
  17312. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  17313. var ready = function () {
  17314. return _reduce(requires, function (a, x) {
  17315. return (a && results.hasOwnProperty(x));
  17316. }, true) && !results.hasOwnProperty(k);
  17317. };
  17318. if (ready()) {
  17319. task[task.length - 1](taskCallback, results);
  17320. }
  17321. else {
  17322. var listener = function () {
  17323. if (ready()) {
  17324. removeListener(listener);
  17325. task[task.length - 1](taskCallback, results);
  17326. }
  17327. };
  17328. addListener(listener);
  17329. }
  17330. });
  17331. };
  17332. async.retry = function(times, task, callback) {
  17333. var DEFAULT_TIMES = 5;
  17334. var attempts = [];
  17335. // Use defaults if times not passed
  17336. if (typeof times === 'function') {
  17337. callback = task;
  17338. task = times;
  17339. times = DEFAULT_TIMES;
  17340. }
  17341. // Make sure times is a number
  17342. times = parseInt(times, 10) || DEFAULT_TIMES;
  17343. var wrappedTask = function(wrappedCallback, wrappedResults) {
  17344. var retryAttempt = function(task, finalAttempt) {
  17345. return function(seriesCallback) {
  17346. task(function(err, result){
  17347. seriesCallback(!err || finalAttempt, {err: err, result: result});
  17348. }, wrappedResults);
  17349. };
  17350. };
  17351. while (times) {
  17352. attempts.push(retryAttempt(task, !(times-=1)));
  17353. }
  17354. async.series(attempts, function(done, data){
  17355. data = data[data.length - 1];
  17356. (wrappedCallback || callback)(data.err, data.result);
  17357. });
  17358. }
  17359. // If a callback is passed, run this as a controll flow
  17360. return callback ? wrappedTask() : wrappedTask
  17361. };
  17362. async.waterfall = function (tasks, callback) {
  17363. callback = callback || function () {};
  17364. if (!_isArray(tasks)) {
  17365. var err = new Error('First argument to waterfall must be an array of functions');
  17366. return callback(err);
  17367. }
  17368. if (!tasks.length) {
  17369. return callback();
  17370. }
  17371. var wrapIterator = function (iterator) {
  17372. return function (err) {
  17373. if (err) {
  17374. callback.apply(null, arguments);
  17375. callback = function () {};
  17376. }
  17377. else {
  17378. var args = Array.prototype.slice.call(arguments, 1);
  17379. var next = iterator.next();
  17380. if (next) {
  17381. args.push(wrapIterator(next));
  17382. }
  17383. else {
  17384. args.push(callback);
  17385. }
  17386. async.setImmediate(function () {
  17387. iterator.apply(null, args);
  17388. });
  17389. }
  17390. };
  17391. };
  17392. wrapIterator(async.iterator(tasks))();
  17393. };
  17394. var _parallel = function(eachfn, tasks, callback) {
  17395. callback = callback || function () {};
  17396. if (_isArray(tasks)) {
  17397. eachfn.map(tasks, function (fn, callback) {
  17398. if (fn) {
  17399. fn(function (err) {
  17400. var args = Array.prototype.slice.call(arguments, 1);
  17401. if (args.length <= 1) {
  17402. args = args[0];
  17403. }
  17404. callback.call(null, err, args);
  17405. });
  17406. }
  17407. }, callback);
  17408. }
  17409. else {
  17410. var results = {};
  17411. eachfn.each(_keys(tasks), function (k, callback) {
  17412. tasks[k](function (err) {
  17413. var args = Array.prototype.slice.call(arguments, 1);
  17414. if (args.length <= 1) {
  17415. args = args[0];
  17416. }
  17417. results[k] = args;
  17418. callback(err);
  17419. });
  17420. }, function (err) {
  17421. callback(err, results);
  17422. });
  17423. }
  17424. };
  17425. async.parallel = function (tasks, callback) {
  17426. _parallel({ map: async.map, each: async.each }, tasks, callback);
  17427. };
  17428. async.parallelLimit = function(tasks, limit, callback) {
  17429. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  17430. };
  17431. async.series = function (tasks, callback) {
  17432. callback = callback || function () {};
  17433. if (_isArray(tasks)) {
  17434. async.mapSeries(tasks, function (fn, callback) {
  17435. if (fn) {
  17436. fn(function (err) {
  17437. var args = Array.prototype.slice.call(arguments, 1);
  17438. if (args.length <= 1) {
  17439. args = args[0];
  17440. }
  17441. callback.call(null, err, args);
  17442. });
  17443. }
  17444. }, callback);
  17445. }
  17446. else {
  17447. var results = {};
  17448. async.eachSeries(_keys(tasks), function (k, callback) {
  17449. tasks[k](function (err) {
  17450. var args = Array.prototype.slice.call(arguments, 1);
  17451. if (args.length <= 1) {
  17452. args = args[0];
  17453. }
  17454. results[k] = args;
  17455. callback(err);
  17456. });
  17457. }, function (err) {
  17458. callback(err, results);
  17459. });
  17460. }
  17461. };
  17462. async.iterator = function (tasks) {
  17463. var makeCallback = function (index) {
  17464. var fn = function () {
  17465. if (tasks.length) {
  17466. tasks[index].apply(null, arguments);
  17467. }
  17468. return fn.next();
  17469. };
  17470. fn.next = function () {
  17471. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  17472. };
  17473. return fn;
  17474. };
  17475. return makeCallback(0);
  17476. };
  17477. async.apply = function (fn) {
  17478. var args = Array.prototype.slice.call(arguments, 1);
  17479. return function () {
  17480. return fn.apply(
  17481. null, args.concat(Array.prototype.slice.call(arguments))
  17482. );
  17483. };
  17484. };
  17485. var _concat = function (eachfn, arr, fn, callback) {
  17486. var r = [];
  17487. eachfn(arr, function (x, cb) {
  17488. fn(x, function (err, y) {
  17489. r = r.concat(y || []);
  17490. cb(err);
  17491. });
  17492. }, function (err) {
  17493. callback(err, r);
  17494. });
  17495. };
  17496. async.concat = doParallel(_concat);
  17497. async.concatSeries = doSeries(_concat);
  17498. async.whilst = function (test, iterator, callback) {
  17499. if (test()) {
  17500. iterator(function (err) {
  17501. if (err) {
  17502. return callback(err);
  17503. }
  17504. async.whilst(test, iterator, callback);
  17505. });
  17506. }
  17507. else {
  17508. callback();
  17509. }
  17510. };
  17511. async.doWhilst = function (iterator, test, callback) {
  17512. iterator(function (err) {
  17513. if (err) {
  17514. return callback(err);
  17515. }
  17516. var args = Array.prototype.slice.call(arguments, 1);
  17517. if (test.apply(null, args)) {
  17518. async.doWhilst(iterator, test, callback);
  17519. }
  17520. else {
  17521. callback();
  17522. }
  17523. });
  17524. };
  17525. async.until = function (test, iterator, callback) {
  17526. if (!test()) {
  17527. iterator(function (err) {
  17528. if (err) {
  17529. return callback(err);
  17530. }
  17531. async.until(test, iterator, callback);
  17532. });
  17533. }
  17534. else {
  17535. callback();
  17536. }
  17537. };
  17538. async.doUntil = function (iterator, test, callback) {
  17539. iterator(function (err) {
  17540. if (err) {
  17541. return callback(err);
  17542. }
  17543. var args = Array.prototype.slice.call(arguments, 1);
  17544. if (!test.apply(null, args)) {
  17545. async.doUntil(iterator, test, callback);
  17546. }
  17547. else {
  17548. callback();
  17549. }
  17550. });
  17551. };
  17552. async.queue = function (worker, concurrency) {
  17553. if (concurrency === undefined) {
  17554. concurrency = 1;
  17555. }
  17556. function _insert(q, data, pos, callback) {
  17557. if (!q.started){
  17558. q.started = true;
  17559. }
  17560. if (!_isArray(data)) {
  17561. data = [data];
  17562. }
  17563. if(data.length == 0) {
  17564. // call drain immediately if there are no tasks
  17565. return async.setImmediate(function() {
  17566. if (q.drain) {
  17567. q.drain();
  17568. }
  17569. });
  17570. }
  17571. _each(data, function(task) {
  17572. var item = {
  17573. data: task,
  17574. callback: typeof callback === 'function' ? callback : null
  17575. };
  17576. if (pos) {
  17577. q.tasks.unshift(item);
  17578. } else {
  17579. q.tasks.push(item);
  17580. }
  17581. if (q.saturated && q.tasks.length === q.concurrency) {
  17582. q.saturated();
  17583. }
  17584. async.setImmediate(q.process);
  17585. });
  17586. }
  17587. var workers = 0;
  17588. var q = {
  17589. tasks: [],
  17590. concurrency: concurrency,
  17591. saturated: null,
  17592. empty: null,
  17593. drain: null,
  17594. started: false,
  17595. paused: false,
  17596. push: function (data, callback) {
  17597. _insert(q, data, false, callback);
  17598. },
  17599. kill: function () {
  17600. q.drain = null;
  17601. q.tasks = [];
  17602. },
  17603. unshift: function (data, callback) {
  17604. _insert(q, data, true, callback);
  17605. },
  17606. process: function () {
  17607. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  17608. var task = q.tasks.shift();
  17609. if (q.empty && q.tasks.length === 0) {
  17610. q.empty();
  17611. }
  17612. workers += 1;
  17613. var next = function () {
  17614. workers -= 1;
  17615. if (task.callback) {
  17616. task.callback.apply(task, arguments);
  17617. }
  17618. if (q.drain && q.tasks.length + workers === 0) {
  17619. q.drain();
  17620. }
  17621. q.process();
  17622. };
  17623. var cb = only_once(next);
  17624. worker(task.data, cb);
  17625. }
  17626. },
  17627. length: function () {
  17628. return q.tasks.length;
  17629. },
  17630. running: function () {
  17631. return workers;
  17632. },
  17633. idle: function() {
  17634. return q.tasks.length + workers === 0;
  17635. },
  17636. pause: function () {
  17637. if (q.paused === true) { return; }
  17638. q.paused = true;
  17639. q.process();
  17640. },
  17641. resume: function () {
  17642. if (q.paused === false) { return; }
  17643. q.paused = false;
  17644. q.process();
  17645. }
  17646. };
  17647. return q;
  17648. };
  17649. async.priorityQueue = function (worker, concurrency) {
  17650. function _compareTasks(a, b){
  17651. return a.priority - b.priority;
  17652. };
  17653. function _binarySearch(sequence, item, compare) {
  17654. var beg = -1,
  17655. end = sequence.length - 1;
  17656. while (beg < end) {
  17657. var mid = beg + ((end - beg + 1) >>> 1);
  17658. if (compare(item, sequence[mid]) >= 0) {
  17659. beg = mid;
  17660. } else {
  17661. end = mid - 1;
  17662. }
  17663. }
  17664. return beg;
  17665. }
  17666. function _insert(q, data, priority, callback) {
  17667. if (!q.started){
  17668. q.started = true;
  17669. }
  17670. if (!_isArray(data)) {
  17671. data = [data];
  17672. }
  17673. if(data.length == 0) {
  17674. // call drain immediately if there are no tasks
  17675. return async.setImmediate(function() {
  17676. if (q.drain) {
  17677. q.drain();
  17678. }
  17679. });
  17680. }
  17681. _each(data, function(task) {
  17682. var item = {
  17683. data: task,
  17684. priority: priority,
  17685. callback: typeof callback === 'function' ? callback : null
  17686. };
  17687. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  17688. if (q.saturated && q.tasks.length === q.concurrency) {
  17689. q.saturated();
  17690. }
  17691. async.setImmediate(q.process);
  17692. });
  17693. }
  17694. // Start with a normal queue
  17695. var q = async.queue(worker, concurrency);
  17696. // Override push to accept second parameter representing priority
  17697. q.push = function (data, priority, callback) {
  17698. _insert(q, data, priority, callback);
  17699. };
  17700. // Remove unshift function
  17701. delete q.unshift;
  17702. return q;
  17703. };
  17704. async.cargo = function (worker, payload) {
  17705. var working = false,
  17706. tasks = [];
  17707. var cargo = {
  17708. tasks: tasks,
  17709. payload: payload,
  17710. saturated: null,
  17711. empty: null,
  17712. drain: null,
  17713. drained: true,
  17714. push: function (data, callback) {
  17715. if (!_isArray(data)) {
  17716. data = [data];
  17717. }
  17718. _each(data, function(task) {
  17719. tasks.push({
  17720. data: task,
  17721. callback: typeof callback === 'function' ? callback : null
  17722. });
  17723. cargo.drained = false;
  17724. if (cargo.saturated && tasks.length === payload) {
  17725. cargo.saturated();
  17726. }
  17727. });
  17728. async.setImmediate(cargo.process);
  17729. },
  17730. process: function process() {
  17731. if (working) return;
  17732. if (tasks.length === 0) {
  17733. if(cargo.drain && !cargo.drained) cargo.drain();
  17734. cargo.drained = true;
  17735. return;
  17736. }
  17737. var ts = typeof payload === 'number'
  17738. ? tasks.splice(0, payload)
  17739. : tasks.splice(0, tasks.length);
  17740. var ds = _map(ts, function (task) {
  17741. return task.data;
  17742. });
  17743. if(cargo.empty) cargo.empty();
  17744. working = true;
  17745. worker(ds, function () {
  17746. working = false;
  17747. var args = arguments;
  17748. _each(ts, function (data) {
  17749. if (data.callback) {
  17750. data.callback.apply(null, args);
  17751. }
  17752. });
  17753. process();
  17754. });
  17755. },
  17756. length: function () {
  17757. return tasks.length;
  17758. },
  17759. running: function () {
  17760. return working;
  17761. }
  17762. };
  17763. return cargo;
  17764. };
  17765. var _console_fn = function (name) {
  17766. return function (fn) {
  17767. var args = Array.prototype.slice.call(arguments, 1);
  17768. fn.apply(null, args.concat([function (err) {
  17769. var args = Array.prototype.slice.call(arguments, 1);
  17770. if (typeof console !== 'undefined') {
  17771. if (err) {
  17772. if (console.error) {
  17773. console.error(err);
  17774. }
  17775. }
  17776. else if (console[name]) {
  17777. _each(args, function (x) {
  17778. console[name](x);
  17779. });
  17780. }
  17781. }
  17782. }]));
  17783. };
  17784. };
  17785. async.log = _console_fn('log');
  17786. async.dir = _console_fn('dir');
  17787. /*async.info = _console_fn('info');
  17788. async.warn = _console_fn('warn');
  17789. async.error = _console_fn('error');*/
  17790. async.memoize = function (fn, hasher) {
  17791. var memo = {};
  17792. var queues = {};
  17793. hasher = hasher || function (x) {
  17794. return x;
  17795. };
  17796. var memoized = function () {
  17797. var args = Array.prototype.slice.call(arguments);
  17798. var callback = args.pop();
  17799. var key = hasher.apply(null, args);
  17800. if (key in memo) {
  17801. async.nextTick(function () {
  17802. callback.apply(null, memo[key]);
  17803. });
  17804. }
  17805. else if (key in queues) {
  17806. queues[key].push(callback);
  17807. }
  17808. else {
  17809. queues[key] = [callback];
  17810. fn.apply(null, args.concat([function () {
  17811. memo[key] = arguments;
  17812. var q = queues[key];
  17813. delete queues[key];
  17814. for (var i = 0, l = q.length; i < l; i++) {
  17815. q[i].apply(null, arguments);
  17816. }
  17817. }]));
  17818. }
  17819. };
  17820. memoized.memo = memo;
  17821. memoized.unmemoized = fn;
  17822. return memoized;
  17823. };
  17824. async.unmemoize = function (fn) {
  17825. return function () {
  17826. return (fn.unmemoized || fn).apply(null, arguments);
  17827. };
  17828. };
  17829. async.times = function (count, iterator, callback) {
  17830. var counter = [];
  17831. for (var i = 0; i < count; i++) {
  17832. counter.push(i);
  17833. }
  17834. return async.map(counter, iterator, callback);
  17835. };
  17836. async.timesSeries = function (count, iterator, callback) {
  17837. var counter = [];
  17838. for (var i = 0; i < count; i++) {
  17839. counter.push(i);
  17840. }
  17841. return async.mapSeries(counter, iterator, callback);
  17842. };
  17843. async.seq = function (/* functions... */) {
  17844. var fns = arguments;
  17845. return function () {
  17846. var that = this;
  17847. var args = Array.prototype.slice.call(arguments);
  17848. var callback = args.pop();
  17849. async.reduce(fns, args, function (newargs, fn, cb) {
  17850. fn.apply(that, newargs.concat([function () {
  17851. var err = arguments[0];
  17852. var nextargs = Array.prototype.slice.call(arguments, 1);
  17853. cb(err, nextargs);
  17854. }]))
  17855. },
  17856. function (err, results) {
  17857. callback.apply(that, [err].concat(results));
  17858. });
  17859. };
  17860. };
  17861. async.compose = function (/* functions... */) {
  17862. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  17863. };
  17864. var _applyEach = function (eachfn, fns /*args...*/) {
  17865. var go = function () {
  17866. var that = this;
  17867. var args = Array.prototype.slice.call(arguments);
  17868. var callback = args.pop();
  17869. return eachfn(fns, function (fn, cb) {
  17870. fn.apply(that, args.concat([cb]));
  17871. },
  17872. callback);
  17873. };
  17874. if (arguments.length > 2) {
  17875. var args = Array.prototype.slice.call(arguments, 2);
  17876. return go.apply(this, args);
  17877. }
  17878. else {
  17879. return go;
  17880. }
  17881. };
  17882. async.applyEach = doParallel(_applyEach);
  17883. async.applyEachSeries = doSeries(_applyEach);
  17884. async.forever = function (fn, callback) {
  17885. function next(err) {
  17886. if (err) {
  17887. if (callback) {
  17888. return callback(err);
  17889. }
  17890. throw err;
  17891. }
  17892. fn(next);
  17893. }
  17894. next();
  17895. };
  17896. // Node.js
  17897. if (typeof module !== 'undefined' && module.exports) {
  17898. module.exports = async;
  17899. }
  17900. // AMD / RequireJS
  17901. else if (typeof define !== 'undefined' && define.amd) {
  17902. define([], function () {
  17903. return async;
  17904. });
  17905. }
  17906. // included directly via <script> tag
  17907. else {
  17908. root.async = async;
  17909. }
  17910. }());
  17911. }).call(this,require('_process'))
  17912. },{"_process":2}],71:[function(require,module,exports){
  17913. // i18next, v1.7.7
  17914. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  17915. // Distributed under MIT license
  17916. // http://i18next.com
  17917. (function() {
  17918. // add indexOf to non ECMA-262 standard compliant browsers
  17919. if (!Array.prototype.indexOf) {
  17920. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  17921. "use strict";
  17922. if (this == null) {
  17923. throw new TypeError();
  17924. }
  17925. var t = Object(this);
  17926. var len = t.length >>> 0;
  17927. if (len === 0) {
  17928. return -1;
  17929. }
  17930. var n = 0;
  17931. if (arguments.length > 0) {
  17932. n = Number(arguments[1]);
  17933. if (n != n) { // shortcut for verifying if it's NaN
  17934. n = 0;
  17935. } else if (n != 0 && n != Infinity && n != -Infinity) {
  17936. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  17937. }
  17938. }
  17939. if (n >= len) {
  17940. return -1;
  17941. }
  17942. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  17943. for (; k < len; k++) {
  17944. if (k in t && t[k] === searchElement) {
  17945. return k;
  17946. }
  17947. }
  17948. return -1;
  17949. }
  17950. }
  17951. // add lastIndexOf to non ECMA-262 standard compliant browsers
  17952. if (!Array.prototype.lastIndexOf) {
  17953. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  17954. "use strict";
  17955. if (this == null) {
  17956. throw new TypeError();
  17957. }
  17958. var t = Object(this);
  17959. var len = t.length >>> 0;
  17960. if (len === 0) {
  17961. return -1;
  17962. }
  17963. var n = len;
  17964. if (arguments.length > 1) {
  17965. n = Number(arguments[1]);
  17966. if (n != n) {
  17967. n = 0;
  17968. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  17969. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  17970. }
  17971. }
  17972. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  17973. for (; k >= 0; k--) {
  17974. if (k in t && t[k] === searchElement) {
  17975. return k;
  17976. }
  17977. }
  17978. return -1;
  17979. };
  17980. }
  17981. // Add string trim for IE8.
  17982. if (typeof String.prototype.trim !== 'function') {
  17983. String.prototype.trim = function() {
  17984. return this.replace(/^\s+|\s+$/g, '');
  17985. }
  17986. }
  17987. var root = this
  17988. , $ = root.jQuery || root.Zepto
  17989. , i18n = {}
  17990. , resStore = {}
  17991. , currentLng
  17992. , replacementCounter = 0
  17993. , languages = []
  17994. , initialized = false
  17995. , sync = {};
  17996. // Export the i18next object for **CommonJS**.
  17997. // If we're not in CommonJS, add `i18n` to the
  17998. // global object or to jquery.
  17999. if (typeof module !== 'undefined' && module.exports) {
  18000. if (!$) {
  18001. try {
  18002. $ = require('jquery');
  18003. } catch(e) {
  18004. // just ignore
  18005. }
  18006. }
  18007. if ($) {
  18008. $.i18n = $.i18n || i18n;
  18009. }
  18010. module.exports = i18n;
  18011. } else {
  18012. if ($) {
  18013. $.i18n = $.i18n || i18n;
  18014. }
  18015. root.i18n = root.i18n || i18n;
  18016. }
  18017. sync = {
  18018. load: function(lngs, options, cb) {
  18019. if (options.useLocalStorage) {
  18020. sync._loadLocal(lngs, options, function(err, store) {
  18021. var missingLngs = [];
  18022. for (var i = 0, len = lngs.length; i < len; i++) {
  18023. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  18024. }
  18025. if (missingLngs.length > 0) {
  18026. sync._fetch(missingLngs, options, function(err, fetched) {
  18027. f.extend(store, fetched);
  18028. sync._storeLocal(fetched);
  18029. cb(null, store);
  18030. });
  18031. } else {
  18032. cb(null, store);
  18033. }
  18034. });
  18035. } else {
  18036. sync._fetch(lngs, options, function(err, store){
  18037. cb(null, store);
  18038. });
  18039. }
  18040. },
  18041. _loadLocal: function(lngs, options, cb) {
  18042. var store = {}
  18043. , nowMS = new Date().getTime();
  18044. if(window.localStorage) {
  18045. var todo = lngs.length;
  18046. f.each(lngs, function(key, lng) {
  18047. var local = window.localStorage.getItem('res_' + lng);
  18048. if (local) {
  18049. local = JSON.parse(local);
  18050. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  18051. store[lng] = local;
  18052. }
  18053. }
  18054. todo--; // wait for all done befor callback
  18055. if (todo === 0) cb(null, store);
  18056. });
  18057. }
  18058. },
  18059. _storeLocal: function(store) {
  18060. if(window.localStorage) {
  18061. for (var m in store) {
  18062. store[m].i18nStamp = new Date().getTime();
  18063. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  18064. }
  18065. }
  18066. return;
  18067. },
  18068. _fetch: function(lngs, options, cb) {
  18069. var ns = options.ns
  18070. , store = {};
  18071. if (!options.dynamicLoad) {
  18072. var todo = ns.namespaces.length * lngs.length
  18073. , errors;
  18074. // load each file individual
  18075. f.each(ns.namespaces, function(nsIndex, nsValue) {
  18076. f.each(lngs, function(lngIndex, lngValue) {
  18077. // Call this once our translation has returned.
  18078. var loadComplete = function(err, data) {
  18079. if (err) {
  18080. errors = errors || [];
  18081. errors.push(err);
  18082. }
  18083. store[lngValue] = store[lngValue] || {};
  18084. store[lngValue][nsValue] = data;
  18085. todo--; // wait for all done befor callback
  18086. if (todo === 0) cb(errors, store);
  18087. };
  18088. if(typeof options.customLoad == 'function'){
  18089. // Use the specified custom callback.
  18090. options.customLoad(lngValue, nsValue, options, loadComplete);
  18091. } else {
  18092. //~ // Use our inbuilt sync.
  18093. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  18094. }
  18095. });
  18096. });
  18097. } else {
  18098. // Call this once our translation has returned.
  18099. var loadComplete = function(err, data) {
  18100. cb(null, data);
  18101. };
  18102. if(typeof options.customLoad == 'function'){
  18103. // Use the specified custom callback.
  18104. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  18105. } else {
  18106. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  18107. // load all needed stuff once
  18108. f.ajax({
  18109. url: url,
  18110. success: function(data, status, xhr) {
  18111. f.log('loaded: ' + url);
  18112. loadComplete(null, data);
  18113. },
  18114. error : function(xhr, status, error) {
  18115. f.log('failed loading: ' + url);
  18116. loadComplete('failed loading resource.json error: ' + error);
  18117. },
  18118. dataType: "json",
  18119. async : options.getAsync
  18120. });
  18121. }
  18122. }
  18123. },
  18124. _fetchOne: function(lng, ns, options, done) {
  18125. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  18126. f.ajax({
  18127. url: url,
  18128. success: function(data, status, xhr) {
  18129. f.log('loaded: ' + url);
  18130. done(null, data);
  18131. },
  18132. error : function(xhr, status, error) {
  18133. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  18134. // file loaded but invalid json, stop waste time !
  18135. f.error('There is a typo in: ' + url);
  18136. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  18137. f.log('Does not exist: ' + url);
  18138. } else {
  18139. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  18140. f.log(theStatus + ' when loading ' + url);
  18141. }
  18142. done(error, {});
  18143. },
  18144. dataType: "json",
  18145. async : options.getAsync
  18146. });
  18147. },
  18148. postMissing: function(lng, ns, key, defaultValue, lngs) {
  18149. var payload = {};
  18150. payload[key] = defaultValue;
  18151. var urls = [];
  18152. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  18153. for (var i = 0; i < o.fallbackLng.length; i++) {
  18154. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  18155. }
  18156. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  18157. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  18158. } else if (o.sendMissingTo === 'all') {
  18159. for (var i = 0, l = lngs.length; i < l; i++) {
  18160. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  18161. }
  18162. }
  18163. for (var y = 0, len = urls.length; y < len; y++) {
  18164. var item = urls[y];
  18165. f.ajax({
  18166. url: item.url,
  18167. type: o.sendType,
  18168. data: payload,
  18169. success: function(data, status, xhr) {
  18170. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  18171. // add key to resStore
  18172. var keys = key.split('.');
  18173. var x = 0;
  18174. var value = resStore[item.lng][ns];
  18175. while (keys[x]) {
  18176. if (x === keys.length - 1) {
  18177. value = value[keys[x]] = defaultValue;
  18178. } else {
  18179. value = value[keys[x]] = value[keys[x]] || {};
  18180. }
  18181. x++;
  18182. }
  18183. },
  18184. error : function(xhr, status, error) {
  18185. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  18186. },
  18187. dataType: "json",
  18188. async : o.postAsync
  18189. });
  18190. }
  18191. },
  18192. reload: reload
  18193. };
  18194. // defaults
  18195. var o = {
  18196. lng: undefined,
  18197. load: 'all',
  18198. preload: [],
  18199. lowerCaseLng: false,
  18200. returnObjectTrees: false,
  18201. fallbackLng: ['dev'],
  18202. fallbackNS: [],
  18203. detectLngQS: 'setLng',
  18204. detectLngFromLocalStorage: false,
  18205. ns: 'translation',
  18206. fallbackOnNull: true,
  18207. fallbackOnEmpty: false,
  18208. fallbackToDefaultNS: false,
  18209. nsseparator: ':',
  18210. keyseparator: '.',
  18211. selectorAttr: 'data-i18n',
  18212. debug: false,
  18213. resGetPath: 'locales/__lng__/__ns__.json',
  18214. resPostPath: 'locales/add/__lng__/__ns__',
  18215. getAsync: true,
  18216. postAsync: true,
  18217. resStore: undefined,
  18218. useLocalStorage: false,
  18219. localStorageExpirationTime: 7*24*60*60*1000,
  18220. dynamicLoad: false,
  18221. sendMissing: false,
  18222. sendMissingTo: 'fallback', // current | all
  18223. sendType: 'POST',
  18224. interpolationPrefix: '__',
  18225. interpolationSuffix: '__',
  18226. defaultVariables: false,
  18227. reusePrefix: '$t(',
  18228. reuseSuffix: ')',
  18229. pluralSuffix: '_plural',
  18230. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  18231. contextNotFound: ['context_not_found', Math.random()].join(''),
  18232. escapeInterpolation: false,
  18233. indefiniteSuffix: '_indefinite',
  18234. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  18235. setJqueryExt: true,
  18236. defaultValueFromContent: true,
  18237. useDataAttrOptions: false,
  18238. cookieExpirationTime: undefined,
  18239. useCookie: true,
  18240. cookieName: 'i18next',
  18241. cookieDomain: undefined,
  18242. objectTreeKeyHandler: undefined,
  18243. postProcess: undefined,
  18244. parseMissingKey: undefined,
  18245. missingKeyHandler: sync.postMissing,
  18246. shortcutFunction: 'sprintf' // or: defaultValue
  18247. };
  18248. function _extend(target, source) {
  18249. if (!source || typeof source === 'function') {
  18250. return target;
  18251. }
  18252. for (var attr in source) { target[attr] = source[attr]; }
  18253. return target;
  18254. }
  18255. function _deepExtend(target, source) {
  18256. for (var prop in source)
  18257. if (prop in target)
  18258. _deepExtend(target[prop], source[prop]);
  18259. else
  18260. target[prop] = source[prop];
  18261. return target;
  18262. }
  18263. function _each(object, callback, args) {
  18264. var name, i = 0,
  18265. length = object.length,
  18266. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  18267. if (args) {
  18268. if (isObj) {
  18269. for (name in object) {
  18270. if (callback.apply(object[name], args) === false) {
  18271. break;
  18272. }
  18273. }
  18274. } else {
  18275. for ( ; i < length; ) {
  18276. if (callback.apply(object[i++], args) === false) {
  18277. break;
  18278. }
  18279. }
  18280. }
  18281. // A special, fast, case for the most common use of each
  18282. } else {
  18283. if (isObj) {
  18284. for (name in object) {
  18285. if (callback.call(object[name], name, object[name]) === false) {
  18286. break;
  18287. }
  18288. }
  18289. } else {
  18290. for ( ; i < length; ) {
  18291. if (callback.call(object[i], i, object[i++]) === false) {
  18292. break;
  18293. }
  18294. }
  18295. }
  18296. }
  18297. return object;
  18298. }
  18299. var _entityMap = {
  18300. "&": "&amp;",
  18301. "<": "&lt;",
  18302. ">": "&gt;",
  18303. '"': '&quot;',
  18304. "'": '&#39;',
  18305. "/": '&#x2F;'
  18306. };
  18307. function _escape(data) {
  18308. if (typeof data === 'string') {
  18309. return data.replace(/[&<>"'\/]/g, function (s) {
  18310. return _entityMap[s];
  18311. });
  18312. }else{
  18313. return data;
  18314. }
  18315. }
  18316. function _ajax(options) {
  18317. // v0.5.0 of https://github.com/goloroden/http.js
  18318. var getXhr = function (callback) {
  18319. // Use the native XHR object if the browser supports it.
  18320. if (window.XMLHttpRequest) {
  18321. return callback(null, new XMLHttpRequest());
  18322. } else if (window.ActiveXObject) {
  18323. // In Internet Explorer check for ActiveX versions of the XHR object.
  18324. try {
  18325. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  18326. } catch (e) {
  18327. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  18328. }
  18329. }
  18330. // If no XHR support was found, throw an error.
  18331. return callback(new Error());
  18332. };
  18333. var encodeUsingUrlEncoding = function (data) {
  18334. if(typeof data === 'string') {
  18335. return data;
  18336. }
  18337. var result = [];
  18338. for(var dataItem in data) {
  18339. if(data.hasOwnProperty(dataItem)) {
  18340. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  18341. }
  18342. }
  18343. return result.join('&');
  18344. };
  18345. var utf8 = function (text) {
  18346. text = text.replace(/\r\n/g, '\n');
  18347. var result = '';
  18348. for(var i = 0; i < text.length; i++) {
  18349. var c = text.charCodeAt(i);
  18350. if(c < 128) {
  18351. result += String.fromCharCode(c);
  18352. } else if((c > 127) && (c < 2048)) {
  18353. result += String.fromCharCode((c >> 6) | 192);
  18354. result += String.fromCharCode((c & 63) | 128);
  18355. } else {
  18356. result += String.fromCharCode((c >> 12) | 224);
  18357. result += String.fromCharCode(((c >> 6) & 63) | 128);
  18358. result += String.fromCharCode((c & 63) | 128);
  18359. }
  18360. }
  18361. return result;
  18362. };
  18363. var base64 = function (text) {
  18364. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  18365. text = utf8(text);
  18366. var result = '',
  18367. chr1, chr2, chr3,
  18368. enc1, enc2, enc3, enc4,
  18369. i = 0;
  18370. do {
  18371. chr1 = text.charCodeAt(i++);
  18372. chr2 = text.charCodeAt(i++);
  18373. chr3 = text.charCodeAt(i++);
  18374. enc1 = chr1 >> 2;
  18375. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  18376. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  18377. enc4 = chr3 & 63;
  18378. if(isNaN(chr2)) {
  18379. enc3 = enc4 = 64;
  18380. } else if(isNaN(chr3)) {
  18381. enc4 = 64;
  18382. }
  18383. result +=
  18384. keyStr.charAt(enc1) +
  18385. keyStr.charAt(enc2) +
  18386. keyStr.charAt(enc3) +
  18387. keyStr.charAt(enc4);
  18388. chr1 = chr2 = chr3 = '';
  18389. enc1 = enc2 = enc3 = enc4 = '';
  18390. } while(i < text.length);
  18391. return result;
  18392. };
  18393. var mergeHeaders = function () {
  18394. // Use the first header object as base.
  18395. var result = arguments[0];
  18396. // Iterate through the remaining header objects and add them.
  18397. for(var i = 1; i < arguments.length; i++) {
  18398. var currentHeaders = arguments[i];
  18399. for(var header in currentHeaders) {
  18400. if(currentHeaders.hasOwnProperty(header)) {
  18401. result[header] = currentHeaders[header];
  18402. }
  18403. }
  18404. }
  18405. // Return the merged headers.
  18406. return result;
  18407. };
  18408. var ajax = function (method, url, options, callback) {
  18409. // Adjust parameters.
  18410. if(typeof options === 'function') {
  18411. callback = options;
  18412. options = {};
  18413. }
  18414. // Set default parameter values.
  18415. options.cache = options.cache || false;
  18416. options.data = options.data || {};
  18417. options.headers = options.headers || {};
  18418. options.jsonp = options.jsonp || false;
  18419. options.async = options.async === undefined ? true : options.async;
  18420. // Merge the various header objects.
  18421. var headers = mergeHeaders({
  18422. 'accept': '*/*',
  18423. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  18424. }, ajax.headers, options.headers);
  18425. // Encode the data according to the content-type.
  18426. var payload;
  18427. if (headers['content-type'] === 'application/json') {
  18428. payload = JSON.stringify(options.data);
  18429. } else {
  18430. payload = encodeUsingUrlEncoding(options.data);
  18431. }
  18432. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  18433. // if neccessary.
  18434. if(method === 'GET') {
  18435. // Setup the query string.
  18436. var queryString = [];
  18437. if(payload) {
  18438. queryString.push(payload);
  18439. payload = null;
  18440. }
  18441. // Handle caching.
  18442. if(!options.cache) {
  18443. queryString.push('_=' + (new Date()).getTime());
  18444. }
  18445. // If neccessary prepare the query string for a JSONP call.
  18446. if(options.jsonp) {
  18447. queryString.push('callback=' + options.jsonp);
  18448. queryString.push('jsonp=' + options.jsonp);
  18449. }
  18450. // Merge the query string and attach it to the url.
  18451. queryString = queryString.join('&');
  18452. if (queryString.length > 1) {
  18453. if (url.indexOf('?') > -1) {
  18454. url += '&' + queryString;
  18455. } else {
  18456. url += '?' + queryString;
  18457. }
  18458. }
  18459. // Make a JSONP call if neccessary.
  18460. if(options.jsonp) {
  18461. var head = document.getElementsByTagName('head')[0];
  18462. var script = document.createElement('script');
  18463. script.type = 'text/javascript';
  18464. script.src = url;
  18465. head.appendChild(script);
  18466. return;
  18467. }
  18468. }
  18469. // Since we got here, it is no JSONP request, so make a normal XHR request.
  18470. getXhr(function (err, xhr) {
  18471. if(err) return callback(err);
  18472. // Open the request.
  18473. xhr.open(method, url, options.async);
  18474. // Set the request headers.
  18475. for(var header in headers) {
  18476. if(headers.hasOwnProperty(header)) {
  18477. xhr.setRequestHeader(header, headers[header]);
  18478. }
  18479. }
  18480. // Handle the request events.
  18481. xhr.onreadystatechange = function () {
  18482. if(xhr.readyState === 4) {
  18483. var data = xhr.responseText || '';
  18484. // If no callback is given, return.
  18485. if(!callback) {
  18486. return;
  18487. }
  18488. // Return an object that provides access to the data as text and JSON.
  18489. callback(xhr.status, {
  18490. text: function () {
  18491. return data;
  18492. },
  18493. json: function () {
  18494. try {
  18495. return JSON.parse(data)
  18496. } catch (e) {
  18497. f.error('Can not parse JSON. URL: ' + url);
  18498. return {};
  18499. }
  18500. }
  18501. });
  18502. }
  18503. };
  18504. // Actually send the XHR request.
  18505. xhr.send(payload);
  18506. });
  18507. };
  18508. // Define the external interface.
  18509. var http = {
  18510. authBasic: function (username, password) {
  18511. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  18512. },
  18513. connect: function (url, options, callback) {
  18514. return ajax('CONNECT', url, options, callback);
  18515. },
  18516. del: function (url, options, callback) {
  18517. return ajax('DELETE', url, options, callback);
  18518. },
  18519. get: function (url, options, callback) {
  18520. return ajax('GET', url, options, callback);
  18521. },
  18522. head: function (url, options, callback) {
  18523. return ajax('HEAD', url, options, callback);
  18524. },
  18525. headers: function (headers) {
  18526. ajax.headers = headers || {};
  18527. },
  18528. isAllowed: function (url, verb, callback) {
  18529. this.options(url, function (status, data) {
  18530. callback(data.text().indexOf(verb) !== -1);
  18531. });
  18532. },
  18533. options: function (url, options, callback) {
  18534. return ajax('OPTIONS', url, options, callback);
  18535. },
  18536. patch: function (url, options, callback) {
  18537. return ajax('PATCH', url, options, callback);
  18538. },
  18539. post: function (url, options, callback) {
  18540. return ajax('POST', url, options, callback);
  18541. },
  18542. put: function (url, options, callback) {
  18543. return ajax('PUT', url, options, callback);
  18544. },
  18545. trace: function (url, options, callback) {
  18546. return ajax('TRACE', url, options, callback);
  18547. }
  18548. };
  18549. var methode = options.type ? options.type.toLowerCase() : 'get';
  18550. http[methode](options.url, options, function (status, data) {
  18551. // file: protocol always gives status code 0, so check for data
  18552. if (status === 200 || (status === 0 && data.text())) {
  18553. options.success(data.json(), status, null);
  18554. } else {
  18555. options.error(data.text(), status, null);
  18556. }
  18557. });
  18558. }
  18559. var _cookie = {
  18560. create: function(name,value,minutes,domain) {
  18561. var expires;
  18562. if (minutes) {
  18563. var date = new Date();
  18564. date.setTime(date.getTime()+(minutes*60*1000));
  18565. expires = "; expires="+date.toGMTString();
  18566. }
  18567. else expires = "";
  18568. domain = (domain)? "domain="+domain+";" : "";
  18569. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  18570. },
  18571. read: function(name) {
  18572. var nameEQ = name + "=";
  18573. var ca = document.cookie.split(';');
  18574. for(var i=0;i < ca.length;i++) {
  18575. var c = ca[i];
  18576. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  18577. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  18578. }
  18579. return null;
  18580. },
  18581. remove: function(name) {
  18582. this.create(name,"",-1);
  18583. }
  18584. };
  18585. var cookie_noop = {
  18586. create: function(name,value,minutes,domain) {},
  18587. read: function(name) { return null; },
  18588. remove: function(name) {}
  18589. };
  18590. // move dependent functions to a container so that
  18591. // they can be overriden easier in no jquery environment (node.js)
  18592. var f = {
  18593. extend: $ ? $.extend : _extend,
  18594. deepExtend: _deepExtend,
  18595. each: $ ? $.each : _each,
  18596. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  18597. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  18598. detectLanguage: detectLanguage,
  18599. escape: _escape,
  18600. log: function(str) {
  18601. if (o.debug && typeof console !== "undefined") console.log(str);
  18602. },
  18603. error: function(str) {
  18604. if (typeof console !== "undefined") console.error(str);
  18605. },
  18606. getCountyIndexOfLng: function(lng) {
  18607. var lng_index = 0;
  18608. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  18609. return lng_index;
  18610. },
  18611. toLanguages: function(lng) {
  18612. var log = this.log;
  18613. function applyCase(l) {
  18614. var ret = l;
  18615. if (typeof l === 'string' && l.indexOf('-') > -1) {
  18616. var parts = l.split('-');
  18617. ret = o.lowerCaseLng ?
  18618. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  18619. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  18620. } else {
  18621. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  18622. }
  18623. return ret;
  18624. }
  18625. var languages = [];
  18626. var whitelist = o.lngWhitelist || false;
  18627. var addLanguage = function(language){
  18628. //reject langs not whitelisted
  18629. if(!whitelist || whitelist.indexOf(language) > -1){
  18630. languages.push(language);
  18631. }else{
  18632. log('rejecting non-whitelisted language: ' + language);
  18633. }
  18634. };
  18635. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  18636. var parts = lng.split('-');
  18637. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  18638. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  18639. } else {
  18640. addLanguage(applyCase(lng));
  18641. }
  18642. for (var i = 0; i < o.fallbackLng.length; i++) {
  18643. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  18644. }
  18645. return languages;
  18646. },
  18647. regexEscape: function(str) {
  18648. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  18649. },
  18650. regexReplacementEscape: function(strOrFn) {
  18651. if (typeof strOrFn === 'string') {
  18652. return strOrFn.replace(/\$/g, "$$$$");
  18653. } else {
  18654. return strOrFn;
  18655. }
  18656. },
  18657. localStorage: {
  18658. setItem: function(key, value) {
  18659. if (window.localStorage) {
  18660. try {
  18661. window.localStorage.setItem(key, value);
  18662. } catch (e) {
  18663. f.log('failed to set value for key "' + key + '" to localStorage.');
  18664. }
  18665. }
  18666. }
  18667. }
  18668. };
  18669. function init(options, cb) {
  18670. if (typeof options === 'function') {
  18671. cb = options;
  18672. options = {};
  18673. }
  18674. options = options || {};
  18675. // override defaults with passed in options
  18676. f.extend(o, options);
  18677. delete o.fixLng; /* passed in each time */
  18678. // override functions: .log(), .detectLanguage(), etc
  18679. if (o.functions) {
  18680. delete o.functions;
  18681. f.extend(f, options.functions);
  18682. }
  18683. // create namespace object if namespace is passed in as string
  18684. if (typeof o.ns == 'string') {
  18685. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  18686. }
  18687. // fallback namespaces
  18688. if (typeof o.fallbackNS == 'string') {
  18689. o.fallbackNS = [o.fallbackNS];
  18690. }
  18691. // fallback languages
  18692. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  18693. o.fallbackLng = [o.fallbackLng];
  18694. }
  18695. // escape prefix/suffix
  18696. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  18697. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  18698. if (!o.lng) o.lng = f.detectLanguage();
  18699. languages = f.toLanguages(o.lng);
  18700. currentLng = languages[0];
  18701. f.log('currentLng set to: ' + currentLng);
  18702. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  18703. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  18704. }
  18705. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  18706. f.localStorage.setItem('i18next_lng', currentLng);
  18707. }
  18708. var lngTranslate = translate;
  18709. if (options.fixLng) {
  18710. lngTranslate = function(key, options) {
  18711. options = options || {};
  18712. options.lng = options.lng || lngTranslate.lng;
  18713. return translate(key, options);
  18714. };
  18715. lngTranslate.lng = currentLng;
  18716. }
  18717. pluralExtensions.setCurrentLng(currentLng);
  18718. // add JQuery extensions
  18719. if ($ && o.setJqueryExt) addJqueryFunct();
  18720. // jQuery deferred
  18721. var deferred;
  18722. if ($ && $.Deferred) {
  18723. deferred = $.Deferred();
  18724. }
  18725. // return immidiatly if res are passed in
  18726. if (o.resStore) {
  18727. resStore = o.resStore;
  18728. initialized = true;
  18729. if (cb) cb(lngTranslate);
  18730. if (deferred) deferred.resolve(lngTranslate);
  18731. if (deferred) return deferred.promise();
  18732. return;
  18733. }
  18734. // languages to load
  18735. var lngsToLoad = f.toLanguages(o.lng);
  18736. if (typeof o.preload === 'string') o.preload = [o.preload];
  18737. for (var i = 0, l = o.preload.length; i < l; i++) {
  18738. var pres = f.toLanguages(o.preload[i]);
  18739. for (var y = 0, len = pres.length; y < len; y++) {
  18740. if (lngsToLoad.indexOf(pres[y]) < 0) {
  18741. lngsToLoad.push(pres[y]);
  18742. }
  18743. }
  18744. }
  18745. // else load them
  18746. i18n.sync.load(lngsToLoad, o, function(err, store) {
  18747. resStore = store;
  18748. initialized = true;
  18749. if (cb) cb(lngTranslate);
  18750. if (deferred) deferred.resolve(lngTranslate);
  18751. });
  18752. if (deferred) return deferred.promise();
  18753. }
  18754. function preload(lngs, cb) {
  18755. if (typeof lngs === 'string') lngs = [lngs];
  18756. for (var i = 0, l = lngs.length; i < l; i++) {
  18757. if (o.preload.indexOf(lngs[i]) < 0) {
  18758. o.preload.push(lngs[i]);
  18759. }
  18760. }
  18761. return init(cb);
  18762. }
  18763. function addResourceBundle(lng, ns, resources, deep) {
  18764. if (typeof ns !== 'string') {
  18765. resources = ns;
  18766. ns = o.ns.defaultNs;
  18767. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18768. o.ns.namespaces.push(ns);
  18769. }
  18770. resStore[lng] = resStore[lng] || {};
  18771. resStore[lng][ns] = resStore[lng][ns] || {};
  18772. if (deep) {
  18773. f.deepExtend(resStore[lng][ns], resources);
  18774. } else {
  18775. f.extend(resStore[lng][ns], resources);
  18776. }
  18777. }
  18778. function hasResourceBundle(lng, ns) {
  18779. if (typeof ns !== 'string') {
  18780. ns = o.ns.defaultNs;
  18781. }
  18782. resStore[lng] = resStore[lng] || {};
  18783. var res = resStore[lng][ns] || {};
  18784. var hasValues = false;
  18785. for(var prop in res) {
  18786. if (res.hasOwnProperty(prop)) {
  18787. hasValues = true;
  18788. }
  18789. }
  18790. return hasValues;
  18791. }
  18792. function removeResourceBundle(lng, ns) {
  18793. if (typeof ns !== 'string') {
  18794. ns = o.ns.defaultNs;
  18795. }
  18796. resStore[lng] = resStore[lng] || {};
  18797. resStore[lng][ns] = {};
  18798. }
  18799. function addResource(lng, ns, key, value) {
  18800. if (typeof ns !== 'string') {
  18801. resource = ns;
  18802. ns = o.ns.defaultNs;
  18803. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18804. o.ns.namespaces.push(ns);
  18805. }
  18806. resStore[lng] = resStore[lng] || {};
  18807. resStore[lng][ns] = resStore[lng][ns] || {};
  18808. var keys = key.split(o.keyseparator);
  18809. var x = 0;
  18810. var node = resStore[lng][ns];
  18811. var origRef = node;
  18812. while (keys[x]) {
  18813. if (x == keys.length - 1)
  18814. node[keys[x]] = value;
  18815. else {
  18816. if (node[keys[x]] == null)
  18817. node[keys[x]] = {};
  18818. node = node[keys[x]];
  18819. }
  18820. x++;
  18821. }
  18822. }
  18823. function addResources(lng, ns, resources) {
  18824. if (typeof ns !== 'string') {
  18825. resource = ns;
  18826. ns = o.ns.defaultNs;
  18827. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18828. o.ns.namespaces.push(ns);
  18829. }
  18830. for (var m in resources) {
  18831. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  18832. }
  18833. }
  18834. function setDefaultNamespace(ns) {
  18835. o.ns.defaultNs = ns;
  18836. }
  18837. function loadNamespace(namespace, cb) {
  18838. loadNamespaces([namespace], cb);
  18839. }
  18840. function loadNamespaces(namespaces, cb) {
  18841. var opts = {
  18842. dynamicLoad: o.dynamicLoad,
  18843. resGetPath: o.resGetPath,
  18844. getAsync: o.getAsync,
  18845. customLoad: o.customLoad,
  18846. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  18847. };
  18848. // languages to load
  18849. var lngsToLoad = f.toLanguages(o.lng);
  18850. if (typeof o.preload === 'string') o.preload = [o.preload];
  18851. for (var i = 0, l = o.preload.length; i < l; i++) {
  18852. var pres = f.toLanguages(o.preload[i]);
  18853. for (var y = 0, len = pres.length; y < len; y++) {
  18854. if (lngsToLoad.indexOf(pres[y]) < 0) {
  18855. lngsToLoad.push(pres[y]);
  18856. }
  18857. }
  18858. }
  18859. // check if we have to load
  18860. var lngNeedLoad = [];
  18861. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  18862. var needLoad = false;
  18863. var resSet = resStore[lngsToLoad[a]];
  18864. if (resSet) {
  18865. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  18866. if (!resSet[namespaces[b]]) needLoad = true;
  18867. }
  18868. } else {
  18869. needLoad = true;
  18870. }
  18871. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  18872. }
  18873. if (lngNeedLoad.length) {
  18874. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  18875. var todo = namespaces.length * lngNeedLoad.length;
  18876. // load each file individual
  18877. f.each(namespaces, function(nsIndex, nsValue) {
  18878. // append namespace to namespace array
  18879. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  18880. o.ns.namespaces.push(nsValue);
  18881. }
  18882. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  18883. resStore[lngValue] = resStore[lngValue] || {};
  18884. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  18885. todo--; // wait for all done befor callback
  18886. if (todo === 0 && cb) {
  18887. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  18888. cb();
  18889. }
  18890. });
  18891. });
  18892. });
  18893. } else {
  18894. if (cb) cb();
  18895. }
  18896. }
  18897. function setLng(lng, options, cb) {
  18898. if (typeof options === 'function') {
  18899. cb = options;
  18900. options = {};
  18901. } else if (!options) {
  18902. options = {};
  18903. }
  18904. options.lng = lng;
  18905. return init(options, cb);
  18906. }
  18907. function lng() {
  18908. return currentLng;
  18909. }
  18910. function reload(cb) {
  18911. resStore = {};
  18912. setLng(currentLng, cb);
  18913. }
  18914. function addJqueryFunct() {
  18915. // $.t shortcut
  18916. $.t = $.t || translate;
  18917. function parse(ele, key, options) {
  18918. if (key.length === 0) return;
  18919. var attr = 'text';
  18920. if (key.indexOf('[') === 0) {
  18921. var parts = key.split(']');
  18922. key = parts[1];
  18923. attr = parts[0].substr(1, parts[0].length-1);
  18924. }
  18925. if (key.indexOf(';') === key.length-1) {
  18926. key = key.substr(0, key.length-2);
  18927. }
  18928. var optionsToUse;
  18929. if (attr === 'html') {
  18930. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18931. ele.html($.t(key, optionsToUse));
  18932. } else if (attr === 'text') {
  18933. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  18934. ele.text($.t(key, optionsToUse));
  18935. } else if (attr === 'prepend') {
  18936. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18937. ele.prepend($.t(key, optionsToUse));
  18938. } else if (attr === 'append') {
  18939. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18940. ele.append($.t(key, optionsToUse));
  18941. } else if (attr.indexOf("data-") === 0) {
  18942. var dataAttr = attr.substr(("data-").length);
  18943. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  18944. var translated = $.t(key, optionsToUse);
  18945. //we change into the data cache
  18946. ele.data(dataAttr, translated);
  18947. //we change into the dom
  18948. ele.attr(attr, translated);
  18949. } else {
  18950. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  18951. ele.attr(attr, $.t(key, optionsToUse));
  18952. }
  18953. }
  18954. function localize(ele, options) {
  18955. var key = ele.attr(o.selectorAttr);
  18956. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  18957. if (!key) return;
  18958. var target = ele
  18959. , targetSelector = ele.data("i18n-target");
  18960. if (targetSelector) {
  18961. target = ele.find(targetSelector) || ele;
  18962. }
  18963. if (!options && o.useDataAttrOptions === true) {
  18964. options = ele.data("i18n-options");
  18965. }
  18966. options = options || {};
  18967. if (key.indexOf(';') >= 0) {
  18968. var keys = key.split(';');
  18969. $.each(keys, function(m, k) {
  18970. if (k !== '') parse(target, k, options);
  18971. });
  18972. } else {
  18973. parse(target, key, options);
  18974. }
  18975. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  18976. }
  18977. // fn
  18978. $.fn.i18n = function (options) {
  18979. return this.each(function() {
  18980. // localize element itself
  18981. localize($(this), options);
  18982. // localize childs
  18983. var elements = $(this).find('[' + o.selectorAttr + ']');
  18984. elements.each(function() {
  18985. localize($(this), options);
  18986. });
  18987. });
  18988. };
  18989. }
  18990. function applyReplacement(str, replacementHash, nestedKey, options) {
  18991. if (!str) return str;
  18992. options = options || replacementHash; // first call uses replacement hash combined with options
  18993. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  18994. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  18995. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  18996. , unEscapingSuffix = 'HTML'+suffix;
  18997. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  18998. f.each(hash, function(key, value) {
  18999. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  19000. if (typeof value === 'object' && value !== null) {
  19001. str = applyReplacement(str, value, nextKey, options);
  19002. } else {
  19003. if (options.escapeInterpolation || o.escapeInterpolation) {
  19004. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  19005. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  19006. } else {
  19007. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  19008. }
  19009. // str = options.escapeInterpolation;
  19010. }
  19011. });
  19012. return str;
  19013. }
  19014. // append it to functions
  19015. f.applyReplacement = applyReplacement;
  19016. function applyReuse(translated, options) {
  19017. var comma = ',';
  19018. var options_open = '{';
  19019. var options_close = '}';
  19020. var opts = f.extend({}, options);
  19021. delete opts.postProcess;
  19022. while (translated.indexOf(o.reusePrefix) != -1) {
  19023. replacementCounter++;
  19024. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  19025. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  19026. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  19027. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  19028. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  19029. if (index_of_end_of_closing <= index_of_opening) {
  19030. f.error('there is an missing closing in following translation value', translated);
  19031. return '';
  19032. }
  19033. if (token_without_symbols.indexOf(comma) != -1) {
  19034. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  19035. 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) {
  19036. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  19037. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  19038. try {
  19039. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  19040. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  19041. } catch (e) {
  19042. }
  19043. }
  19044. }
  19045. var translated_token = _translate(token_without_symbols, opts);
  19046. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  19047. }
  19048. return translated;
  19049. }
  19050. function hasContext(options) {
  19051. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  19052. }
  19053. function needsPlural(options, lng) {
  19054. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  19055. }
  19056. function needsIndefiniteArticle(options) {
  19057. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  19058. }
  19059. function exists(key, options) {
  19060. options = options || {};
  19061. var notFound = _getDefaultValue(key, options)
  19062. , found = _find(key, options);
  19063. return found !== undefined || found === notFound;
  19064. }
  19065. function translate(key, options) {
  19066. options = options || {};
  19067. if (!initialized) {
  19068. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  19069. return options.defaultValue || '';
  19070. };
  19071. replacementCounter = 0;
  19072. return _translate.apply(null, arguments);
  19073. }
  19074. function _getDefaultValue(key, options) {
  19075. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  19076. }
  19077. function _injectSprintfProcessor() {
  19078. var values = [];
  19079. // mh: build array from second argument onwards
  19080. for (var i = 1; i < arguments.length; i++) {
  19081. values.push(arguments[i]);
  19082. }
  19083. return {
  19084. postProcess: 'sprintf',
  19085. sprintf: values
  19086. };
  19087. }
  19088. function _translate(potentialKeys, options) {
  19089. if (options && typeof options !== 'object') {
  19090. if (o.shortcutFunction === 'sprintf') {
  19091. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  19092. options = _injectSprintfProcessor.apply(null, arguments);
  19093. } else if (o.shortcutFunction === 'defaultValue') {
  19094. options = {
  19095. defaultValue: options
  19096. }
  19097. }
  19098. } else {
  19099. options = options || {};
  19100. }
  19101. if (typeof o.defaultVariables === 'object') {
  19102. options = f.extend({}, o.defaultVariables, options);
  19103. }
  19104. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  19105. if (typeof potentialKeys === 'string') {
  19106. potentialKeys = [potentialKeys];
  19107. }
  19108. var key = potentialKeys[0];
  19109. if (potentialKeys.length > 1) {
  19110. for (var i = 0; i < potentialKeys.length; i++) {
  19111. key = potentialKeys[i];
  19112. if (exists(key, options)) {
  19113. break;
  19114. }
  19115. }
  19116. }
  19117. var notFound = _getDefaultValue(key, options)
  19118. , found = _find(key, options)
  19119. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  19120. , ns = options.ns || o.ns.defaultNs
  19121. , parts;
  19122. // split ns and key
  19123. if (key.indexOf(o.nsseparator) > -1) {
  19124. parts = key.split(o.nsseparator);
  19125. ns = parts[0];
  19126. key = parts[1];
  19127. }
  19128. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  19129. if (options.lng) {
  19130. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  19131. } else {
  19132. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  19133. }
  19134. }
  19135. var postProcessor = options.postProcess || o.postProcess;
  19136. if (found !== undefined && postProcessor) {
  19137. if (postProcessors[postProcessor]) {
  19138. found = postProcessors[postProcessor](found, key, options);
  19139. }
  19140. }
  19141. // process notFound if function exists
  19142. var splitNotFound = notFound;
  19143. if (notFound.indexOf(o.nsseparator) > -1) {
  19144. parts = notFound.split(o.nsseparator);
  19145. splitNotFound = parts[1];
  19146. }
  19147. if (splitNotFound === key && o.parseMissingKey) {
  19148. notFound = o.parseMissingKey(notFound);
  19149. }
  19150. if (found === undefined) {
  19151. notFound = applyReplacement(notFound, options);
  19152. notFound = applyReuse(notFound, options);
  19153. if (postProcessor && postProcessors[postProcessor]) {
  19154. var val = _getDefaultValue(key, options);
  19155. found = postProcessors[postProcessor](val, key, options);
  19156. }
  19157. }
  19158. return (found !== undefined) ? found : notFound;
  19159. }
  19160. function _find(key, options) {
  19161. options = options || {};
  19162. var optionWithoutCount, translated
  19163. , notFound = _getDefaultValue(key, options)
  19164. , lngs = languages;
  19165. if (!resStore) { return notFound; } // no resStore to translate from
  19166. // CI mode
  19167. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  19168. // passed in lng
  19169. if (options.lngs) lngs = options.lngs;
  19170. if (options.lng) {
  19171. lngs = f.toLanguages(options.lng, options.fallbackLng);
  19172. if (!resStore[lngs[0]]) {
  19173. var oldAsync = o.getAsync;
  19174. o.getAsync = false;
  19175. i18n.sync.load(lngs, o, function(err, store) {
  19176. f.extend(resStore, store);
  19177. o.getAsync = oldAsync;
  19178. });
  19179. }
  19180. }
  19181. var ns = options.ns || o.ns.defaultNs;
  19182. if (key.indexOf(o.nsseparator) > -1) {
  19183. var parts = key.split(o.nsseparator);
  19184. ns = parts[0];
  19185. key = parts[1];
  19186. }
  19187. if (hasContext(options)) {
  19188. optionWithoutCount = f.extend({}, options);
  19189. delete optionWithoutCount.context;
  19190. optionWithoutCount.defaultValue = o.contextNotFound;
  19191. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  19192. translated = translate(contextKey, optionWithoutCount);
  19193. if (translated != o.contextNotFound) {
  19194. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  19195. } // else continue translation with original/nonContext key
  19196. }
  19197. if (needsPlural(options, lngs[0])) {
  19198. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  19199. delete optionWithoutCount.count;
  19200. delete optionWithoutCount.lng;
  19201. optionWithoutCount.defaultValue = o.pluralNotFound;
  19202. var pluralKey;
  19203. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  19204. pluralKey = ns + o.nsseparator + key;
  19205. } else {
  19206. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  19207. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  19208. if (pluralExtension >= 0) {
  19209. pluralKey = pluralKey + '_' + pluralExtension;
  19210. } else if (pluralExtension === 1) {
  19211. pluralKey = ns + o.nsseparator + key; // singular
  19212. }
  19213. }
  19214. translated = translate(pluralKey, optionWithoutCount);
  19215. if (translated != o.pluralNotFound) {
  19216. return applyReplacement(translated, {
  19217. count: options.count,
  19218. interpolationPrefix: options.interpolationPrefix,
  19219. interpolationSuffix: options.interpolationSuffix
  19220. }); // apply replacement for count only
  19221. } else if (lngs.length > 1) {
  19222. // remove failed lng
  19223. var clone = lngs.slice();
  19224. clone.shift();
  19225. options = f.extend(options, { lngs: clone });
  19226. delete options.lng;
  19227. // retry with fallbacks
  19228. translated = translate(ns + o.nsseparator + key, options);
  19229. if (translated != o.pluralNotFound) return translated;
  19230. } else {
  19231. return translated;
  19232. }
  19233. }
  19234. if (needsIndefiniteArticle(options)) {
  19235. var optionsWithoutIndef = f.extend({}, options);
  19236. delete optionsWithoutIndef.indefinite_article;
  19237. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  19238. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  19239. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  19240. translated = translate(indefiniteKey, optionsWithoutIndef);
  19241. if (translated != o.indefiniteNotFound) {
  19242. return translated;
  19243. }
  19244. }
  19245. var found;
  19246. var keys = key.split(o.keyseparator);
  19247. for (var i = 0, len = lngs.length; i < len; i++ ) {
  19248. if (found !== undefined) break;
  19249. var l = lngs[i];
  19250. var x = 0;
  19251. var value = resStore[l] && resStore[l][ns];
  19252. while (keys[x]) {
  19253. value = value && value[keys[x]];
  19254. x++;
  19255. }
  19256. if (value !== undefined) {
  19257. var valueType = Object.prototype.toString.apply(value);
  19258. if (typeof value === 'string') {
  19259. value = applyReplacement(value, options);
  19260. value = applyReuse(value, options);
  19261. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  19262. value = value.join('\n');
  19263. value = applyReplacement(value, options);
  19264. value = applyReuse(value, options);
  19265. } else if (value === null && o.fallbackOnNull === true) {
  19266. value = undefined;
  19267. } else if (value !== null) {
  19268. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  19269. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  19270. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  19271. } else {
  19272. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  19273. 'returned an object instead of string.';
  19274. f.log(value);
  19275. }
  19276. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  19277. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  19278. f.each(value, function(m) {
  19279. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  19280. });
  19281. value = copy;
  19282. }
  19283. }
  19284. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  19285. value = undefined;
  19286. found = value;
  19287. }
  19288. }
  19289. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  19290. // set flag for fallback lookup - avoid recursion
  19291. options.isFallbackLookup = true;
  19292. if (o.fallbackNS.length) {
  19293. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  19294. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  19295. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  19296. /* compare value without namespace */
  19297. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  19298. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  19299. if (foundValue !== notFoundValue) break;
  19300. }
  19301. }
  19302. } else {
  19303. found = _find(key, options); // fallback to default NS
  19304. }
  19305. options.isFallbackLookup = false;
  19306. }
  19307. return found;
  19308. }
  19309. function detectLanguage() {
  19310. var detectedLng;
  19311. var whitelist = o.lngWhitelist || [];
  19312. var userLngChoices = [];
  19313. // get from qs
  19314. var qsParm = [];
  19315. if (typeof window !== 'undefined') {
  19316. (function() {
  19317. var query = window.location.search.substring(1);
  19318. var params = query.split('&');
  19319. for (var i=0; i<params.length; i++) {
  19320. var pos = params[i].indexOf('=');
  19321. if (pos > 0) {
  19322. var key = params[i].substring(0,pos);
  19323. if (key == o.detectLngQS) {
  19324. userLngChoices.push(params[i].substring(pos+1));
  19325. }
  19326. }
  19327. }
  19328. })();
  19329. }
  19330. // get from cookie
  19331. if (o.useCookie && typeof document !== 'undefined') {
  19332. var c = f.cookie.read(o.cookieName);
  19333. if (c) userLngChoices.push(c);
  19334. }
  19335. // get from localStorage
  19336. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  19337. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  19338. }
  19339. // get from navigator
  19340. if (typeof navigator !== 'undefined') {
  19341. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  19342. for (var i=0;i<navigator.languages.length;i++) {
  19343. userLngChoices.push(navigator.languages[i]);
  19344. }
  19345. }
  19346. if (navigator.userLanguage) {
  19347. userLngChoices.push(navigator.userLanguage);
  19348. }
  19349. if (navigator.language) {
  19350. userLngChoices.push(navigator.language);
  19351. }
  19352. }
  19353. (function() {
  19354. for (var i=0;i<userLngChoices.length;i++) {
  19355. var lng = userLngChoices[i];
  19356. if (lng.indexOf('-') > -1) {
  19357. var parts = lng.split('-');
  19358. lng = o.lowerCaseLng ?
  19359. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  19360. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  19361. }
  19362. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  19363. detectedLng = lng;
  19364. break;
  19365. }
  19366. }
  19367. })();
  19368. //fallback
  19369. if (!detectedLng){
  19370. detectedLng = o.fallbackLng[0];
  19371. }
  19372. return detectedLng;
  19373. }
  19374. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  19375. /* [code, name, numbers, pluralsType] */
  19376. var _rules = [
  19377. ["ach", "Acholi", [1,2], 1],
  19378. ["af", "Afrikaans",[1,2], 2],
  19379. ["ak", "Akan", [1,2], 1],
  19380. ["am", "Amharic", [1,2], 1],
  19381. ["an", "Aragonese",[1,2], 2],
  19382. ["ar", "Arabic", [0,1,2,3,11,100],5],
  19383. ["arn", "Mapudungun",[1,2], 1],
  19384. ["ast", "Asturian", [1,2], 2],
  19385. ["ay", "Aymará", [1], 3],
  19386. ["az", "Azerbaijani",[1,2],2],
  19387. ["be", "Belarusian",[1,2,5],4],
  19388. ["bg", "Bulgarian",[1,2], 2],
  19389. ["bn", "Bengali", [1,2], 2],
  19390. ["bo", "Tibetan", [1], 3],
  19391. ["br", "Breton", [1,2], 1],
  19392. ["bs", "Bosnian", [1,2,5],4],
  19393. ["ca", "Catalan", [1,2], 2],
  19394. ["cgg", "Chiga", [1], 3],
  19395. ["cs", "Czech", [1,2,5],6],
  19396. ["csb", "Kashubian",[1,2,5],7],
  19397. ["cy", "Welsh", [1,2,3,8],8],
  19398. ["da", "Danish", [1,2], 2],
  19399. ["de", "German", [1,2], 2],
  19400. ["dev", "Development Fallback", [1,2], 2],
  19401. ["dz", "Dzongkha", [1], 3],
  19402. ["el", "Greek", [1,2], 2],
  19403. ["en", "English", [1,2], 2],
  19404. ["eo", "Esperanto",[1,2], 2],
  19405. ["es", "Spanish", [1,2], 2],
  19406. ["es_ar","Argentinean Spanish", [1,2], 2],
  19407. ["et", "Estonian", [1,2], 2],
  19408. ["eu", "Basque", [1,2], 2],
  19409. ["fa", "Persian", [1], 3],
  19410. ["fi", "Finnish", [1,2], 2],
  19411. ["fil", "Filipino", [1,2], 1],
  19412. ["fo", "Faroese", [1,2], 2],
  19413. ["fr", "French", [1,2], 9],
  19414. ["fur", "Friulian", [1,2], 2],
  19415. ["fy", "Frisian", [1,2], 2],
  19416. ["ga", "Irish", [1,2,3,7,11],10],
  19417. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  19418. ["gl", "Galician", [1,2], 2],
  19419. ["gu", "Gujarati", [1,2], 2],
  19420. ["gun", "Gun", [1,2], 1],
  19421. ["ha", "Hausa", [1,2], 2],
  19422. ["he", "Hebrew", [1,2], 2],
  19423. ["hi", "Hindi", [1,2], 2],
  19424. ["hr", "Croatian", [1,2,5],4],
  19425. ["hu", "Hungarian",[1,2], 2],
  19426. ["hy", "Armenian", [1,2], 2],
  19427. ["ia", "Interlingua",[1,2],2],
  19428. ["id", "Indonesian",[1], 3],
  19429. ["is", "Icelandic",[1,2], 12],
  19430. ["it", "Italian", [1,2], 2],
  19431. ["ja", "Japanese", [1], 3],
  19432. ["jbo", "Lojban", [1], 3],
  19433. ["jv", "Javanese", [0,1], 13],
  19434. ["ka", "Georgian", [1], 3],
  19435. ["kk", "Kazakh", [1], 3],
  19436. ["km", "Khmer", [1], 3],
  19437. ["kn", "Kannada", [1,2], 2],
  19438. ["ko", "Korean", [1], 3],
  19439. ["ku", "Kurdish", [1,2], 2],
  19440. ["kw", "Cornish", [1,2,3,4],14],
  19441. ["ky", "Kyrgyz", [1], 3],
  19442. ["lb", "Letzeburgesch",[1,2],2],
  19443. ["ln", "Lingala", [1,2], 1],
  19444. ["lo", "Lao", [1], 3],
  19445. ["lt", "Lithuanian",[1,2,10],15],
  19446. ["lv", "Latvian", [1,2,0],16],
  19447. ["mai", "Maithili", [1,2], 2],
  19448. ["mfe", "Mauritian Creole",[1,2],1],
  19449. ["mg", "Malagasy", [1,2], 1],
  19450. ["mi", "Maori", [1,2], 1],
  19451. ["mk", "Macedonian",[1,2],17],
  19452. ["ml", "Malayalam",[1,2], 2],
  19453. ["mn", "Mongolian",[1,2], 2],
  19454. ["mnk", "Mandinka", [0,1,2],18],
  19455. ["mr", "Marathi", [1,2], 2],
  19456. ["ms", "Malay", [1], 3],
  19457. ["mt", "Maltese", [1,2,11,20],19],
  19458. ["nah", "Nahuatl", [1,2], 2],
  19459. ["nap", "Neapolitan",[1,2], 2],
  19460. ["nb", "Norwegian Bokmal",[1,2],2],
  19461. ["ne", "Nepali", [1,2], 2],
  19462. ["nl", "Dutch", [1,2], 2],
  19463. ["nn", "Norwegian Nynorsk",[1,2],2],
  19464. ["no", "Norwegian",[1,2], 2],
  19465. ["nso", "Northern Sotho",[1,2],2],
  19466. ["oc", "Occitan", [1,2], 1],
  19467. ["or", "Oriya", [2,1], 2],
  19468. ["pa", "Punjabi", [1,2], 2],
  19469. ["pap", "Papiamento",[1,2], 2],
  19470. ["pl", "Polish", [1,2,5],7],
  19471. ["pms", "Piemontese",[1,2], 2],
  19472. ["ps", "Pashto", [1,2], 2],
  19473. ["pt", "Portuguese",[1,2], 2],
  19474. ["pt_br","Brazilian Portuguese",[1,2], 2],
  19475. ["rm", "Romansh", [1,2], 2],
  19476. ["ro", "Romanian", [1,2,20],20],
  19477. ["ru", "Russian", [1,2,5],4],
  19478. ["sah", "Yakut", [1], 3],
  19479. ["sco", "Scots", [1,2], 2],
  19480. ["se", "Northern Sami",[1,2], 2],
  19481. ["si", "Sinhala", [1,2], 2],
  19482. ["sk", "Slovak", [1,2,5],6],
  19483. ["sl", "Slovenian",[5,1,2,3],21],
  19484. ["so", "Somali", [1,2], 2],
  19485. ["son", "Songhay", [1,2], 2],
  19486. ["sq", "Albanian", [1,2], 2],
  19487. ["sr", "Serbian", [1,2,5],4],
  19488. ["su", "Sundanese",[1], 3],
  19489. ["sv", "Swedish", [1,2], 2],
  19490. ["sw", "Swahili", [1,2], 2],
  19491. ["ta", "Tamil", [1,2], 2],
  19492. ["te", "Telugu", [1,2], 2],
  19493. ["tg", "Tajik", [1,2], 1],
  19494. ["th", "Thai", [1], 3],
  19495. ["ti", "Tigrinya", [1,2], 1],
  19496. ["tk", "Turkmen", [1,2], 2],
  19497. ["tr", "Turkish", [1,2], 1],
  19498. ["tt", "Tatar", [1], 3],
  19499. ["ug", "Uyghur", [1], 3],
  19500. ["uk", "Ukrainian",[1,2,5],4],
  19501. ["ur", "Urdu", [1,2], 2],
  19502. ["uz", "Uzbek", [1,2], 1],
  19503. ["vi", "Vietnamese",[1], 3],
  19504. ["wa", "Walloon", [1,2], 1],
  19505. ["wo", "Wolof", [1], 3],
  19506. ["yo", "Yoruba", [1,2], 2],
  19507. ["zh", "Chinese", [1], 3]
  19508. ];
  19509. var _rulesPluralsTypes = {
  19510. 1: function(n) {return Number(n > 1);},
  19511. 2: function(n) {return Number(n != 1);},
  19512. 3: function(n) {return 0;},
  19513. 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);},
  19514. 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);},
  19515. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  19516. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  19517. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  19518. 9: function(n) {return Number(n >= 2);},
  19519. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  19520. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  19521. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  19522. 13: function(n) {return Number(n !== 0);},
  19523. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  19524. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  19525. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  19526. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  19527. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  19528. 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);},
  19529. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  19530. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  19531. };
  19532. var pluralExtensions = {
  19533. rules: (function () {
  19534. var l, rules = {};
  19535. for (l=_rules.length; l-- ;) {
  19536. rules[_rules[l][0]] = {
  19537. name: _rules[l][1],
  19538. numbers: _rules[l][2],
  19539. plurals: _rulesPluralsTypes[_rules[l][3]]
  19540. }
  19541. }
  19542. return rules;
  19543. }()),
  19544. // you can add your own pluralExtensions
  19545. addRule: function(lng, obj) {
  19546. pluralExtensions.rules[lng] = obj;
  19547. },
  19548. setCurrentLng: function(lng) {
  19549. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  19550. var parts = lng.split('-');
  19551. pluralExtensions.currentRule = {
  19552. lng: lng,
  19553. rule: pluralExtensions.rules[parts[0]]
  19554. };
  19555. }
  19556. },
  19557. needsPlural: function(lng, count) {
  19558. var parts = lng.split('-');
  19559. var ext;
  19560. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  19561. ext = pluralExtensions.currentRule.rule;
  19562. } else {
  19563. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  19564. }
  19565. if (ext && ext.numbers.length <= 1) {
  19566. return false;
  19567. } else {
  19568. return this.get(lng, count) !== 1;
  19569. }
  19570. },
  19571. get: function(lng, count) {
  19572. var parts = lng.split('-');
  19573. function getResult(l, c) {
  19574. var ext;
  19575. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  19576. ext = pluralExtensions.currentRule.rule;
  19577. } else {
  19578. ext = pluralExtensions.rules[l];
  19579. }
  19580. if (ext) {
  19581. var i;
  19582. if (ext.noAbs) {
  19583. i = ext.plurals(c);
  19584. } else {
  19585. i = ext.plurals(Math.abs(c));
  19586. }
  19587. var number = ext.numbers[i];
  19588. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  19589. if (number === 2) {
  19590. number = -1; // regular plural
  19591. } else if (number === 1) {
  19592. number = 1; // singular
  19593. }
  19594. }//console.log(count + '-' + number);
  19595. return number;
  19596. } else {
  19597. return c === 1 ? '1' : '-1';
  19598. }
  19599. }
  19600. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  19601. }
  19602. };
  19603. var postProcessors = {};
  19604. var addPostProcessor = function(name, fc) {
  19605. postProcessors[name] = fc;
  19606. };
  19607. // sprintf support
  19608. var sprintf = (function() {
  19609. function get_type(variable) {
  19610. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  19611. }
  19612. function str_repeat(input, multiplier) {
  19613. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  19614. return output.join('');
  19615. }
  19616. var str_format = function() {
  19617. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  19618. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  19619. }
  19620. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  19621. };
  19622. str_format.format = function(parse_tree, argv) {
  19623. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  19624. for (i = 0; i < tree_length; i++) {
  19625. node_type = get_type(parse_tree[i]);
  19626. if (node_type === 'string') {
  19627. output.push(parse_tree[i]);
  19628. }
  19629. else if (node_type === 'array') {
  19630. match = parse_tree[i]; // convenience purposes only
  19631. if (match[2]) { // keyword argument
  19632. arg = argv[cursor];
  19633. for (k = 0; k < match[2].length; k++) {
  19634. if (!arg.hasOwnProperty(match[2][k])) {
  19635. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  19636. }
  19637. arg = arg[match[2][k]];
  19638. }
  19639. }
  19640. else if (match[1]) { // positional argument (explicit)
  19641. arg = argv[match[1]];
  19642. }
  19643. else { // positional argument (implicit)
  19644. arg = argv[cursor++];
  19645. }
  19646. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  19647. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  19648. }
  19649. switch (match[8]) {
  19650. case 'b': arg = arg.toString(2); break;
  19651. case 'c': arg = String.fromCharCode(arg); break;
  19652. case 'd': arg = parseInt(arg, 10); break;
  19653. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  19654. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  19655. case 'o': arg = arg.toString(8); break;
  19656. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  19657. case 'u': arg = Math.abs(arg); break;
  19658. case 'x': arg = arg.toString(16); break;
  19659. case 'X': arg = arg.toString(16).toUpperCase(); break;
  19660. }
  19661. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  19662. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  19663. pad_length = match[6] - String(arg).length;
  19664. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  19665. output.push(match[5] ? arg + pad : pad + arg);
  19666. }
  19667. }
  19668. return output.join('');
  19669. };
  19670. str_format.cache = {};
  19671. str_format.parse = function(fmt) {
  19672. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  19673. while (_fmt) {
  19674. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  19675. parse_tree.push(match[0]);
  19676. }
  19677. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  19678. parse_tree.push('%');
  19679. }
  19680. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  19681. if (match[2]) {
  19682. arg_names |= 1;
  19683. var field_list = [], replacement_field = match[2], field_match = [];
  19684. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  19685. field_list.push(field_match[1]);
  19686. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  19687. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  19688. field_list.push(field_match[1]);
  19689. }
  19690. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  19691. field_list.push(field_match[1]);
  19692. }
  19693. else {
  19694. throw('[sprintf] huh?');
  19695. }
  19696. }
  19697. }
  19698. else {
  19699. throw('[sprintf] huh?');
  19700. }
  19701. match[2] = field_list;
  19702. }
  19703. else {
  19704. arg_names |= 2;
  19705. }
  19706. if (arg_names === 3) {
  19707. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  19708. }
  19709. parse_tree.push(match);
  19710. }
  19711. else {
  19712. throw('[sprintf] huh?');
  19713. }
  19714. _fmt = _fmt.substring(match[0].length);
  19715. }
  19716. return parse_tree;
  19717. };
  19718. return str_format;
  19719. })();
  19720. var vsprintf = function(fmt, argv) {
  19721. argv.unshift(fmt);
  19722. return sprintf.apply(null, argv);
  19723. };
  19724. addPostProcessor("sprintf", function(val, key, opts) {
  19725. if (!opts.sprintf) return val;
  19726. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  19727. return vsprintf(val, opts.sprintf);
  19728. } else if (typeof opts.sprintf === 'object') {
  19729. return sprintf(val, opts.sprintf);
  19730. }
  19731. return val;
  19732. });
  19733. // public api interface
  19734. i18n.init = init;
  19735. i18n.setLng = setLng;
  19736. i18n.preload = preload;
  19737. i18n.addResourceBundle = addResourceBundle;
  19738. i18n.hasResourceBundle = hasResourceBundle;
  19739. i18n.addResource = addResource;
  19740. i18n.addResources = addResources;
  19741. i18n.removeResourceBundle = removeResourceBundle;
  19742. i18n.loadNamespace = loadNamespace;
  19743. i18n.loadNamespaces = loadNamespaces;
  19744. i18n.setDefaultNamespace = setDefaultNamespace;
  19745. i18n.t = translate;
  19746. i18n.translate = translate;
  19747. i18n.exists = exists;
  19748. i18n.detectLanguage = f.detectLanguage;
  19749. i18n.pluralExtensions = pluralExtensions;
  19750. i18n.sync = sync;
  19751. i18n.functions = f;
  19752. i18n.lng = lng;
  19753. i18n.addPostProcessor = addPostProcessor;
  19754. i18n.options = o;
  19755. })();
  19756. },{"jquery":"jquery"}],72:[function(require,module,exports){
  19757. // Top level file is just a mixin of submodules & constants
  19758. 'use strict';
  19759. var assign = require('./lib/utils/common').assign;
  19760. var deflate = require('./lib/deflate');
  19761. var inflate = require('./lib/inflate');
  19762. var constants = require('./lib/zlib/constants');
  19763. var pako = {};
  19764. assign(pako, deflate, inflate, constants);
  19765. module.exports = pako;
  19766. },{"./lib/deflate":73,"./lib/inflate":74,"./lib/utils/common":75,"./lib/zlib/constants":78}],73:[function(require,module,exports){
  19767. 'use strict';
  19768. var zlib_deflate = require('./zlib/deflate.js');
  19769. var utils = require('./utils/common');
  19770. var strings = require('./utils/strings');
  19771. var msg = require('./zlib/messages');
  19772. var zstream = require('./zlib/zstream');
  19773. var toString = Object.prototype.toString;
  19774. /* Public constants ==========================================================*/
  19775. /* ===========================================================================*/
  19776. var Z_NO_FLUSH = 0;
  19777. var Z_FINISH = 4;
  19778. var Z_OK = 0;
  19779. var Z_STREAM_END = 1;
  19780. var Z_SYNC_FLUSH = 2;
  19781. var Z_DEFAULT_COMPRESSION = -1;
  19782. var Z_DEFAULT_STRATEGY = 0;
  19783. var Z_DEFLATED = 8;
  19784. /* ===========================================================================*/
  19785. /**
  19786. * class Deflate
  19787. *
  19788. * Generic JS-style wrapper for zlib calls. If you don't need
  19789. * streaming behaviour - use more simple functions: [[deflate]],
  19790. * [[deflateRaw]] and [[gzip]].
  19791. **/
  19792. /* internal
  19793. * Deflate.chunks -> Array
  19794. *
  19795. * Chunks of output data, if [[Deflate#onData]] not overriden.
  19796. **/
  19797. /**
  19798. * Deflate.result -> Uint8Array|Array
  19799. *
  19800. * Compressed result, generated by default [[Deflate#onData]]
  19801. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  19802. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  19803. * push a chunk with explicit flush (call [[Deflate#push]] with
  19804. * `Z_SYNC_FLUSH` param).
  19805. **/
  19806. /**
  19807. * Deflate.err -> Number
  19808. *
  19809. * Error code after deflate finished. 0 (Z_OK) on success.
  19810. * You will not need it in real life, because deflate errors
  19811. * are possible only on wrong options or bad `onData` / `onEnd`
  19812. * custom handlers.
  19813. **/
  19814. /**
  19815. * Deflate.msg -> String
  19816. *
  19817. * Error message, if [[Deflate.err]] != 0
  19818. **/
  19819. /**
  19820. * new Deflate(options)
  19821. * - options (Object): zlib deflate options.
  19822. *
  19823. * Creates new deflator instance with specified params. Throws exception
  19824. * on bad params. Supported options:
  19825. *
  19826. * - `level`
  19827. * - `windowBits`
  19828. * - `memLevel`
  19829. * - `strategy`
  19830. *
  19831. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19832. * for more information on these.
  19833. *
  19834. * Additional options, for internal needs:
  19835. *
  19836. * - `chunkSize` - size of generated data chunks (16K by default)
  19837. * - `raw` (Boolean) - do raw deflate
  19838. * - `gzip` (Boolean) - create gzip wrapper
  19839. * - `to` (String) - if equal to 'string', then result will be "binary string"
  19840. * (each char code [0..255])
  19841. * - `header` (Object) - custom header for gzip
  19842. * - `text` (Boolean) - true if compressed data believed to be text
  19843. * - `time` (Number) - modification time, unix timestamp
  19844. * - `os` (Number) - operation system code
  19845. * - `extra` (Array) - array of bytes with extra data (max 65536)
  19846. * - `name` (String) - file name (binary string)
  19847. * - `comment` (String) - comment (binary string)
  19848. * - `hcrc` (Boolean) - true if header crc should be added
  19849. *
  19850. * ##### Example:
  19851. *
  19852. * ```javascript
  19853. * var pako = require('pako')
  19854. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  19855. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  19856. *
  19857. * var deflate = new pako.Deflate({ level: 3});
  19858. *
  19859. * deflate.push(chunk1, false);
  19860. * deflate.push(chunk2, true); // true -> last chunk
  19861. *
  19862. * if (deflate.err) { throw new Error(deflate.err); }
  19863. *
  19864. * console.log(deflate.result);
  19865. * ```
  19866. **/
  19867. var Deflate = function(options) {
  19868. this.options = utils.assign({
  19869. level: Z_DEFAULT_COMPRESSION,
  19870. method: Z_DEFLATED,
  19871. chunkSize: 16384,
  19872. windowBits: 15,
  19873. memLevel: 8,
  19874. strategy: Z_DEFAULT_STRATEGY,
  19875. to: ''
  19876. }, options || {});
  19877. var opt = this.options;
  19878. if (opt.raw && (opt.windowBits > 0)) {
  19879. opt.windowBits = -opt.windowBits;
  19880. }
  19881. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  19882. opt.windowBits += 16;
  19883. }
  19884. this.err = 0; // error code, if happens (0 = Z_OK)
  19885. this.msg = ''; // error message
  19886. this.ended = false; // used to avoid multiple onEnd() calls
  19887. this.chunks = []; // chunks of compressed data
  19888. this.strm = new zstream();
  19889. this.strm.avail_out = 0;
  19890. var status = zlib_deflate.deflateInit2(
  19891. this.strm,
  19892. opt.level,
  19893. opt.method,
  19894. opt.windowBits,
  19895. opt.memLevel,
  19896. opt.strategy
  19897. );
  19898. if (status !== Z_OK) {
  19899. throw new Error(msg[status]);
  19900. }
  19901. if (opt.header) {
  19902. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  19903. }
  19904. };
  19905. /**
  19906. * Deflate#push(data[, mode]) -> Boolean
  19907. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  19908. * converted to utf8 byte sequence.
  19909. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  19910. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  19911. *
  19912. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  19913. * new compressed chunks. Returns `true` on success. The last data block must have
  19914. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  19915. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  19916. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  19917. *
  19918. * On fail call [[Deflate#onEnd]] with error code and return false.
  19919. *
  19920. * We strongly recommend to use `Uint8Array` on input for best speed (output
  19921. * array format is detected automatically). Also, don't skip last param and always
  19922. * use the same type in your code (boolean or number). That will improve JS speed.
  19923. *
  19924. * For regular `Array`-s make sure all elements are [0..255].
  19925. *
  19926. * ##### Example
  19927. *
  19928. * ```javascript
  19929. * push(chunk, false); // push one of data chunks
  19930. * ...
  19931. * push(chunk, true); // push last chunk
  19932. * ```
  19933. **/
  19934. Deflate.prototype.push = function(data, mode) {
  19935. var strm = this.strm;
  19936. var chunkSize = this.options.chunkSize;
  19937. var status, _mode;
  19938. if (this.ended) { return false; }
  19939. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  19940. // Convert data if needed
  19941. if (typeof data === 'string') {
  19942. // If we need to compress text, change encoding to utf8.
  19943. strm.input = strings.string2buf(data);
  19944. } else if (toString.call(data) === '[object ArrayBuffer]') {
  19945. strm.input = new Uint8Array(data);
  19946. } else {
  19947. strm.input = data;
  19948. }
  19949. strm.next_in = 0;
  19950. strm.avail_in = strm.input.length;
  19951. do {
  19952. if (strm.avail_out === 0) {
  19953. strm.output = new utils.Buf8(chunkSize);
  19954. strm.next_out = 0;
  19955. strm.avail_out = chunkSize;
  19956. }
  19957. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  19958. if (status !== Z_STREAM_END && status !== Z_OK) {
  19959. this.onEnd(status);
  19960. this.ended = true;
  19961. return false;
  19962. }
  19963. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  19964. if (this.options.to === 'string') {
  19965. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  19966. } else {
  19967. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  19968. }
  19969. }
  19970. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  19971. // Finalize on the last chunk.
  19972. if (_mode === Z_FINISH) {
  19973. status = zlib_deflate.deflateEnd(this.strm);
  19974. this.onEnd(status);
  19975. this.ended = true;
  19976. return status === Z_OK;
  19977. }
  19978. // callback interim results if Z_SYNC_FLUSH.
  19979. if (_mode === Z_SYNC_FLUSH) {
  19980. this.onEnd(Z_OK);
  19981. strm.avail_out = 0;
  19982. return true;
  19983. }
  19984. return true;
  19985. };
  19986. /**
  19987. * Deflate#onData(chunk) -> Void
  19988. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  19989. * on js engine support. When string output requested, each chunk
  19990. * will be string.
  19991. *
  19992. * By default, stores data blocks in `chunks[]` property and glue
  19993. * those in `onEnd`. Override this handler, if you need another behaviour.
  19994. **/
  19995. Deflate.prototype.onData = function(chunk) {
  19996. this.chunks.push(chunk);
  19997. };
  19998. /**
  19999. * Deflate#onEnd(status) -> Void
  20000. * - status (Number): deflate status. 0 (Z_OK) on success,
  20001. * other if not.
  20002. *
  20003. * Called once after you tell deflate that the input stream is
  20004. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  20005. * or if an error happened. By default - join collected chunks,
  20006. * free memory and fill `results` / `err` properties.
  20007. **/
  20008. Deflate.prototype.onEnd = function(status) {
  20009. // On success - join
  20010. if (status === Z_OK) {
  20011. if (this.options.to === 'string') {
  20012. this.result = this.chunks.join('');
  20013. } else {
  20014. this.result = utils.flattenChunks(this.chunks);
  20015. }
  20016. }
  20017. this.chunks = [];
  20018. this.err = status;
  20019. this.msg = this.strm.msg;
  20020. };
  20021. /**
  20022. * deflate(data[, options]) -> Uint8Array|Array|String
  20023. * - data (Uint8Array|Array|String): input data to compress.
  20024. * - options (Object): zlib deflate options.
  20025. *
  20026. * Compress `data` with deflate alrorythm and `options`.
  20027. *
  20028. * Supported options are:
  20029. *
  20030. * - level
  20031. * - windowBits
  20032. * - memLevel
  20033. * - strategy
  20034. *
  20035. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  20036. * for more information on these.
  20037. *
  20038. * Sugar (options):
  20039. *
  20040. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  20041. * negative windowBits implicitly.
  20042. * - `to` (String) - if equal to 'string', then result will be "binary string"
  20043. * (each char code [0..255])
  20044. *
  20045. * ##### Example:
  20046. *
  20047. * ```javascript
  20048. * var pako = require('pako')
  20049. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  20050. *
  20051. * console.log(pako.deflate(data));
  20052. * ```
  20053. **/
  20054. function deflate(input, options) {
  20055. var deflator = new Deflate(options);
  20056. deflator.push(input, true);
  20057. // That will never happens, if you don't cheat with options :)
  20058. if (deflator.err) { throw deflator.msg; }
  20059. return deflator.result;
  20060. }
  20061. /**
  20062. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  20063. * - data (Uint8Array|Array|String): input data to compress.
  20064. * - options (Object): zlib deflate options.
  20065. *
  20066. * The same as [[deflate]], but creates raw data, without wrapper
  20067. * (header and adler32 crc).
  20068. **/
  20069. function deflateRaw(input, options) {
  20070. options = options || {};
  20071. options.raw = true;
  20072. return deflate(input, options);
  20073. }
  20074. /**
  20075. * gzip(data[, options]) -> Uint8Array|Array|String
  20076. * - data (Uint8Array|Array|String): input data to compress.
  20077. * - options (Object): zlib deflate options.
  20078. *
  20079. * The same as [[deflate]], but create gzip wrapper instead of
  20080. * deflate one.
  20081. **/
  20082. function gzip(input, options) {
  20083. options = options || {};
  20084. options.gzip = true;
  20085. return deflate(input, options);
  20086. }
  20087. exports.Deflate = Deflate;
  20088. exports.deflate = deflate;
  20089. exports.deflateRaw = deflateRaw;
  20090. exports.gzip = gzip;
  20091. },{"./utils/common":75,"./utils/strings":76,"./zlib/deflate.js":80,"./zlib/messages":85,"./zlib/zstream":87}],74:[function(require,module,exports){
  20092. 'use strict';
  20093. var zlib_inflate = require('./zlib/inflate.js');
  20094. var utils = require('./utils/common');
  20095. var strings = require('./utils/strings');
  20096. var c = require('./zlib/constants');
  20097. var msg = require('./zlib/messages');
  20098. var zstream = require('./zlib/zstream');
  20099. var gzheader = require('./zlib/gzheader');
  20100. var toString = Object.prototype.toString;
  20101. /**
  20102. * class Inflate
  20103. *
  20104. * Generic JS-style wrapper for zlib calls. If you don't need
  20105. * streaming behaviour - use more simple functions: [[inflate]]
  20106. * and [[inflateRaw]].
  20107. **/
  20108. /* internal
  20109. * inflate.chunks -> Array
  20110. *
  20111. * Chunks of output data, if [[Inflate#onData]] not overriden.
  20112. **/
  20113. /**
  20114. * Inflate.result -> Uint8Array|Array|String
  20115. *
  20116. * Uncompressed result, generated by default [[Inflate#onData]]
  20117. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  20118. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  20119. * push a chunk with explicit flush (call [[Inflate#push]] with
  20120. * `Z_SYNC_FLUSH` param).
  20121. **/
  20122. /**
  20123. * Inflate.err -> Number
  20124. *
  20125. * Error code after inflate finished. 0 (Z_OK) on success.
  20126. * Should be checked if broken data possible.
  20127. **/
  20128. /**
  20129. * Inflate.msg -> String
  20130. *
  20131. * Error message, if [[Inflate.err]] != 0
  20132. **/
  20133. /**
  20134. * new Inflate(options)
  20135. * - options (Object): zlib inflate options.
  20136. *
  20137. * Creates new inflator instance with specified params. Throws exception
  20138. * on bad params. Supported options:
  20139. *
  20140. * - `windowBits`
  20141. *
  20142. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  20143. * for more information on these.
  20144. *
  20145. * Additional options, for internal needs:
  20146. *
  20147. * - `chunkSize` - size of generated data chunks (16K by default)
  20148. * - `raw` (Boolean) - do raw inflate
  20149. * - `to` (String) - if equal to 'string', then result will be converted
  20150. * from utf8 to utf16 (javascript) string. When string output requested,
  20151. * chunk length can differ from `chunkSize`, depending on content.
  20152. *
  20153. * By default, when no options set, autodetect deflate/gzip data format via
  20154. * wrapper header.
  20155. *
  20156. * ##### Example:
  20157. *
  20158. * ```javascript
  20159. * var pako = require('pako')
  20160. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  20161. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  20162. *
  20163. * var inflate = new pako.Inflate({ level: 3});
  20164. *
  20165. * inflate.push(chunk1, false);
  20166. * inflate.push(chunk2, true); // true -> last chunk
  20167. *
  20168. * if (inflate.err) { throw new Error(inflate.err); }
  20169. *
  20170. * console.log(inflate.result);
  20171. * ```
  20172. **/
  20173. var Inflate = function(options) {
  20174. this.options = utils.assign({
  20175. chunkSize: 16384,
  20176. windowBits: 0,
  20177. to: ''
  20178. }, options || {});
  20179. var opt = this.options;
  20180. // Force window size for `raw` data, if not set directly,
  20181. // because we have no header for autodetect.
  20182. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  20183. opt.windowBits = -opt.windowBits;
  20184. if (opt.windowBits === 0) { opt.windowBits = -15; }
  20185. }
  20186. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  20187. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  20188. !(options && options.windowBits)) {
  20189. opt.windowBits += 32;
  20190. }
  20191. // Gzip header has no info about windows size, we can do autodetect only
  20192. // for deflate. So, if window size not set, force it to max when gzip possible
  20193. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  20194. // bit 3 (16) -> gzipped data
  20195. // bit 4 (32) -> autodetect gzip/deflate
  20196. if ((opt.windowBits & 15) === 0) {
  20197. opt.windowBits |= 15;
  20198. }
  20199. }
  20200. this.err = 0; // error code, if happens (0 = Z_OK)
  20201. this.msg = ''; // error message
  20202. this.ended = false; // used to avoid multiple onEnd() calls
  20203. this.chunks = []; // chunks of compressed data
  20204. this.strm = new zstream();
  20205. this.strm.avail_out = 0;
  20206. var status = zlib_inflate.inflateInit2(
  20207. this.strm,
  20208. opt.windowBits
  20209. );
  20210. if (status !== c.Z_OK) {
  20211. throw new Error(msg[status]);
  20212. }
  20213. this.header = new gzheader();
  20214. zlib_inflate.inflateGetHeader(this.strm, this.header);
  20215. };
  20216. /**
  20217. * Inflate#push(data[, mode]) -> Boolean
  20218. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  20219. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  20220. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  20221. *
  20222. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  20223. * new output chunks. Returns `true` on success. The last data block must have
  20224. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  20225. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  20226. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  20227. *
  20228. * On fail call [[Inflate#onEnd]] with error code and return false.
  20229. *
  20230. * We strongly recommend to use `Uint8Array` on input for best speed (output
  20231. * format is detected automatically). Also, don't skip last param and always
  20232. * use the same type in your code (boolean or number). That will improve JS speed.
  20233. *
  20234. * For regular `Array`-s make sure all elements are [0..255].
  20235. *
  20236. * ##### Example
  20237. *
  20238. * ```javascript
  20239. * push(chunk, false); // push one of data chunks
  20240. * ...
  20241. * push(chunk, true); // push last chunk
  20242. * ```
  20243. **/
  20244. Inflate.prototype.push = function(data, mode) {
  20245. var strm = this.strm;
  20246. var chunkSize = this.options.chunkSize;
  20247. var status, _mode;
  20248. var next_out_utf8, tail, utf8str;
  20249. if (this.ended) { return false; }
  20250. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  20251. // Convert data if needed
  20252. if (typeof data === 'string') {
  20253. // Only binary strings can be decompressed on practice
  20254. strm.input = strings.binstring2buf(data);
  20255. } else if (toString.call(data) === '[object ArrayBuffer]') {
  20256. strm.input = new Uint8Array(data);
  20257. } else {
  20258. strm.input = data;
  20259. }
  20260. strm.next_in = 0;
  20261. strm.avail_in = strm.input.length;
  20262. do {
  20263. if (strm.avail_out === 0) {
  20264. strm.output = new utils.Buf8(chunkSize);
  20265. strm.next_out = 0;
  20266. strm.avail_out = chunkSize;
  20267. }
  20268. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  20269. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  20270. this.onEnd(status);
  20271. this.ended = true;
  20272. return false;
  20273. }
  20274. if (strm.next_out) {
  20275. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  20276. if (this.options.to === 'string') {
  20277. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  20278. tail = strm.next_out - next_out_utf8;
  20279. utf8str = strings.buf2string(strm.output, next_out_utf8);
  20280. // move tail
  20281. strm.next_out = tail;
  20282. strm.avail_out = chunkSize - tail;
  20283. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  20284. this.onData(utf8str);
  20285. } else {
  20286. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  20287. }
  20288. }
  20289. }
  20290. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  20291. if (status === c.Z_STREAM_END) {
  20292. _mode = c.Z_FINISH;
  20293. }
  20294. // Finalize on the last chunk.
  20295. if (_mode === c.Z_FINISH) {
  20296. status = zlib_inflate.inflateEnd(this.strm);
  20297. this.onEnd(status);
  20298. this.ended = true;
  20299. return status === c.Z_OK;
  20300. }
  20301. // callback interim results if Z_SYNC_FLUSH.
  20302. if (_mode === c.Z_SYNC_FLUSH) {
  20303. this.onEnd(c.Z_OK);
  20304. strm.avail_out = 0;
  20305. return true;
  20306. }
  20307. return true;
  20308. };
  20309. /**
  20310. * Inflate#onData(chunk) -> Void
  20311. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  20312. * on js engine support. When string output requested, each chunk
  20313. * will be string.
  20314. *
  20315. * By default, stores data blocks in `chunks[]` property and glue
  20316. * those in `onEnd`. Override this handler, if you need another behaviour.
  20317. **/
  20318. Inflate.prototype.onData = function(chunk) {
  20319. this.chunks.push(chunk);
  20320. };
  20321. /**
  20322. * Inflate#onEnd(status) -> Void
  20323. * - status (Number): inflate status. 0 (Z_OK) on success,
  20324. * other if not.
  20325. *
  20326. * Called either after you tell inflate that the input stream is
  20327. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  20328. * or if an error happened. By default - join collected chunks,
  20329. * free memory and fill `results` / `err` properties.
  20330. **/
  20331. Inflate.prototype.onEnd = function(status) {
  20332. // On success - join
  20333. if (status === c.Z_OK) {
  20334. if (this.options.to === 'string') {
  20335. // Glue & convert here, until we teach pako to send
  20336. // utf8 alligned strings to onData
  20337. this.result = this.chunks.join('');
  20338. } else {
  20339. this.result = utils.flattenChunks(this.chunks);
  20340. }
  20341. }
  20342. this.chunks = [];
  20343. this.err = status;
  20344. this.msg = this.strm.msg;
  20345. };
  20346. /**
  20347. * inflate(data[, options]) -> Uint8Array|Array|String
  20348. * - data (Uint8Array|Array|String): input data to decompress.
  20349. * - options (Object): zlib inflate options.
  20350. *
  20351. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  20352. * format via wrapper header by default. That's why we don't provide
  20353. * separate `ungzip` method.
  20354. *
  20355. * Supported options are:
  20356. *
  20357. * - windowBits
  20358. *
  20359. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  20360. * for more information.
  20361. *
  20362. * Sugar (options):
  20363. *
  20364. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  20365. * negative windowBits implicitly.
  20366. * - `to` (String) - if equal to 'string', then result will be converted
  20367. * from utf8 to utf16 (javascript) string. When string output requested,
  20368. * chunk length can differ from `chunkSize`, depending on content.
  20369. *
  20370. *
  20371. * ##### Example:
  20372. *
  20373. * ```javascript
  20374. * var pako = require('pako')
  20375. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  20376. * , output;
  20377. *
  20378. * try {
  20379. * output = pako.inflate(input);
  20380. * } catch (err)
  20381. * console.log(err);
  20382. * }
  20383. * ```
  20384. **/
  20385. function inflate(input, options) {
  20386. var inflator = new Inflate(options);
  20387. inflator.push(input, true);
  20388. // That will never happens, if you don't cheat with options :)
  20389. if (inflator.err) { throw inflator.msg; }
  20390. return inflator.result;
  20391. }
  20392. /**
  20393. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  20394. * - data (Uint8Array|Array|String): input data to decompress.
  20395. * - options (Object): zlib inflate options.
  20396. *
  20397. * The same as [[inflate]], but creates raw data, without wrapper
  20398. * (header and adler32 crc).
  20399. **/
  20400. function inflateRaw(input, options) {
  20401. options = options || {};
  20402. options.raw = true;
  20403. return inflate(input, options);
  20404. }
  20405. /**
  20406. * ungzip(data[, options]) -> Uint8Array|Array|String
  20407. * - data (Uint8Array|Array|String): input data to decompress.
  20408. * - options (Object): zlib inflate options.
  20409. *
  20410. * Just shortcut to [[inflate]], because it autodetects format
  20411. * by header.content. Done for convenience.
  20412. **/
  20413. exports.Inflate = Inflate;
  20414. exports.inflate = inflate;
  20415. exports.inflateRaw = inflateRaw;
  20416. exports.ungzip = inflate;
  20417. },{"./utils/common":75,"./utils/strings":76,"./zlib/constants":78,"./zlib/gzheader":81,"./zlib/inflate.js":83,"./zlib/messages":85,"./zlib/zstream":87}],75:[function(require,module,exports){
  20418. 'use strict';
  20419. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  20420. (typeof Uint16Array !== 'undefined') &&
  20421. (typeof Int32Array !== 'undefined');
  20422. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  20423. var sources = Array.prototype.slice.call(arguments, 1);
  20424. while (sources.length) {
  20425. var source = sources.shift();
  20426. if (!source) { continue; }
  20427. if (typeof source !== 'object') {
  20428. throw new TypeError(source + 'must be non-object');
  20429. }
  20430. for (var p in source) {
  20431. if (source.hasOwnProperty(p)) {
  20432. obj[p] = source[p];
  20433. }
  20434. }
  20435. }
  20436. return obj;
  20437. };
  20438. // reduce buffer size, avoiding mem copy
  20439. exports.shrinkBuf = function (buf, size) {
  20440. if (buf.length === size) { return buf; }
  20441. if (buf.subarray) { return buf.subarray(0, size); }
  20442. buf.length = size;
  20443. return buf;
  20444. };
  20445. var fnTyped = {
  20446. arraySet: function (dest, src, src_offs, len, dest_offs) {
  20447. if (src.subarray && dest.subarray) {
  20448. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  20449. return;
  20450. }
  20451. // Fallback to ordinary array
  20452. for (var i=0; i<len; i++) {
  20453. dest[dest_offs + i] = src[src_offs + i];
  20454. }
  20455. },
  20456. // Join array of chunks to single array.
  20457. flattenChunks: function(chunks) {
  20458. var i, l, len, pos, chunk, result;
  20459. // calculate data length
  20460. len = 0;
  20461. for (i=0, l=chunks.length; i<l; i++) {
  20462. len += chunks[i].length;
  20463. }
  20464. // join chunks
  20465. result = new Uint8Array(len);
  20466. pos = 0;
  20467. for (i=0, l=chunks.length; i<l; i++) {
  20468. chunk = chunks[i];
  20469. result.set(chunk, pos);
  20470. pos += chunk.length;
  20471. }
  20472. return result;
  20473. }
  20474. };
  20475. var fnUntyped = {
  20476. arraySet: function (dest, src, src_offs, len, dest_offs) {
  20477. for (var i=0; i<len; i++) {
  20478. dest[dest_offs + i] = src[src_offs + i];
  20479. }
  20480. },
  20481. // Join array of chunks to single array.
  20482. flattenChunks: function(chunks) {
  20483. return [].concat.apply([], chunks);
  20484. }
  20485. };
  20486. // Enable/Disable typed arrays use, for testing
  20487. //
  20488. exports.setTyped = function (on) {
  20489. if (on) {
  20490. exports.Buf8 = Uint8Array;
  20491. exports.Buf16 = Uint16Array;
  20492. exports.Buf32 = Int32Array;
  20493. exports.assign(exports, fnTyped);
  20494. } else {
  20495. exports.Buf8 = Array;
  20496. exports.Buf16 = Array;
  20497. exports.Buf32 = Array;
  20498. exports.assign(exports, fnUntyped);
  20499. }
  20500. };
  20501. exports.setTyped(TYPED_OK);
  20502. },{}],76:[function(require,module,exports){
  20503. // String encode/decode helpers
  20504. 'use strict';
  20505. var utils = require('./common');
  20506. // Quick check if we can use fast array to bin string conversion
  20507. //
  20508. // - apply(Array) can fail on Android 2.2
  20509. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  20510. //
  20511. var STR_APPLY_OK = true;
  20512. var STR_APPLY_UIA_OK = true;
  20513. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  20514. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  20515. // Table with utf8 lengths (calculated by first byte of sequence)
  20516. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  20517. // because max possible codepoint is 0x10ffff
  20518. var _utf8len = new utils.Buf8(256);
  20519. for (var q=0; q<256; q++) {
  20520. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  20521. }
  20522. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  20523. // convert string to array (typed, when possible)
  20524. exports.string2buf = function (str) {
  20525. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  20526. // count binary size
  20527. for (m_pos = 0; m_pos < str_len; m_pos++) {
  20528. c = str.charCodeAt(m_pos);
  20529. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  20530. c2 = str.charCodeAt(m_pos+1);
  20531. if ((c2 & 0xfc00) === 0xdc00) {
  20532. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  20533. m_pos++;
  20534. }
  20535. }
  20536. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  20537. }
  20538. // allocate buffer
  20539. buf = new utils.Buf8(buf_len);
  20540. // convert
  20541. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  20542. c = str.charCodeAt(m_pos);
  20543. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  20544. c2 = str.charCodeAt(m_pos+1);
  20545. if ((c2 & 0xfc00) === 0xdc00) {
  20546. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  20547. m_pos++;
  20548. }
  20549. }
  20550. if (c < 0x80) {
  20551. /* one byte */
  20552. buf[i++] = c;
  20553. } else if (c < 0x800) {
  20554. /* two bytes */
  20555. buf[i++] = 0xC0 | (c >>> 6);
  20556. buf[i++] = 0x80 | (c & 0x3f);
  20557. } else if (c < 0x10000) {
  20558. /* three bytes */
  20559. buf[i++] = 0xE0 | (c >>> 12);
  20560. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  20561. buf[i++] = 0x80 | (c & 0x3f);
  20562. } else {
  20563. /* four bytes */
  20564. buf[i++] = 0xf0 | (c >>> 18);
  20565. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  20566. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  20567. buf[i++] = 0x80 | (c & 0x3f);
  20568. }
  20569. }
  20570. return buf;
  20571. };
  20572. // Helper (used in 2 places)
  20573. function buf2binstring(buf, len) {
  20574. // use fallback for big arrays to avoid stack overflow
  20575. if (len < 65537) {
  20576. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  20577. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  20578. }
  20579. }
  20580. var result = '';
  20581. for (var i=0; i < len; i++) {
  20582. result += String.fromCharCode(buf[i]);
  20583. }
  20584. return result;
  20585. }
  20586. // Convert byte array to binary string
  20587. exports.buf2binstring = function(buf) {
  20588. return buf2binstring(buf, buf.length);
  20589. };
  20590. // Convert binary string (typed, when possible)
  20591. exports.binstring2buf = function(str) {
  20592. var buf = new utils.Buf8(str.length);
  20593. for (var i=0, len=buf.length; i < len; i++) {
  20594. buf[i] = str.charCodeAt(i);
  20595. }
  20596. return buf;
  20597. };
  20598. // convert array to string
  20599. exports.buf2string = function (buf, max) {
  20600. var i, out, c, c_len;
  20601. var len = max || buf.length;
  20602. // Reserve max possible length (2 words per char)
  20603. // NB: by unknown reasons, Array is significantly faster for
  20604. // String.fromCharCode.apply than Uint16Array.
  20605. var utf16buf = new Array(len*2);
  20606. for (out=0, i=0; i<len;) {
  20607. c = buf[i++];
  20608. // quick process ascii
  20609. if (c < 0x80) { utf16buf[out++] = c; continue; }
  20610. c_len = _utf8len[c];
  20611. // skip 5 & 6 byte codes
  20612. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  20613. // apply mask on first byte
  20614. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  20615. // join the rest
  20616. while (c_len > 1 && i < len) {
  20617. c = (c << 6) | (buf[i++] & 0x3f);
  20618. c_len--;
  20619. }
  20620. // terminated by end of string?
  20621. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  20622. if (c < 0x10000) {
  20623. utf16buf[out++] = c;
  20624. } else {
  20625. c -= 0x10000;
  20626. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  20627. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  20628. }
  20629. }
  20630. return buf2binstring(utf16buf, out);
  20631. };
  20632. // Calculate max possible position in utf8 buffer,
  20633. // that will not break sequence. If that's not possible
  20634. // - (very small limits) return max size as is.
  20635. //
  20636. // buf[] - utf8 bytes array
  20637. // max - length limit (mandatory);
  20638. exports.utf8border = function(buf, max) {
  20639. var pos;
  20640. max = max || buf.length;
  20641. if (max > buf.length) { max = buf.length; }
  20642. // go back from last position, until start of sequence found
  20643. pos = max-1;
  20644. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  20645. // Fuckup - very small and broken sequence,
  20646. // return max, because we should return something anyway.
  20647. if (pos < 0) { return max; }
  20648. // If we came to start of buffer - that means vuffer is too small,
  20649. // return max too.
  20650. if (pos === 0) { return max; }
  20651. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  20652. };
  20653. },{"./common":75}],77:[function(require,module,exports){
  20654. 'use strict';
  20655. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  20656. // It doesn't worth to make additional optimizationa as in original.
  20657. // Small size is preferable.
  20658. function adler32(adler, buf, len, pos) {
  20659. var s1 = (adler & 0xffff) |0,
  20660. s2 = ((adler >>> 16) & 0xffff) |0,
  20661. n = 0;
  20662. while (len !== 0) {
  20663. // Set limit ~ twice less than 5552, to keep
  20664. // s2 in 31-bits, because we force signed ints.
  20665. // in other case %= will fail.
  20666. n = len > 2000 ? 2000 : len;
  20667. len -= n;
  20668. do {
  20669. s1 = (s1 + buf[pos++]) |0;
  20670. s2 = (s2 + s1) |0;
  20671. } while (--n);
  20672. s1 %= 65521;
  20673. s2 %= 65521;
  20674. }
  20675. return (s1 | (s2 << 16)) |0;
  20676. }
  20677. module.exports = adler32;
  20678. },{}],78:[function(require,module,exports){
  20679. module.exports = {
  20680. /* Allowed flush values; see deflate() and inflate() below for details */
  20681. Z_NO_FLUSH: 0,
  20682. Z_PARTIAL_FLUSH: 1,
  20683. Z_SYNC_FLUSH: 2,
  20684. Z_FULL_FLUSH: 3,
  20685. Z_FINISH: 4,
  20686. Z_BLOCK: 5,
  20687. Z_TREES: 6,
  20688. /* Return codes for the compression/decompression functions. Negative values
  20689. * are errors, positive values are used for special but normal events.
  20690. */
  20691. Z_OK: 0,
  20692. Z_STREAM_END: 1,
  20693. Z_NEED_DICT: 2,
  20694. Z_ERRNO: -1,
  20695. Z_STREAM_ERROR: -2,
  20696. Z_DATA_ERROR: -3,
  20697. //Z_MEM_ERROR: -4,
  20698. Z_BUF_ERROR: -5,
  20699. //Z_VERSION_ERROR: -6,
  20700. /* compression levels */
  20701. Z_NO_COMPRESSION: 0,
  20702. Z_BEST_SPEED: 1,
  20703. Z_BEST_COMPRESSION: 9,
  20704. Z_DEFAULT_COMPRESSION: -1,
  20705. Z_FILTERED: 1,
  20706. Z_HUFFMAN_ONLY: 2,
  20707. Z_RLE: 3,
  20708. Z_FIXED: 4,
  20709. Z_DEFAULT_STRATEGY: 0,
  20710. /* Possible values of the data_type field (though see inflate()) */
  20711. Z_BINARY: 0,
  20712. Z_TEXT: 1,
  20713. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  20714. Z_UNKNOWN: 2,
  20715. /* The deflate compression method */
  20716. Z_DEFLATED: 8
  20717. //Z_NULL: null // Use -1 or null inline, depending on var type
  20718. };
  20719. },{}],79:[function(require,module,exports){
  20720. 'use strict';
  20721. // Note: we can't get significant speed boost here.
  20722. // So write code to minimize size - no pregenerated tables
  20723. // and array tools dependencies.
  20724. // Use ordinary array, since untyped makes no boost here
  20725. function makeTable() {
  20726. var c, table = [];
  20727. for (var n =0; n < 256; n++) {
  20728. c = n;
  20729. for (var k =0; k < 8; k++) {
  20730. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  20731. }
  20732. table[n] = c;
  20733. }
  20734. return table;
  20735. }
  20736. // Create table on load. Just 255 signed longs. Not a problem.
  20737. var crcTable = makeTable();
  20738. function crc32(crc, buf, len, pos) {
  20739. var t = crcTable,
  20740. end = pos + len;
  20741. crc = crc ^ (-1);
  20742. for (var i = pos; i < end; i++) {
  20743. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  20744. }
  20745. return (crc ^ (-1)); // >>> 0;
  20746. }
  20747. module.exports = crc32;
  20748. },{}],80:[function(require,module,exports){
  20749. 'use strict';
  20750. var utils = require('../utils/common');
  20751. var trees = require('./trees');
  20752. var adler32 = require('./adler32');
  20753. var crc32 = require('./crc32');
  20754. var msg = require('./messages');
  20755. /* Public constants ==========================================================*/
  20756. /* ===========================================================================*/
  20757. /* Allowed flush values; see deflate() and inflate() below for details */
  20758. var Z_NO_FLUSH = 0;
  20759. var Z_PARTIAL_FLUSH = 1;
  20760. //var Z_SYNC_FLUSH = 2;
  20761. var Z_FULL_FLUSH = 3;
  20762. var Z_FINISH = 4;
  20763. var Z_BLOCK = 5;
  20764. //var Z_TREES = 6;
  20765. /* Return codes for the compression/decompression functions. Negative values
  20766. * are errors, positive values are used for special but normal events.
  20767. */
  20768. var Z_OK = 0;
  20769. var Z_STREAM_END = 1;
  20770. //var Z_NEED_DICT = 2;
  20771. //var Z_ERRNO = -1;
  20772. var Z_STREAM_ERROR = -2;
  20773. var Z_DATA_ERROR = -3;
  20774. //var Z_MEM_ERROR = -4;
  20775. var Z_BUF_ERROR = -5;
  20776. //var Z_VERSION_ERROR = -6;
  20777. /* compression levels */
  20778. //var Z_NO_COMPRESSION = 0;
  20779. //var Z_BEST_SPEED = 1;
  20780. //var Z_BEST_COMPRESSION = 9;
  20781. var Z_DEFAULT_COMPRESSION = -1;
  20782. var Z_FILTERED = 1;
  20783. var Z_HUFFMAN_ONLY = 2;
  20784. var Z_RLE = 3;
  20785. var Z_FIXED = 4;
  20786. var Z_DEFAULT_STRATEGY = 0;
  20787. /* Possible values of the data_type field (though see inflate()) */
  20788. //var Z_BINARY = 0;
  20789. //var Z_TEXT = 1;
  20790. //var Z_ASCII = 1; // = Z_TEXT
  20791. var Z_UNKNOWN = 2;
  20792. /* The deflate compression method */
  20793. var Z_DEFLATED = 8;
  20794. /*============================================================================*/
  20795. var MAX_MEM_LEVEL = 9;
  20796. /* Maximum value for memLevel in deflateInit2 */
  20797. var MAX_WBITS = 15;
  20798. /* 32K LZ77 window */
  20799. var DEF_MEM_LEVEL = 8;
  20800. var LENGTH_CODES = 29;
  20801. /* number of length codes, not counting the special END_BLOCK code */
  20802. var LITERALS = 256;
  20803. /* number of literal bytes 0..255 */
  20804. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  20805. /* number of Literal or Length codes, including the END_BLOCK code */
  20806. var D_CODES = 30;
  20807. /* number of distance codes */
  20808. var BL_CODES = 19;
  20809. /* number of codes used to transfer the bit lengths */
  20810. var HEAP_SIZE = 2*L_CODES + 1;
  20811. /* maximum heap size */
  20812. var MAX_BITS = 15;
  20813. /* All codes must not exceed MAX_BITS bits */
  20814. var MIN_MATCH = 3;
  20815. var MAX_MATCH = 258;
  20816. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  20817. var PRESET_DICT = 0x20;
  20818. var INIT_STATE = 42;
  20819. var EXTRA_STATE = 69;
  20820. var NAME_STATE = 73;
  20821. var COMMENT_STATE = 91;
  20822. var HCRC_STATE = 103;
  20823. var BUSY_STATE = 113;
  20824. var FINISH_STATE = 666;
  20825. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  20826. var BS_BLOCK_DONE = 2; /* block flush performed */
  20827. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  20828. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  20829. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  20830. function err(strm, errorCode) {
  20831. strm.msg = msg[errorCode];
  20832. return errorCode;
  20833. }
  20834. function rank(f) {
  20835. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  20836. }
  20837. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  20838. /* =========================================================================
  20839. * Flush as much pending output as possible. All deflate() output goes
  20840. * through this function so some applications may wish to modify it
  20841. * to avoid allocating a large strm->output buffer and copying into it.
  20842. * (See also read_buf()).
  20843. */
  20844. function flush_pending(strm) {
  20845. var s = strm.state;
  20846. //_tr_flush_bits(s);
  20847. var len = s.pending;
  20848. if (len > strm.avail_out) {
  20849. len = strm.avail_out;
  20850. }
  20851. if (len === 0) { return; }
  20852. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  20853. strm.next_out += len;
  20854. s.pending_out += len;
  20855. strm.total_out += len;
  20856. strm.avail_out -= len;
  20857. s.pending -= len;
  20858. if (s.pending === 0) {
  20859. s.pending_out = 0;
  20860. }
  20861. }
  20862. function flush_block_only (s, last) {
  20863. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  20864. s.block_start = s.strstart;
  20865. flush_pending(s.strm);
  20866. }
  20867. function put_byte(s, b) {
  20868. s.pending_buf[s.pending++] = b;
  20869. }
  20870. /* =========================================================================
  20871. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  20872. * IN assertion: the stream state is correct and there is enough room in
  20873. * pending_buf.
  20874. */
  20875. function putShortMSB(s, b) {
  20876. // put_byte(s, (Byte)(b >> 8));
  20877. // put_byte(s, (Byte)(b & 0xff));
  20878. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  20879. s.pending_buf[s.pending++] = b & 0xff;
  20880. }
  20881. /* ===========================================================================
  20882. * Read a new buffer from the current input stream, update the adler32
  20883. * and total number of bytes read. All deflate() input goes through
  20884. * this function so some applications may wish to modify it to avoid
  20885. * allocating a large strm->input buffer and copying from it.
  20886. * (See also flush_pending()).
  20887. */
  20888. function read_buf(strm, buf, start, size) {
  20889. var len = strm.avail_in;
  20890. if (len > size) { len = size; }
  20891. if (len === 0) { return 0; }
  20892. strm.avail_in -= len;
  20893. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  20894. if (strm.state.wrap === 1) {
  20895. strm.adler = adler32(strm.adler, buf, len, start);
  20896. }
  20897. else if (strm.state.wrap === 2) {
  20898. strm.adler = crc32(strm.adler, buf, len, start);
  20899. }
  20900. strm.next_in += len;
  20901. strm.total_in += len;
  20902. return len;
  20903. }
  20904. /* ===========================================================================
  20905. * Set match_start to the longest match starting at the given string and
  20906. * return its length. Matches shorter or equal to prev_length are discarded,
  20907. * in which case the result is equal to prev_length and match_start is
  20908. * garbage.
  20909. * IN assertions: cur_match is the head of the hash chain for the current
  20910. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  20911. * OUT assertion: the match length is not greater than s->lookahead.
  20912. */
  20913. function longest_match(s, cur_match) {
  20914. var chain_length = s.max_chain_length; /* max hash chain length */
  20915. var scan = s.strstart; /* current string */
  20916. var match; /* matched string */
  20917. var len; /* length of current match */
  20918. var best_len = s.prev_length; /* best match length so far */
  20919. var nice_match = s.nice_match; /* stop if match long enough */
  20920. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  20921. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  20922. var _win = s.window; // shortcut
  20923. var wmask = s.w_mask;
  20924. var prev = s.prev;
  20925. /* Stop when cur_match becomes <= limit. To simplify the code,
  20926. * we prevent matches with the string of window index 0.
  20927. */
  20928. var strend = s.strstart + MAX_MATCH;
  20929. var scan_end1 = _win[scan + best_len - 1];
  20930. var scan_end = _win[scan + best_len];
  20931. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  20932. * It is easy to get rid of this optimization if necessary.
  20933. */
  20934. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  20935. /* Do not waste too much time if we already have a good match: */
  20936. if (s.prev_length >= s.good_match) {
  20937. chain_length >>= 2;
  20938. }
  20939. /* Do not look for matches beyond the end of the input. This is necessary
  20940. * to make deflate deterministic.
  20941. */
  20942. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  20943. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  20944. do {
  20945. // Assert(cur_match < s->strstart, "no future");
  20946. match = cur_match;
  20947. /* Skip to next match if the match length cannot increase
  20948. * or if the match length is less than 2. Note that the checks below
  20949. * for insufficient lookahead only occur occasionally for performance
  20950. * reasons. Therefore uninitialized memory will be accessed, and
  20951. * conditional jumps will be made that depend on those values.
  20952. * However the length of the match is limited to the lookahead, so
  20953. * the output of deflate is not affected by the uninitialized values.
  20954. */
  20955. if (_win[match + best_len] !== scan_end ||
  20956. _win[match + best_len - 1] !== scan_end1 ||
  20957. _win[match] !== _win[scan] ||
  20958. _win[++match] !== _win[scan + 1]) {
  20959. continue;
  20960. }
  20961. /* The check at best_len-1 can be removed because it will be made
  20962. * again later. (This heuristic is not always a win.)
  20963. * It is not necessary to compare scan[2] and match[2] since they
  20964. * are always equal when the other bytes match, given that
  20965. * the hash keys are equal and that HASH_BITS >= 8.
  20966. */
  20967. scan += 2;
  20968. match++;
  20969. // Assert(*scan == *match, "match[2]?");
  20970. /* We check for insufficient lookahead only every 8th comparison;
  20971. * the 256th check will be made at strstart+258.
  20972. */
  20973. do {
  20974. /*jshint noempty:false*/
  20975. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20976. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20977. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20978. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20979. scan < strend);
  20980. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  20981. len = MAX_MATCH - (strend - scan);
  20982. scan = strend - MAX_MATCH;
  20983. if (len > best_len) {
  20984. s.match_start = cur_match;
  20985. best_len = len;
  20986. if (len >= nice_match) {
  20987. break;
  20988. }
  20989. scan_end1 = _win[scan + best_len - 1];
  20990. scan_end = _win[scan + best_len];
  20991. }
  20992. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  20993. if (best_len <= s.lookahead) {
  20994. return best_len;
  20995. }
  20996. return s.lookahead;
  20997. }
  20998. /* ===========================================================================
  20999. * Fill the window when the lookahead becomes insufficient.
  21000. * Updates strstart and lookahead.
  21001. *
  21002. * IN assertion: lookahead < MIN_LOOKAHEAD
  21003. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  21004. * At least one byte has been read, or avail_in == 0; reads are
  21005. * performed for at least two bytes (required for the zip translate_eol
  21006. * option -- not supported here).
  21007. */
  21008. function fill_window(s) {
  21009. var _w_size = s.w_size;
  21010. var p, n, m, more, str;
  21011. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  21012. do {
  21013. more = s.window_size - s.lookahead - s.strstart;
  21014. // JS ints have 32 bit, block below not needed
  21015. /* Deal with !@#$% 64K limit: */
  21016. //if (sizeof(int) <= 2) {
  21017. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  21018. // more = wsize;
  21019. //
  21020. // } else if (more == (unsigned)(-1)) {
  21021. // /* Very unlikely, but possible on 16 bit machine if
  21022. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  21023. // */
  21024. // more--;
  21025. // }
  21026. //}
  21027. /* If the window is almost full and there is insufficient lookahead,
  21028. * move the upper half to the lower one to make room in the upper half.
  21029. */
  21030. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  21031. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  21032. s.match_start -= _w_size;
  21033. s.strstart -= _w_size;
  21034. /* we now have strstart >= MAX_DIST */
  21035. s.block_start -= _w_size;
  21036. /* Slide the hash table (could be avoided with 32 bit values
  21037. at the expense of memory usage). We slide even when level == 0
  21038. to keep the hash table consistent if we switch back to level > 0
  21039. later. (Using level 0 permanently is not an optimal usage of
  21040. zlib, so we don't care about this pathological case.)
  21041. */
  21042. n = s.hash_size;
  21043. p = n;
  21044. do {
  21045. m = s.head[--p];
  21046. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  21047. } while (--n);
  21048. n = _w_size;
  21049. p = n;
  21050. do {
  21051. m = s.prev[--p];
  21052. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  21053. /* If n is not on any hash chain, prev[n] is garbage but
  21054. * its value will never be used.
  21055. */
  21056. } while (--n);
  21057. more += _w_size;
  21058. }
  21059. if (s.strm.avail_in === 0) {
  21060. break;
  21061. }
  21062. /* If there was no sliding:
  21063. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  21064. * more == window_size - lookahead - strstart
  21065. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  21066. * => more >= window_size - 2*WSIZE + 2
  21067. * In the BIG_MEM or MMAP case (not yet supported),
  21068. * window_size == input_size + MIN_LOOKAHEAD &&
  21069. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  21070. * Otherwise, window_size == 2*WSIZE so more >= 2.
  21071. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  21072. */
  21073. //Assert(more >= 2, "more < 2");
  21074. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  21075. s.lookahead += n;
  21076. /* Initialize the hash value now that we have some input: */
  21077. if (s.lookahead + s.insert >= MIN_MATCH) {
  21078. str = s.strstart - s.insert;
  21079. s.ins_h = s.window[str];
  21080. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  21081. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  21082. //#if MIN_MATCH != 3
  21083. // Call update_hash() MIN_MATCH-3 more times
  21084. //#endif
  21085. while (s.insert) {
  21086. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  21087. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  21088. s.prev[str & s.w_mask] = s.head[s.ins_h];
  21089. s.head[s.ins_h] = str;
  21090. str++;
  21091. s.insert--;
  21092. if (s.lookahead + s.insert < MIN_MATCH) {
  21093. break;
  21094. }
  21095. }
  21096. }
  21097. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  21098. * but this is not important since only literal bytes will be emitted.
  21099. */
  21100. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  21101. /* If the WIN_INIT bytes after the end of the current data have never been
  21102. * written, then zero those bytes in order to avoid memory check reports of
  21103. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  21104. * the longest match routines. Update the high water mark for the next
  21105. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  21106. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  21107. */
  21108. // if (s.high_water < s.window_size) {
  21109. // var curr = s.strstart + s.lookahead;
  21110. // var init = 0;
  21111. //
  21112. // if (s.high_water < curr) {
  21113. // /* Previous high water mark below current data -- zero WIN_INIT
  21114. // * bytes or up to end of window, whichever is less.
  21115. // */
  21116. // init = s.window_size - curr;
  21117. // if (init > WIN_INIT)
  21118. // init = WIN_INIT;
  21119. // zmemzero(s->window + curr, (unsigned)init);
  21120. // s->high_water = curr + init;
  21121. // }
  21122. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  21123. // /* High water mark at or above current data, but below current data
  21124. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  21125. // * to end of window, whichever is less.
  21126. // */
  21127. // init = (ulg)curr + WIN_INIT - s->high_water;
  21128. // if (init > s->window_size - s->high_water)
  21129. // init = s->window_size - s->high_water;
  21130. // zmemzero(s->window + s->high_water, (unsigned)init);
  21131. // s->high_water += init;
  21132. // }
  21133. // }
  21134. //
  21135. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  21136. // "not enough room for search");
  21137. }
  21138. /* ===========================================================================
  21139. * Copy without compression as much as possible from the input stream, return
  21140. * the current block state.
  21141. * This function does not insert new strings in the dictionary since
  21142. * uncompressible data is probably not useful. This function is used
  21143. * only for the level=0 compression option.
  21144. * NOTE: this function should be optimized to avoid extra copying from
  21145. * window to pending_buf.
  21146. */
  21147. function deflate_stored(s, flush) {
  21148. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  21149. * to pending_buf_size, and each stored block has a 5 byte header:
  21150. */
  21151. var max_block_size = 0xffff;
  21152. if (max_block_size > s.pending_buf_size - 5) {
  21153. max_block_size = s.pending_buf_size - 5;
  21154. }
  21155. /* Copy as much as possible from input to output: */
  21156. for (;;) {
  21157. /* Fill the window as much as possible: */
  21158. if (s.lookahead <= 1) {
  21159. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  21160. // s->block_start >= (long)s->w_size, "slide too late");
  21161. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  21162. // s.block_start >= s.w_size)) {
  21163. // throw new Error("slide too late");
  21164. // }
  21165. fill_window(s);
  21166. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  21167. return BS_NEED_MORE;
  21168. }
  21169. if (s.lookahead === 0) {
  21170. break;
  21171. }
  21172. /* flush the current block */
  21173. }
  21174. //Assert(s->block_start >= 0L, "block gone");
  21175. // if (s.block_start < 0) throw new Error("block gone");
  21176. s.strstart += s.lookahead;
  21177. s.lookahead = 0;
  21178. /* Emit a stored block if pending_buf will be full: */
  21179. var max_start = s.block_start + max_block_size;
  21180. if (s.strstart === 0 || s.strstart >= max_start) {
  21181. /* strstart == 0 is possible when wraparound on 16-bit machine */
  21182. s.lookahead = s.strstart - max_start;
  21183. s.strstart = max_start;
  21184. /*** FLUSH_BLOCK(s, 0); ***/
  21185. flush_block_only(s, false);
  21186. if (s.strm.avail_out === 0) {
  21187. return BS_NEED_MORE;
  21188. }
  21189. /***/
  21190. }
  21191. /* Flush if we may have to slide, otherwise block_start may become
  21192. * negative and the data will be gone:
  21193. */
  21194. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  21195. /*** FLUSH_BLOCK(s, 0); ***/
  21196. flush_block_only(s, false);
  21197. if (s.strm.avail_out === 0) {
  21198. return BS_NEED_MORE;
  21199. }
  21200. /***/
  21201. }
  21202. }
  21203. s.insert = 0;
  21204. if (flush === Z_FINISH) {
  21205. /*** FLUSH_BLOCK(s, 1); ***/
  21206. flush_block_only(s, true);
  21207. if (s.strm.avail_out === 0) {
  21208. return BS_FINISH_STARTED;
  21209. }
  21210. /***/
  21211. return BS_FINISH_DONE;
  21212. }
  21213. if (s.strstart > s.block_start) {
  21214. /*** FLUSH_BLOCK(s, 0); ***/
  21215. flush_block_only(s, false);
  21216. if (s.strm.avail_out === 0) {
  21217. return BS_NEED_MORE;
  21218. }
  21219. /***/
  21220. }
  21221. return BS_NEED_MORE;
  21222. }
  21223. /* ===========================================================================
  21224. * Compress as much as possible from the input stream, return the current
  21225. * block state.
  21226. * This function does not perform lazy evaluation of matches and inserts
  21227. * new strings in the dictionary only for unmatched strings or for short
  21228. * matches. It is used only for the fast compression options.
  21229. */
  21230. function deflate_fast(s, flush) {
  21231. var hash_head; /* head of the hash chain */
  21232. var bflush; /* set if current block must be flushed */
  21233. for (;;) {
  21234. /* Make sure that we always have enough lookahead, except
  21235. * at the end of the input file. We need MAX_MATCH bytes
  21236. * for the next match, plus MIN_MATCH bytes to insert the
  21237. * string following the next match.
  21238. */
  21239. if (s.lookahead < MIN_LOOKAHEAD) {
  21240. fill_window(s);
  21241. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  21242. return BS_NEED_MORE;
  21243. }
  21244. if (s.lookahead === 0) {
  21245. break; /* flush the current block */
  21246. }
  21247. }
  21248. /* Insert the string window[strstart .. strstart+2] in the
  21249. * dictionary, and set hash_head to the head of the hash chain:
  21250. */
  21251. hash_head = 0/*NIL*/;
  21252. if (s.lookahead >= MIN_MATCH) {
  21253. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21254. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21255. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21256. s.head[s.ins_h] = s.strstart;
  21257. /***/
  21258. }
  21259. /* Find the longest match, discarding those <= prev_length.
  21260. * At this point we have always match_length < MIN_MATCH
  21261. */
  21262. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  21263. /* To simplify the code, we prevent matches with the string
  21264. * of window index 0 (in particular we have to avoid a match
  21265. * of the string with itself at the start of the input file).
  21266. */
  21267. s.match_length = longest_match(s, hash_head);
  21268. /* longest_match() sets match_start */
  21269. }
  21270. if (s.match_length >= MIN_MATCH) {
  21271. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  21272. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  21273. s.match_length - MIN_MATCH, bflush); ***/
  21274. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  21275. s.lookahead -= s.match_length;
  21276. /* Insert new strings in the hash table only if the match length
  21277. * is not too large. This saves time but degrades compression.
  21278. */
  21279. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  21280. s.match_length--; /* string at strstart already in table */
  21281. do {
  21282. s.strstart++;
  21283. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21284. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21285. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21286. s.head[s.ins_h] = s.strstart;
  21287. /***/
  21288. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  21289. * always MIN_MATCH bytes ahead.
  21290. */
  21291. } while (--s.match_length !== 0);
  21292. s.strstart++;
  21293. } else
  21294. {
  21295. s.strstart += s.match_length;
  21296. s.match_length = 0;
  21297. s.ins_h = s.window[s.strstart];
  21298. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  21299. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  21300. //#if MIN_MATCH != 3
  21301. // Call UPDATE_HASH() MIN_MATCH-3 more times
  21302. //#endif
  21303. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  21304. * matter since it will be recomputed at next deflate call.
  21305. */
  21306. }
  21307. } else {
  21308. /* No match, output a literal byte */
  21309. //Tracevv((stderr,"%c", s.window[s.strstart]));
  21310. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21311. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21312. s.lookahead--;
  21313. s.strstart++;
  21314. }
  21315. if (bflush) {
  21316. /*** FLUSH_BLOCK(s, 0); ***/
  21317. flush_block_only(s, false);
  21318. if (s.strm.avail_out === 0) {
  21319. return BS_NEED_MORE;
  21320. }
  21321. /***/
  21322. }
  21323. }
  21324. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  21325. if (flush === Z_FINISH) {
  21326. /*** FLUSH_BLOCK(s, 1); ***/
  21327. flush_block_only(s, true);
  21328. if (s.strm.avail_out === 0) {
  21329. return BS_FINISH_STARTED;
  21330. }
  21331. /***/
  21332. return BS_FINISH_DONE;
  21333. }
  21334. if (s.last_lit) {
  21335. /*** FLUSH_BLOCK(s, 0); ***/
  21336. flush_block_only(s, false);
  21337. if (s.strm.avail_out === 0) {
  21338. return BS_NEED_MORE;
  21339. }
  21340. /***/
  21341. }
  21342. return BS_BLOCK_DONE;
  21343. }
  21344. /* ===========================================================================
  21345. * Same as above, but achieves better compression. We use a lazy
  21346. * evaluation for matches: a match is finally adopted only if there is
  21347. * no better match at the next window position.
  21348. */
  21349. function deflate_slow(s, flush) {
  21350. var hash_head; /* head of hash chain */
  21351. var bflush; /* set if current block must be flushed */
  21352. var max_insert;
  21353. /* Process the input block. */
  21354. for (;;) {
  21355. /* Make sure that we always have enough lookahead, except
  21356. * at the end of the input file. We need MAX_MATCH bytes
  21357. * for the next match, plus MIN_MATCH bytes to insert the
  21358. * string following the next match.
  21359. */
  21360. if (s.lookahead < MIN_LOOKAHEAD) {
  21361. fill_window(s);
  21362. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  21363. return BS_NEED_MORE;
  21364. }
  21365. if (s.lookahead === 0) { break; } /* flush the current block */
  21366. }
  21367. /* Insert the string window[strstart .. strstart+2] in the
  21368. * dictionary, and set hash_head to the head of the hash chain:
  21369. */
  21370. hash_head = 0/*NIL*/;
  21371. if (s.lookahead >= MIN_MATCH) {
  21372. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21373. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21374. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21375. s.head[s.ins_h] = s.strstart;
  21376. /***/
  21377. }
  21378. /* Find the longest match, discarding those <= prev_length.
  21379. */
  21380. s.prev_length = s.match_length;
  21381. s.prev_match = s.match_start;
  21382. s.match_length = MIN_MATCH-1;
  21383. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  21384. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  21385. /* To simplify the code, we prevent matches with the string
  21386. * of window index 0 (in particular we have to avoid a match
  21387. * of the string with itself at the start of the input file).
  21388. */
  21389. s.match_length = longest_match(s, hash_head);
  21390. /* longest_match() sets match_start */
  21391. if (s.match_length <= 5 &&
  21392. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  21393. /* If prev_match is also MIN_MATCH, match_start is garbage
  21394. * but we will ignore the current match anyway.
  21395. */
  21396. s.match_length = MIN_MATCH-1;
  21397. }
  21398. }
  21399. /* If there was a match at the previous step and the current
  21400. * match is not better, output the previous match:
  21401. */
  21402. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  21403. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  21404. /* Do not insert strings in hash table beyond this. */
  21405. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  21406. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  21407. s.prev_length - MIN_MATCH, bflush);***/
  21408. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  21409. /* Insert in hash table all strings up to the end of the match.
  21410. * strstart-1 and strstart are already inserted. If there is not
  21411. * enough lookahead, the last two strings are not inserted in
  21412. * the hash table.
  21413. */
  21414. s.lookahead -= s.prev_length-1;
  21415. s.prev_length -= 2;
  21416. do {
  21417. if (++s.strstart <= max_insert) {
  21418. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21419. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21420. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21421. s.head[s.ins_h] = s.strstart;
  21422. /***/
  21423. }
  21424. } while (--s.prev_length !== 0);
  21425. s.match_available = 0;
  21426. s.match_length = MIN_MATCH-1;
  21427. s.strstart++;
  21428. if (bflush) {
  21429. /*** FLUSH_BLOCK(s, 0); ***/
  21430. flush_block_only(s, false);
  21431. if (s.strm.avail_out === 0) {
  21432. return BS_NEED_MORE;
  21433. }
  21434. /***/
  21435. }
  21436. } else if (s.match_available) {
  21437. /* If there was no match at the previous position, output a
  21438. * single literal. If there was a match but the current match
  21439. * is longer, truncate the previous match to a single literal.
  21440. */
  21441. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  21442. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  21443. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  21444. if (bflush) {
  21445. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  21446. flush_block_only(s, false);
  21447. /***/
  21448. }
  21449. s.strstart++;
  21450. s.lookahead--;
  21451. if (s.strm.avail_out === 0) {
  21452. return BS_NEED_MORE;
  21453. }
  21454. } else {
  21455. /* There is no previous match to compare with, wait for
  21456. * the next step to decide.
  21457. */
  21458. s.match_available = 1;
  21459. s.strstart++;
  21460. s.lookahead--;
  21461. }
  21462. }
  21463. //Assert (flush != Z_NO_FLUSH, "no flush?");
  21464. if (s.match_available) {
  21465. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  21466. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  21467. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  21468. s.match_available = 0;
  21469. }
  21470. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  21471. if (flush === Z_FINISH) {
  21472. /*** FLUSH_BLOCK(s, 1); ***/
  21473. flush_block_only(s, true);
  21474. if (s.strm.avail_out === 0) {
  21475. return BS_FINISH_STARTED;
  21476. }
  21477. /***/
  21478. return BS_FINISH_DONE;
  21479. }
  21480. if (s.last_lit) {
  21481. /*** FLUSH_BLOCK(s, 0); ***/
  21482. flush_block_only(s, false);
  21483. if (s.strm.avail_out === 0) {
  21484. return BS_NEED_MORE;
  21485. }
  21486. /***/
  21487. }
  21488. return BS_BLOCK_DONE;
  21489. }
  21490. /* ===========================================================================
  21491. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  21492. * one. Do not maintain a hash table. (It will be regenerated if this run of
  21493. * deflate switches away from Z_RLE.)
  21494. */
  21495. function deflate_rle(s, flush) {
  21496. var bflush; /* set if current block must be flushed */
  21497. var prev; /* byte at distance one to match */
  21498. var scan, strend; /* scan goes up to strend for length of run */
  21499. var _win = s.window;
  21500. for (;;) {
  21501. /* Make sure that we always have enough lookahead, except
  21502. * at the end of the input file. We need MAX_MATCH bytes
  21503. * for the longest run, plus one for the unrolled loop.
  21504. */
  21505. if (s.lookahead <= MAX_MATCH) {
  21506. fill_window(s);
  21507. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  21508. return BS_NEED_MORE;
  21509. }
  21510. if (s.lookahead === 0) { break; } /* flush the current block */
  21511. }
  21512. /* See how many times the previous byte repeats */
  21513. s.match_length = 0;
  21514. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  21515. scan = s.strstart - 1;
  21516. prev = _win[scan];
  21517. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  21518. strend = s.strstart + MAX_MATCH;
  21519. do {
  21520. /*jshint noempty:false*/
  21521. } while (prev === _win[++scan] && prev === _win[++scan] &&
  21522. prev === _win[++scan] && prev === _win[++scan] &&
  21523. prev === _win[++scan] && prev === _win[++scan] &&
  21524. prev === _win[++scan] && prev === _win[++scan] &&
  21525. scan < strend);
  21526. s.match_length = MAX_MATCH - (strend - scan);
  21527. if (s.match_length > s.lookahead) {
  21528. s.match_length = s.lookahead;
  21529. }
  21530. }
  21531. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  21532. }
  21533. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  21534. if (s.match_length >= MIN_MATCH) {
  21535. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  21536. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  21537. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  21538. s.lookahead -= s.match_length;
  21539. s.strstart += s.match_length;
  21540. s.match_length = 0;
  21541. } else {
  21542. /* No match, output a literal byte */
  21543. //Tracevv((stderr,"%c", s->window[s->strstart]));
  21544. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21545. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21546. s.lookahead--;
  21547. s.strstart++;
  21548. }
  21549. if (bflush) {
  21550. /*** FLUSH_BLOCK(s, 0); ***/
  21551. flush_block_only(s, false);
  21552. if (s.strm.avail_out === 0) {
  21553. return BS_NEED_MORE;
  21554. }
  21555. /***/
  21556. }
  21557. }
  21558. s.insert = 0;
  21559. if (flush === Z_FINISH) {
  21560. /*** FLUSH_BLOCK(s, 1); ***/
  21561. flush_block_only(s, true);
  21562. if (s.strm.avail_out === 0) {
  21563. return BS_FINISH_STARTED;
  21564. }
  21565. /***/
  21566. return BS_FINISH_DONE;
  21567. }
  21568. if (s.last_lit) {
  21569. /*** FLUSH_BLOCK(s, 0); ***/
  21570. flush_block_only(s, false);
  21571. if (s.strm.avail_out === 0) {
  21572. return BS_NEED_MORE;
  21573. }
  21574. /***/
  21575. }
  21576. return BS_BLOCK_DONE;
  21577. }
  21578. /* ===========================================================================
  21579. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  21580. * (It will be regenerated if this run of deflate switches away from Huffman.)
  21581. */
  21582. function deflate_huff(s, flush) {
  21583. var bflush; /* set if current block must be flushed */
  21584. for (;;) {
  21585. /* Make sure that we have a literal to write. */
  21586. if (s.lookahead === 0) {
  21587. fill_window(s);
  21588. if (s.lookahead === 0) {
  21589. if (flush === Z_NO_FLUSH) {
  21590. return BS_NEED_MORE;
  21591. }
  21592. break; /* flush the current block */
  21593. }
  21594. }
  21595. /* Output a literal byte */
  21596. s.match_length = 0;
  21597. //Tracevv((stderr,"%c", s->window[s->strstart]));
  21598. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21599. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21600. s.lookahead--;
  21601. s.strstart++;
  21602. if (bflush) {
  21603. /*** FLUSH_BLOCK(s, 0); ***/
  21604. flush_block_only(s, false);
  21605. if (s.strm.avail_out === 0) {
  21606. return BS_NEED_MORE;
  21607. }
  21608. /***/
  21609. }
  21610. }
  21611. s.insert = 0;
  21612. if (flush === Z_FINISH) {
  21613. /*** FLUSH_BLOCK(s, 1); ***/
  21614. flush_block_only(s, true);
  21615. if (s.strm.avail_out === 0) {
  21616. return BS_FINISH_STARTED;
  21617. }
  21618. /***/
  21619. return BS_FINISH_DONE;
  21620. }
  21621. if (s.last_lit) {
  21622. /*** FLUSH_BLOCK(s, 0); ***/
  21623. flush_block_only(s, false);
  21624. if (s.strm.avail_out === 0) {
  21625. return BS_NEED_MORE;
  21626. }
  21627. /***/
  21628. }
  21629. return BS_BLOCK_DONE;
  21630. }
  21631. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  21632. * the desired pack level (0..9). The values given below have been tuned to
  21633. * exclude worst case performance for pathological files. Better values may be
  21634. * found for specific files.
  21635. */
  21636. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  21637. this.good_length = good_length;
  21638. this.max_lazy = max_lazy;
  21639. this.nice_length = nice_length;
  21640. this.max_chain = max_chain;
  21641. this.func = func;
  21642. };
  21643. var configuration_table;
  21644. configuration_table = [
  21645. /* good lazy nice chain */
  21646. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  21647. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  21648. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  21649. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  21650. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  21651. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  21652. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  21653. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  21654. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  21655. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  21656. ];
  21657. /* ===========================================================================
  21658. * Initialize the "longest match" routines for a new zlib stream
  21659. */
  21660. function lm_init(s) {
  21661. s.window_size = 2 * s.w_size;
  21662. /*** CLEAR_HASH(s); ***/
  21663. zero(s.head); // Fill with NIL (= 0);
  21664. /* Set the default configuration parameters:
  21665. */
  21666. s.max_lazy_match = configuration_table[s.level].max_lazy;
  21667. s.good_match = configuration_table[s.level].good_length;
  21668. s.nice_match = configuration_table[s.level].nice_length;
  21669. s.max_chain_length = configuration_table[s.level].max_chain;
  21670. s.strstart = 0;
  21671. s.block_start = 0;
  21672. s.lookahead = 0;
  21673. s.insert = 0;
  21674. s.match_length = s.prev_length = MIN_MATCH - 1;
  21675. s.match_available = 0;
  21676. s.ins_h = 0;
  21677. }
  21678. function DeflateState() {
  21679. this.strm = null; /* pointer back to this zlib stream */
  21680. this.status = 0; /* as the name implies */
  21681. this.pending_buf = null; /* output still pending */
  21682. this.pending_buf_size = 0; /* size of pending_buf */
  21683. this.pending_out = 0; /* next pending byte to output to the stream */
  21684. this.pending = 0; /* nb of bytes in the pending buffer */
  21685. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  21686. this.gzhead = null; /* gzip header information to write */
  21687. this.gzindex = 0; /* where in extra, name, or comment */
  21688. this.method = Z_DEFLATED; /* can only be DEFLATED */
  21689. this.last_flush = -1; /* value of flush param for previous deflate call */
  21690. this.w_size = 0; /* LZ77 window size (32K by default) */
  21691. this.w_bits = 0; /* log2(w_size) (8..16) */
  21692. this.w_mask = 0; /* w_size - 1 */
  21693. this.window = null;
  21694. /* Sliding window. Input bytes are read into the second half of the window,
  21695. * and move to the first half later to keep a dictionary of at least wSize
  21696. * bytes. With this organization, matches are limited to a distance of
  21697. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  21698. * performed with a length multiple of the block size.
  21699. */
  21700. this.window_size = 0;
  21701. /* Actual size of window: 2*wSize, except when the user input buffer
  21702. * is directly used as sliding window.
  21703. */
  21704. this.prev = null;
  21705. /* Link to older string with same hash index. To limit the size of this
  21706. * array to 64K, this link is maintained only for the last 32K strings.
  21707. * An index in this array is thus a window index modulo 32K.
  21708. */
  21709. this.head = null; /* Heads of the hash chains or NIL. */
  21710. this.ins_h = 0; /* hash index of string to be inserted */
  21711. this.hash_size = 0; /* number of elements in hash table */
  21712. this.hash_bits = 0; /* log2(hash_size) */
  21713. this.hash_mask = 0; /* hash_size-1 */
  21714. this.hash_shift = 0;
  21715. /* Number of bits by which ins_h must be shifted at each input
  21716. * step. It must be such that after MIN_MATCH steps, the oldest
  21717. * byte no longer takes part in the hash key, that is:
  21718. * hash_shift * MIN_MATCH >= hash_bits
  21719. */
  21720. this.block_start = 0;
  21721. /* Window position at the beginning of the current output block. Gets
  21722. * negative when the window is moved backwards.
  21723. */
  21724. this.match_length = 0; /* length of best match */
  21725. this.prev_match = 0; /* previous match */
  21726. this.match_available = 0; /* set if previous match exists */
  21727. this.strstart = 0; /* start of string to insert */
  21728. this.match_start = 0; /* start of matching string */
  21729. this.lookahead = 0; /* number of valid bytes ahead in window */
  21730. this.prev_length = 0;
  21731. /* Length of the best match at previous step. Matches not greater than this
  21732. * are discarded. This is used in the lazy match evaluation.
  21733. */
  21734. this.max_chain_length = 0;
  21735. /* To speed up deflation, hash chains are never searched beyond this
  21736. * length. A higher limit improves compression ratio but degrades the
  21737. * speed.
  21738. */
  21739. this.max_lazy_match = 0;
  21740. /* Attempt to find a better match only when the current match is strictly
  21741. * smaller than this value. This mechanism is used only for compression
  21742. * levels >= 4.
  21743. */
  21744. // That's alias to max_lazy_match, don't use directly
  21745. //this.max_insert_length = 0;
  21746. /* Insert new strings in the hash table only if the match length is not
  21747. * greater than this length. This saves time but degrades compression.
  21748. * max_insert_length is used only for compression levels <= 3.
  21749. */
  21750. this.level = 0; /* compression level (1..9) */
  21751. this.strategy = 0; /* favor or force Huffman coding*/
  21752. this.good_match = 0;
  21753. /* Use a faster search when the previous match is longer than this */
  21754. this.nice_match = 0; /* Stop searching when current match exceeds this */
  21755. /* used by trees.c: */
  21756. /* Didn't use ct_data typedef below to suppress compiler warning */
  21757. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  21758. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  21759. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  21760. // Use flat array of DOUBLE size, with interleaved fata,
  21761. // because JS does not support effective
  21762. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  21763. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  21764. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  21765. zero(this.dyn_ltree);
  21766. zero(this.dyn_dtree);
  21767. zero(this.bl_tree);
  21768. this.l_desc = null; /* desc. for literal tree */
  21769. this.d_desc = null; /* desc. for distance tree */
  21770. this.bl_desc = null; /* desc. for bit length tree */
  21771. //ush bl_count[MAX_BITS+1];
  21772. this.bl_count = new utils.Buf16(MAX_BITS+1);
  21773. /* number of codes at each bit length for an optimal tree */
  21774. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  21775. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  21776. zero(this.heap);
  21777. this.heap_len = 0; /* number of elements in the heap */
  21778. this.heap_max = 0; /* element of largest frequency */
  21779. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  21780. * The same heap array is used to build all trees.
  21781. */
  21782. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  21783. zero(this.depth);
  21784. /* Depth of each subtree used as tie breaker for trees of equal frequency
  21785. */
  21786. this.l_buf = 0; /* buffer index for literals or lengths */
  21787. this.lit_bufsize = 0;
  21788. /* Size of match buffer for literals/lengths. There are 4 reasons for
  21789. * limiting lit_bufsize to 64K:
  21790. * - frequencies can be kept in 16 bit counters
  21791. * - if compression is not successful for the first block, all input
  21792. * data is still in the window so we can still emit a stored block even
  21793. * when input comes from standard input. (This can also be done for
  21794. * all blocks if lit_bufsize is not greater than 32K.)
  21795. * - if compression is not successful for a file smaller than 64K, we can
  21796. * even emit a stored file instead of a stored block (saving 5 bytes).
  21797. * This is applicable only for zip (not gzip or zlib).
  21798. * - creating new Huffman trees less frequently may not provide fast
  21799. * adaptation to changes in the input data statistics. (Take for
  21800. * example a binary file with poorly compressible code followed by
  21801. * a highly compressible string table.) Smaller buffer sizes give
  21802. * fast adaptation but have of course the overhead of transmitting
  21803. * trees more frequently.
  21804. * - I can't count above 4
  21805. */
  21806. this.last_lit = 0; /* running index in l_buf */
  21807. this.d_buf = 0;
  21808. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  21809. * the same number of elements. To use different lengths, an extra flag
  21810. * array would be necessary.
  21811. */
  21812. this.opt_len = 0; /* bit length of current block with optimal trees */
  21813. this.static_len = 0; /* bit length of current block with static trees */
  21814. this.matches = 0; /* number of string matches in current block */
  21815. this.insert = 0; /* bytes at end of window left to insert */
  21816. this.bi_buf = 0;
  21817. /* Output buffer. bits are inserted starting at the bottom (least
  21818. * significant bits).
  21819. */
  21820. this.bi_valid = 0;
  21821. /* Number of valid bits in bi_buf. All bits above the last valid bit
  21822. * are always zero.
  21823. */
  21824. // Used for window memory init. We safely ignore it for JS. That makes
  21825. // sense only for pointers and memory check tools.
  21826. //this.high_water = 0;
  21827. /* High water mark offset in window for initialized bytes -- bytes above
  21828. * this are set to zero in order to avoid memory check warnings when
  21829. * longest match routines access bytes past the input. This is then
  21830. * updated to the new high water mark.
  21831. */
  21832. }
  21833. function deflateResetKeep(strm) {
  21834. var s;
  21835. if (!strm || !strm.state) {
  21836. return err(strm, Z_STREAM_ERROR);
  21837. }
  21838. strm.total_in = strm.total_out = 0;
  21839. strm.data_type = Z_UNKNOWN;
  21840. s = strm.state;
  21841. s.pending = 0;
  21842. s.pending_out = 0;
  21843. if (s.wrap < 0) {
  21844. s.wrap = -s.wrap;
  21845. /* was made negative by deflate(..., Z_FINISH); */
  21846. }
  21847. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  21848. strm.adler = (s.wrap === 2) ?
  21849. 0 // crc32(0, Z_NULL, 0)
  21850. :
  21851. 1; // adler32(0, Z_NULL, 0)
  21852. s.last_flush = Z_NO_FLUSH;
  21853. trees._tr_init(s);
  21854. return Z_OK;
  21855. }
  21856. function deflateReset(strm) {
  21857. var ret = deflateResetKeep(strm);
  21858. if (ret === Z_OK) {
  21859. lm_init(strm.state);
  21860. }
  21861. return ret;
  21862. }
  21863. function deflateSetHeader(strm, head) {
  21864. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21865. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  21866. strm.state.gzhead = head;
  21867. return Z_OK;
  21868. }
  21869. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  21870. if (!strm) { // === Z_NULL
  21871. return Z_STREAM_ERROR;
  21872. }
  21873. var wrap = 1;
  21874. if (level === Z_DEFAULT_COMPRESSION) {
  21875. level = 6;
  21876. }
  21877. if (windowBits < 0) { /* suppress zlib wrapper */
  21878. wrap = 0;
  21879. windowBits = -windowBits;
  21880. }
  21881. else if (windowBits > 15) {
  21882. wrap = 2; /* write gzip wrapper instead */
  21883. windowBits -= 16;
  21884. }
  21885. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  21886. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  21887. strategy < 0 || strategy > Z_FIXED) {
  21888. return err(strm, Z_STREAM_ERROR);
  21889. }
  21890. if (windowBits === 8) {
  21891. windowBits = 9;
  21892. }
  21893. /* until 256-byte window bug fixed */
  21894. var s = new DeflateState();
  21895. strm.state = s;
  21896. s.strm = strm;
  21897. s.wrap = wrap;
  21898. s.gzhead = null;
  21899. s.w_bits = windowBits;
  21900. s.w_size = 1 << s.w_bits;
  21901. s.w_mask = s.w_size - 1;
  21902. s.hash_bits = memLevel + 7;
  21903. s.hash_size = 1 << s.hash_bits;
  21904. s.hash_mask = s.hash_size - 1;
  21905. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  21906. s.window = new utils.Buf8(s.w_size * 2);
  21907. s.head = new utils.Buf16(s.hash_size);
  21908. s.prev = new utils.Buf16(s.w_size);
  21909. // Don't need mem init magic for JS.
  21910. //s.high_water = 0; /* nothing written to s->window yet */
  21911. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  21912. s.pending_buf_size = s.lit_bufsize * 4;
  21913. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  21914. s.d_buf = s.lit_bufsize >> 1;
  21915. s.l_buf = (1 + 2) * s.lit_bufsize;
  21916. s.level = level;
  21917. s.strategy = strategy;
  21918. s.method = method;
  21919. return deflateReset(strm);
  21920. }
  21921. function deflateInit(strm, level) {
  21922. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  21923. }
  21924. function deflate(strm, flush) {
  21925. var old_flush, s;
  21926. var beg, val; // for gzip header write only
  21927. if (!strm || !strm.state ||
  21928. flush > Z_BLOCK || flush < 0) {
  21929. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  21930. }
  21931. s = strm.state;
  21932. if (!strm.output ||
  21933. (!strm.input && strm.avail_in !== 0) ||
  21934. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  21935. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  21936. }
  21937. s.strm = strm; /* just in case */
  21938. old_flush = s.last_flush;
  21939. s.last_flush = flush;
  21940. /* Write the header */
  21941. if (s.status === INIT_STATE) {
  21942. if (s.wrap === 2) { // GZIP header
  21943. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  21944. put_byte(s, 31);
  21945. put_byte(s, 139);
  21946. put_byte(s, 8);
  21947. if (!s.gzhead) { // s->gzhead == Z_NULL
  21948. put_byte(s, 0);
  21949. put_byte(s, 0);
  21950. put_byte(s, 0);
  21951. put_byte(s, 0);
  21952. put_byte(s, 0);
  21953. put_byte(s, s.level === 9 ? 2 :
  21954. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  21955. 4 : 0));
  21956. put_byte(s, OS_CODE);
  21957. s.status = BUSY_STATE;
  21958. }
  21959. else {
  21960. put_byte(s, (s.gzhead.text ? 1 : 0) +
  21961. (s.gzhead.hcrc ? 2 : 0) +
  21962. (!s.gzhead.extra ? 0 : 4) +
  21963. (!s.gzhead.name ? 0 : 8) +
  21964. (!s.gzhead.comment ? 0 : 16)
  21965. );
  21966. put_byte(s, s.gzhead.time & 0xff);
  21967. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  21968. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  21969. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  21970. put_byte(s, s.level === 9 ? 2 :
  21971. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  21972. 4 : 0));
  21973. put_byte(s, s.gzhead.os & 0xff);
  21974. if (s.gzhead.extra && s.gzhead.extra.length) {
  21975. put_byte(s, s.gzhead.extra.length & 0xff);
  21976. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  21977. }
  21978. if (s.gzhead.hcrc) {
  21979. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  21980. }
  21981. s.gzindex = 0;
  21982. s.status = EXTRA_STATE;
  21983. }
  21984. }
  21985. else // DEFLATE header
  21986. {
  21987. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  21988. var level_flags = -1;
  21989. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  21990. level_flags = 0;
  21991. } else if (s.level < 6) {
  21992. level_flags = 1;
  21993. } else if (s.level === 6) {
  21994. level_flags = 2;
  21995. } else {
  21996. level_flags = 3;
  21997. }
  21998. header |= (level_flags << 6);
  21999. if (s.strstart !== 0) { header |= PRESET_DICT; }
  22000. header += 31 - (header % 31);
  22001. s.status = BUSY_STATE;
  22002. putShortMSB(s, header);
  22003. /* Save the adler32 of the preset dictionary: */
  22004. if (s.strstart !== 0) {
  22005. putShortMSB(s, strm.adler >>> 16);
  22006. putShortMSB(s, strm.adler & 0xffff);
  22007. }
  22008. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  22009. }
  22010. }
  22011. //#ifdef GZIP
  22012. if (s.status === EXTRA_STATE) {
  22013. if (s.gzhead.extra/* != Z_NULL*/) {
  22014. beg = s.pending; /* start of bytes to update crc */
  22015. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  22016. if (s.pending === s.pending_buf_size) {
  22017. if (s.gzhead.hcrc && s.pending > beg) {
  22018. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22019. }
  22020. flush_pending(strm);
  22021. beg = s.pending;
  22022. if (s.pending === s.pending_buf_size) {
  22023. break;
  22024. }
  22025. }
  22026. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  22027. s.gzindex++;
  22028. }
  22029. if (s.gzhead.hcrc && s.pending > beg) {
  22030. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22031. }
  22032. if (s.gzindex === s.gzhead.extra.length) {
  22033. s.gzindex = 0;
  22034. s.status = NAME_STATE;
  22035. }
  22036. }
  22037. else {
  22038. s.status = NAME_STATE;
  22039. }
  22040. }
  22041. if (s.status === NAME_STATE) {
  22042. if (s.gzhead.name/* != Z_NULL*/) {
  22043. beg = s.pending; /* start of bytes to update crc */
  22044. //int val;
  22045. do {
  22046. if (s.pending === s.pending_buf_size) {
  22047. if (s.gzhead.hcrc && s.pending > beg) {
  22048. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22049. }
  22050. flush_pending(strm);
  22051. beg = s.pending;
  22052. if (s.pending === s.pending_buf_size) {
  22053. val = 1;
  22054. break;
  22055. }
  22056. }
  22057. // JS specific: little magic to add zero terminator to end of string
  22058. if (s.gzindex < s.gzhead.name.length) {
  22059. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  22060. } else {
  22061. val = 0;
  22062. }
  22063. put_byte(s, val);
  22064. } while (val !== 0);
  22065. if (s.gzhead.hcrc && s.pending > beg) {
  22066. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22067. }
  22068. if (val === 0) {
  22069. s.gzindex = 0;
  22070. s.status = COMMENT_STATE;
  22071. }
  22072. }
  22073. else {
  22074. s.status = COMMENT_STATE;
  22075. }
  22076. }
  22077. if (s.status === COMMENT_STATE) {
  22078. if (s.gzhead.comment/* != Z_NULL*/) {
  22079. beg = s.pending; /* start of bytes to update crc */
  22080. //int val;
  22081. do {
  22082. if (s.pending === s.pending_buf_size) {
  22083. if (s.gzhead.hcrc && s.pending > beg) {
  22084. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22085. }
  22086. flush_pending(strm);
  22087. beg = s.pending;
  22088. if (s.pending === s.pending_buf_size) {
  22089. val = 1;
  22090. break;
  22091. }
  22092. }
  22093. // JS specific: little magic to add zero terminator to end of string
  22094. if (s.gzindex < s.gzhead.comment.length) {
  22095. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  22096. } else {
  22097. val = 0;
  22098. }
  22099. put_byte(s, val);
  22100. } while (val !== 0);
  22101. if (s.gzhead.hcrc && s.pending > beg) {
  22102. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22103. }
  22104. if (val === 0) {
  22105. s.status = HCRC_STATE;
  22106. }
  22107. }
  22108. else {
  22109. s.status = HCRC_STATE;
  22110. }
  22111. }
  22112. if (s.status === HCRC_STATE) {
  22113. if (s.gzhead.hcrc) {
  22114. if (s.pending + 2 > s.pending_buf_size) {
  22115. flush_pending(strm);
  22116. }
  22117. if (s.pending + 2 <= s.pending_buf_size) {
  22118. put_byte(s, strm.adler & 0xff);
  22119. put_byte(s, (strm.adler >> 8) & 0xff);
  22120. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  22121. s.status = BUSY_STATE;
  22122. }
  22123. }
  22124. else {
  22125. s.status = BUSY_STATE;
  22126. }
  22127. }
  22128. //#endif
  22129. /* Flush as much pending output as possible */
  22130. if (s.pending !== 0) {
  22131. flush_pending(strm);
  22132. if (strm.avail_out === 0) {
  22133. /* Since avail_out is 0, deflate will be called again with
  22134. * more output space, but possibly with both pending and
  22135. * avail_in equal to zero. There won't be anything to do,
  22136. * but this is not an error situation so make sure we
  22137. * return OK instead of BUF_ERROR at next call of deflate:
  22138. */
  22139. s.last_flush = -1;
  22140. return Z_OK;
  22141. }
  22142. /* Make sure there is something to do and avoid duplicate consecutive
  22143. * flushes. For repeated and useless calls with Z_FINISH, we keep
  22144. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  22145. */
  22146. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  22147. flush !== Z_FINISH) {
  22148. return err(strm, Z_BUF_ERROR);
  22149. }
  22150. /* User must not provide more input after the first FINISH: */
  22151. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  22152. return err(strm, Z_BUF_ERROR);
  22153. }
  22154. /* Start a new block or continue the current one.
  22155. */
  22156. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  22157. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  22158. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  22159. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  22160. configuration_table[s.level].func(s, flush));
  22161. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  22162. s.status = FINISH_STATE;
  22163. }
  22164. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  22165. if (strm.avail_out === 0) {
  22166. s.last_flush = -1;
  22167. /* avoid BUF_ERROR next call, see above */
  22168. }
  22169. return Z_OK;
  22170. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  22171. * of deflate should use the same flush parameter to make sure
  22172. * that the flush is complete. So we don't have to output an
  22173. * empty block here, this will be done at next call. This also
  22174. * ensures that for a very small output buffer, we emit at most
  22175. * one empty block.
  22176. */
  22177. }
  22178. if (bstate === BS_BLOCK_DONE) {
  22179. if (flush === Z_PARTIAL_FLUSH) {
  22180. trees._tr_align(s);
  22181. }
  22182. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  22183. trees._tr_stored_block(s, 0, 0, false);
  22184. /* For a full flush, this empty block will be recognized
  22185. * as a special marker by inflate_sync().
  22186. */
  22187. if (flush === Z_FULL_FLUSH) {
  22188. /*** CLEAR_HASH(s); ***/ /* forget history */
  22189. zero(s.head); // Fill with NIL (= 0);
  22190. if (s.lookahead === 0) {
  22191. s.strstart = 0;
  22192. s.block_start = 0;
  22193. s.insert = 0;
  22194. }
  22195. }
  22196. }
  22197. flush_pending(strm);
  22198. if (strm.avail_out === 0) {
  22199. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  22200. return Z_OK;
  22201. }
  22202. }
  22203. }
  22204. //Assert(strm->avail_out > 0, "bug2");
  22205. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  22206. if (flush !== Z_FINISH) { return Z_OK; }
  22207. if (s.wrap <= 0) { return Z_STREAM_END; }
  22208. /* Write the trailer */
  22209. if (s.wrap === 2) {
  22210. put_byte(s, strm.adler & 0xff);
  22211. put_byte(s, (strm.adler >> 8) & 0xff);
  22212. put_byte(s, (strm.adler >> 16) & 0xff);
  22213. put_byte(s, (strm.adler >> 24) & 0xff);
  22214. put_byte(s, strm.total_in & 0xff);
  22215. put_byte(s, (strm.total_in >> 8) & 0xff);
  22216. put_byte(s, (strm.total_in >> 16) & 0xff);
  22217. put_byte(s, (strm.total_in >> 24) & 0xff);
  22218. }
  22219. else
  22220. {
  22221. putShortMSB(s, strm.adler >>> 16);
  22222. putShortMSB(s, strm.adler & 0xffff);
  22223. }
  22224. flush_pending(strm);
  22225. /* If avail_out is zero, the application will call deflate again
  22226. * to flush the rest.
  22227. */
  22228. if (s.wrap > 0) { s.wrap = -s.wrap; }
  22229. /* write the trailer only once! */
  22230. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  22231. }
  22232. function deflateEnd(strm) {
  22233. var status;
  22234. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  22235. return Z_STREAM_ERROR;
  22236. }
  22237. status = strm.state.status;
  22238. if (status !== INIT_STATE &&
  22239. status !== EXTRA_STATE &&
  22240. status !== NAME_STATE &&
  22241. status !== COMMENT_STATE &&
  22242. status !== HCRC_STATE &&
  22243. status !== BUSY_STATE &&
  22244. status !== FINISH_STATE
  22245. ) {
  22246. return err(strm, Z_STREAM_ERROR);
  22247. }
  22248. strm.state = null;
  22249. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  22250. }
  22251. /* =========================================================================
  22252. * Copy the source state to the destination state
  22253. */
  22254. //function deflateCopy(dest, source) {
  22255. //
  22256. //}
  22257. exports.deflateInit = deflateInit;
  22258. exports.deflateInit2 = deflateInit2;
  22259. exports.deflateReset = deflateReset;
  22260. exports.deflateResetKeep = deflateResetKeep;
  22261. exports.deflateSetHeader = deflateSetHeader;
  22262. exports.deflate = deflate;
  22263. exports.deflateEnd = deflateEnd;
  22264. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  22265. /* Not implemented
  22266. exports.deflateBound = deflateBound;
  22267. exports.deflateCopy = deflateCopy;
  22268. exports.deflateSetDictionary = deflateSetDictionary;
  22269. exports.deflateParams = deflateParams;
  22270. exports.deflatePending = deflatePending;
  22271. exports.deflatePrime = deflatePrime;
  22272. exports.deflateTune = deflateTune;
  22273. */
  22274. },{"../utils/common":75,"./adler32":77,"./crc32":79,"./messages":85,"./trees":86}],81:[function(require,module,exports){
  22275. 'use strict';
  22276. function GZheader() {
  22277. /* true if compressed data believed to be text */
  22278. this.text = 0;
  22279. /* modification time */
  22280. this.time = 0;
  22281. /* extra flags (not used when writing a gzip file) */
  22282. this.xflags = 0;
  22283. /* operating system */
  22284. this.os = 0;
  22285. /* pointer to extra field or Z_NULL if none */
  22286. this.extra = null;
  22287. /* extra field length (valid if extra != Z_NULL) */
  22288. this.extra_len = 0; // Actually, we don't need it in JS,
  22289. // but leave for few code modifications
  22290. //
  22291. // Setup limits is not necessary because in js we should not preallocate memory
  22292. // for inflate use constant limit in 65536 bytes
  22293. //
  22294. /* space at extra (only when reading header) */
  22295. // this.extra_max = 0;
  22296. /* pointer to zero-terminated file name or Z_NULL */
  22297. this.name = '';
  22298. /* space at name (only when reading header) */
  22299. // this.name_max = 0;
  22300. /* pointer to zero-terminated comment or Z_NULL */
  22301. this.comment = '';
  22302. /* space at comment (only when reading header) */
  22303. // this.comm_max = 0;
  22304. /* true if there was or will be a header crc */
  22305. this.hcrc = 0;
  22306. /* true when done reading gzip header (not used when writing a gzip file) */
  22307. this.done = false;
  22308. }
  22309. module.exports = GZheader;
  22310. },{}],82:[function(require,module,exports){
  22311. 'use strict';
  22312. // See state defs from inflate.js
  22313. var BAD = 30; /* got a data error -- remain here until reset */
  22314. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  22315. /*
  22316. Decode literal, length, and distance codes and write out the resulting
  22317. literal and match bytes until either not enough input or output is
  22318. available, an end-of-block is encountered, or a data error is encountered.
  22319. When large enough input and output buffers are supplied to inflate(), for
  22320. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  22321. inflate execution time is spent in this routine.
  22322. Entry assumptions:
  22323. state.mode === LEN
  22324. strm.avail_in >= 6
  22325. strm.avail_out >= 258
  22326. start >= strm.avail_out
  22327. state.bits < 8
  22328. On return, state.mode is one of:
  22329. LEN -- ran out of enough output space or enough available input
  22330. TYPE -- reached end of block code, inflate() to interpret next block
  22331. BAD -- error in block data
  22332. Notes:
  22333. - The maximum input bits used by a length/distance pair is 15 bits for the
  22334. length code, 5 bits for the length extra, 15 bits for the distance code,
  22335. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  22336. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  22337. checking for available input while decoding.
  22338. - The maximum bytes that a single length/distance pair can output is 258
  22339. bytes, which is the maximum length that can be coded. inflate_fast()
  22340. requires strm.avail_out >= 258 for each loop to avoid checking for
  22341. output space.
  22342. */
  22343. module.exports = function inflate_fast(strm, start) {
  22344. var state;
  22345. var _in; /* local strm.input */
  22346. var last; /* have enough input while in < last */
  22347. var _out; /* local strm.output */
  22348. var beg; /* inflate()'s initial strm.output */
  22349. var end; /* while out < end, enough space available */
  22350. //#ifdef INFLATE_STRICT
  22351. var dmax; /* maximum distance from zlib header */
  22352. //#endif
  22353. var wsize; /* window size or zero if not using window */
  22354. var whave; /* valid bytes in the window */
  22355. var wnext; /* window write index */
  22356. var window; /* allocated sliding window, if wsize != 0 */
  22357. var hold; /* local strm.hold */
  22358. var bits; /* local strm.bits */
  22359. var lcode; /* local strm.lencode */
  22360. var dcode; /* local strm.distcode */
  22361. var lmask; /* mask for first level of length codes */
  22362. var dmask; /* mask for first level of distance codes */
  22363. var here; /* retrieved table entry */
  22364. var op; /* code bits, operation, extra bits, or */
  22365. /* window position, window bytes to copy */
  22366. var len; /* match length, unused bytes */
  22367. var dist; /* match distance */
  22368. var from; /* where to copy match from */
  22369. var from_source;
  22370. var input, output; // JS specific, because we have no pointers
  22371. /* copy state to local variables */
  22372. state = strm.state;
  22373. //here = state.here;
  22374. _in = strm.next_in;
  22375. input = strm.input;
  22376. last = _in + (strm.avail_in - 5);
  22377. _out = strm.next_out;
  22378. output = strm.output;
  22379. beg = _out - (start - strm.avail_out);
  22380. end = _out + (strm.avail_out - 257);
  22381. //#ifdef INFLATE_STRICT
  22382. dmax = state.dmax;
  22383. //#endif
  22384. wsize = state.wsize;
  22385. whave = state.whave;
  22386. wnext = state.wnext;
  22387. window = state.window;
  22388. hold = state.hold;
  22389. bits = state.bits;
  22390. lcode = state.lencode;
  22391. dcode = state.distcode;
  22392. lmask = (1 << state.lenbits) - 1;
  22393. dmask = (1 << state.distbits) - 1;
  22394. /* decode literals and length/distances until end-of-block or not enough
  22395. input data or output space */
  22396. top:
  22397. do {
  22398. if (bits < 15) {
  22399. hold += input[_in++] << bits;
  22400. bits += 8;
  22401. hold += input[_in++] << bits;
  22402. bits += 8;
  22403. }
  22404. here = lcode[hold & lmask];
  22405. dolen:
  22406. for (;;) { // Goto emulation
  22407. op = here >>> 24/*here.bits*/;
  22408. hold >>>= op;
  22409. bits -= op;
  22410. op = (here >>> 16) & 0xff/*here.op*/;
  22411. if (op === 0) { /* literal */
  22412. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  22413. // "inflate: literal '%c'\n" :
  22414. // "inflate: literal 0x%02x\n", here.val));
  22415. output[_out++] = here & 0xffff/*here.val*/;
  22416. }
  22417. else if (op & 16) { /* length base */
  22418. len = here & 0xffff/*here.val*/;
  22419. op &= 15; /* number of extra bits */
  22420. if (op) {
  22421. if (bits < op) {
  22422. hold += input[_in++] << bits;
  22423. bits += 8;
  22424. }
  22425. len += hold & ((1 << op) - 1);
  22426. hold >>>= op;
  22427. bits -= op;
  22428. }
  22429. //Tracevv((stderr, "inflate: length %u\n", len));
  22430. if (bits < 15) {
  22431. hold += input[_in++] << bits;
  22432. bits += 8;
  22433. hold += input[_in++] << bits;
  22434. bits += 8;
  22435. }
  22436. here = dcode[hold & dmask];
  22437. dodist:
  22438. for (;;) { // goto emulation
  22439. op = here >>> 24/*here.bits*/;
  22440. hold >>>= op;
  22441. bits -= op;
  22442. op = (here >>> 16) & 0xff/*here.op*/;
  22443. if (op & 16) { /* distance base */
  22444. dist = here & 0xffff/*here.val*/;
  22445. op &= 15; /* number of extra bits */
  22446. if (bits < op) {
  22447. hold += input[_in++] << bits;
  22448. bits += 8;
  22449. if (bits < op) {
  22450. hold += input[_in++] << bits;
  22451. bits += 8;
  22452. }
  22453. }
  22454. dist += hold & ((1 << op) - 1);
  22455. //#ifdef INFLATE_STRICT
  22456. if (dist > dmax) {
  22457. strm.msg = 'invalid distance too far back';
  22458. state.mode = BAD;
  22459. break top;
  22460. }
  22461. //#endif
  22462. hold >>>= op;
  22463. bits -= op;
  22464. //Tracevv((stderr, "inflate: distance %u\n", dist));
  22465. op = _out - beg; /* max distance in output */
  22466. if (dist > op) { /* see if copy from window */
  22467. op = dist - op; /* distance back in window */
  22468. if (op > whave) {
  22469. if (state.sane) {
  22470. strm.msg = 'invalid distance too far back';
  22471. state.mode = BAD;
  22472. break top;
  22473. }
  22474. // (!) This block is disabled in zlib defailts,
  22475. // don't enable it for binary compatibility
  22476. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  22477. // if (len <= op - whave) {
  22478. // do {
  22479. // output[_out++] = 0;
  22480. // } while (--len);
  22481. // continue top;
  22482. // }
  22483. // len -= op - whave;
  22484. // do {
  22485. // output[_out++] = 0;
  22486. // } while (--op > whave);
  22487. // if (op === 0) {
  22488. // from = _out - dist;
  22489. // do {
  22490. // output[_out++] = output[from++];
  22491. // } while (--len);
  22492. // continue top;
  22493. // }
  22494. //#endif
  22495. }
  22496. from = 0; // window index
  22497. from_source = window;
  22498. if (wnext === 0) { /* very common case */
  22499. from += wsize - op;
  22500. if (op < len) { /* some from window */
  22501. len -= op;
  22502. do {
  22503. output[_out++] = window[from++];
  22504. } while (--op);
  22505. from = _out - dist; /* rest from output */
  22506. from_source = output;
  22507. }
  22508. }
  22509. else if (wnext < op) { /* wrap around window */
  22510. from += wsize + wnext - op;
  22511. op -= wnext;
  22512. if (op < len) { /* some from end of window */
  22513. len -= op;
  22514. do {
  22515. output[_out++] = window[from++];
  22516. } while (--op);
  22517. from = 0;
  22518. if (wnext < len) { /* some from start of window */
  22519. op = wnext;
  22520. len -= op;
  22521. do {
  22522. output[_out++] = window[from++];
  22523. } while (--op);
  22524. from = _out - dist; /* rest from output */
  22525. from_source = output;
  22526. }
  22527. }
  22528. }
  22529. else { /* contiguous in window */
  22530. from += wnext - op;
  22531. if (op < len) { /* some from window */
  22532. len -= op;
  22533. do {
  22534. output[_out++] = window[from++];
  22535. } while (--op);
  22536. from = _out - dist; /* rest from output */
  22537. from_source = output;
  22538. }
  22539. }
  22540. while (len > 2) {
  22541. output[_out++] = from_source[from++];
  22542. output[_out++] = from_source[from++];
  22543. output[_out++] = from_source[from++];
  22544. len -= 3;
  22545. }
  22546. if (len) {
  22547. output[_out++] = from_source[from++];
  22548. if (len > 1) {
  22549. output[_out++] = from_source[from++];
  22550. }
  22551. }
  22552. }
  22553. else {
  22554. from = _out - dist; /* copy direct from output */
  22555. do { /* minimum length is three */
  22556. output[_out++] = output[from++];
  22557. output[_out++] = output[from++];
  22558. output[_out++] = output[from++];
  22559. len -= 3;
  22560. } while (len > 2);
  22561. if (len) {
  22562. output[_out++] = output[from++];
  22563. if (len > 1) {
  22564. output[_out++] = output[from++];
  22565. }
  22566. }
  22567. }
  22568. }
  22569. else if ((op & 64) === 0) { /* 2nd level distance code */
  22570. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  22571. continue dodist;
  22572. }
  22573. else {
  22574. strm.msg = 'invalid distance code';
  22575. state.mode = BAD;
  22576. break top;
  22577. }
  22578. break; // need to emulate goto via "continue"
  22579. }
  22580. }
  22581. else if ((op & 64) === 0) { /* 2nd level length code */
  22582. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  22583. continue dolen;
  22584. }
  22585. else if (op & 32) { /* end-of-block */
  22586. //Tracevv((stderr, "inflate: end of block\n"));
  22587. state.mode = TYPE;
  22588. break top;
  22589. }
  22590. else {
  22591. strm.msg = 'invalid literal/length code';
  22592. state.mode = BAD;
  22593. break top;
  22594. }
  22595. break; // need to emulate goto via "continue"
  22596. }
  22597. } while (_in < last && _out < end);
  22598. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  22599. len = bits >> 3;
  22600. _in -= len;
  22601. bits -= len << 3;
  22602. hold &= (1 << bits) - 1;
  22603. /* update state and return */
  22604. strm.next_in = _in;
  22605. strm.next_out = _out;
  22606. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  22607. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  22608. state.hold = hold;
  22609. state.bits = bits;
  22610. return;
  22611. };
  22612. },{}],83:[function(require,module,exports){
  22613. 'use strict';
  22614. var utils = require('../utils/common');
  22615. var adler32 = require('./adler32');
  22616. var crc32 = require('./crc32');
  22617. var inflate_fast = require('./inffast');
  22618. var inflate_table = require('./inftrees');
  22619. var CODES = 0;
  22620. var LENS = 1;
  22621. var DISTS = 2;
  22622. /* Public constants ==========================================================*/
  22623. /* ===========================================================================*/
  22624. /* Allowed flush values; see deflate() and inflate() below for details */
  22625. //var Z_NO_FLUSH = 0;
  22626. //var Z_PARTIAL_FLUSH = 1;
  22627. //var Z_SYNC_FLUSH = 2;
  22628. //var Z_FULL_FLUSH = 3;
  22629. var Z_FINISH = 4;
  22630. var Z_BLOCK = 5;
  22631. var Z_TREES = 6;
  22632. /* Return codes for the compression/decompression functions. Negative values
  22633. * are errors, positive values are used for special but normal events.
  22634. */
  22635. var Z_OK = 0;
  22636. var Z_STREAM_END = 1;
  22637. var Z_NEED_DICT = 2;
  22638. //var Z_ERRNO = -1;
  22639. var Z_STREAM_ERROR = -2;
  22640. var Z_DATA_ERROR = -3;
  22641. var Z_MEM_ERROR = -4;
  22642. var Z_BUF_ERROR = -5;
  22643. //var Z_VERSION_ERROR = -6;
  22644. /* The deflate compression method */
  22645. var Z_DEFLATED = 8;
  22646. /* STATES ====================================================================*/
  22647. /* ===========================================================================*/
  22648. var HEAD = 1; /* i: waiting for magic header */
  22649. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  22650. var TIME = 3; /* i: waiting for modification time (gzip) */
  22651. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  22652. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  22653. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  22654. var NAME = 7; /* i: waiting for end of file name (gzip) */
  22655. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  22656. var HCRC = 9; /* i: waiting for header crc (gzip) */
  22657. var DICTID = 10; /* i: waiting for dictionary check value */
  22658. var DICT = 11; /* waiting for inflateSetDictionary() call */
  22659. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  22660. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  22661. var STORED = 14; /* i: waiting for stored size (length and complement) */
  22662. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  22663. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  22664. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  22665. var LENLENS = 18; /* i: waiting for code length code lengths */
  22666. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  22667. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  22668. var LEN = 21; /* i: waiting for length/lit/eob code */
  22669. var LENEXT = 22; /* i: waiting for length extra bits */
  22670. var DIST = 23; /* i: waiting for distance code */
  22671. var DISTEXT = 24; /* i: waiting for distance extra bits */
  22672. var MATCH = 25; /* o: waiting for output space to copy string */
  22673. var LIT = 26; /* o: waiting for output space to write literal */
  22674. var CHECK = 27; /* i: waiting for 32-bit check value */
  22675. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  22676. var DONE = 29; /* finished check, done -- remain here until reset */
  22677. var BAD = 30; /* got a data error -- remain here until reset */
  22678. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  22679. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  22680. /* ===========================================================================*/
  22681. var ENOUGH_LENS = 852;
  22682. var ENOUGH_DISTS = 592;
  22683. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  22684. var MAX_WBITS = 15;
  22685. /* 32K LZ77 window */
  22686. var DEF_WBITS = MAX_WBITS;
  22687. function ZSWAP32(q) {
  22688. return (((q >>> 24) & 0xff) +
  22689. ((q >>> 8) & 0xff00) +
  22690. ((q & 0xff00) << 8) +
  22691. ((q & 0xff) << 24));
  22692. }
  22693. function InflateState() {
  22694. this.mode = 0; /* current inflate mode */
  22695. this.last = false; /* true if processing last block */
  22696. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  22697. this.havedict = false; /* true if dictionary provided */
  22698. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  22699. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  22700. this.check = 0; /* protected copy of check value */
  22701. this.total = 0; /* protected copy of output count */
  22702. // TODO: may be {}
  22703. this.head = null; /* where to save gzip header information */
  22704. /* sliding window */
  22705. this.wbits = 0; /* log base 2 of requested window size */
  22706. this.wsize = 0; /* window size or zero if not using window */
  22707. this.whave = 0; /* valid bytes in the window */
  22708. this.wnext = 0; /* window write index */
  22709. this.window = null; /* allocated sliding window, if needed */
  22710. /* bit accumulator */
  22711. this.hold = 0; /* input bit accumulator */
  22712. this.bits = 0; /* number of bits in "in" */
  22713. /* for string and stored block copying */
  22714. this.length = 0; /* literal or length of data to copy */
  22715. this.offset = 0; /* distance back to copy string from */
  22716. /* for table and code decoding */
  22717. this.extra = 0; /* extra bits needed */
  22718. /* fixed and dynamic code tables */
  22719. this.lencode = null; /* starting table for length/literal codes */
  22720. this.distcode = null; /* starting table for distance codes */
  22721. this.lenbits = 0; /* index bits for lencode */
  22722. this.distbits = 0; /* index bits for distcode */
  22723. /* dynamic table building */
  22724. this.ncode = 0; /* number of code length code lengths */
  22725. this.nlen = 0; /* number of length code lengths */
  22726. this.ndist = 0; /* number of distance code lengths */
  22727. this.have = 0; /* number of code lengths in lens[] */
  22728. this.next = null; /* next available space in codes[] */
  22729. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  22730. this.work = new utils.Buf16(288); /* work area for code table building */
  22731. /*
  22732. because we don't have pointers in js, we use lencode and distcode directly
  22733. as buffers so we don't need codes
  22734. */
  22735. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  22736. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  22737. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  22738. this.sane = 0; /* if false, allow invalid distance too far */
  22739. this.back = 0; /* bits back of last unprocessed length/lit */
  22740. this.was = 0; /* initial length of match */
  22741. }
  22742. function inflateResetKeep(strm) {
  22743. var state;
  22744. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22745. state = strm.state;
  22746. strm.total_in = strm.total_out = state.total = 0;
  22747. strm.msg = ''; /*Z_NULL*/
  22748. if (state.wrap) { /* to support ill-conceived Java test suite */
  22749. strm.adler = state.wrap & 1;
  22750. }
  22751. state.mode = HEAD;
  22752. state.last = 0;
  22753. state.havedict = 0;
  22754. state.dmax = 32768;
  22755. state.head = null/*Z_NULL*/;
  22756. state.hold = 0;
  22757. state.bits = 0;
  22758. //state.lencode = state.distcode = state.next = state.codes;
  22759. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  22760. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  22761. state.sane = 1;
  22762. state.back = -1;
  22763. //Tracev((stderr, "inflate: reset\n"));
  22764. return Z_OK;
  22765. }
  22766. function inflateReset(strm) {
  22767. var state;
  22768. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22769. state = strm.state;
  22770. state.wsize = 0;
  22771. state.whave = 0;
  22772. state.wnext = 0;
  22773. return inflateResetKeep(strm);
  22774. }
  22775. function inflateReset2(strm, windowBits) {
  22776. var wrap;
  22777. var state;
  22778. /* get the state */
  22779. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22780. state = strm.state;
  22781. /* extract wrap request from windowBits parameter */
  22782. if (windowBits < 0) {
  22783. wrap = 0;
  22784. windowBits = -windowBits;
  22785. }
  22786. else {
  22787. wrap = (windowBits >> 4) + 1;
  22788. if (windowBits < 48) {
  22789. windowBits &= 15;
  22790. }
  22791. }
  22792. /* set number of window bits, free window if different */
  22793. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  22794. return Z_STREAM_ERROR;
  22795. }
  22796. if (state.window !== null && state.wbits !== windowBits) {
  22797. state.window = null;
  22798. }
  22799. /* update state and reset the rest of it */
  22800. state.wrap = wrap;
  22801. state.wbits = windowBits;
  22802. return inflateReset(strm);
  22803. }
  22804. function inflateInit2(strm, windowBits) {
  22805. var ret;
  22806. var state;
  22807. if (!strm) { return Z_STREAM_ERROR; }
  22808. //strm.msg = Z_NULL; /* in case we return an error */
  22809. state = new InflateState();
  22810. //if (state === Z_NULL) return Z_MEM_ERROR;
  22811. //Tracev((stderr, "inflate: allocated\n"));
  22812. strm.state = state;
  22813. state.window = null/*Z_NULL*/;
  22814. ret = inflateReset2(strm, windowBits);
  22815. if (ret !== Z_OK) {
  22816. strm.state = null/*Z_NULL*/;
  22817. }
  22818. return ret;
  22819. }
  22820. function inflateInit(strm) {
  22821. return inflateInit2(strm, DEF_WBITS);
  22822. }
  22823. /*
  22824. Return state with length and distance decoding tables and index sizes set to
  22825. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  22826. If BUILDFIXED is defined, then instead this routine builds the tables the
  22827. first time it's called, and returns those tables the first time and
  22828. thereafter. This reduces the size of the code by about 2K bytes, in
  22829. exchange for a little execution time. However, BUILDFIXED should not be
  22830. used for threaded applications, since the rewriting of the tables and virgin
  22831. may not be thread-safe.
  22832. */
  22833. var virgin = true;
  22834. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  22835. function fixedtables(state) {
  22836. /* build fixed huffman tables if first call (may not be thread safe) */
  22837. if (virgin) {
  22838. var sym;
  22839. lenfix = new utils.Buf32(512);
  22840. distfix = new utils.Buf32(32);
  22841. /* literal/length table */
  22842. sym = 0;
  22843. while (sym < 144) { state.lens[sym++] = 8; }
  22844. while (sym < 256) { state.lens[sym++] = 9; }
  22845. while (sym < 280) { state.lens[sym++] = 7; }
  22846. while (sym < 288) { state.lens[sym++] = 8; }
  22847. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  22848. /* distance table */
  22849. sym = 0;
  22850. while (sym < 32) { state.lens[sym++] = 5; }
  22851. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  22852. /* do this just once */
  22853. virgin = false;
  22854. }
  22855. state.lencode = lenfix;
  22856. state.lenbits = 9;
  22857. state.distcode = distfix;
  22858. state.distbits = 5;
  22859. }
  22860. /*
  22861. Update the window with the last wsize (normally 32K) bytes written before
  22862. returning. If window does not exist yet, create it. This is only called
  22863. when a window is already in use, or when output has been written during this
  22864. inflate call, but the end of the deflate stream has not been reached yet.
  22865. It is also called to create a window for dictionary data when a dictionary
  22866. is loaded.
  22867. Providing output buffers larger than 32K to inflate() should provide a speed
  22868. advantage, since only the last 32K of output is copied to the sliding window
  22869. upon return from inflate(), and since all distances after the first 32K of
  22870. output will fall in the output data, making match copies simpler and faster.
  22871. The advantage may be dependent on the size of the processor's data caches.
  22872. */
  22873. function updatewindow(strm, src, end, copy) {
  22874. var dist;
  22875. var state = strm.state;
  22876. /* if it hasn't been done already, allocate space for the window */
  22877. if (state.window === null) {
  22878. state.wsize = 1 << state.wbits;
  22879. state.wnext = 0;
  22880. state.whave = 0;
  22881. state.window = new utils.Buf8(state.wsize);
  22882. }
  22883. /* copy state->wsize or less output bytes into the circular window */
  22884. if (copy >= state.wsize) {
  22885. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  22886. state.wnext = 0;
  22887. state.whave = state.wsize;
  22888. }
  22889. else {
  22890. dist = state.wsize - state.wnext;
  22891. if (dist > copy) {
  22892. dist = copy;
  22893. }
  22894. //zmemcpy(state->window + state->wnext, end - copy, dist);
  22895. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  22896. copy -= dist;
  22897. if (copy) {
  22898. //zmemcpy(state->window, end - copy, copy);
  22899. utils.arraySet(state.window,src, end - copy, copy, 0);
  22900. state.wnext = copy;
  22901. state.whave = state.wsize;
  22902. }
  22903. else {
  22904. state.wnext += dist;
  22905. if (state.wnext === state.wsize) { state.wnext = 0; }
  22906. if (state.whave < state.wsize) { state.whave += dist; }
  22907. }
  22908. }
  22909. return 0;
  22910. }
  22911. function inflate(strm, flush) {
  22912. var state;
  22913. var input, output; // input/output buffers
  22914. var next; /* next input INDEX */
  22915. var put; /* next output INDEX */
  22916. var have, left; /* available input and output */
  22917. var hold; /* bit buffer */
  22918. var bits; /* bits in bit buffer */
  22919. var _in, _out; /* save starting available input and output */
  22920. var copy; /* number of stored or match bytes to copy */
  22921. var from; /* where to copy match bytes from */
  22922. var from_source;
  22923. var here = 0; /* current decoding table entry */
  22924. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  22925. //var last; /* parent table entry */
  22926. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  22927. var len; /* length to copy for repeats, bits to drop */
  22928. var ret; /* return code */
  22929. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  22930. var opts;
  22931. var n; // temporary var for NEED_BITS
  22932. var order = /* permutation of code lengths */
  22933. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  22934. if (!strm || !strm.state || !strm.output ||
  22935. (!strm.input && strm.avail_in !== 0)) {
  22936. return Z_STREAM_ERROR;
  22937. }
  22938. state = strm.state;
  22939. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  22940. //--- LOAD() ---
  22941. put = strm.next_out;
  22942. output = strm.output;
  22943. left = strm.avail_out;
  22944. next = strm.next_in;
  22945. input = strm.input;
  22946. have = strm.avail_in;
  22947. hold = state.hold;
  22948. bits = state.bits;
  22949. //---
  22950. _in = have;
  22951. _out = left;
  22952. ret = Z_OK;
  22953. inf_leave: // goto emulation
  22954. for (;;) {
  22955. switch (state.mode) {
  22956. case HEAD:
  22957. if (state.wrap === 0) {
  22958. state.mode = TYPEDO;
  22959. break;
  22960. }
  22961. //=== NEEDBITS(16);
  22962. while (bits < 16) {
  22963. if (have === 0) { break inf_leave; }
  22964. have--;
  22965. hold += input[next++] << bits;
  22966. bits += 8;
  22967. }
  22968. //===//
  22969. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  22970. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  22971. //=== CRC2(state.check, hold);
  22972. hbuf[0] = hold & 0xff;
  22973. hbuf[1] = (hold >>> 8) & 0xff;
  22974. state.check = crc32(state.check, hbuf, 2, 0);
  22975. //===//
  22976. //=== INITBITS();
  22977. hold = 0;
  22978. bits = 0;
  22979. //===//
  22980. state.mode = FLAGS;
  22981. break;
  22982. }
  22983. state.flags = 0; /* expect zlib header */
  22984. if (state.head) {
  22985. state.head.done = false;
  22986. }
  22987. if (!(state.wrap & 1) || /* check if zlib header allowed */
  22988. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  22989. strm.msg = 'incorrect header check';
  22990. state.mode = BAD;
  22991. break;
  22992. }
  22993. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  22994. strm.msg = 'unknown compression method';
  22995. state.mode = BAD;
  22996. break;
  22997. }
  22998. //--- DROPBITS(4) ---//
  22999. hold >>>= 4;
  23000. bits -= 4;
  23001. //---//
  23002. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  23003. if (state.wbits === 0) {
  23004. state.wbits = len;
  23005. }
  23006. else if (len > state.wbits) {
  23007. strm.msg = 'invalid window size';
  23008. state.mode = BAD;
  23009. break;
  23010. }
  23011. state.dmax = 1 << len;
  23012. //Tracev((stderr, "inflate: zlib header ok\n"));
  23013. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  23014. state.mode = hold & 0x200 ? DICTID : TYPE;
  23015. //=== INITBITS();
  23016. hold = 0;
  23017. bits = 0;
  23018. //===//
  23019. break;
  23020. case FLAGS:
  23021. //=== NEEDBITS(16); */
  23022. while (bits < 16) {
  23023. if (have === 0) { break inf_leave; }
  23024. have--;
  23025. hold += input[next++] << bits;
  23026. bits += 8;
  23027. }
  23028. //===//
  23029. state.flags = hold;
  23030. if ((state.flags & 0xff) !== Z_DEFLATED) {
  23031. strm.msg = 'unknown compression method';
  23032. state.mode = BAD;
  23033. break;
  23034. }
  23035. if (state.flags & 0xe000) {
  23036. strm.msg = 'unknown header flags set';
  23037. state.mode = BAD;
  23038. break;
  23039. }
  23040. if (state.head) {
  23041. state.head.text = ((hold >> 8) & 1);
  23042. }
  23043. if (state.flags & 0x0200) {
  23044. //=== CRC2(state.check, hold);
  23045. hbuf[0] = hold & 0xff;
  23046. hbuf[1] = (hold >>> 8) & 0xff;
  23047. state.check = crc32(state.check, hbuf, 2, 0);
  23048. //===//
  23049. }
  23050. //=== INITBITS();
  23051. hold = 0;
  23052. bits = 0;
  23053. //===//
  23054. state.mode = TIME;
  23055. /* falls through */
  23056. case TIME:
  23057. //=== NEEDBITS(32); */
  23058. while (bits < 32) {
  23059. if (have === 0) { break inf_leave; }
  23060. have--;
  23061. hold += input[next++] << bits;
  23062. bits += 8;
  23063. }
  23064. //===//
  23065. if (state.head) {
  23066. state.head.time = hold;
  23067. }
  23068. if (state.flags & 0x0200) {
  23069. //=== CRC4(state.check, hold)
  23070. hbuf[0] = hold & 0xff;
  23071. hbuf[1] = (hold >>> 8) & 0xff;
  23072. hbuf[2] = (hold >>> 16) & 0xff;
  23073. hbuf[3] = (hold >>> 24) & 0xff;
  23074. state.check = crc32(state.check, hbuf, 4, 0);
  23075. //===
  23076. }
  23077. //=== INITBITS();
  23078. hold = 0;
  23079. bits = 0;
  23080. //===//
  23081. state.mode = OS;
  23082. /* falls through */
  23083. case OS:
  23084. //=== NEEDBITS(16); */
  23085. while (bits < 16) {
  23086. if (have === 0) { break inf_leave; }
  23087. have--;
  23088. hold += input[next++] << bits;
  23089. bits += 8;
  23090. }
  23091. //===//
  23092. if (state.head) {
  23093. state.head.xflags = (hold & 0xff);
  23094. state.head.os = (hold >> 8);
  23095. }
  23096. if (state.flags & 0x0200) {
  23097. //=== CRC2(state.check, hold);
  23098. hbuf[0] = hold & 0xff;
  23099. hbuf[1] = (hold >>> 8) & 0xff;
  23100. state.check = crc32(state.check, hbuf, 2, 0);
  23101. //===//
  23102. }
  23103. //=== INITBITS();
  23104. hold = 0;
  23105. bits = 0;
  23106. //===//
  23107. state.mode = EXLEN;
  23108. /* falls through */
  23109. case EXLEN:
  23110. if (state.flags & 0x0400) {
  23111. //=== NEEDBITS(16); */
  23112. while (bits < 16) {
  23113. if (have === 0) { break inf_leave; }
  23114. have--;
  23115. hold += input[next++] << bits;
  23116. bits += 8;
  23117. }
  23118. //===//
  23119. state.length = hold;
  23120. if (state.head) {
  23121. state.head.extra_len = hold;
  23122. }
  23123. if (state.flags & 0x0200) {
  23124. //=== CRC2(state.check, hold);
  23125. hbuf[0] = hold & 0xff;
  23126. hbuf[1] = (hold >>> 8) & 0xff;
  23127. state.check = crc32(state.check, hbuf, 2, 0);
  23128. //===//
  23129. }
  23130. //=== INITBITS();
  23131. hold = 0;
  23132. bits = 0;
  23133. //===//
  23134. }
  23135. else if (state.head) {
  23136. state.head.extra = null/*Z_NULL*/;
  23137. }
  23138. state.mode = EXTRA;
  23139. /* falls through */
  23140. case EXTRA:
  23141. if (state.flags & 0x0400) {
  23142. copy = state.length;
  23143. if (copy > have) { copy = have; }
  23144. if (copy) {
  23145. if (state.head) {
  23146. len = state.head.extra_len - state.length;
  23147. if (!state.head.extra) {
  23148. // Use untyped array for more conveniend processing later
  23149. state.head.extra = new Array(state.head.extra_len);
  23150. }
  23151. utils.arraySet(
  23152. state.head.extra,
  23153. input,
  23154. next,
  23155. // extra field is limited to 65536 bytes
  23156. // - no need for additional size check
  23157. copy,
  23158. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  23159. len
  23160. );
  23161. //zmemcpy(state.head.extra + len, next,
  23162. // len + copy > state.head.extra_max ?
  23163. // state.head.extra_max - len : copy);
  23164. }
  23165. if (state.flags & 0x0200) {
  23166. state.check = crc32(state.check, input, copy, next);
  23167. }
  23168. have -= copy;
  23169. next += copy;
  23170. state.length -= copy;
  23171. }
  23172. if (state.length) { break inf_leave; }
  23173. }
  23174. state.length = 0;
  23175. state.mode = NAME;
  23176. /* falls through */
  23177. case NAME:
  23178. if (state.flags & 0x0800) {
  23179. if (have === 0) { break inf_leave; }
  23180. copy = 0;
  23181. do {
  23182. // TODO: 2 or 1 bytes?
  23183. len = input[next + copy++];
  23184. /* use constant limit because in js we should not preallocate memory */
  23185. if (state.head && len &&
  23186. (state.length < 65536 /*state.head.name_max*/)) {
  23187. state.head.name += String.fromCharCode(len);
  23188. }
  23189. } while (len && copy < have);
  23190. if (state.flags & 0x0200) {
  23191. state.check = crc32(state.check, input, copy, next);
  23192. }
  23193. have -= copy;
  23194. next += copy;
  23195. if (len) { break inf_leave; }
  23196. }
  23197. else if (state.head) {
  23198. state.head.name = null;
  23199. }
  23200. state.length = 0;
  23201. state.mode = COMMENT;
  23202. /* falls through */
  23203. case COMMENT:
  23204. if (state.flags & 0x1000) {
  23205. if (have === 0) { break inf_leave; }
  23206. copy = 0;
  23207. do {
  23208. len = input[next + copy++];
  23209. /* use constant limit because in js we should not preallocate memory */
  23210. if (state.head && len &&
  23211. (state.length < 65536 /*state.head.comm_max*/)) {
  23212. state.head.comment += String.fromCharCode(len);
  23213. }
  23214. } while (len && copy < have);
  23215. if (state.flags & 0x0200) {
  23216. state.check = crc32(state.check, input, copy, next);
  23217. }
  23218. have -= copy;
  23219. next += copy;
  23220. if (len) { break inf_leave; }
  23221. }
  23222. else if (state.head) {
  23223. state.head.comment = null;
  23224. }
  23225. state.mode = HCRC;
  23226. /* falls through */
  23227. case HCRC:
  23228. if (state.flags & 0x0200) {
  23229. //=== NEEDBITS(16); */
  23230. while (bits < 16) {
  23231. if (have === 0) { break inf_leave; }
  23232. have--;
  23233. hold += input[next++] << bits;
  23234. bits += 8;
  23235. }
  23236. //===//
  23237. if (hold !== (state.check & 0xffff)) {
  23238. strm.msg = 'header crc mismatch';
  23239. state.mode = BAD;
  23240. break;
  23241. }
  23242. //=== INITBITS();
  23243. hold = 0;
  23244. bits = 0;
  23245. //===//
  23246. }
  23247. if (state.head) {
  23248. state.head.hcrc = ((state.flags >> 9) & 1);
  23249. state.head.done = true;
  23250. }
  23251. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  23252. state.mode = TYPE;
  23253. break;
  23254. case DICTID:
  23255. //=== NEEDBITS(32); */
  23256. while (bits < 32) {
  23257. if (have === 0) { break inf_leave; }
  23258. have--;
  23259. hold += input[next++] << bits;
  23260. bits += 8;
  23261. }
  23262. //===//
  23263. strm.adler = state.check = ZSWAP32(hold);
  23264. //=== INITBITS();
  23265. hold = 0;
  23266. bits = 0;
  23267. //===//
  23268. state.mode = DICT;
  23269. /* falls through */
  23270. case DICT:
  23271. if (state.havedict === 0) {
  23272. //--- RESTORE() ---
  23273. strm.next_out = put;
  23274. strm.avail_out = left;
  23275. strm.next_in = next;
  23276. strm.avail_in = have;
  23277. state.hold = hold;
  23278. state.bits = bits;
  23279. //---
  23280. return Z_NEED_DICT;
  23281. }
  23282. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  23283. state.mode = TYPE;
  23284. /* falls through */
  23285. case TYPE:
  23286. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  23287. /* falls through */
  23288. case TYPEDO:
  23289. if (state.last) {
  23290. //--- BYTEBITS() ---//
  23291. hold >>>= bits & 7;
  23292. bits -= bits & 7;
  23293. //---//
  23294. state.mode = CHECK;
  23295. break;
  23296. }
  23297. //=== NEEDBITS(3); */
  23298. while (bits < 3) {
  23299. if (have === 0) { break inf_leave; }
  23300. have--;
  23301. hold += input[next++] << bits;
  23302. bits += 8;
  23303. }
  23304. //===//
  23305. state.last = (hold & 0x01)/*BITS(1)*/;
  23306. //--- DROPBITS(1) ---//
  23307. hold >>>= 1;
  23308. bits -= 1;
  23309. //---//
  23310. switch ((hold & 0x03)/*BITS(2)*/) {
  23311. case 0: /* stored block */
  23312. //Tracev((stderr, "inflate: stored block%s\n",
  23313. // state.last ? " (last)" : ""));
  23314. state.mode = STORED;
  23315. break;
  23316. case 1: /* fixed block */
  23317. fixedtables(state);
  23318. //Tracev((stderr, "inflate: fixed codes block%s\n",
  23319. // state.last ? " (last)" : ""));
  23320. state.mode = LEN_; /* decode codes */
  23321. if (flush === Z_TREES) {
  23322. //--- DROPBITS(2) ---//
  23323. hold >>>= 2;
  23324. bits -= 2;
  23325. //---//
  23326. break inf_leave;
  23327. }
  23328. break;
  23329. case 2: /* dynamic block */
  23330. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  23331. // state.last ? " (last)" : ""));
  23332. state.mode = TABLE;
  23333. break;
  23334. case 3:
  23335. strm.msg = 'invalid block type';
  23336. state.mode = BAD;
  23337. }
  23338. //--- DROPBITS(2) ---//
  23339. hold >>>= 2;
  23340. bits -= 2;
  23341. //---//
  23342. break;
  23343. case STORED:
  23344. //--- BYTEBITS() ---// /* go to byte boundary */
  23345. hold >>>= bits & 7;
  23346. bits -= bits & 7;
  23347. //---//
  23348. //=== NEEDBITS(32); */
  23349. while (bits < 32) {
  23350. if (have === 0) { break inf_leave; }
  23351. have--;
  23352. hold += input[next++] << bits;
  23353. bits += 8;
  23354. }
  23355. //===//
  23356. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  23357. strm.msg = 'invalid stored block lengths';
  23358. state.mode = BAD;
  23359. break;
  23360. }
  23361. state.length = hold & 0xffff;
  23362. //Tracev((stderr, "inflate: stored length %u\n",
  23363. // state.length));
  23364. //=== INITBITS();
  23365. hold = 0;
  23366. bits = 0;
  23367. //===//
  23368. state.mode = COPY_;
  23369. if (flush === Z_TREES) { break inf_leave; }
  23370. /* falls through */
  23371. case COPY_:
  23372. state.mode = COPY;
  23373. /* falls through */
  23374. case COPY:
  23375. copy = state.length;
  23376. if (copy) {
  23377. if (copy > have) { copy = have; }
  23378. if (copy > left) { copy = left; }
  23379. if (copy === 0) { break inf_leave; }
  23380. //--- zmemcpy(put, next, copy); ---
  23381. utils.arraySet(output, input, next, copy, put);
  23382. //---//
  23383. have -= copy;
  23384. next += copy;
  23385. left -= copy;
  23386. put += copy;
  23387. state.length -= copy;
  23388. break;
  23389. }
  23390. //Tracev((stderr, "inflate: stored end\n"));
  23391. state.mode = TYPE;
  23392. break;
  23393. case TABLE:
  23394. //=== NEEDBITS(14); */
  23395. while (bits < 14) {
  23396. if (have === 0) { break inf_leave; }
  23397. have--;
  23398. hold += input[next++] << bits;
  23399. bits += 8;
  23400. }
  23401. //===//
  23402. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  23403. //--- DROPBITS(5) ---//
  23404. hold >>>= 5;
  23405. bits -= 5;
  23406. //---//
  23407. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  23408. //--- DROPBITS(5) ---//
  23409. hold >>>= 5;
  23410. bits -= 5;
  23411. //---//
  23412. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  23413. //--- DROPBITS(4) ---//
  23414. hold >>>= 4;
  23415. bits -= 4;
  23416. //---//
  23417. //#ifndef PKZIP_BUG_WORKAROUND
  23418. if (state.nlen > 286 || state.ndist > 30) {
  23419. strm.msg = 'too many length or distance symbols';
  23420. state.mode = BAD;
  23421. break;
  23422. }
  23423. //#endif
  23424. //Tracev((stderr, "inflate: table sizes ok\n"));
  23425. state.have = 0;
  23426. state.mode = LENLENS;
  23427. /* falls through */
  23428. case LENLENS:
  23429. while (state.have < state.ncode) {
  23430. //=== NEEDBITS(3);
  23431. while (bits < 3) {
  23432. if (have === 0) { break inf_leave; }
  23433. have--;
  23434. hold += input[next++] << bits;
  23435. bits += 8;
  23436. }
  23437. //===//
  23438. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  23439. //--- DROPBITS(3) ---//
  23440. hold >>>= 3;
  23441. bits -= 3;
  23442. //---//
  23443. }
  23444. while (state.have < 19) {
  23445. state.lens[order[state.have++]] = 0;
  23446. }
  23447. // We have separate tables & no pointers. 2 commented lines below not needed.
  23448. //state.next = state.codes;
  23449. //state.lencode = state.next;
  23450. // Switch to use dynamic table
  23451. state.lencode = state.lendyn;
  23452. state.lenbits = 7;
  23453. opts = {bits: state.lenbits};
  23454. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  23455. state.lenbits = opts.bits;
  23456. if (ret) {
  23457. strm.msg = 'invalid code lengths set';
  23458. state.mode = BAD;
  23459. break;
  23460. }
  23461. //Tracev((stderr, "inflate: code lengths ok\n"));
  23462. state.have = 0;
  23463. state.mode = CODELENS;
  23464. /* falls through */
  23465. case CODELENS:
  23466. while (state.have < state.nlen + state.ndist) {
  23467. for (;;) {
  23468. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  23469. here_bits = here >>> 24;
  23470. here_op = (here >>> 16) & 0xff;
  23471. here_val = here & 0xffff;
  23472. if ((here_bits) <= bits) { break; }
  23473. //--- PULLBYTE() ---//
  23474. if (have === 0) { break inf_leave; }
  23475. have--;
  23476. hold += input[next++] << bits;
  23477. bits += 8;
  23478. //---//
  23479. }
  23480. if (here_val < 16) {
  23481. //--- DROPBITS(here.bits) ---//
  23482. hold >>>= here_bits;
  23483. bits -= here_bits;
  23484. //---//
  23485. state.lens[state.have++] = here_val;
  23486. }
  23487. else {
  23488. if (here_val === 16) {
  23489. //=== NEEDBITS(here.bits + 2);
  23490. n = here_bits + 2;
  23491. while (bits < n) {
  23492. if (have === 0) { break inf_leave; }
  23493. have--;
  23494. hold += input[next++] << bits;
  23495. bits += 8;
  23496. }
  23497. //===//
  23498. //--- DROPBITS(here.bits) ---//
  23499. hold >>>= here_bits;
  23500. bits -= here_bits;
  23501. //---//
  23502. if (state.have === 0) {
  23503. strm.msg = 'invalid bit length repeat';
  23504. state.mode = BAD;
  23505. break;
  23506. }
  23507. len = state.lens[state.have - 1];
  23508. copy = 3 + (hold & 0x03);//BITS(2);
  23509. //--- DROPBITS(2) ---//
  23510. hold >>>= 2;
  23511. bits -= 2;
  23512. //---//
  23513. }
  23514. else if (here_val === 17) {
  23515. //=== NEEDBITS(here.bits + 3);
  23516. n = here_bits + 3;
  23517. while (bits < n) {
  23518. if (have === 0) { break inf_leave; }
  23519. have--;
  23520. hold += input[next++] << bits;
  23521. bits += 8;
  23522. }
  23523. //===//
  23524. //--- DROPBITS(here.bits) ---//
  23525. hold >>>= here_bits;
  23526. bits -= here_bits;
  23527. //---//
  23528. len = 0;
  23529. copy = 3 + (hold & 0x07);//BITS(3);
  23530. //--- DROPBITS(3) ---//
  23531. hold >>>= 3;
  23532. bits -= 3;
  23533. //---//
  23534. }
  23535. else {
  23536. //=== NEEDBITS(here.bits + 7);
  23537. n = here_bits + 7;
  23538. while (bits < n) {
  23539. if (have === 0) { break inf_leave; }
  23540. have--;
  23541. hold += input[next++] << bits;
  23542. bits += 8;
  23543. }
  23544. //===//
  23545. //--- DROPBITS(here.bits) ---//
  23546. hold >>>= here_bits;
  23547. bits -= here_bits;
  23548. //---//
  23549. len = 0;
  23550. copy = 11 + (hold & 0x7f);//BITS(7);
  23551. //--- DROPBITS(7) ---//
  23552. hold >>>= 7;
  23553. bits -= 7;
  23554. //---//
  23555. }
  23556. if (state.have + copy > state.nlen + state.ndist) {
  23557. strm.msg = 'invalid bit length repeat';
  23558. state.mode = BAD;
  23559. break;
  23560. }
  23561. while (copy--) {
  23562. state.lens[state.have++] = len;
  23563. }
  23564. }
  23565. }
  23566. /* handle error breaks in while */
  23567. if (state.mode === BAD) { break; }
  23568. /* check for end-of-block code (better have one) */
  23569. if (state.lens[256] === 0) {
  23570. strm.msg = 'invalid code -- missing end-of-block';
  23571. state.mode = BAD;
  23572. break;
  23573. }
  23574. /* build code tables -- note: do not change the lenbits or distbits
  23575. values here (9 and 6) without reading the comments in inftrees.h
  23576. concerning the ENOUGH constants, which depend on those values */
  23577. state.lenbits = 9;
  23578. opts = {bits: state.lenbits};
  23579. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  23580. // We have separate tables & no pointers. 2 commented lines below not needed.
  23581. // state.next_index = opts.table_index;
  23582. state.lenbits = opts.bits;
  23583. // state.lencode = state.next;
  23584. if (ret) {
  23585. strm.msg = 'invalid literal/lengths set';
  23586. state.mode = BAD;
  23587. break;
  23588. }
  23589. state.distbits = 6;
  23590. //state.distcode.copy(state.codes);
  23591. // Switch to use dynamic table
  23592. state.distcode = state.distdyn;
  23593. opts = {bits: state.distbits};
  23594. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  23595. // We have separate tables & no pointers. 2 commented lines below not needed.
  23596. // state.next_index = opts.table_index;
  23597. state.distbits = opts.bits;
  23598. // state.distcode = state.next;
  23599. if (ret) {
  23600. strm.msg = 'invalid distances set';
  23601. state.mode = BAD;
  23602. break;
  23603. }
  23604. //Tracev((stderr, 'inflate: codes ok\n'));
  23605. state.mode = LEN_;
  23606. if (flush === Z_TREES) { break inf_leave; }
  23607. /* falls through */
  23608. case LEN_:
  23609. state.mode = LEN;
  23610. /* falls through */
  23611. case LEN:
  23612. if (have >= 6 && left >= 258) {
  23613. //--- RESTORE() ---
  23614. strm.next_out = put;
  23615. strm.avail_out = left;
  23616. strm.next_in = next;
  23617. strm.avail_in = have;
  23618. state.hold = hold;
  23619. state.bits = bits;
  23620. //---
  23621. inflate_fast(strm, _out);
  23622. //--- LOAD() ---
  23623. put = strm.next_out;
  23624. output = strm.output;
  23625. left = strm.avail_out;
  23626. next = strm.next_in;
  23627. input = strm.input;
  23628. have = strm.avail_in;
  23629. hold = state.hold;
  23630. bits = state.bits;
  23631. //---
  23632. if (state.mode === TYPE) {
  23633. state.back = -1;
  23634. }
  23635. break;
  23636. }
  23637. state.back = 0;
  23638. for (;;) {
  23639. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  23640. here_bits = here >>> 24;
  23641. here_op = (here >>> 16) & 0xff;
  23642. here_val = here & 0xffff;
  23643. if (here_bits <= bits) { break; }
  23644. //--- PULLBYTE() ---//
  23645. if (have === 0) { break inf_leave; }
  23646. have--;
  23647. hold += input[next++] << bits;
  23648. bits += 8;
  23649. //---//
  23650. }
  23651. if (here_op && (here_op & 0xf0) === 0) {
  23652. last_bits = here_bits;
  23653. last_op = here_op;
  23654. last_val = here_val;
  23655. for (;;) {
  23656. here = state.lencode[last_val +
  23657. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  23658. here_bits = here >>> 24;
  23659. here_op = (here >>> 16) & 0xff;
  23660. here_val = here & 0xffff;
  23661. if ((last_bits + here_bits) <= bits) { break; }
  23662. //--- PULLBYTE() ---//
  23663. if (have === 0) { break inf_leave; }
  23664. have--;
  23665. hold += input[next++] << bits;
  23666. bits += 8;
  23667. //---//
  23668. }
  23669. //--- DROPBITS(last.bits) ---//
  23670. hold >>>= last_bits;
  23671. bits -= last_bits;
  23672. //---//
  23673. state.back += last_bits;
  23674. }
  23675. //--- DROPBITS(here.bits) ---//
  23676. hold >>>= here_bits;
  23677. bits -= here_bits;
  23678. //---//
  23679. state.back += here_bits;
  23680. state.length = here_val;
  23681. if (here_op === 0) {
  23682. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  23683. // "inflate: literal '%c'\n" :
  23684. // "inflate: literal 0x%02x\n", here.val));
  23685. state.mode = LIT;
  23686. break;
  23687. }
  23688. if (here_op & 32) {
  23689. //Tracevv((stderr, "inflate: end of block\n"));
  23690. state.back = -1;
  23691. state.mode = TYPE;
  23692. break;
  23693. }
  23694. if (here_op & 64) {
  23695. strm.msg = 'invalid literal/length code';
  23696. state.mode = BAD;
  23697. break;
  23698. }
  23699. state.extra = here_op & 15;
  23700. state.mode = LENEXT;
  23701. /* falls through */
  23702. case LENEXT:
  23703. if (state.extra) {
  23704. //=== NEEDBITS(state.extra);
  23705. n = state.extra;
  23706. while (bits < n) {
  23707. if (have === 0) { break inf_leave; }
  23708. have--;
  23709. hold += input[next++] << bits;
  23710. bits += 8;
  23711. }
  23712. //===//
  23713. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  23714. //--- DROPBITS(state.extra) ---//
  23715. hold >>>= state.extra;
  23716. bits -= state.extra;
  23717. //---//
  23718. state.back += state.extra;
  23719. }
  23720. //Tracevv((stderr, "inflate: length %u\n", state.length));
  23721. state.was = state.length;
  23722. state.mode = DIST;
  23723. /* falls through */
  23724. case DIST:
  23725. for (;;) {
  23726. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  23727. here_bits = here >>> 24;
  23728. here_op = (here >>> 16) & 0xff;
  23729. here_val = here & 0xffff;
  23730. if ((here_bits) <= bits) { break; }
  23731. //--- PULLBYTE() ---//
  23732. if (have === 0) { break inf_leave; }
  23733. have--;
  23734. hold += input[next++] << bits;
  23735. bits += 8;
  23736. //---//
  23737. }
  23738. if ((here_op & 0xf0) === 0) {
  23739. last_bits = here_bits;
  23740. last_op = here_op;
  23741. last_val = here_val;
  23742. for (;;) {
  23743. here = state.distcode[last_val +
  23744. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  23745. here_bits = here >>> 24;
  23746. here_op = (here >>> 16) & 0xff;
  23747. here_val = here & 0xffff;
  23748. if ((last_bits + here_bits) <= bits) { break; }
  23749. //--- PULLBYTE() ---//
  23750. if (have === 0) { break inf_leave; }
  23751. have--;
  23752. hold += input[next++] << bits;
  23753. bits += 8;
  23754. //---//
  23755. }
  23756. //--- DROPBITS(last.bits) ---//
  23757. hold >>>= last_bits;
  23758. bits -= last_bits;
  23759. //---//
  23760. state.back += last_bits;
  23761. }
  23762. //--- DROPBITS(here.bits) ---//
  23763. hold >>>= here_bits;
  23764. bits -= here_bits;
  23765. //---//
  23766. state.back += here_bits;
  23767. if (here_op & 64) {
  23768. strm.msg = 'invalid distance code';
  23769. state.mode = BAD;
  23770. break;
  23771. }
  23772. state.offset = here_val;
  23773. state.extra = (here_op) & 15;
  23774. state.mode = DISTEXT;
  23775. /* falls through */
  23776. case DISTEXT:
  23777. if (state.extra) {
  23778. //=== NEEDBITS(state.extra);
  23779. n = state.extra;
  23780. while (bits < n) {
  23781. if (have === 0) { break inf_leave; }
  23782. have--;
  23783. hold += input[next++] << bits;
  23784. bits += 8;
  23785. }
  23786. //===//
  23787. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  23788. //--- DROPBITS(state.extra) ---//
  23789. hold >>>= state.extra;
  23790. bits -= state.extra;
  23791. //---//
  23792. state.back += state.extra;
  23793. }
  23794. //#ifdef INFLATE_STRICT
  23795. if (state.offset > state.dmax) {
  23796. strm.msg = 'invalid distance too far back';
  23797. state.mode = BAD;
  23798. break;
  23799. }
  23800. //#endif
  23801. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  23802. state.mode = MATCH;
  23803. /* falls through */
  23804. case MATCH:
  23805. if (left === 0) { break inf_leave; }
  23806. copy = _out - left;
  23807. if (state.offset > copy) { /* copy from window */
  23808. copy = state.offset - copy;
  23809. if (copy > state.whave) {
  23810. if (state.sane) {
  23811. strm.msg = 'invalid distance too far back';
  23812. state.mode = BAD;
  23813. break;
  23814. }
  23815. // (!) This block is disabled in zlib defailts,
  23816. // don't enable it for binary compatibility
  23817. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  23818. // Trace((stderr, "inflate.c too far\n"));
  23819. // copy -= state.whave;
  23820. // if (copy > state.length) { copy = state.length; }
  23821. // if (copy > left) { copy = left; }
  23822. // left -= copy;
  23823. // state.length -= copy;
  23824. // do {
  23825. // output[put++] = 0;
  23826. // } while (--copy);
  23827. // if (state.length === 0) { state.mode = LEN; }
  23828. // break;
  23829. //#endif
  23830. }
  23831. if (copy > state.wnext) {
  23832. copy -= state.wnext;
  23833. from = state.wsize - copy;
  23834. }
  23835. else {
  23836. from = state.wnext - copy;
  23837. }
  23838. if (copy > state.length) { copy = state.length; }
  23839. from_source = state.window;
  23840. }
  23841. else { /* copy from output */
  23842. from_source = output;
  23843. from = put - state.offset;
  23844. copy = state.length;
  23845. }
  23846. if (copy > left) { copy = left; }
  23847. left -= copy;
  23848. state.length -= copy;
  23849. do {
  23850. output[put++] = from_source[from++];
  23851. } while (--copy);
  23852. if (state.length === 0) { state.mode = LEN; }
  23853. break;
  23854. case LIT:
  23855. if (left === 0) { break inf_leave; }
  23856. output[put++] = state.length;
  23857. left--;
  23858. state.mode = LEN;
  23859. break;
  23860. case CHECK:
  23861. if (state.wrap) {
  23862. //=== NEEDBITS(32);
  23863. while (bits < 32) {
  23864. if (have === 0) { break inf_leave; }
  23865. have--;
  23866. // Use '|' insdead of '+' to make sure that result is signed
  23867. hold |= input[next++] << bits;
  23868. bits += 8;
  23869. }
  23870. //===//
  23871. _out -= left;
  23872. strm.total_out += _out;
  23873. state.total += _out;
  23874. if (_out) {
  23875. strm.adler = state.check =
  23876. /*UPDATE(state.check, put - _out, _out);*/
  23877. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  23878. }
  23879. _out = left;
  23880. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  23881. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  23882. strm.msg = 'incorrect data check';
  23883. state.mode = BAD;
  23884. break;
  23885. }
  23886. //=== INITBITS();
  23887. hold = 0;
  23888. bits = 0;
  23889. //===//
  23890. //Tracev((stderr, "inflate: check matches trailer\n"));
  23891. }
  23892. state.mode = LENGTH;
  23893. /* falls through */
  23894. case LENGTH:
  23895. if (state.wrap && state.flags) {
  23896. //=== NEEDBITS(32);
  23897. while (bits < 32) {
  23898. if (have === 0) { break inf_leave; }
  23899. have--;
  23900. hold += input[next++] << bits;
  23901. bits += 8;
  23902. }
  23903. //===//
  23904. if (hold !== (state.total & 0xffffffff)) {
  23905. strm.msg = 'incorrect length check';
  23906. state.mode = BAD;
  23907. break;
  23908. }
  23909. //=== INITBITS();
  23910. hold = 0;
  23911. bits = 0;
  23912. //===//
  23913. //Tracev((stderr, "inflate: length matches trailer\n"));
  23914. }
  23915. state.mode = DONE;
  23916. /* falls through */
  23917. case DONE:
  23918. ret = Z_STREAM_END;
  23919. break inf_leave;
  23920. case BAD:
  23921. ret = Z_DATA_ERROR;
  23922. break inf_leave;
  23923. case MEM:
  23924. return Z_MEM_ERROR;
  23925. case SYNC:
  23926. /* falls through */
  23927. default:
  23928. return Z_STREAM_ERROR;
  23929. }
  23930. }
  23931. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  23932. /*
  23933. Return from inflate(), updating the total counts and the check value.
  23934. If there was no progress during the inflate() call, return a buffer
  23935. error. Call updatewindow() to create and/or update the window state.
  23936. Note: a memory error from inflate() is non-recoverable.
  23937. */
  23938. //--- RESTORE() ---
  23939. strm.next_out = put;
  23940. strm.avail_out = left;
  23941. strm.next_in = next;
  23942. strm.avail_in = have;
  23943. state.hold = hold;
  23944. state.bits = bits;
  23945. //---
  23946. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  23947. (state.mode < CHECK || flush !== Z_FINISH))) {
  23948. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  23949. state.mode = MEM;
  23950. return Z_MEM_ERROR;
  23951. }
  23952. }
  23953. _in -= strm.avail_in;
  23954. _out -= strm.avail_out;
  23955. strm.total_in += _in;
  23956. strm.total_out += _out;
  23957. state.total += _out;
  23958. if (state.wrap && _out) {
  23959. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  23960. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  23961. }
  23962. strm.data_type = state.bits + (state.last ? 64 : 0) +
  23963. (state.mode === TYPE ? 128 : 0) +
  23964. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  23965. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  23966. ret = Z_BUF_ERROR;
  23967. }
  23968. return ret;
  23969. }
  23970. function inflateEnd(strm) {
  23971. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  23972. return Z_STREAM_ERROR;
  23973. }
  23974. var state = strm.state;
  23975. if (state.window) {
  23976. state.window = null;
  23977. }
  23978. strm.state = null;
  23979. return Z_OK;
  23980. }
  23981. function inflateGetHeader(strm, head) {
  23982. var state;
  23983. /* check state */
  23984. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  23985. state = strm.state;
  23986. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  23987. /* save header structure */
  23988. state.head = head;
  23989. head.done = false;
  23990. return Z_OK;
  23991. }
  23992. exports.inflateReset = inflateReset;
  23993. exports.inflateReset2 = inflateReset2;
  23994. exports.inflateResetKeep = inflateResetKeep;
  23995. exports.inflateInit = inflateInit;
  23996. exports.inflateInit2 = inflateInit2;
  23997. exports.inflate = inflate;
  23998. exports.inflateEnd = inflateEnd;
  23999. exports.inflateGetHeader = inflateGetHeader;
  24000. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  24001. /* Not implemented
  24002. exports.inflateCopy = inflateCopy;
  24003. exports.inflateGetDictionary = inflateGetDictionary;
  24004. exports.inflateMark = inflateMark;
  24005. exports.inflatePrime = inflatePrime;
  24006. exports.inflateSetDictionary = inflateSetDictionary;
  24007. exports.inflateSync = inflateSync;
  24008. exports.inflateSyncPoint = inflateSyncPoint;
  24009. exports.inflateUndermine = inflateUndermine;
  24010. */
  24011. },{"../utils/common":75,"./adler32":77,"./crc32":79,"./inffast":82,"./inftrees":84}],84:[function(require,module,exports){
  24012. 'use strict';
  24013. var utils = require('../utils/common');
  24014. var MAXBITS = 15;
  24015. var ENOUGH_LENS = 852;
  24016. var ENOUGH_DISTS = 592;
  24017. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  24018. var CODES = 0;
  24019. var LENS = 1;
  24020. var DISTS = 2;
  24021. var lbase = [ /* Length codes 257..285 base */
  24022. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  24023. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  24024. ];
  24025. var lext = [ /* Length codes 257..285 extra */
  24026. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  24027. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  24028. ];
  24029. var dbase = [ /* Distance codes 0..29 base */
  24030. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  24031. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  24032. 8193, 12289, 16385, 24577, 0, 0
  24033. ];
  24034. var dext = [ /* Distance codes 0..29 extra */
  24035. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  24036. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  24037. 28, 28, 29, 29, 64, 64
  24038. ];
  24039. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  24040. {
  24041. var bits = opts.bits;
  24042. //here = opts.here; /* table entry for duplication */
  24043. var len = 0; /* a code's length in bits */
  24044. var sym = 0; /* index of code symbols */
  24045. var min = 0, max = 0; /* minimum and maximum code lengths */
  24046. var root = 0; /* number of index bits for root table */
  24047. var curr = 0; /* number of index bits for current table */
  24048. var drop = 0; /* code bits to drop for sub-table */
  24049. var left = 0; /* number of prefix codes available */
  24050. var used = 0; /* code entries in table used */
  24051. var huff = 0; /* Huffman code */
  24052. var incr; /* for incrementing code, index */
  24053. var fill; /* index for replicating entries */
  24054. var low; /* low bits for current root entry */
  24055. var mask; /* mask for low root bits */
  24056. var next; /* next available space in table */
  24057. var base = null; /* base value table to use */
  24058. var base_index = 0;
  24059. // var shoextra; /* extra bits table to use */
  24060. var end; /* use base and extra for symbol > end */
  24061. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  24062. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  24063. var extra = null;
  24064. var extra_index = 0;
  24065. var here_bits, here_op, here_val;
  24066. /*
  24067. Process a set of code lengths to create a canonical Huffman code. The
  24068. code lengths are lens[0..codes-1]. Each length corresponds to the
  24069. symbols 0..codes-1. The Huffman code is generated by first sorting the
  24070. symbols by length from short to long, and retaining the symbol order
  24071. for codes with equal lengths. Then the code starts with all zero bits
  24072. for the first code of the shortest length, and the codes are integer
  24073. increments for the same length, and zeros are appended as the length
  24074. increases. For the deflate format, these bits are stored backwards
  24075. from their more natural integer increment ordering, and so when the
  24076. decoding tables are built in the large loop below, the integer codes
  24077. are incremented backwards.
  24078. This routine assumes, but does not check, that all of the entries in
  24079. lens[] are in the range 0..MAXBITS. The caller must assure this.
  24080. 1..MAXBITS is interpreted as that code length. zero means that that
  24081. symbol does not occur in this code.
  24082. The codes are sorted by computing a count of codes for each length,
  24083. creating from that a table of starting indices for each length in the
  24084. sorted table, and then entering the symbols in order in the sorted
  24085. table. The sorted table is work[], with that space being provided by
  24086. the caller.
  24087. The length counts are used for other purposes as well, i.e. finding
  24088. the minimum and maximum length codes, determining if there are any
  24089. codes at all, checking for a valid set of lengths, and looking ahead
  24090. at length counts to determine sub-table sizes when building the
  24091. decoding tables.
  24092. */
  24093. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  24094. for (len = 0; len <= MAXBITS; len++) {
  24095. count[len] = 0;
  24096. }
  24097. for (sym = 0; sym < codes; sym++) {
  24098. count[lens[lens_index + sym]]++;
  24099. }
  24100. /* bound code lengths, force root to be within code lengths */
  24101. root = bits;
  24102. for (max = MAXBITS; max >= 1; max--) {
  24103. if (count[max] !== 0) { break; }
  24104. }
  24105. if (root > max) {
  24106. root = max;
  24107. }
  24108. if (max === 0) { /* no symbols to code at all */
  24109. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  24110. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  24111. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  24112. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  24113. //table.op[opts.table_index] = 64;
  24114. //table.bits[opts.table_index] = 1;
  24115. //table.val[opts.table_index++] = 0;
  24116. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  24117. opts.bits = 1;
  24118. return 0; /* no symbols, but wait for decoding to report error */
  24119. }
  24120. for (min = 1; min < max; min++) {
  24121. if (count[min] !== 0) { break; }
  24122. }
  24123. if (root < min) {
  24124. root = min;
  24125. }
  24126. /* check for an over-subscribed or incomplete set of lengths */
  24127. left = 1;
  24128. for (len = 1; len <= MAXBITS; len++) {
  24129. left <<= 1;
  24130. left -= count[len];
  24131. if (left < 0) {
  24132. return -1;
  24133. } /* over-subscribed */
  24134. }
  24135. if (left > 0 && (type === CODES || max !== 1)) {
  24136. return -1; /* incomplete set */
  24137. }
  24138. /* generate offsets into symbol table for each length for sorting */
  24139. offs[1] = 0;
  24140. for (len = 1; len < MAXBITS; len++) {
  24141. offs[len + 1] = offs[len] + count[len];
  24142. }
  24143. /* sort symbols by length, by symbol order within each length */
  24144. for (sym = 0; sym < codes; sym++) {
  24145. if (lens[lens_index + sym] !== 0) {
  24146. work[offs[lens[lens_index + sym]]++] = sym;
  24147. }
  24148. }
  24149. /*
  24150. Create and fill in decoding tables. In this loop, the table being
  24151. filled is at next and has curr index bits. The code being used is huff
  24152. with length len. That code is converted to an index by dropping drop
  24153. bits off of the bottom. For codes where len is less than drop + curr,
  24154. those top drop + curr - len bits are incremented through all values to
  24155. fill the table with replicated entries.
  24156. root is the number of index bits for the root table. When len exceeds
  24157. root, sub-tables are created pointed to by the root entry with an index
  24158. of the low root bits of huff. This is saved in low to check for when a
  24159. new sub-table should be started. drop is zero when the root table is
  24160. being filled, and drop is root when sub-tables are being filled.
  24161. When a new sub-table is needed, it is necessary to look ahead in the
  24162. code lengths to determine what size sub-table is needed. The length
  24163. counts are used for this, and so count[] is decremented as codes are
  24164. entered in the tables.
  24165. used keeps track of how many table entries have been allocated from the
  24166. provided *table space. It is checked for LENS and DIST tables against
  24167. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  24168. the initial root table size constants. See the comments in inftrees.h
  24169. for more information.
  24170. sym increments through all symbols, and the loop terminates when
  24171. all codes of length max, i.e. all codes, have been processed. This
  24172. routine permits incomplete codes, so another loop after this one fills
  24173. in the rest of the decoding tables with invalid code markers.
  24174. */
  24175. /* set up for code type */
  24176. // poor man optimization - use if-else instead of switch,
  24177. // to avoid deopts in old v8
  24178. if (type === CODES) {
  24179. base = extra = work; /* dummy value--not used */
  24180. end = 19;
  24181. } else if (type === LENS) {
  24182. base = lbase;
  24183. base_index -= 257;
  24184. extra = lext;
  24185. extra_index -= 257;
  24186. end = 256;
  24187. } else { /* DISTS */
  24188. base = dbase;
  24189. extra = dext;
  24190. end = -1;
  24191. }
  24192. /* initialize opts for loop */
  24193. huff = 0; /* starting code */
  24194. sym = 0; /* starting code symbol */
  24195. len = min; /* starting code length */
  24196. next = table_index; /* current table to fill in */
  24197. curr = root; /* current table index bits */
  24198. drop = 0; /* current bits to drop from code for index */
  24199. low = -1; /* trigger new sub-table when len > root */
  24200. used = 1 << root; /* use root table entries */
  24201. mask = used - 1; /* mask for comparing low */
  24202. /* check available table space */
  24203. if ((type === LENS && used > ENOUGH_LENS) ||
  24204. (type === DISTS && used > ENOUGH_DISTS)) {
  24205. return 1;
  24206. }
  24207. var i=0;
  24208. /* process all codes and make table entries */
  24209. for (;;) {
  24210. i++;
  24211. /* create table entry */
  24212. here_bits = len - drop;
  24213. if (work[sym] < end) {
  24214. here_op = 0;
  24215. here_val = work[sym];
  24216. }
  24217. else if (work[sym] > end) {
  24218. here_op = extra[extra_index + work[sym]];
  24219. here_val = base[base_index + work[sym]];
  24220. }
  24221. else {
  24222. here_op = 32 + 64; /* end of block */
  24223. here_val = 0;
  24224. }
  24225. /* replicate for those indices with low len bits equal to huff */
  24226. incr = 1 << (len - drop);
  24227. fill = 1 << curr;
  24228. min = fill; /* save offset to next table */
  24229. do {
  24230. fill -= incr;
  24231. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  24232. } while (fill !== 0);
  24233. /* backwards increment the len-bit code huff */
  24234. incr = 1 << (len - 1);
  24235. while (huff & incr) {
  24236. incr >>= 1;
  24237. }
  24238. if (incr !== 0) {
  24239. huff &= incr - 1;
  24240. huff += incr;
  24241. } else {
  24242. huff = 0;
  24243. }
  24244. /* go to next symbol, update count, len */
  24245. sym++;
  24246. if (--count[len] === 0) {
  24247. if (len === max) { break; }
  24248. len = lens[lens_index + work[sym]];
  24249. }
  24250. /* create new sub-table if needed */
  24251. if (len > root && (huff & mask) !== low) {
  24252. /* if first time, transition to sub-tables */
  24253. if (drop === 0) {
  24254. drop = root;
  24255. }
  24256. /* increment past last table */
  24257. next += min; /* here min is 1 << curr */
  24258. /* determine length of next table */
  24259. curr = len - drop;
  24260. left = 1 << curr;
  24261. while (curr + drop < max) {
  24262. left -= count[curr + drop];
  24263. if (left <= 0) { break; }
  24264. curr++;
  24265. left <<= 1;
  24266. }
  24267. /* check for enough space */
  24268. used += 1 << curr;
  24269. if ((type === LENS && used > ENOUGH_LENS) ||
  24270. (type === DISTS && used > ENOUGH_DISTS)) {
  24271. return 1;
  24272. }
  24273. /* point entry in root table to sub-table */
  24274. low = huff & mask;
  24275. /*table.op[low] = curr;
  24276. table.bits[low] = root;
  24277. table.val[low] = next - opts.table_index;*/
  24278. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  24279. }
  24280. }
  24281. /* fill in remaining table entry if code is incomplete (guaranteed to have
  24282. at most one remaining entry, since if the code is incomplete, the
  24283. maximum code length that was allowed to get this far is one bit) */
  24284. if (huff !== 0) {
  24285. //table.op[next + huff] = 64; /* invalid code marker */
  24286. //table.bits[next + huff] = len - drop;
  24287. //table.val[next + huff] = 0;
  24288. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  24289. }
  24290. /* set return parameters */
  24291. //opts.table_index += used;
  24292. opts.bits = root;
  24293. return 0;
  24294. };
  24295. },{"../utils/common":75}],85:[function(require,module,exports){
  24296. 'use strict';
  24297. module.exports = {
  24298. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  24299. '1': 'stream end', /* Z_STREAM_END 1 */
  24300. '0': '', /* Z_OK 0 */
  24301. '-1': 'file error', /* Z_ERRNO (-1) */
  24302. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  24303. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  24304. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  24305. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  24306. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  24307. };
  24308. },{}],86:[function(require,module,exports){
  24309. 'use strict';
  24310. var utils = require('../utils/common');
  24311. /* Public constants ==========================================================*/
  24312. /* ===========================================================================*/
  24313. //var Z_FILTERED = 1;
  24314. //var Z_HUFFMAN_ONLY = 2;
  24315. //var Z_RLE = 3;
  24316. var Z_FIXED = 4;
  24317. //var Z_DEFAULT_STRATEGY = 0;
  24318. /* Possible values of the data_type field (though see inflate()) */
  24319. var Z_BINARY = 0;
  24320. var Z_TEXT = 1;
  24321. //var Z_ASCII = 1; // = Z_TEXT
  24322. var Z_UNKNOWN = 2;
  24323. /*============================================================================*/
  24324. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  24325. // From zutil.h
  24326. var STORED_BLOCK = 0;
  24327. var STATIC_TREES = 1;
  24328. var DYN_TREES = 2;
  24329. /* The three kinds of block type */
  24330. var MIN_MATCH = 3;
  24331. var MAX_MATCH = 258;
  24332. /* The minimum and maximum match lengths */
  24333. // From deflate.h
  24334. /* ===========================================================================
  24335. * Internal compression state.
  24336. */
  24337. var LENGTH_CODES = 29;
  24338. /* number of length codes, not counting the special END_BLOCK code */
  24339. var LITERALS = 256;
  24340. /* number of literal bytes 0..255 */
  24341. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  24342. /* number of Literal or Length codes, including the END_BLOCK code */
  24343. var D_CODES = 30;
  24344. /* number of distance codes */
  24345. var BL_CODES = 19;
  24346. /* number of codes used to transfer the bit lengths */
  24347. var HEAP_SIZE = 2*L_CODES + 1;
  24348. /* maximum heap size */
  24349. var MAX_BITS = 15;
  24350. /* All codes must not exceed MAX_BITS bits */
  24351. var Buf_size = 16;
  24352. /* size of bit buffer in bi_buf */
  24353. /* ===========================================================================
  24354. * Constants
  24355. */
  24356. var MAX_BL_BITS = 7;
  24357. /* Bit length codes must not exceed MAX_BL_BITS bits */
  24358. var END_BLOCK = 256;
  24359. /* end of block literal code */
  24360. var REP_3_6 = 16;
  24361. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  24362. var REPZ_3_10 = 17;
  24363. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  24364. var REPZ_11_138 = 18;
  24365. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  24366. var extra_lbits = /* extra bits for each length code */
  24367. [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];
  24368. var extra_dbits = /* extra bits for each distance code */
  24369. [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];
  24370. var extra_blbits = /* extra bits for each bit length code */
  24371. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  24372. var bl_order =
  24373. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  24374. /* The lengths of the bit length codes are sent in order of decreasing
  24375. * probability, to avoid transmitting the lengths for unused bit length codes.
  24376. */
  24377. /* ===========================================================================
  24378. * Local data. These are initialized only once.
  24379. */
  24380. // We pre-fill arrays with 0 to avoid uninitialized gaps
  24381. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  24382. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  24383. var static_ltree = new Array((L_CODES+2) * 2);
  24384. zero(static_ltree);
  24385. /* The static literal tree. Since the bit lengths are imposed, there is no
  24386. * need for the L_CODES extra codes used during heap construction. However
  24387. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  24388. * below).
  24389. */
  24390. var static_dtree = new Array(D_CODES * 2);
  24391. zero(static_dtree);
  24392. /* The static distance tree. (Actually a trivial tree since all codes use
  24393. * 5 bits.)
  24394. */
  24395. var _dist_code = new Array(DIST_CODE_LEN);
  24396. zero(_dist_code);
  24397. /* Distance codes. The first 256 values correspond to the distances
  24398. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  24399. * the 15 bit distances.
  24400. */
  24401. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  24402. zero(_length_code);
  24403. /* length code for each normalized match length (0 == MIN_MATCH) */
  24404. var base_length = new Array(LENGTH_CODES);
  24405. zero(base_length);
  24406. /* First normalized length for each code (0 = MIN_MATCH) */
  24407. var base_dist = new Array(D_CODES);
  24408. zero(base_dist);
  24409. /* First normalized distance for each code (0 = distance of 1) */
  24410. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  24411. this.static_tree = static_tree; /* static tree or NULL */
  24412. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  24413. this.extra_base = extra_base; /* base index for extra_bits */
  24414. this.elems = elems; /* max number of elements in the tree */
  24415. this.max_length = max_length; /* max bit length for the codes */
  24416. // show if `static_tree` has data or dummy - needed for monomorphic objects
  24417. this.has_stree = static_tree && static_tree.length;
  24418. };
  24419. var static_l_desc;
  24420. var static_d_desc;
  24421. var static_bl_desc;
  24422. var TreeDesc = function(dyn_tree, stat_desc) {
  24423. this.dyn_tree = dyn_tree; /* the dynamic tree */
  24424. this.max_code = 0; /* largest code with non zero frequency */
  24425. this.stat_desc = stat_desc; /* the corresponding static tree */
  24426. };
  24427. function d_code(dist) {
  24428. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  24429. }
  24430. /* ===========================================================================
  24431. * Output a short LSB first on the stream.
  24432. * IN assertion: there is enough room in pendingBuf.
  24433. */
  24434. function put_short (s, w) {
  24435. // put_byte(s, (uch)((w) & 0xff));
  24436. // put_byte(s, (uch)((ush)(w) >> 8));
  24437. s.pending_buf[s.pending++] = (w) & 0xff;
  24438. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  24439. }
  24440. /* ===========================================================================
  24441. * Send a value on a given number of bits.
  24442. * IN assertion: length <= 16 and value fits in length bits.
  24443. */
  24444. function send_bits(s, value, length) {
  24445. if (s.bi_valid > (Buf_size - length)) {
  24446. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  24447. put_short(s, s.bi_buf);
  24448. s.bi_buf = value >> (Buf_size - s.bi_valid);
  24449. s.bi_valid += length - Buf_size;
  24450. } else {
  24451. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  24452. s.bi_valid += length;
  24453. }
  24454. }
  24455. function send_code(s, c, tree) {
  24456. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  24457. }
  24458. /* ===========================================================================
  24459. * Reverse the first len bits of a code, using straightforward code (a faster
  24460. * method would use a table)
  24461. * IN assertion: 1 <= len <= 15
  24462. */
  24463. function bi_reverse(code, len) {
  24464. var res = 0;
  24465. do {
  24466. res |= code & 1;
  24467. code >>>= 1;
  24468. res <<= 1;
  24469. } while (--len > 0);
  24470. return res >>> 1;
  24471. }
  24472. /* ===========================================================================
  24473. * Flush the bit buffer, keeping at most 7 bits in it.
  24474. */
  24475. function bi_flush(s) {
  24476. if (s.bi_valid === 16) {
  24477. put_short(s, s.bi_buf);
  24478. s.bi_buf = 0;
  24479. s.bi_valid = 0;
  24480. } else if (s.bi_valid >= 8) {
  24481. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  24482. s.bi_buf >>= 8;
  24483. s.bi_valid -= 8;
  24484. }
  24485. }
  24486. /* ===========================================================================
  24487. * Compute the optimal bit lengths for a tree and update the total bit length
  24488. * for the current block.
  24489. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  24490. * above are the tree nodes sorted by increasing frequency.
  24491. * OUT assertions: the field len is set to the optimal bit length, the
  24492. * array bl_count contains the frequencies for each bit length.
  24493. * The length opt_len is updated; static_len is also updated if stree is
  24494. * not null.
  24495. */
  24496. function gen_bitlen(s, desc)
  24497. // deflate_state *s;
  24498. // tree_desc *desc; /* the tree descriptor */
  24499. {
  24500. var tree = desc.dyn_tree;
  24501. var max_code = desc.max_code;
  24502. var stree = desc.stat_desc.static_tree;
  24503. var has_stree = desc.stat_desc.has_stree;
  24504. var extra = desc.stat_desc.extra_bits;
  24505. var base = desc.stat_desc.extra_base;
  24506. var max_length = desc.stat_desc.max_length;
  24507. var h; /* heap index */
  24508. var n, m; /* iterate over the tree elements */
  24509. var bits; /* bit length */
  24510. var xbits; /* extra bits */
  24511. var f; /* frequency */
  24512. var overflow = 0; /* number of elements with bit length too large */
  24513. for (bits = 0; bits <= MAX_BITS; bits++) {
  24514. s.bl_count[bits] = 0;
  24515. }
  24516. /* In a first pass, compute the optimal bit lengths (which may
  24517. * overflow in the case of the bit length tree).
  24518. */
  24519. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  24520. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  24521. n = s.heap[h];
  24522. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  24523. if (bits > max_length) {
  24524. bits = max_length;
  24525. overflow++;
  24526. }
  24527. tree[n*2 + 1]/*.Len*/ = bits;
  24528. /* We overwrite tree[n].Dad which is no longer needed */
  24529. if (n > max_code) { continue; } /* not a leaf node */
  24530. s.bl_count[bits]++;
  24531. xbits = 0;
  24532. if (n >= base) {
  24533. xbits = extra[n-base];
  24534. }
  24535. f = tree[n * 2]/*.Freq*/;
  24536. s.opt_len += f * (bits + xbits);
  24537. if (has_stree) {
  24538. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  24539. }
  24540. }
  24541. if (overflow === 0) { return; }
  24542. // Trace((stderr,"\nbit length overflow\n"));
  24543. /* This happens for example on obj2 and pic of the Calgary corpus */
  24544. /* Find the first bit length which could increase: */
  24545. do {
  24546. bits = max_length-1;
  24547. while (s.bl_count[bits] === 0) { bits--; }
  24548. s.bl_count[bits]--; /* move one leaf down the tree */
  24549. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  24550. s.bl_count[max_length]--;
  24551. /* The brother of the overflow item also moves one step up,
  24552. * but this does not affect bl_count[max_length]
  24553. */
  24554. overflow -= 2;
  24555. } while (overflow > 0);
  24556. /* Now recompute all bit lengths, scanning in increasing frequency.
  24557. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  24558. * lengths instead of fixing only the wrong ones. This idea is taken
  24559. * from 'ar' written by Haruhiko Okumura.)
  24560. */
  24561. for (bits = max_length; bits !== 0; bits--) {
  24562. n = s.bl_count[bits];
  24563. while (n !== 0) {
  24564. m = s.heap[--h];
  24565. if (m > max_code) { continue; }
  24566. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  24567. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  24568. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  24569. tree[m*2 + 1]/*.Len*/ = bits;
  24570. }
  24571. n--;
  24572. }
  24573. }
  24574. }
  24575. /* ===========================================================================
  24576. * Generate the codes for a given tree and bit counts (which need not be
  24577. * optimal).
  24578. * IN assertion: the array bl_count contains the bit length statistics for
  24579. * the given tree and the field len is set for all tree elements.
  24580. * OUT assertion: the field code is set for all tree elements of non
  24581. * zero code length.
  24582. */
  24583. function gen_codes(tree, max_code, bl_count)
  24584. // ct_data *tree; /* the tree to decorate */
  24585. // int max_code; /* largest code with non zero frequency */
  24586. // ushf *bl_count; /* number of codes at each bit length */
  24587. {
  24588. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  24589. var code = 0; /* running code value */
  24590. var bits; /* bit index */
  24591. var n; /* code index */
  24592. /* The distribution counts are first used to generate the code values
  24593. * without bit reversal.
  24594. */
  24595. for (bits = 1; bits <= MAX_BITS; bits++) {
  24596. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  24597. }
  24598. /* Check that the bit counts in bl_count are consistent. The last code
  24599. * must be all ones.
  24600. */
  24601. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  24602. // "inconsistent bit counts");
  24603. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  24604. for (n = 0; n <= max_code; n++) {
  24605. var len = tree[n*2 + 1]/*.Len*/;
  24606. if (len === 0) { continue; }
  24607. /* Now reverse the bits */
  24608. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  24609. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  24610. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  24611. }
  24612. }
  24613. /* ===========================================================================
  24614. * Initialize the various 'constant' tables.
  24615. */
  24616. function tr_static_init() {
  24617. var n; /* iterates over tree elements */
  24618. var bits; /* bit counter */
  24619. var length; /* length value */
  24620. var code; /* code value */
  24621. var dist; /* distance index */
  24622. var bl_count = new Array(MAX_BITS+1);
  24623. /* number of codes at each bit length for an optimal tree */
  24624. // do check in _tr_init()
  24625. //if (static_init_done) return;
  24626. /* For some embedded targets, global variables are not initialized: */
  24627. /*#ifdef NO_INIT_GLOBAL_POINTERS
  24628. static_l_desc.static_tree = static_ltree;
  24629. static_l_desc.extra_bits = extra_lbits;
  24630. static_d_desc.static_tree = static_dtree;
  24631. static_d_desc.extra_bits = extra_dbits;
  24632. static_bl_desc.extra_bits = extra_blbits;
  24633. #endif*/
  24634. /* Initialize the mapping length (0..255) -> length code (0..28) */
  24635. length = 0;
  24636. for (code = 0; code < LENGTH_CODES-1; code++) {
  24637. base_length[code] = length;
  24638. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  24639. _length_code[length++] = code;
  24640. }
  24641. }
  24642. //Assert (length == 256, "tr_static_init: length != 256");
  24643. /* Note that the length 255 (match length 258) can be represented
  24644. * in two different ways: code 284 + 5 bits or code 285, so we
  24645. * overwrite length_code[255] to use the best encoding:
  24646. */
  24647. _length_code[length-1] = code;
  24648. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  24649. dist = 0;
  24650. for (code = 0 ; code < 16; code++) {
  24651. base_dist[code] = dist;
  24652. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  24653. _dist_code[dist++] = code;
  24654. }
  24655. }
  24656. //Assert (dist == 256, "tr_static_init: dist != 256");
  24657. dist >>= 7; /* from now on, all distances are divided by 128 */
  24658. for (; code < D_CODES; code++) {
  24659. base_dist[code] = dist << 7;
  24660. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  24661. _dist_code[256 + dist++] = code;
  24662. }
  24663. }
  24664. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  24665. /* Construct the codes of the static literal tree */
  24666. for (bits = 0; bits <= MAX_BITS; bits++) {
  24667. bl_count[bits] = 0;
  24668. }
  24669. n = 0;
  24670. while (n <= 143) {
  24671. static_ltree[n*2 + 1]/*.Len*/ = 8;
  24672. n++;
  24673. bl_count[8]++;
  24674. }
  24675. while (n <= 255) {
  24676. static_ltree[n*2 + 1]/*.Len*/ = 9;
  24677. n++;
  24678. bl_count[9]++;
  24679. }
  24680. while (n <= 279) {
  24681. static_ltree[n*2 + 1]/*.Len*/ = 7;
  24682. n++;
  24683. bl_count[7]++;
  24684. }
  24685. while (n <= 287) {
  24686. static_ltree[n*2 + 1]/*.Len*/ = 8;
  24687. n++;
  24688. bl_count[8]++;
  24689. }
  24690. /* Codes 286 and 287 do not exist, but we must include them in the
  24691. * tree construction to get a canonical Huffman tree (longest code
  24692. * all ones)
  24693. */
  24694. gen_codes(static_ltree, L_CODES+1, bl_count);
  24695. /* The static distance tree is trivial: */
  24696. for (n = 0; n < D_CODES; n++) {
  24697. static_dtree[n*2 + 1]/*.Len*/ = 5;
  24698. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  24699. }
  24700. // Now data ready and we can init static trees
  24701. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  24702. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  24703. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  24704. //static_init_done = true;
  24705. }
  24706. /* ===========================================================================
  24707. * Initialize a new block.
  24708. */
  24709. function init_block(s) {
  24710. var n; /* iterates over tree elements */
  24711. /* Initialize the trees. */
  24712. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  24713. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  24714. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  24715. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  24716. s.opt_len = s.static_len = 0;
  24717. s.last_lit = s.matches = 0;
  24718. }
  24719. /* ===========================================================================
  24720. * Flush the bit buffer and align the output on a byte boundary
  24721. */
  24722. function bi_windup(s)
  24723. {
  24724. if (s.bi_valid > 8) {
  24725. put_short(s, s.bi_buf);
  24726. } else if (s.bi_valid > 0) {
  24727. //put_byte(s, (Byte)s->bi_buf);
  24728. s.pending_buf[s.pending++] = s.bi_buf;
  24729. }
  24730. s.bi_buf = 0;
  24731. s.bi_valid = 0;
  24732. }
  24733. /* ===========================================================================
  24734. * Copy a stored block, storing first the length and its
  24735. * one's complement if requested.
  24736. */
  24737. function copy_block(s, buf, len, header)
  24738. //DeflateState *s;
  24739. //charf *buf; /* the input data */
  24740. //unsigned len; /* its length */
  24741. //int header; /* true if block header must be written */
  24742. {
  24743. bi_windup(s); /* align on byte boundary */
  24744. if (header) {
  24745. put_short(s, len);
  24746. put_short(s, ~len);
  24747. }
  24748. // while (len--) {
  24749. // put_byte(s, *buf++);
  24750. // }
  24751. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  24752. s.pending += len;
  24753. }
  24754. /* ===========================================================================
  24755. * Compares to subtrees, using the tree depth as tie breaker when
  24756. * the subtrees have equal frequency. This minimizes the worst case length.
  24757. */
  24758. function smaller(tree, n, m, depth) {
  24759. var _n2 = n*2;
  24760. var _m2 = m*2;
  24761. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  24762. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  24763. }
  24764. /* ===========================================================================
  24765. * Restore the heap property by moving down the tree starting at node k,
  24766. * exchanging a node with the smallest of its two sons if necessary, stopping
  24767. * when the heap property is re-established (each father smaller than its
  24768. * two sons).
  24769. */
  24770. function pqdownheap(s, tree, k)
  24771. // deflate_state *s;
  24772. // ct_data *tree; /* the tree to restore */
  24773. // int k; /* node to move down */
  24774. {
  24775. var v = s.heap[k];
  24776. var j = k << 1; /* left son of k */
  24777. while (j <= s.heap_len) {
  24778. /* Set j to the smallest of the two sons: */
  24779. if (j < s.heap_len &&
  24780. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  24781. j++;
  24782. }
  24783. /* Exit if v is smaller than both sons */
  24784. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  24785. /* Exchange v with the smallest son */
  24786. s.heap[k] = s.heap[j];
  24787. k = j;
  24788. /* And continue down the tree, setting j to the left son of k */
  24789. j <<= 1;
  24790. }
  24791. s.heap[k] = v;
  24792. }
  24793. // inlined manually
  24794. // var SMALLEST = 1;
  24795. /* ===========================================================================
  24796. * Send the block data compressed using the given Huffman trees
  24797. */
  24798. function compress_block(s, ltree, dtree)
  24799. // deflate_state *s;
  24800. // const ct_data *ltree; /* literal tree */
  24801. // const ct_data *dtree; /* distance tree */
  24802. {
  24803. var dist; /* distance of matched string */
  24804. var lc; /* match length or unmatched char (if dist == 0) */
  24805. var lx = 0; /* running index in l_buf */
  24806. var code; /* the code to send */
  24807. var extra; /* number of extra bits to send */
  24808. if (s.last_lit !== 0) {
  24809. do {
  24810. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  24811. lc = s.pending_buf[s.l_buf + lx];
  24812. lx++;
  24813. if (dist === 0) {
  24814. send_code(s, lc, ltree); /* send a literal byte */
  24815. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  24816. } else {
  24817. /* Here, lc is the match length - MIN_MATCH */
  24818. code = _length_code[lc];
  24819. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  24820. extra = extra_lbits[code];
  24821. if (extra !== 0) {
  24822. lc -= base_length[code];
  24823. send_bits(s, lc, extra); /* send the extra length bits */
  24824. }
  24825. dist--; /* dist is now the match distance - 1 */
  24826. code = d_code(dist);
  24827. //Assert (code < D_CODES, "bad d_code");
  24828. send_code(s, code, dtree); /* send the distance code */
  24829. extra = extra_dbits[code];
  24830. if (extra !== 0) {
  24831. dist -= base_dist[code];
  24832. send_bits(s, dist, extra); /* send the extra distance bits */
  24833. }
  24834. } /* literal or match pair ? */
  24835. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  24836. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  24837. // "pendingBuf overflow");
  24838. } while (lx < s.last_lit);
  24839. }
  24840. send_code(s, END_BLOCK, ltree);
  24841. }
  24842. /* ===========================================================================
  24843. * Construct one Huffman tree and assigns the code bit strings and lengths.
  24844. * Update the total bit length for the current block.
  24845. * IN assertion: the field freq is set for all tree elements.
  24846. * OUT assertions: the fields len and code are set to the optimal bit length
  24847. * and corresponding code. The length opt_len is updated; static_len is
  24848. * also updated if stree is not null. The field max_code is set.
  24849. */
  24850. function build_tree(s, desc)
  24851. // deflate_state *s;
  24852. // tree_desc *desc; /* the tree descriptor */
  24853. {
  24854. var tree = desc.dyn_tree;
  24855. var stree = desc.stat_desc.static_tree;
  24856. var has_stree = desc.stat_desc.has_stree;
  24857. var elems = desc.stat_desc.elems;
  24858. var n, m; /* iterate over heap elements */
  24859. var max_code = -1; /* largest code with non zero frequency */
  24860. var node; /* new node being created */
  24861. /* Construct the initial heap, with least frequent element in
  24862. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  24863. * heap[0] is not used.
  24864. */
  24865. s.heap_len = 0;
  24866. s.heap_max = HEAP_SIZE;
  24867. for (n = 0; n < elems; n++) {
  24868. if (tree[n * 2]/*.Freq*/ !== 0) {
  24869. s.heap[++s.heap_len] = max_code = n;
  24870. s.depth[n] = 0;
  24871. } else {
  24872. tree[n*2 + 1]/*.Len*/ = 0;
  24873. }
  24874. }
  24875. /* The pkzip format requires that at least one distance code exists,
  24876. * and that at least one bit should be sent even if there is only one
  24877. * possible code. So to avoid special checks later on we force at least
  24878. * two codes of non zero frequency.
  24879. */
  24880. while (s.heap_len < 2) {
  24881. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  24882. tree[node * 2]/*.Freq*/ = 1;
  24883. s.depth[node] = 0;
  24884. s.opt_len--;
  24885. if (has_stree) {
  24886. s.static_len -= stree[node*2 + 1]/*.Len*/;
  24887. }
  24888. /* node is 0 or 1 so it does not have extra bits */
  24889. }
  24890. desc.max_code = max_code;
  24891. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  24892. * establish sub-heaps of increasing lengths:
  24893. */
  24894. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  24895. /* Construct the Huffman tree by repeatedly combining the least two
  24896. * frequent nodes.
  24897. */
  24898. node = elems; /* next internal node of the tree */
  24899. do {
  24900. //pqremove(s, tree, n); /* n = node of least frequency */
  24901. /*** pqremove ***/
  24902. n = s.heap[1/*SMALLEST*/];
  24903. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  24904. pqdownheap(s, tree, 1/*SMALLEST*/);
  24905. /***/
  24906. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  24907. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  24908. s.heap[--s.heap_max] = m;
  24909. /* Create a new node father of n and m */
  24910. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  24911. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  24912. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  24913. /* and insert the new node in the heap */
  24914. s.heap[1/*SMALLEST*/] = node++;
  24915. pqdownheap(s, tree, 1/*SMALLEST*/);
  24916. } while (s.heap_len >= 2);
  24917. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  24918. /* At this point, the fields freq and dad are set. We can now
  24919. * generate the bit lengths.
  24920. */
  24921. gen_bitlen(s, desc);
  24922. /* The field len is now set, we can generate the bit codes */
  24923. gen_codes(tree, max_code, s.bl_count);
  24924. }
  24925. /* ===========================================================================
  24926. * Scan a literal or distance tree to determine the frequencies of the codes
  24927. * in the bit length tree.
  24928. */
  24929. function scan_tree(s, tree, max_code)
  24930. // deflate_state *s;
  24931. // ct_data *tree; /* the tree to be scanned */
  24932. // int max_code; /* and its largest code of non zero frequency */
  24933. {
  24934. var n; /* iterates over all tree elements */
  24935. var prevlen = -1; /* last emitted length */
  24936. var curlen; /* length of current code */
  24937. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  24938. var count = 0; /* repeat count of the current code */
  24939. var max_count = 7; /* max repeat count */
  24940. var min_count = 4; /* min repeat count */
  24941. if (nextlen === 0) {
  24942. max_count = 138;
  24943. min_count = 3;
  24944. }
  24945. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  24946. for (n = 0; n <= max_code; n++) {
  24947. curlen = nextlen;
  24948. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  24949. if (++count < max_count && curlen === nextlen) {
  24950. continue;
  24951. } else if (count < min_count) {
  24952. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  24953. } else if (curlen !== 0) {
  24954. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  24955. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  24956. } else if (count <= 10) {
  24957. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  24958. } else {
  24959. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  24960. }
  24961. count = 0;
  24962. prevlen = curlen;
  24963. if (nextlen === 0) {
  24964. max_count = 138;
  24965. min_count = 3;
  24966. } else if (curlen === nextlen) {
  24967. max_count = 6;
  24968. min_count = 3;
  24969. } else {
  24970. max_count = 7;
  24971. min_count = 4;
  24972. }
  24973. }
  24974. }
  24975. /* ===========================================================================
  24976. * Send a literal or distance tree in compressed form, using the codes in
  24977. * bl_tree.
  24978. */
  24979. function send_tree(s, tree, max_code)
  24980. // deflate_state *s;
  24981. // ct_data *tree; /* the tree to be scanned */
  24982. // int max_code; /* and its largest code of non zero frequency */
  24983. {
  24984. var n; /* iterates over all tree elements */
  24985. var prevlen = -1; /* last emitted length */
  24986. var curlen; /* length of current code */
  24987. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  24988. var count = 0; /* repeat count of the current code */
  24989. var max_count = 7; /* max repeat count */
  24990. var min_count = 4; /* min repeat count */
  24991. /* tree[max_code+1].Len = -1; */ /* guard already set */
  24992. if (nextlen === 0) {
  24993. max_count = 138;
  24994. min_count = 3;
  24995. }
  24996. for (n = 0; n <= max_code; n++) {
  24997. curlen = nextlen;
  24998. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  24999. if (++count < max_count && curlen === nextlen) {
  25000. continue;
  25001. } else if (count < min_count) {
  25002. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  25003. } else if (curlen !== 0) {
  25004. if (curlen !== prevlen) {
  25005. send_code(s, curlen, s.bl_tree);
  25006. count--;
  25007. }
  25008. //Assert(count >= 3 && count <= 6, " 3_6?");
  25009. send_code(s, REP_3_6, s.bl_tree);
  25010. send_bits(s, count-3, 2);
  25011. } else if (count <= 10) {
  25012. send_code(s, REPZ_3_10, s.bl_tree);
  25013. send_bits(s, count-3, 3);
  25014. } else {
  25015. send_code(s, REPZ_11_138, s.bl_tree);
  25016. send_bits(s, count-11, 7);
  25017. }
  25018. count = 0;
  25019. prevlen = curlen;
  25020. if (nextlen === 0) {
  25021. max_count = 138;
  25022. min_count = 3;
  25023. } else if (curlen === nextlen) {
  25024. max_count = 6;
  25025. min_count = 3;
  25026. } else {
  25027. max_count = 7;
  25028. min_count = 4;
  25029. }
  25030. }
  25031. }
  25032. /* ===========================================================================
  25033. * Construct the Huffman tree for the bit lengths and return the index in
  25034. * bl_order of the last bit length code to send.
  25035. */
  25036. function build_bl_tree(s) {
  25037. var max_blindex; /* index of last bit length code of non zero freq */
  25038. /* Determine the bit length frequencies for literal and distance trees */
  25039. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  25040. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  25041. /* Build the bit length tree: */
  25042. build_tree(s, s.bl_desc);
  25043. /* opt_len now includes the length of the tree representations, except
  25044. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  25045. */
  25046. /* Determine the number of bit length codes to send. The pkzip format
  25047. * requires that at least 4 bit length codes be sent. (appnote.txt says
  25048. * 3 but the actual value used is 4.)
  25049. */
  25050. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  25051. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  25052. break;
  25053. }
  25054. }
  25055. /* Update opt_len to include the bit length tree and counts */
  25056. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  25057. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  25058. // s->opt_len, s->static_len));
  25059. return max_blindex;
  25060. }
  25061. /* ===========================================================================
  25062. * Send the header for a block using dynamic Huffman trees: the counts, the
  25063. * lengths of the bit length codes, the literal tree and the distance tree.
  25064. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  25065. */
  25066. function send_all_trees(s, lcodes, dcodes, blcodes)
  25067. // deflate_state *s;
  25068. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  25069. {
  25070. var rank; /* index in bl_order */
  25071. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  25072. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  25073. // "too many codes");
  25074. //Tracev((stderr, "\nbl counts: "));
  25075. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  25076. send_bits(s, dcodes-1, 5);
  25077. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  25078. for (rank = 0; rank < blcodes; rank++) {
  25079. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  25080. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  25081. }
  25082. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  25083. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  25084. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  25085. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  25086. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  25087. }
  25088. /* ===========================================================================
  25089. * Check if the data type is TEXT or BINARY, using the following algorithm:
  25090. * - TEXT if the two conditions below are satisfied:
  25091. * a) There are no non-portable control characters belonging to the
  25092. * "black list" (0..6, 14..25, 28..31).
  25093. * b) There is at least one printable character belonging to the
  25094. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  25095. * - BINARY otherwise.
  25096. * - The following partially-portable control characters form a
  25097. * "gray list" that is ignored in this detection algorithm:
  25098. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  25099. * IN assertion: the fields Freq of dyn_ltree are set.
  25100. */
  25101. function detect_data_type(s) {
  25102. /* black_mask is the bit mask of black-listed bytes
  25103. * set bits 0..6, 14..25, and 28..31
  25104. * 0xf3ffc07f = binary 11110011111111111100000001111111
  25105. */
  25106. var black_mask = 0xf3ffc07f;
  25107. var n;
  25108. /* Check for non-textual ("black-listed") bytes. */
  25109. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  25110. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  25111. return Z_BINARY;
  25112. }
  25113. }
  25114. /* Check for textual ("white-listed") bytes. */
  25115. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  25116. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  25117. return Z_TEXT;
  25118. }
  25119. for (n = 32; n < LITERALS; n++) {
  25120. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  25121. return Z_TEXT;
  25122. }
  25123. }
  25124. /* There are no "black-listed" or "white-listed" bytes:
  25125. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  25126. */
  25127. return Z_BINARY;
  25128. }
  25129. var static_init_done = false;
  25130. /* ===========================================================================
  25131. * Initialize the tree data structures for a new zlib stream.
  25132. */
  25133. function _tr_init(s)
  25134. {
  25135. if (!static_init_done) {
  25136. tr_static_init();
  25137. static_init_done = true;
  25138. }
  25139. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  25140. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  25141. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  25142. s.bi_buf = 0;
  25143. s.bi_valid = 0;
  25144. /* Initialize the first block of the first file: */
  25145. init_block(s);
  25146. }
  25147. /* ===========================================================================
  25148. * Send a stored block
  25149. */
  25150. function _tr_stored_block(s, buf, stored_len, last)
  25151. //DeflateState *s;
  25152. //charf *buf; /* input block */
  25153. //ulg stored_len; /* length of input block */
  25154. //int last; /* one if this is the last block for a file */
  25155. {
  25156. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  25157. copy_block(s, buf, stored_len, true); /* with header */
  25158. }
  25159. /* ===========================================================================
  25160. * Send one empty static block to give enough lookahead for inflate.
  25161. * This takes 10 bits, of which 7 may remain in the bit buffer.
  25162. */
  25163. function _tr_align(s) {
  25164. send_bits(s, STATIC_TREES<<1, 3);
  25165. send_code(s, END_BLOCK, static_ltree);
  25166. bi_flush(s);
  25167. }
  25168. /* ===========================================================================
  25169. * Determine the best encoding for the current block: dynamic trees, static
  25170. * trees or store, and output the encoded block to the zip file.
  25171. */
  25172. function _tr_flush_block(s, buf, stored_len, last)
  25173. //DeflateState *s;
  25174. //charf *buf; /* input block, or NULL if too old */
  25175. //ulg stored_len; /* length of input block */
  25176. //int last; /* one if this is the last block for a file */
  25177. {
  25178. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  25179. var max_blindex = 0; /* index of last bit length code of non zero freq */
  25180. /* Build the Huffman trees unless a stored block is forced */
  25181. if (s.level > 0) {
  25182. /* Check if the file is binary or text */
  25183. if (s.strm.data_type === Z_UNKNOWN) {
  25184. s.strm.data_type = detect_data_type(s);
  25185. }
  25186. /* Construct the literal and distance trees */
  25187. build_tree(s, s.l_desc);
  25188. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  25189. // s->static_len));
  25190. build_tree(s, s.d_desc);
  25191. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  25192. // s->static_len));
  25193. /* At this point, opt_len and static_len are the total bit lengths of
  25194. * the compressed block data, excluding the tree representations.
  25195. */
  25196. /* Build the bit length tree for the above two trees, and get the index
  25197. * in bl_order of the last bit length code to send.
  25198. */
  25199. max_blindex = build_bl_tree(s);
  25200. /* Determine the best encoding. Compute the block lengths in bytes. */
  25201. opt_lenb = (s.opt_len+3+7) >>> 3;
  25202. static_lenb = (s.static_len+3+7) >>> 3;
  25203. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  25204. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  25205. // s->last_lit));
  25206. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  25207. } else {
  25208. // Assert(buf != (char*)0, "lost buf");
  25209. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  25210. }
  25211. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  25212. /* 4: two words for the lengths */
  25213. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  25214. * Otherwise we can't have processed more than WSIZE input bytes since
  25215. * the last block flush, because compression would have been
  25216. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  25217. * transform a block into a stored block.
  25218. */
  25219. _tr_stored_block(s, buf, stored_len, last);
  25220. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  25221. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  25222. compress_block(s, static_ltree, static_dtree);
  25223. } else {
  25224. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  25225. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  25226. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  25227. }
  25228. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  25229. /* The above check is made mod 2^32, for files larger than 512 MB
  25230. * and uLong implemented on 32 bits.
  25231. */
  25232. init_block(s);
  25233. if (last) {
  25234. bi_windup(s);
  25235. }
  25236. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  25237. // s->compressed_len-7*last));
  25238. }
  25239. /* ===========================================================================
  25240. * Save the match info and tally the frequency counts. Return true if
  25241. * the current block must be flushed.
  25242. */
  25243. function _tr_tally(s, dist, lc)
  25244. // deflate_state *s;
  25245. // unsigned dist; /* distance of matched string */
  25246. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  25247. {
  25248. //var out_length, in_length, dcode;
  25249. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  25250. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  25251. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  25252. s.last_lit++;
  25253. if (dist === 0) {
  25254. /* lc is the unmatched char */
  25255. s.dyn_ltree[lc*2]/*.Freq*/++;
  25256. } else {
  25257. s.matches++;
  25258. /* Here, lc is the match length - MIN_MATCH */
  25259. dist--; /* dist = match distance - 1 */
  25260. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  25261. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  25262. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  25263. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  25264. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  25265. }
  25266. // (!) This block is disabled in zlib defailts,
  25267. // don't enable it for binary compatibility
  25268. //#ifdef TRUNCATE_BLOCK
  25269. // /* Try to guess if it is profitable to stop the current block here */
  25270. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  25271. // /* Compute an upper bound for the compressed length */
  25272. // out_length = s.last_lit*8;
  25273. // in_length = s.strstart - s.block_start;
  25274. //
  25275. // for (dcode = 0; dcode < D_CODES; dcode++) {
  25276. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  25277. // }
  25278. // out_length >>>= 3;
  25279. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  25280. // // s->last_lit, in_length, out_length,
  25281. // // 100L - out_length*100L/in_length));
  25282. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  25283. // return true;
  25284. // }
  25285. // }
  25286. //#endif
  25287. return (s.last_lit === s.lit_bufsize-1);
  25288. /* We avoid equality with lit_bufsize because of wraparound at 64K
  25289. * on 16 bit machines and because stored blocks are restricted to
  25290. * 64K-1 bytes.
  25291. */
  25292. }
  25293. exports._tr_init = _tr_init;
  25294. exports._tr_stored_block = _tr_stored_block;
  25295. exports._tr_flush_block = _tr_flush_block;
  25296. exports._tr_tally = _tr_tally;
  25297. exports._tr_align = _tr_align;
  25298. },{"../utils/common":75}],87:[function(require,module,exports){
  25299. 'use strict';
  25300. function ZStream() {
  25301. /* next input byte */
  25302. this.input = null; // JS specific, because we have no pointers
  25303. this.next_in = 0;
  25304. /* number of bytes available at input */
  25305. this.avail_in = 0;
  25306. /* total number of input bytes read so far */
  25307. this.total_in = 0;
  25308. /* next output byte should be put there */
  25309. this.output = null; // JS specific, because we have no pointers
  25310. this.next_out = 0;
  25311. /* remaining free space at output */
  25312. this.avail_out = 0;
  25313. /* total number of bytes output so far */
  25314. this.total_out = 0;
  25315. /* last error message, NULL if no error */
  25316. this.msg = ''/*Z_NULL*/;
  25317. /* not visible by applications */
  25318. this.state = null;
  25319. /* best guess about the data type: binary or text */
  25320. this.data_type = 2/*Z_UNKNOWN*/;
  25321. /* adler32 value of the uncompressed data */
  25322. this.adler = 0;
  25323. }
  25324. module.exports = ZStream;
  25325. },{}],88:[function(require,module,exports){
  25326. module.exports = require('./lib/retry');
  25327. },{"./lib/retry":89}],89:[function(require,module,exports){
  25328. var RetryOperation = require('./retry_operation');
  25329. exports.operation = function(options) {
  25330. var timeouts = exports.timeouts(options);
  25331. return new RetryOperation(timeouts);
  25332. };
  25333. exports.timeouts = function(options) {
  25334. if (options instanceof Array) {
  25335. return [].concat(options);
  25336. }
  25337. var opts = {
  25338. retries: 10,
  25339. factor: 2,
  25340. minTimeout: 1 * 1000,
  25341. maxTimeout: Infinity,
  25342. randomize: false
  25343. };
  25344. for (var key in options) {
  25345. opts[key] = options[key];
  25346. }
  25347. if (opts.minTimeout > opts.maxTimeout) {
  25348. throw new Error('minTimeout is greater than maxTimeout');
  25349. }
  25350. var timeouts = [];
  25351. for (var i = 0; i < opts.retries; i++) {
  25352. timeouts.push(this._createTimeout(i, opts));
  25353. }
  25354. // sort the array numerically ascending
  25355. timeouts.sort(function(a,b) {
  25356. return a - b;
  25357. });
  25358. return timeouts;
  25359. };
  25360. exports._createTimeout = function(attempt, opts) {
  25361. var random = (opts.randomize)
  25362. ? (Math.random() + 1)
  25363. : 1;
  25364. var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
  25365. timeout = Math.min(timeout, opts.maxTimeout);
  25366. return timeout;
  25367. };
  25368. },{"./retry_operation":90}],90:[function(require,module,exports){
  25369. function RetryOperation(timeouts) {
  25370. this._timeouts = timeouts;
  25371. this._fn = null;
  25372. this._errors = [];
  25373. this._attempts = 1;
  25374. this._operationTimeout = null;
  25375. this._operationTimeoutCb = null;
  25376. this._timeout = null;
  25377. }
  25378. module.exports = RetryOperation;
  25379. RetryOperation.prototype.retry = function(err) {
  25380. if (this._timeout) {
  25381. clearTimeout(this._timeout);
  25382. }
  25383. if (!err) {
  25384. return false;
  25385. }
  25386. this._errors.push(err);
  25387. var timeout = this._timeouts.shift();
  25388. if (timeout === undefined) {
  25389. return false;
  25390. }
  25391. this._attempts++;
  25392. var self = this;
  25393. setTimeout(function() {
  25394. self._fn(self._attempts);
  25395. if (self._operationTimeoutCb) {
  25396. self._timeout = setTimeout(function() {
  25397. self._operationTimeoutCb(self._attempts);
  25398. }, self._operationTimeout);
  25399. }
  25400. }, timeout);
  25401. return true;
  25402. };
  25403. RetryOperation.prototype.attempt = function(fn, timeoutOps) {
  25404. this._fn = fn;
  25405. if (timeoutOps) {
  25406. if (timeoutOps.timeout) {
  25407. this._operationTimeout = timeoutOps.timeout;
  25408. }
  25409. if (timeoutOps.cb) {
  25410. this._operationTimeoutCb = timeoutOps.cb;
  25411. }
  25412. }
  25413. this._fn(this._attempts);
  25414. var self = this;
  25415. if (this._operationTimeoutCb) {
  25416. this._timeout = setTimeout(function() {
  25417. self._operationTimeoutCb();
  25418. }, self._operationTimeout);
  25419. }
  25420. };
  25421. RetryOperation.prototype.try = function(fn) {
  25422. console.log('Using RetryOperation.try() is deprecated');
  25423. this.attempt(fn);
  25424. };
  25425. RetryOperation.prototype.start = function(fn) {
  25426. console.log('Using RetryOperation.start() is deprecated');
  25427. this.attempt(fn);
  25428. };
  25429. RetryOperation.prototype.start = RetryOperation.prototype.try;
  25430. RetryOperation.prototype.errors = function() {
  25431. return this._errors;
  25432. };
  25433. RetryOperation.prototype.attempts = function() {
  25434. return this._attempts;
  25435. };
  25436. RetryOperation.prototype.mainError = function() {
  25437. if (this._errors.length === 0) {
  25438. return null;
  25439. }
  25440. var counts = {};
  25441. var mainError = null;
  25442. var mainErrorCount = 0;
  25443. for (var i = 0; i < this._errors.length; i++) {
  25444. var error = this._errors[i];
  25445. var message = error.message;
  25446. var count = (counts[message] || 0) + 1;
  25447. counts[message] = count;
  25448. if (count >= mainErrorCount) {
  25449. mainError = error;
  25450. mainErrorCount = count;
  25451. }
  25452. }
  25453. return mainError;
  25454. };
  25455. },{}],91:[function(require,module,exports){
  25456. module.exports = function arrayEquals(array) {
  25457. // if the other array is a falsy value, return
  25458. if (!array)
  25459. return false;
  25460. // compare lengths - can save a lot of time
  25461. if (this.length != array.length)
  25462. return false;
  25463. for (var i = 0, l = this.length; i < l; i++) {
  25464. // Check if we have nested arrays
  25465. if (this[i] instanceof Array && array[i] instanceof Array) {
  25466. // recurse into the nested arrays
  25467. if (!arrayEquals.apply(this[i], [array[i]]))
  25468. return false;
  25469. } else if (this[i] != array[i]) {
  25470. // Warning - two different object instances will never be equal:
  25471. // {x:20} != {x:20}
  25472. return false;
  25473. }
  25474. }
  25475. return true;
  25476. }
  25477. },{}],92:[function(require,module,exports){
  25478. exports.Interop = require('./interop');
  25479. },{"./interop":93}],93:[function(require,module,exports){
  25480. "use strict";
  25481. var transform = require('./transform');
  25482. var arrayEquals = require('./array-equals');
  25483. function Interop() {
  25484. /**
  25485. * This map holds the most recent Unified Plan offer/answer SDP that was
  25486. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  25487. * the SDP string as values.
  25488. *
  25489. * @type {{}}
  25490. */
  25491. this.cache = {};
  25492. }
  25493. module.exports = Interop;
  25494. /**
  25495. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  25496. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  25497. * application.
  25498. *
  25499. * @param desc
  25500. * @returns {*}
  25501. */
  25502. Interop.prototype.toPlanB = function(desc) {
  25503. //#region Preliminary input validation.
  25504. if (typeof desc !== 'object' || desc === null ||
  25505. typeof desc.sdp !== 'string') {
  25506. console.warn('An empty description was passed as an argument.');
  25507. return desc;
  25508. }
  25509. // Objectify the SDP for easier manipulation.
  25510. var session = transform.parse(desc.sdp);
  25511. // If the SDP contains no media, there's nothing to transform.
  25512. if (typeof session.media === 'undefined' ||
  25513. !Array.isArray(session.media) || session.media.length === 0) {
  25514. console.warn('The description has no media.');
  25515. return desc;
  25516. }
  25517. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  25518. // SDP has a video, an audio and a data "channel" at most.
  25519. if (session.media.length <= 3 && session.media.every(function(m) {
  25520. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  25521. })) {
  25522. console.warn('This description does not look like Unified Plan.');
  25523. return desc;
  25524. }
  25525. //#endregion
  25526. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  25527. // -> Unified Plan transformation.
  25528. this.cache[desc.type] = desc.sdp;
  25529. //#region Convert from Unified Plan to Plan B.
  25530. // We rebuild the session.media array.
  25531. var media = session.media;
  25532. session.media = [];
  25533. // Associative array that maps channel types to channel objects for fast
  25534. // access to channel objects by their type, e.g. type2bl['audio']->channel
  25535. // obj.
  25536. var type2bl = {};
  25537. // Used to build the group:BUNDLE value after the channels construction
  25538. // loop.
  25539. var types = [];
  25540. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  25541. media.forEach(function(unifiedLine) {
  25542. // rtcp-mux is required in the Plan B SDP.
  25543. if ((typeof unifiedLine.rtcpMux !== 'string' ||
  25544. unifiedLine.rtcpMux !== 'rtcp-mux') &&
  25545. unifiedLine.direction !== 'inactive') {
  25546. throw new Error('Cannot convert to Plan B because m-lines ' +
  25547. 'without the rtcp-mux attribute were found.');
  25548. }
  25549. if (unifiedLine.type === 'application') {
  25550. session.media.push(unifiedLine);
  25551. types.push(unifiedLine.mid);
  25552. return;
  25553. }
  25554. // If we don't have a channel for this unifiedLine.type, then use this unifiedLine
  25555. // as the channel basis.
  25556. if (typeof type2bl[unifiedLine.type] === 'undefined') {
  25557. type2bl[unifiedLine.type] = unifiedLine;
  25558. }
  25559. // Add sources to the channel and handle a=msid.
  25560. if (typeof unifiedLine.sources === 'object') {
  25561. Object.keys(unifiedLine.sources).forEach(function(ssrc) {
  25562. if (typeof type2bl[unifiedLine.type].sources !== 'object')
  25563. type2bl[unifiedLine.type].sources = {};
  25564. // Assign the sources to the channel.
  25565. type2bl[unifiedLine.type].sources[ssrc] = unifiedLine.sources[ssrc];
  25566. if (typeof unifiedLine.msid !== 'undefined') {
  25567. // In Plan B the msid is an SSRC attribute. Also, we don't
  25568. // care about the obsolete label and mslabel attributes.
  25569. //
  25570. // Note that it is not guaranteed that the unifiedLine will have
  25571. // an msid. recvonly channels in particular don't have one.
  25572. type2bl[unifiedLine.type].sources[ssrc].msid = unifiedLine.msid;
  25573. }
  25574. // NOTE ssrcs in ssrc groups will share msids, as
  25575. // draft-uberti-rtcweb-plan-00 mandates.
  25576. });
  25577. }
  25578. // Add ssrc groups to the channel.
  25579. if (typeof unifiedLine.ssrcGroups !== 'undefined' &&
  25580. Array.isArray(unifiedLine.ssrcGroups)) {
  25581. // Create the ssrcGroups array, if it's not defined.
  25582. if (typeof type2bl[unifiedLine.type].ssrcGroups === 'undefined' ||
  25583. !Array.isArray(type2bl[unifiedLine.type].ssrcGroups)) {
  25584. type2bl[unifiedLine.type].ssrcGroups = [];
  25585. }
  25586. type2bl[unifiedLine.type].ssrcGroups = type2bl[unifiedLine.type].ssrcGroups.concat(unifiedLine.ssrcGroups);
  25587. }
  25588. if (type2bl[unifiedLine.type] === unifiedLine) {
  25589. // Copy ICE related stuff from the principal media line.
  25590. unifiedLine.candidates = media[0].candidates;
  25591. unifiedLine.iceUfrag = media[0].iceUfrag;
  25592. unifiedLine.icePwd = media[0].icePwd;
  25593. unifiedLine.fingerprint = media[0].fingerprint;
  25594. // Plan B mids are in ['audio', 'video', 'data']
  25595. unifiedLine.mid = unifiedLine.type;
  25596. // Plan B doesn't support/need the bundle-only attribute.
  25597. delete unifiedLine.bundleOnly;
  25598. // In Plan B the msid is an SSRC attribute.
  25599. delete unifiedLine.msid;
  25600. // Used to build the group:BUNDLE value after this loop.
  25601. types.push(unifiedLine.type);
  25602. // Add the channel to the new media array.
  25603. session.media.push(unifiedLine);
  25604. }
  25605. });
  25606. // We regenerate the BUNDLE group with the new mids.
  25607. session.groups.some(function(group) {
  25608. if (group.type === 'BUNDLE') {
  25609. group.mids = types.join(' ');
  25610. return true;
  25611. }
  25612. });
  25613. // msid semantic
  25614. session.msidSemantic = {
  25615. semantic: 'WMS',
  25616. token: '*'
  25617. };
  25618. var resStr = transform.write(session);
  25619. return new RTCSessionDescription({
  25620. type: desc.type,
  25621. sdp: resStr
  25622. });
  25623. //#endregion
  25624. };
  25625. /**
  25626. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  25627. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  25628. * to FF.
  25629. *
  25630. * @param desc
  25631. * @returns {*}
  25632. */
  25633. Interop.prototype.toUnifiedPlan = function(desc) {
  25634. //#region Preliminary input validation.
  25635. if (typeof desc !== 'object' || desc === null ||
  25636. typeof desc.sdp !== 'string') {
  25637. console.warn('An empty description was passed as an argument.');
  25638. return desc;
  25639. }
  25640. var session = transform.parse(desc.sdp);
  25641. // If the SDP contains no media, there's nothing to transform.
  25642. if (typeof session.media === 'undefined' ||
  25643. !Array.isArray(session.media) || session.media.length === 0) {
  25644. console.warn('The description has no media.');
  25645. return desc;
  25646. }
  25647. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  25648. // a video, an audio and a data "channel" at most.
  25649. if (session.media.length > 3 || !session.media.every(function(m) {
  25650. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  25651. })) {
  25652. console.warn('This description does not look like Plan B.');
  25653. return desc;
  25654. }
  25655. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  25656. var mids = [];
  25657. session.media.forEach(function(m) {
  25658. mids.push(m.mid);
  25659. });
  25660. var hasBundle = false;
  25661. if (typeof session.groups !== 'undefined' &&
  25662. Array.isArray(session.groups)) {
  25663. hasBundle = session.groups.every(function(g) {
  25664. return g.type !== 'BUNDLE' ||
  25665. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  25666. });
  25667. }
  25668. if (!hasBundle) {
  25669. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  25670. " are not bundled were found.");
  25671. }
  25672. //#endregion
  25673. //#region Convert from Plan B to Unified Plan.
  25674. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  25675. // rebuild an equivalent Unified Plan offer/answer.
  25676. //
  25677. // For example, if this is a local answer (in Unified Plan style) that we
  25678. // convert to Plan B prior to handing it over to the application (the
  25679. // PeerConnection wrapper called us, for instance, after a successful
  25680. // createAnswer), we want to remember the m-line at which we've seen the
  25681. // (local) SSRC. That's because when the application wants to do call the
  25682. // SLD method, forcing us to do the inverse transformation (from Plan B to
  25683. // Unified Plan), we need to know to which m-line to assign the (local)
  25684. // SSRC. We also need to know all the other m-lines that the original
  25685. // answer had and include them in the transformed answer as well.
  25686. //
  25687. // Another example is if this is a remote offer that we convert to Plan B
  25688. // prior to giving it to the application, we want to remember the mid at
  25689. // which we've seen the (remote) SSRC.
  25690. //
  25691. // In the iteration that follows, we use the cached Unified Plan (if it
  25692. // exists) to assign mids to ssrcs.
  25693. var cached;
  25694. if (typeof this.cache[desc.type] !== 'undefined') {
  25695. cached = transform.parse(this.cache[desc.type]);
  25696. }
  25697. // A helper map that sends mids to m-line objects. We use it later to
  25698. // rebuild the Unified Plan style session.media array.
  25699. var mid2ul = {};
  25700. session.media.forEach(function(bLine) {
  25701. if ((typeof bLine.rtcpMux !== 'string' ||
  25702. bLine.rtcpMux !== 'rtcp-mux') &&
  25703. bLine.direction !== 'inactive') {
  25704. throw new Error("Cannot convert to Unified Plan because m-lines " +
  25705. "without the rtcp-mux attribute were found.");
  25706. }
  25707. if (bLine.type === 'application') {
  25708. mid2ul[bLine.mid] = bLine;
  25709. return;
  25710. }
  25711. // With rtcp-mux and bundle all the channels should have the same ICE
  25712. // stuff.
  25713. var sources = bLine.sources;
  25714. var ssrcGroups = bLine.ssrcGroups;
  25715. var candidates = bLine.candidates;
  25716. var iceUfrag = bLine.iceUfrag;
  25717. var icePwd = bLine.icePwd;
  25718. var fingerprint = bLine.fingerprint;
  25719. var port = bLine.port;
  25720. // We'll use the "bLine" object as a prototype for each new "mLine"
  25721. // that we create, but first we need to clean it up a bit.
  25722. delete bLine.sources;
  25723. delete bLine.ssrcGroups;
  25724. delete bLine.candidates;
  25725. delete bLine.iceUfrag;
  25726. delete bLine.icePwd;
  25727. delete bLine.fingerprint;
  25728. delete bLine.port;
  25729. delete bLine.mid;
  25730. // inverted ssrc group map
  25731. var ssrc2group = {};
  25732. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  25733. ssrcGroups.forEach(function (ssrcGroup) {
  25734. // TODO(gp) find out how to receive simulcast with FF. For the
  25735. // time being, hide it.
  25736. if (ssrcGroup.semantics === 'SIM') {
  25737. return;
  25738. }
  25739. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  25740. Array.isArray(ssrcGroup.ssrcs)) {
  25741. ssrcGroup.ssrcs.forEach(function (ssrc) {
  25742. if (typeof ssrc2group[ssrc] === 'undefined') {
  25743. ssrc2group[ssrc] = [];
  25744. }
  25745. ssrc2group[ssrc].push(ssrcGroup);
  25746. });
  25747. }
  25748. });
  25749. }
  25750. // ssrc to m-line index.
  25751. var ssrc2ml = {};
  25752. if (typeof sources === 'object') {
  25753. // Explode the Plan B channel sources with one m-line per source.
  25754. Object.keys(sources).forEach(function(ssrc) {
  25755. // The (unified) m-line for this SSRC. We either create it from
  25756. // scratch or, if it's a grouped SSRC, we re-use a related
  25757. // mline. In other words, if the source is grouped with another
  25758. // source, put the two together in the same m-line.
  25759. var unifiedLine;
  25760. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  25761. Array.isArray(ssrc2group[ssrc])) {
  25762. ssrc2group[ssrc].some(function (ssrcGroup) {
  25763. // ssrcGroup.ssrcs *is* an Array, no need to check
  25764. // again here.
  25765. return ssrcGroup.ssrcs.some(function (related) {
  25766. if (typeof ssrc2ml[related] === 'object') {
  25767. unifiedLine = ssrc2ml[related];
  25768. return true;
  25769. }
  25770. });
  25771. });
  25772. }
  25773. if (typeof unifiedLine === 'object') {
  25774. // the m-line already exists. Just add the source.
  25775. unifiedLine.sources[ssrc] = sources[ssrc];
  25776. delete sources[ssrc].msid;
  25777. } else {
  25778. // Use the "bLine" as a prototype for the "unifiedLine".
  25779. unifiedLine = Object.create(bLine);
  25780. ssrc2ml[ssrc] = unifiedLine;
  25781. if (typeof sources[ssrc].msid !== 'undefined') {
  25782. // Assign the msid of the source to the m-line. Note
  25783. // that it is not guaranteed that the source will have
  25784. // msid. In particular "recvonly" sources don't have an
  25785. // msid. Note that "recvonly" is a term only defined
  25786. // for m-lines.
  25787. unifiedLine.msid = sources[ssrc].msid;
  25788. delete sources[ssrc].msid;
  25789. }
  25790. // We assign one SSRC per media line.
  25791. unifiedLine.sources = {};
  25792. unifiedLine.sources[ssrc] = sources[ssrc];
  25793. unifiedLine.ssrcGroups = ssrc2group[ssrc];
  25794. // Use the cached Unified Plan SDP (if it exists) to assign
  25795. // SSRCs to mids.
  25796. if (typeof cached !== 'undefined' &&
  25797. typeof cached.media !== 'undefined' &&
  25798. Array.isArray(cached.media)) {
  25799. cached.media.forEach(function (m) {
  25800. if (typeof m.sources === 'object') {
  25801. Object.keys(m.sources).forEach(function (s) {
  25802. if (s === ssrc) {
  25803. unifiedLine.mid = m.mid;
  25804. }
  25805. });
  25806. }
  25807. });
  25808. }
  25809. if (typeof unifiedLine.mid === 'undefined') {
  25810. // If this is an SSRC that we see for the first time
  25811. // assign it a new mid. This is typically the case when
  25812. // this method is called to transform a remote
  25813. // description for the first time or when there is a
  25814. // new SSRC in the remote description because a new
  25815. // peer has joined the conference. Local SSRCs should
  25816. // have already been added to the map in the toPlanB
  25817. // method.
  25818. //
  25819. // Because FF generates answers in Unified Plan style,
  25820. // we MUST already have a cached answer with all the
  25821. // local SSRCs mapped to some m-line/mid.
  25822. if (desc.type === 'answer') {
  25823. throw new Error("An unmapped SSRC was found.");
  25824. }
  25825. unifiedLine.mid = [bLine.type, '-', ssrc].join('');
  25826. }
  25827. // Include the candidates in the 1st media line.
  25828. unifiedLine.candidates = candidates;
  25829. unifiedLine.iceUfrag = iceUfrag;
  25830. unifiedLine.icePwd = icePwd;
  25831. unifiedLine.fingerprint = fingerprint;
  25832. unifiedLine.port = port;
  25833. mid2ul[unifiedLine.mid] = unifiedLine;
  25834. }
  25835. });
  25836. }
  25837. });
  25838. // Rebuild the media array in the right order and add the missing mLines
  25839. // (missing from the Plan B SDP).
  25840. session.media = [];
  25841. mids = []; // reuse
  25842. if (desc.type === 'answer') {
  25843. // The media lines in the answer must match the media lines in the
  25844. // offer. The order is important too. Here we assume that Firefox is the
  25845. // answerer, so we merely have to use the reconstructed (unified) answer
  25846. // to update the cached (unified) answer accordingly.
  25847. //
  25848. // In the general case, one would have to use the cached (unified) offer
  25849. // to find the m-lines that are missing from the reconstructed answer,
  25850. // potentially grabbing them from the cached (unified) answer. One has
  25851. // to be carefull with this approach because inactive m-lines do not
  25852. // always have an mid, making it tricky (impossible?) to find where
  25853. // exactly and which m-lines are missing from the reconstructed answer.
  25854. for (var i = 0; i < cached.media.length; i++) {
  25855. var unifiedLine = cached.media[i];
  25856. if (typeof mid2ul[unifiedLine.mid] === 'undefined') {
  25857. // The mid isn't in the reconstructed (unified) answer.
  25858. // This is either a (unified) m-line containing a remote
  25859. // track only, or a (unified) m-line containing a remote
  25860. // track and a local track that has been removed.
  25861. // In either case, it MUST exist in the cached
  25862. // (unified) answer.
  25863. //
  25864. // In case this is a removed local track, clean-up
  25865. // the (unified) m-line and make sure it's 'recvonly' or
  25866. // 'inactive'.
  25867. delete unifiedLine.msid;
  25868. delete unifiedLine.sources;
  25869. delete unifiedLine.ssrcGroups;
  25870. if (!unifiedLine.direction
  25871. || unifiedLine.direction === 'sendrecv')
  25872. unifiedLine.direction = 'recvonly';
  25873. if (!unifiedLine.direction
  25874. || unifiedLine.direction === 'sendonly')
  25875. unifiedLine.direction = 'inactive';
  25876. } else {
  25877. // This is an (unified) m-line/channel that contains a local
  25878. // track (sendrecv or sendonly channel) or it's a unified
  25879. // recvonly m-line/channel. In either case, since we're
  25880. // going from PlanB -> Unified Plan this m-line MUST
  25881. // exist in the cached answer.
  25882. }
  25883. session.media.push(unifiedLine);
  25884. if (typeof unifiedLine.mid === 'string') {
  25885. // inactive lines don't/may not have an mid.
  25886. mids.push(unifiedLine.mid);
  25887. }
  25888. }
  25889. } else {
  25890. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  25891. // under any circumstances. If we are no longer interested in sending a
  25892. // track, we just remove the msid and ssrc attributes and set it to
  25893. // either a=recvonly (as the reofferer, we must use recvonly if the
  25894. // other side was previously sending on the m-section, but we can also
  25895. // leave the possibility open if it wasn't previously in use), or
  25896. // a=inacive.
  25897. if (typeof cached !== 'undefined' &&
  25898. typeof cached.media !== 'undefined' &&
  25899. Array.isArray(cached.media)) {
  25900. cached.media.forEach(function(unifiedLine) {
  25901. mids.push(unifiedLine.mid);
  25902. if (typeof mid2ul[unifiedLine.mid] !== 'undefined') {
  25903. session.media.push(mid2ul[unifiedLine.mid]);
  25904. } else {
  25905. delete unifiedLine.msid;
  25906. delete unifiedLine.sources;
  25907. delete unifiedLine.ssrcGroups;
  25908. if (!unifiedLine.direction
  25909. || unifiedLine.direction === 'sendrecv')
  25910. unifiedLine.direction = 'recvonly';
  25911. if (!unifiedLine.direction
  25912. || unifiedLine.direction === 'sendonly')
  25913. unifiedLine.direction = 'inactive';
  25914. session.media.push(unifiedLine);
  25915. }
  25916. });
  25917. }
  25918. // Add all the remaining (new) m-lines of the transformed SDP.
  25919. Object.keys(mid2ul).forEach(function(mid) {
  25920. if (mids.indexOf(mid) === -1) {
  25921. mids.push(mid);
  25922. if (typeof mid2ul[mid].direction === 'recvonly') {
  25923. // This is a remote recvonly channel. Add its SSRC to the
  25924. // appropriate sendrecv or sendonly channel.
  25925. // TODO(gp) what if we don't have sendrecv/sendonly channel?
  25926. session.media.some(function (unifiedLine) {
  25927. if ((unifiedLine.direction === 'sendrecv' ||
  25928. unifiedLine.direction === 'sendonly') &&
  25929. unifiedLine.type === mid2ul[mid].type) {
  25930. // mid2ul[mid] shouldn't have any ssrc-groups
  25931. Object.keys(mid2ul[mid].sources).forEach(function (ssrc) {
  25932. unifiedLine.sources[ssrc] = mid2ul[mid].sources[ssrc];
  25933. });
  25934. return true;
  25935. }
  25936. });
  25937. } else {
  25938. session.media.push(mid2ul[mid]);
  25939. }
  25940. }
  25941. });
  25942. }
  25943. // We regenerate the BUNDLE group (since we regenerated the mids)
  25944. session.groups.some(function(group) {
  25945. if (group.type === 'BUNDLE') {
  25946. group.mids = mids.join(' ');
  25947. return true;
  25948. }
  25949. });
  25950. // msid semantic
  25951. session.msidSemantic = {
  25952. semantic: 'WMS',
  25953. token: '*'
  25954. };
  25955. var resStr = transform.write(session);
  25956. // Cache the transformed SDP (Unified Plan) for later re-use in this
  25957. // function.
  25958. this.cache[desc.type] = resStr;
  25959. return new RTCSessionDescription({
  25960. type: desc.type,
  25961. sdp: resStr
  25962. });
  25963. //#endregion
  25964. };
  25965. },{"./array-equals":91,"./transform":94}],94:[function(require,module,exports){
  25966. var transform = require('sdp-transform');
  25967. exports.write = function(session, opts) {
  25968. if (typeof session !== 'undefined' &&
  25969. typeof session.media !== 'undefined' &&
  25970. Array.isArray(session.media)) {
  25971. session.media.forEach(function (mLine) {
  25972. // expand sources to ssrcs
  25973. if (typeof mLine.sources !== 'undefined' &&
  25974. Object.keys(mLine.sources).length !== 0) {
  25975. mLine.ssrcs = [];
  25976. Object.keys(mLine.sources).forEach(function (ssrc) {
  25977. var source = mLine.sources[ssrc];
  25978. Object.keys(source).forEach(function (attribute) {
  25979. mLine.ssrcs.push({
  25980. id: ssrc,
  25981. attribute: attribute,
  25982. value: source[attribute]
  25983. });
  25984. });
  25985. });
  25986. delete mLine.sources;
  25987. }
  25988. // join ssrcs in ssrc groups
  25989. if (typeof mLine.ssrcGroups !== 'undefined' &&
  25990. Array.isArray(mLine.ssrcGroups)) {
  25991. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  25992. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  25993. Array.isArray(ssrcGroup.ssrcs)) {
  25994. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  25995. }
  25996. });
  25997. }
  25998. });
  25999. }
  26000. // join group mids
  26001. if (typeof session !== 'undefined' &&
  26002. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  26003. session.groups.forEach(function (g) {
  26004. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  26005. g.mids = g.mids.join(' ');
  26006. }
  26007. });
  26008. }
  26009. return transform.write(session, opts);
  26010. };
  26011. exports.parse = function(sdp) {
  26012. var session = transform.parse(sdp);
  26013. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  26014. Array.isArray(session.media)) {
  26015. session.media.forEach(function (mLine) {
  26016. // group sources attributes by ssrc
  26017. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  26018. mLine.sources = {};
  26019. mLine.ssrcs.forEach(function (ssrc) {
  26020. if (!mLine.sources[ssrc.id])
  26021. mLine.sources[ssrc.id] = {};
  26022. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  26023. });
  26024. delete mLine.ssrcs;
  26025. }
  26026. // split ssrcs in ssrc groups
  26027. if (typeof mLine.ssrcGroups !== 'undefined' &&
  26028. Array.isArray(mLine.ssrcGroups)) {
  26029. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  26030. if (typeof ssrcGroup.ssrcs === 'string') {
  26031. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  26032. }
  26033. });
  26034. }
  26035. });
  26036. }
  26037. // split group mids
  26038. if (typeof session !== 'undefined' &&
  26039. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  26040. session.groups.forEach(function (g) {
  26041. if (typeof g.mids === 'string') {
  26042. g.mids = g.mids.split(' ');
  26043. }
  26044. });
  26045. }
  26046. return session;
  26047. };
  26048. },{"sdp-transform":96}],95:[function(require,module,exports){
  26049. var grammar = module.exports = {
  26050. v: [{
  26051. name: 'version',
  26052. reg: /^(\d*)$/
  26053. }],
  26054. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  26055. // NB: sessionId will be a String in most cases because it is huge
  26056. name: 'origin',
  26057. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  26058. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  26059. format: "%s %s %d %s IP%d %s"
  26060. }],
  26061. // default parsing of these only (though some of these feel outdated)
  26062. s: [{ name: 'name' }],
  26063. i: [{ name: 'description' }],
  26064. u: [{ name: 'uri' }],
  26065. e: [{ name: 'email' }],
  26066. p: [{ name: 'phone' }],
  26067. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  26068. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  26069. //k: [{}], // outdated thing ignored
  26070. t: [{ //t=0 0
  26071. name: 'timing',
  26072. reg: /^(\d*) (\d*)/,
  26073. names: ['start', 'stop'],
  26074. format: "%d %d"
  26075. }],
  26076. c: [{ //c=IN IP4 10.47.197.26
  26077. name: 'connection',
  26078. reg: /^IN IP(\d) (\S*)/,
  26079. names: ['version', 'ip'],
  26080. format: "IN IP%d %s"
  26081. }],
  26082. b: [{ //b=AS:4000
  26083. push: 'bandwidth',
  26084. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  26085. names: ['type', 'limit'],
  26086. format: "%s:%s"
  26087. }],
  26088. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  26089. // NB: special - pushes to session
  26090. // TODO: rtp/fmtp should be filtered by the payloads found here?
  26091. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  26092. names: ['type', 'port', 'protocol', 'payloads'],
  26093. format: "%s %d %s %s"
  26094. }],
  26095. a: [
  26096. { //a=rtpmap:110 opus/48000/2
  26097. push: 'rtp',
  26098. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  26099. names: ['payload', 'codec', 'rate', 'encoding'],
  26100. format: function (o) {
  26101. return (o.encoding) ?
  26102. "rtpmap:%d %s/%s/%s":
  26103. "rtpmap:%d %s/%s";
  26104. }
  26105. },
  26106. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  26107. push: 'fmtp',
  26108. reg: /^fmtp:(\d*) (\S*)/,
  26109. names: ['payload', 'config'],
  26110. format: "fmtp:%d %s"
  26111. },
  26112. { //a=control:streamid=0
  26113. name: 'control',
  26114. reg: /^control:(.*)/,
  26115. format: "control:%s"
  26116. },
  26117. { //a=rtcp:65179 IN IP4 193.84.77.194
  26118. name: 'rtcp',
  26119. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  26120. names: ['port', 'netType', 'ipVer', 'address'],
  26121. format: function (o) {
  26122. return (o.address != null) ?
  26123. "rtcp:%d %s IP%d %s":
  26124. "rtcp:%d";
  26125. }
  26126. },
  26127. { //a=rtcp-fb:98 trr-int 100
  26128. push: 'rtcpFbTrrInt',
  26129. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  26130. names: ['payload', 'value'],
  26131. format: "rtcp-fb:%d trr-int %d"
  26132. },
  26133. { //a=rtcp-fb:98 nack rpsi
  26134. push: 'rtcpFb',
  26135. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  26136. names: ['payload', 'type', 'subtype'],
  26137. format: function (o) {
  26138. return (o.subtype != null) ?
  26139. "rtcp-fb:%s %s %s":
  26140. "rtcp-fb:%s %s";
  26141. }
  26142. },
  26143. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  26144. //a=extmap:1/recvonly URI-gps-string
  26145. push: 'ext',
  26146. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  26147. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  26148. format: function (o) {
  26149. return (o.config != null) ?
  26150. "extmap:%s %s %s":
  26151. "extmap:%s %s";
  26152. }
  26153. },
  26154. {
  26155. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  26156. push: 'crypto',
  26157. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  26158. names: ['id', 'suite', 'config', 'sessionConfig'],
  26159. format: function (o) {
  26160. return (o.sessionConfig != null) ?
  26161. "crypto:%d %s %s %s":
  26162. "crypto:%d %s %s";
  26163. }
  26164. },
  26165. { //a=setup:actpass
  26166. name: 'setup',
  26167. reg: /^setup:(\w*)/,
  26168. format: "setup:%s"
  26169. },
  26170. { //a=mid:1
  26171. name: 'mid',
  26172. reg: /^mid:([^\s]*)/,
  26173. format: "mid:%s"
  26174. },
  26175. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  26176. name: 'msid',
  26177. reg: /^msid:(.*)/,
  26178. format: "msid:%s"
  26179. },
  26180. { //a=ptime:20
  26181. name: 'ptime',
  26182. reg: /^ptime:(\d*)/,
  26183. format: "ptime:%d"
  26184. },
  26185. { //a=maxptime:60
  26186. name: 'maxptime',
  26187. reg: /^maxptime:(\d*)/,
  26188. format: "maxptime:%d"
  26189. },
  26190. { //a=sendrecv
  26191. name: 'direction',
  26192. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  26193. },
  26194. { //a=ice-lite
  26195. name: 'icelite',
  26196. reg: /^(ice-lite)/
  26197. },
  26198. { //a=ice-ufrag:F7gI
  26199. name: 'iceUfrag',
  26200. reg: /^ice-ufrag:(\S*)/,
  26201. format: "ice-ufrag:%s"
  26202. },
  26203. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  26204. name: 'icePwd',
  26205. reg: /^ice-pwd:(\S*)/,
  26206. format: "ice-pwd:%s"
  26207. },
  26208. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  26209. name: 'fingerprint',
  26210. reg: /^fingerprint:(\S*) (\S*)/,
  26211. names: ['type', 'hash'],
  26212. format: "fingerprint:%s %s"
  26213. },
  26214. {
  26215. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  26216. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  26217. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  26218. push:'candidates',
  26219. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  26220. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  26221. format: function (o) {
  26222. var str = "candidate:%s %d %s %d %s %d typ %s";
  26223. // NB: candidate has two optional chunks, so %void middle one if it's missing
  26224. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  26225. if (o.generation != null) {
  26226. str += " generation %d";
  26227. }
  26228. return str;
  26229. }
  26230. },
  26231. { //a=end-of-candidates (keep after the candidates line for readability)
  26232. name: 'endOfCandidates',
  26233. reg: /^(end-of-candidates)/
  26234. },
  26235. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  26236. name: 'remoteCandidates',
  26237. reg: /^remote-candidates:(.*)/,
  26238. format: "remote-candidates:%s"
  26239. },
  26240. { //a=ice-options:google-ice
  26241. name: 'iceOptions',
  26242. reg: /^ice-options:(\S*)/,
  26243. format: "ice-options:%s"
  26244. },
  26245. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  26246. push: "ssrcs",
  26247. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  26248. names: ['id', 'attribute', 'value'],
  26249. format: "ssrc:%d %s:%s"
  26250. },
  26251. { //a=ssrc-group:FEC 1 2
  26252. push: "ssrcGroups",
  26253. reg: /^ssrc-group:(\w*) (.*)/,
  26254. names: ['semantics', 'ssrcs'],
  26255. format: "ssrc-group:%s %s"
  26256. },
  26257. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  26258. name: "msidSemantic",
  26259. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  26260. names: ['semantic', 'token'],
  26261. format: "msid-semantic: %s %s" // space after ":" is not accidental
  26262. },
  26263. { //a=group:BUNDLE audio video
  26264. push: 'groups',
  26265. reg: /^group:(\w*) (.*)/,
  26266. names: ['type', 'mids'],
  26267. format: "group:%s %s"
  26268. },
  26269. { //a=rtcp-mux
  26270. name: 'rtcpMux',
  26271. reg: /^(rtcp-mux)/
  26272. },
  26273. { //a=rtcp-rsize
  26274. name: 'rtcpRsize',
  26275. reg: /^(rtcp-rsize)/
  26276. },
  26277. { // any a= that we don't understand is kepts verbatim on media.invalid
  26278. push: 'invalid',
  26279. names: ["value"]
  26280. }
  26281. ]
  26282. };
  26283. // set sensible defaults to avoid polluting the grammar with boring details
  26284. Object.keys(grammar).forEach(function (key) {
  26285. var objs = grammar[key];
  26286. objs.forEach(function (obj) {
  26287. if (!obj.reg) {
  26288. obj.reg = /(.*)/;
  26289. }
  26290. if (!obj.format) {
  26291. obj.format = "%s";
  26292. }
  26293. });
  26294. });
  26295. },{}],96:[function(require,module,exports){
  26296. var parser = require('./parser');
  26297. var writer = require('./writer');
  26298. exports.write = writer;
  26299. exports.parse = parser.parse;
  26300. exports.parseFmtpConfig = parser.parseFmtpConfig;
  26301. exports.parsePayloads = parser.parsePayloads;
  26302. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  26303. },{"./parser":97,"./writer":98}],97:[function(require,module,exports){
  26304. var toIntIfInt = function (v) {
  26305. return String(Number(v)) === v ? Number(v) : v;
  26306. };
  26307. var attachProperties = function (match, location, names, rawName) {
  26308. if (rawName && !names) {
  26309. location[rawName] = toIntIfInt(match[1]);
  26310. }
  26311. else {
  26312. for (var i = 0; i < names.length; i += 1) {
  26313. if (match[i+1] != null) {
  26314. location[names[i]] = toIntIfInt(match[i+1]);
  26315. }
  26316. }
  26317. }
  26318. };
  26319. var parseReg = function (obj, location, content) {
  26320. var needsBlank = obj.name && obj.names;
  26321. if (obj.push && !location[obj.push]) {
  26322. location[obj.push] = [];
  26323. }
  26324. else if (needsBlank && !location[obj.name]) {
  26325. location[obj.name] = {};
  26326. }
  26327. var keyLocation = obj.push ?
  26328. {} : // blank object that will be pushed
  26329. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  26330. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  26331. if (obj.push) {
  26332. location[obj.push].push(keyLocation);
  26333. }
  26334. };
  26335. var grammar = require('./grammar');
  26336. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  26337. exports.parse = function (sdp) {
  26338. var session = {}
  26339. , media = []
  26340. , location = session; // points at where properties go under (one of the above)
  26341. // parse lines we understand
  26342. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  26343. var type = l[0];
  26344. var content = l.slice(2);
  26345. if (type === 'm') {
  26346. media.push({rtp: [], fmtp: []});
  26347. location = media[media.length-1]; // point at latest media line
  26348. }
  26349. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  26350. var obj = grammar[type][j];
  26351. if (obj.reg.test(content)) {
  26352. return parseReg(obj, location, content);
  26353. }
  26354. }
  26355. });
  26356. session.media = media; // link it up
  26357. return session;
  26358. };
  26359. var fmtpReducer = function (acc, expr) {
  26360. var s = expr.split('=');
  26361. if (s.length === 2) {
  26362. acc[s[0]] = toIntIfInt(s[1]);
  26363. }
  26364. return acc;
  26365. };
  26366. exports.parseFmtpConfig = function (str) {
  26367. return str.split(';').reduce(fmtpReducer, {});
  26368. };
  26369. exports.parsePayloads = function (str) {
  26370. return str.split(' ').map(Number);
  26371. };
  26372. exports.parseRemoteCandidates = function (str) {
  26373. var candidates = [];
  26374. var parts = str.split(' ').map(toIntIfInt);
  26375. for (var i = 0; i < parts.length; i += 3) {
  26376. candidates.push({
  26377. component: parts[i],
  26378. ip: parts[i + 1],
  26379. port: parts[i + 2]
  26380. });
  26381. }
  26382. return candidates;
  26383. };
  26384. },{"./grammar":95}],98:[function(require,module,exports){
  26385. var grammar = require('./grammar');
  26386. // customized util.format - discards excess arguments and can void middle ones
  26387. var formatRegExp = /%[sdv%]/g;
  26388. var format = function (formatStr) {
  26389. var i = 1;
  26390. var args = arguments;
  26391. var len = args.length;
  26392. return formatStr.replace(formatRegExp, function (x) {
  26393. if (i >= len) {
  26394. return x; // missing argument
  26395. }
  26396. var arg = args[i];
  26397. i += 1;
  26398. switch (x) {
  26399. case '%%':
  26400. return '%';
  26401. case '%s':
  26402. return String(arg);
  26403. case '%d':
  26404. return Number(arg);
  26405. case '%v':
  26406. return '';
  26407. }
  26408. });
  26409. // NB: we discard excess arguments - they are typically undefined from makeLine
  26410. };
  26411. var makeLine = function (type, obj, location) {
  26412. var str = obj.format instanceof Function ?
  26413. (obj.format(obj.push ? location : location[obj.name])) :
  26414. obj.format;
  26415. var args = [type + '=' + str];
  26416. if (obj.names) {
  26417. for (var i = 0; i < obj.names.length; i += 1) {
  26418. var n = obj.names[i];
  26419. if (obj.name) {
  26420. args.push(location[obj.name][n]);
  26421. }
  26422. else { // for mLine and push attributes
  26423. args.push(location[obj.names[i]]);
  26424. }
  26425. }
  26426. }
  26427. else {
  26428. args.push(location[obj.name]);
  26429. }
  26430. return format.apply(null, args);
  26431. };
  26432. // RFC specified order
  26433. // TODO: extend this with all the rest
  26434. var defaultOuterOrder = [
  26435. 'v', 'o', 's', 'i',
  26436. 'u', 'e', 'p', 'c',
  26437. 'b', 't', 'r', 'z', 'a'
  26438. ];
  26439. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  26440. module.exports = function (session, opts) {
  26441. opts = opts || {};
  26442. // ensure certain properties exist
  26443. if (session.version == null) {
  26444. session.version = 0; // "v=0" must be there (only defined version atm)
  26445. }
  26446. if (session.name == null) {
  26447. session.name = " "; // "s= " must be there if no meaningful name set
  26448. }
  26449. session.media.forEach(function (mLine) {
  26450. if (mLine.payloads == null) {
  26451. mLine.payloads = "";
  26452. }
  26453. });
  26454. var outerOrder = opts.outerOrder || defaultOuterOrder;
  26455. var innerOrder = opts.innerOrder || defaultInnerOrder;
  26456. var sdp = [];
  26457. // loop through outerOrder for matching properties on session
  26458. outerOrder.forEach(function (type) {
  26459. grammar[type].forEach(function (obj) {
  26460. if (obj.name in session && session[obj.name] != null) {
  26461. sdp.push(makeLine(type, obj, session));
  26462. }
  26463. else if (obj.push in session && session[obj.push] != null) {
  26464. session[obj.push].forEach(function (el) {
  26465. sdp.push(makeLine(type, obj, el));
  26466. });
  26467. }
  26468. });
  26469. });
  26470. // then for each media line, follow the innerOrder
  26471. session.media.forEach(function (mLine) {
  26472. sdp.push(makeLine('m', grammar.m[0], mLine));
  26473. innerOrder.forEach(function (type) {
  26474. grammar[type].forEach(function (obj) {
  26475. if (obj.name in mLine && mLine[obj.name] != null) {
  26476. sdp.push(makeLine(type, obj, mLine));
  26477. }
  26478. else if (obj.push in mLine && mLine[obj.push] != null) {
  26479. mLine[obj.push].forEach(function (el) {
  26480. sdp.push(makeLine(type, obj, el));
  26481. });
  26482. }
  26483. });
  26484. });
  26485. });
  26486. return sdp.join('\r\n') + '\r\n';
  26487. };
  26488. },{"./grammar":95}],99:[function(require,module,exports){
  26489. var transform = require('sdp-transform');
  26490. var transformUtils = require('./transform-utils');
  26491. var parseSsrcs = transformUtils.parseSsrcs;
  26492. var writeSsrcs = transformUtils.writeSsrcs;
  26493. //region Constants
  26494. var DEFAULT_NUM_OF_LAYERS = 3;
  26495. //endregion
  26496. //region Ctor
  26497. function Simulcast(options) {
  26498. this.options = options ? options : {};
  26499. if (!this.options.numOfLayers) {
  26500. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  26501. }
  26502. this.layers = [];
  26503. }
  26504. //endregion
  26505. //region Stateless private utility functions
  26506. /**
  26507. * Returns a random integer between min (included) and max (excluded)
  26508. * Using Math.round() gives a non-uniform distribution!
  26509. * @returns {number}
  26510. */
  26511. function generateSSRC() {
  26512. var min = 0, max = 0xffffffff;
  26513. return Math.floor(Math.random() * (max - min)) + min;
  26514. };
  26515. function processVideo(session, action) {
  26516. if (session == null || !Array.isArray(session.media)) {
  26517. return;
  26518. }
  26519. session.media.forEach(function (mLine) {
  26520. if (mLine.type === 'video') {
  26521. action(mLine);
  26522. }
  26523. });
  26524. }
  26525. function validateDescription(desc)
  26526. {
  26527. return desc && desc != null
  26528. && desc.type && desc.type != ''
  26529. && desc.sdp && desc.sdp != '';
  26530. }
  26531. function explodeRemoteSimulcast(mLine) {
  26532. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  26533. return;
  26534. }
  26535. var sources = parseSsrcs(mLine);
  26536. var order = [];
  26537. // Find the SIM group and explode its sources.
  26538. var j = mLine.ssrcGroups.length;
  26539. while (j--) {
  26540. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  26541. continue;
  26542. }
  26543. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  26544. for (var i = 0; i < simulcastSsrcs.length; i++) {
  26545. var ssrc = simulcastSsrcs[i];
  26546. order.push(ssrc);
  26547. var parts = sources[ssrc].msid.split(' ');
  26548. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  26549. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  26550. // Remove all the groups that this SSRC participates in.
  26551. mLine.ssrcGroups.forEach(function (relatedGroup) {
  26552. if (relatedGroup.semantics === 'SIM') {
  26553. return;
  26554. }
  26555. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  26556. if (relatedSsrcs.indexOf(ssrc) === -1) {
  26557. return;
  26558. }
  26559. // Nuke all the related SSRCs.
  26560. relatedSsrcs.forEach(function (relatedSSRC) {
  26561. sources[relatedSSRC].msid = sources[ssrc].msid;
  26562. sources[relatedSSRC].cname = sources[ssrc].cname;
  26563. if (relatedSSRC !== ssrc) {
  26564. order.push(relatedSSRC);
  26565. }
  26566. });
  26567. // Schedule the related group for nuking.
  26568. })
  26569. }
  26570. mLine.ssrcs = writeSsrcs(sources, order);
  26571. mLine.ssrcGroups.splice(j, 1);
  26572. };
  26573. }
  26574. function squeezeRemoteSimulcast(mLine) {
  26575. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  26576. return;
  26577. }
  26578. var sources = parseSsrcs(mLine);
  26579. // Find the SIM group and nuke it.
  26580. mLine.ssrcGroups.some(function (simulcastGroup) {
  26581. if (simulcastGroup.semantics !== 'SIM') {
  26582. return false;
  26583. }
  26584. // Schedule the SIM group for nuking.
  26585. simulcastGroup.nuke = true;
  26586. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  26587. // Nuke all the higher layer SSRCs.
  26588. for (var i = 1; i < simulcastSsrcs.length; i++) {
  26589. var ssrc = simulcastSsrcs[i];
  26590. delete sources[ssrc];
  26591. // Remove all the groups that this SSRC participates in.
  26592. mLine.ssrcGroups.forEach(function (relatedGroup) {
  26593. if (relatedGroup.semantics === 'SIM') {
  26594. return;
  26595. }
  26596. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  26597. if (relatedSsrcs.indexOf(ssrc) === -1) {
  26598. return;
  26599. }
  26600. // Nuke all the related SSRCs.
  26601. relatedSsrcs.forEach(function (relatedSSRC) {
  26602. delete sources[relatedSSRC];
  26603. });
  26604. // Schedule the related group for nuking.
  26605. relatedGroup.nuke = true;
  26606. })
  26607. }
  26608. return true;
  26609. });
  26610. mLine.ssrcs = writeSsrcs(sources);
  26611. // Nuke all the scheduled groups.
  26612. var i = mLine.ssrcGroups.length;
  26613. while (i--) {
  26614. if (mLine.ssrcGroups[i].nuke) {
  26615. mLine.ssrcGroups.splice(i, 1);
  26616. }
  26617. }
  26618. }
  26619. function removeGoogConference(mLine) {
  26620. if (!mLine || !Array.isArray(mLine.invalid)) {
  26621. return;
  26622. }
  26623. var i = mLine.invalid.length;
  26624. while (i--) {
  26625. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  26626. mLine.invalid.splice(i, 1);
  26627. }
  26628. }
  26629. }
  26630. function assertGoogConference(mLine) {
  26631. if (!mLine) {
  26632. return;
  26633. }
  26634. if (!Array.isArray(mLine.invalid)) {
  26635. mLine.invalid = [];
  26636. }
  26637. if (!mLine.invalid.some(
  26638. function (i) { return i.value === 'x-google-flag:conference' })) {
  26639. mLine.invalid.push({'value': 'x-google-flag:conference'});
  26640. }
  26641. }
  26642. //endregion
  26643. //region "Private" functions
  26644. /**
  26645. *
  26646. * @param mLine
  26647. * @private
  26648. */
  26649. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  26650. if (!mLine || mLine.type !== 'video') {
  26651. return;
  26652. }
  26653. var sources = parseSsrcs(mLine);
  26654. if (Object.keys(sources).length === 0) {
  26655. // no sources, disable simulcast.
  26656. if (this.layers.length !== 0) {
  26657. this.layers = [];
  26658. }
  26659. return;
  26660. }
  26661. // find the base layer (we'll reuse its msid and cname).
  26662. var baseLayerSSRC = Object.keys(sources)[0];
  26663. var baseLayer = sources[baseLayerSSRC];
  26664. // todo(gp) handle screen sharing.
  26665. // check if base CNAME has changed and reinitialise layers.
  26666. if (this.layers.length > 0
  26667. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  26668. this.layers = [];
  26669. }
  26670. // (re)initialise layers
  26671. if (this.layers.length < 1) {
  26672. // first push the base layer.
  26673. this.layers.push({
  26674. ssrc: baseLayerSSRC,
  26675. msid: baseLayer.msid,
  26676. cname: baseLayer.cname
  26677. });
  26678. var rtx = false; // RFC 4588
  26679. if (Array.isArray(mLine.rtp)) {
  26680. rtx = mLine.rtp.some(
  26681. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  26682. }
  26683. if (rtx) {
  26684. this.layers[0].rtx = generateSSRC();
  26685. }
  26686. // now push additional layers.
  26687. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  26688. var layer = { ssrc: generateSSRC() };
  26689. if (rtx) {
  26690. layer.rtx = generateSSRC();
  26691. }
  26692. this.layers.push(layer);
  26693. }
  26694. }
  26695. };
  26696. /**
  26697. *
  26698. * @param mLine
  26699. * @private
  26700. */
  26701. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  26702. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  26703. var sources = {};
  26704. var msid = this.layers[0].msid;
  26705. var cname = this.layers[0].cname;
  26706. var simulcastSsrcs = [];
  26707. var ssrcGroups = [];
  26708. for (var i = 0; i < this.layers.length; i++) {
  26709. var layer = this.layers[i];
  26710. sources[layer.ssrc] = { msid: msid, cname: cname };
  26711. simulcastSsrcs.push(layer.ssrc);
  26712. if (layer.rtx) {
  26713. sources[layer.rtx] = {
  26714. msid: msid,
  26715. cname: cname
  26716. }
  26717. ssrcGroups.push({
  26718. semantics: 'FID',
  26719. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  26720. });
  26721. }
  26722. }
  26723. ssrcGroups.push({
  26724. semantics: 'SIM',
  26725. ssrcs: simulcastSsrcs.join(' ')
  26726. });
  26727. mLine.ssrcGroups = ssrcGroups;
  26728. mLine.ssrcs = writeSsrcs(sources);
  26729. }
  26730. }
  26731. //endregion
  26732. //region "Public" functions
  26733. Simulcast.prototype.isSupported = function () {
  26734. return window.chrome;
  26735. // TODO this needs improvements. For example I doubt that Chrome in Android
  26736. // has simulcast support. Also, only recent versions of Chromium have native
  26737. // simulcast support.
  26738. }
  26739. /**
  26740. *
  26741. * @param desc
  26742. * @returns {RTCSessionDescription}
  26743. */
  26744. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  26745. if (!validateDescription(desc)) {
  26746. return desc;
  26747. }
  26748. var session = transform.parse(desc.sdp);
  26749. var self = this;
  26750. processVideo(session, function (mLine) {
  26751. // Handle simulcast reception.
  26752. if (self.options.explodeRemoteSimulcast) {
  26753. explodeRemoteSimulcast(mLine);
  26754. } else {
  26755. squeezeRemoteSimulcast(mLine);
  26756. }
  26757. // If native simulcast is enabled, we must append the x-goog-conference
  26758. // attribute to the SDP.
  26759. if (self.layers.length < 1) {
  26760. removeGoogConference(mLine);
  26761. } else {
  26762. assertGoogConference(mLine);
  26763. }
  26764. });
  26765. return new RTCSessionDescription({
  26766. type: desc.type,
  26767. sdp: transform.write(session)
  26768. });
  26769. };
  26770. /**
  26771. *
  26772. * @param desc
  26773. * @returns {RTCSessionDescription}
  26774. */
  26775. Simulcast.prototype.mungeLocalDescription = function (desc) {
  26776. if (!validateDescription(desc) || !this.isSupported()) {
  26777. return desc;
  26778. }
  26779. var session = transform.parse(desc.sdp);
  26780. var self = this;
  26781. processVideo(session, function (mLine) {
  26782. // Initialize native simulcast layers, if not already done.
  26783. self._maybeInitializeLayers(mLine);
  26784. // Update the SDP with the simulcast layers.
  26785. self._restoreSimulcastView(mLine);
  26786. });
  26787. return new RTCSessionDescription({
  26788. type: desc.type,
  26789. sdp: transform.write(session)
  26790. });
  26791. };
  26792. //endregion
  26793. module.exports = Simulcast;
  26794. },{"./transform-utils":100,"sdp-transform":102}],100:[function(require,module,exports){
  26795. exports.writeSsrcs = function(sources, order) {
  26796. var ssrcs = [];
  26797. // expand sources to ssrcs
  26798. if (typeof sources !== 'undefined' &&
  26799. Object.keys(sources).length !== 0) {
  26800. if (Array.isArray(order)) {
  26801. for (var i = 0; i < order.length; i++) {
  26802. var ssrc = order[i];
  26803. var source = sources[ssrc];
  26804. Object.keys(source).forEach(function (attribute) {
  26805. ssrcs.push({
  26806. id: ssrc,
  26807. attribute: attribute,
  26808. value: source[attribute]
  26809. });
  26810. });
  26811. }
  26812. } else {
  26813. Object.keys(sources).forEach(function (ssrc) {
  26814. var source = sources[ssrc];
  26815. Object.keys(source).forEach(function (attribute) {
  26816. ssrcs.push({
  26817. id: ssrc,
  26818. attribute: attribute,
  26819. value: source[attribute]
  26820. });
  26821. });
  26822. });
  26823. }
  26824. }
  26825. return ssrcs;
  26826. };
  26827. exports.parseSsrcs = function (mLine) {
  26828. var sources = {};
  26829. // group sources attributes by ssrc.
  26830. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  26831. mLine.ssrcs.forEach(function (ssrc) {
  26832. if (!sources[ssrc.id])
  26833. sources[ssrc.id] = {};
  26834. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  26835. });
  26836. }
  26837. return sources;
  26838. };
  26839. },{}],101:[function(require,module,exports){
  26840. arguments[4][95][0].apply(exports,arguments)
  26841. },{"dup":95}],102:[function(require,module,exports){
  26842. arguments[4][96][0].apply(exports,arguments)
  26843. },{"./parser":103,"./writer":104,"dup":96}],103:[function(require,module,exports){
  26844. arguments[4][97][0].apply(exports,arguments)
  26845. },{"./grammar":101,"dup":97}],104:[function(require,module,exports){
  26846. arguments[4][98][0].apply(exports,arguments)
  26847. },{"./grammar":101,"dup":98}],105:[function(require,module,exports){
  26848. arguments[4][95][0].apply(exports,arguments)
  26849. },{"dup":95}],106:[function(require,module,exports){
  26850. arguments[4][96][0].apply(exports,arguments)
  26851. },{"./parser":107,"./writer":108,"dup":96}],107:[function(require,module,exports){
  26852. arguments[4][97][0].apply(exports,arguments)
  26853. },{"./grammar":105,"dup":97}],108:[function(require,module,exports){
  26854. arguments[4][98][0].apply(exports,arguments)
  26855. },{"./grammar":105,"dup":98}],109:[function(require,module,exports){
  26856. var MediaStreamType = {
  26857. VIDEO_TYPE: "Video",
  26858. AUDIO_TYPE: "Audio"
  26859. };
  26860. module.exports = MediaStreamType;
  26861. },{}],110:[function(require,module,exports){
  26862. var RTCEvents = {
  26863. RTC_READY: "rtc.ready",
  26864. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  26865. LASTN_CHANGED: "rtc.lastn_changed",
  26866. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  26867. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  26868. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed",
  26869. AUDIO_MUTE: "rtc.audio_mute",
  26870. VIDEO_MUTE: "rtc.video_mute"
  26871. };
  26872. module.exports = RTCEvents;
  26873. },{}],111:[function(require,module,exports){
  26874. var Resolutions = {
  26875. "1080": {
  26876. width: 1920,
  26877. height: 1080,
  26878. order: 7
  26879. },
  26880. "fullhd": {
  26881. width: 1920,
  26882. height: 1080,
  26883. order: 7
  26884. },
  26885. "720": {
  26886. width: 1280,
  26887. height: 720,
  26888. order: 6
  26889. },
  26890. "hd": {
  26891. width: 1280,
  26892. height: 720,
  26893. order: 6
  26894. },
  26895. "960": {
  26896. width: 960,
  26897. height: 720,
  26898. order: 5
  26899. },
  26900. "640": {
  26901. width: 640,
  26902. height: 480,
  26903. order: 4
  26904. },
  26905. "vga": {
  26906. width: 640,
  26907. height: 480,
  26908. order: 4
  26909. },
  26910. "360": {
  26911. width: 640,
  26912. height: 360,
  26913. order: 3
  26914. },
  26915. "320": {
  26916. width: 320,
  26917. height: 240,
  26918. order: 2
  26919. },
  26920. "180": {
  26921. width: 320,
  26922. height: 180,
  26923. order: 1
  26924. }
  26925. };
  26926. module.exports = Resolutions;
  26927. },{}],112:[function(require,module,exports){
  26928. var StreamEventTypes = {
  26929. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  26930. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  26931. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  26932. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  26933. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended"
  26934. };
  26935. module.exports = StreamEventTypes;
  26936. },{}],113:[function(require,module,exports){
  26937. var UIEvents = {
  26938. NICKNAME_CHANGED: "UI.nickname_changed",
  26939. SELECTED_ENDPOINT: "UI.selected_endpoint",
  26940. PINNED_ENDPOINT: "UI.pinned_endpoint",
  26941. LARGEVIDEO_INIT: "UI.largevideo_init"
  26942. };
  26943. module.exports = UIEvents;
  26944. },{}],114:[function(require,module,exports){
  26945. var AuthenticationEvents = {
  26946. /**
  26947. * Event callback arguments:
  26948. * function(authenticationEnabled, userIdentity)
  26949. * authenticationEnabled - indicates whether authentication has been enabled
  26950. * in this session
  26951. * userIdentity - if user has been logged in then it contains user name. If
  26952. * contains 'null' or 'undefined' then user is not logged in.
  26953. */
  26954. IDENTITY_UPDATED: "authentication.identity_updated"
  26955. };
  26956. module.exports = AuthenticationEvents;
  26957. },{}],115:[function(require,module,exports){
  26958. var CQEvents = {
  26959. LOCALSTATS_UPDATED: "cq.localstats_updated",
  26960. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  26961. STOP: "cq.stop"
  26962. };
  26963. module.exports = CQEvents;
  26964. },{}],116:[function(require,module,exports){
  26965. var DesktopSharingEventTypes = {
  26966. INIT: "ds.init",
  26967. SWITCHING_DONE: "ds.switching_done",
  26968. NEW_STREAM_CREATED: "ds.new_stream_created"
  26969. };
  26970. module.exports = DesktopSharingEventTypes;
  26971. },{}],117:[function(require,module,exports){
  26972. var Events = {
  26973. DTMF_SUPPORT_CHANGED: "members.dtmf_support_changed"
  26974. };
  26975. module.exports = Events;
  26976. },{}],118:[function(require,module,exports){
  26977. module.exports = {
  26978. getLanguages : function () {
  26979. var languages = [];
  26980. for(var lang in this)
  26981. {
  26982. if(typeof this[lang] === "string")
  26983. languages.push(this[lang]);
  26984. }
  26985. return languages;
  26986. },
  26987. EN: "en",
  26988. BG: "bg",
  26989. DE: "de",
  26990. TR: "tr",
  26991. FR: "fr"
  26992. }
  26993. },{}],119:[function(require,module,exports){
  26994. var XMPPEvents = {
  26995. CONNECTION_FAILED: "xmpp.connection.failed",
  26996. // Indicates an interrupted connection event.
  26997. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  26998. // Indicates a restored connection event.
  26999. CONNECTION_RESTORED: "xmpp.connection.restored",
  27000. CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle",
  27001. CALL_INCOMING: "xmpp.callincoming.jingle",
  27002. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  27003. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  27004. KICKED: "xmpp.kicked",
  27005. BRIDGE_DOWN: "xmpp.bridge_down",
  27006. USER_ID_CHANGED: "xmpp.user_id_changed",
  27007. // We joined the MUC
  27008. MUC_JOINED: "xmpp.muc_joined",
  27009. // A member joined the MUC
  27010. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  27011. // A member left the MUC
  27012. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  27013. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  27014. MUC_DESTROYED: "xmpp.muc_destroyed",
  27015. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  27016. REMOTE_STATS: "xmpp.remote_stats",
  27017. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  27018. PRESENCE_STATUS: "xmpp.presence_status",
  27019. RESERVATION_ERROR: "xmpp.room_reservation_error",
  27020. SUBJECT_CHANGED: "xmpp.subject_changed",
  27021. MESSAGE_RECEIVED: "xmpp.message_received",
  27022. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  27023. PASSWORD_REQUIRED: "xmpp.password_required",
  27024. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  27025. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  27026. ETHERPAD: "xmpp.etherpad",
  27027. DEVICE_AVAILABLE: "xmpp.device_available",
  27028. VIDEO_TYPE: "xmpp.video_type",
  27029. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  27030. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  27031. AUDIO_MUTED: "xmpp.audio_muted",
  27032. VIDEO_MUTED: "xmpp.video_muted",
  27033. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  27034. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  27035. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  27036. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  27037. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  27038. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  27039. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  27040. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  27041. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  27042. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  27043. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  27044. // xmpp is connected and obtained user media
  27045. READY_TO_JOIN: 'xmpp.ready_to_join'
  27046. };
  27047. module.exports = XMPPEvents;
  27048. },{}]},{},[3])(3)
  27049. });