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

app.bundle.js 1000KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.APP = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. /* jshint -W117 */
  3. /* application specific logic */
  4. var APP =
  5. {
  6. init: function () {
  7. this.UI = require("./modules/UI/UI");
  8. this.API = require("./modules/API/API");
  9. this.connectionquality = require("./modules/connectionquality/connectionquality");
  10. this.statistics = require("./modules/statistics/statistics");
  11. this.RTC = require("./modules/RTC/RTC");
  12. this.desktopsharing = require("./modules/desktopsharing/desktopsharing");
  13. this.xmpp = require("./modules/xmpp/xmpp");
  14. this.keyboardshortcut = require("./modules/keyboardshortcut/keyboardshortcut");
  15. this.translation = require("./modules/translation/translation");
  16. this.settings = require("./modules/settings/Settings");
  17. this.DTMF = require("./modules/DTMF/DTMF");
  18. this.members = require("./modules/members/MemberList");
  19. }
  20. };
  21. function init() {
  22. APP.desktopsharing.init();
  23. APP.RTC.start();
  24. APP.xmpp.start();
  25. APP.statistics.start();
  26. APP.connectionquality.init();
  27. APP.keyboardshortcut.init();
  28. APP.members.start();
  29. }
  30. $(document).ready(function () {
  31. var URLPRocessor = require("./modules/URLProcessor/URLProcessor");
  32. URLPRocessor.setConfigParametersFromUrl();
  33. APP.init();
  34. APP.translation.init();
  35. if(APP.API.isEnabled())
  36. APP.API.init();
  37. APP.UI.start(init);
  38. });
  39. $(window).bind('beforeunload', function () {
  40. if(APP.API.isEnabled())
  41. APP.API.dispose();
  42. });
  43. module.exports = APP;
  44. },{"./modules/API/API":2,"./modules/DTMF/DTMF":3,"./modules/RTC/RTC":7,"./modules/UI/UI":11,"./modules/URLProcessor/URLProcessor":42,"./modules/connectionquality/connectionquality":43,"./modules/desktopsharing/desktopsharing":44,"./modules/keyboardshortcut/keyboardshortcut":45,"./modules/members/MemberList":46,"./modules/settings/Settings":47,"./modules/statistics/statistics":51,"./modules/translation/translation":52,"./modules/xmpp/xmpp":66}],2:[function(require,module,exports){
  45. /**
  46. * Implements API class that communicates with external api class
  47. * and provides interface to access Jitsi Meet features by external
  48. * applications that embed Jitsi Meet
  49. */
  50. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  51. /**
  52. * List of the available commands.
  53. * @type {{
  54. * displayName: inputDisplayNameHandler,
  55. * muteAudio: toggleAudio,
  56. * muteVideo: toggleVideo,
  57. * filmStrip: toggleFilmStrip
  58. * }}
  59. */
  60. var commands = {};
  61. function initCommands() {
  62. commands =
  63. {
  64. displayName: APP.UI.inputDisplayNameHandler,
  65. muteAudio: APP.UI.toggleAudio,
  66. muteVideo: APP.UI.toggleVideo,
  67. toggleFilmStrip: APP.UI.toggleFilmStrip,
  68. toggleChat: APP.UI.toggleChat,
  69. toggleContactList: APP.UI.toggleContactList
  70. };
  71. }
  72. /**
  73. * Maps the supported events and their status
  74. * (true it the event is enabled and false if it is disabled)
  75. * @type {{
  76. * incomingMessage: boolean,
  77. * outgoingMessage: boolean,
  78. * displayNameChange: boolean,
  79. * participantJoined: boolean,
  80. * participantLeft: boolean
  81. * }}
  82. */
  83. var events =
  84. {
  85. incomingMessage: false,
  86. outgoingMessage:false,
  87. displayNameChange: false,
  88. participantJoined: false,
  89. participantLeft: false
  90. };
  91. var displayName = {};
  92. /**
  93. * Processes commands from external applicaiton.
  94. * @param message the object with the command
  95. */
  96. function processCommand(message)
  97. {
  98. if(message.action != "execute")
  99. {
  100. console.error("Unknown action of the message");
  101. return;
  102. }
  103. for(var key in message)
  104. {
  105. if(commands[key])
  106. commands[key].apply(null, message[key]);
  107. }
  108. }
  109. /**
  110. * Processes events objects from external applications
  111. * @param event the event
  112. */
  113. function processEvent(event) {
  114. if(!event.action)
  115. {
  116. console.error("Event with no action is received.");
  117. return;
  118. }
  119. var i = 0;
  120. switch(event.action)
  121. {
  122. case "add":
  123. for(; i < event.events.length; i++)
  124. {
  125. events[event.events[i]] = true;
  126. }
  127. break;
  128. case "remove":
  129. for(; i < event.events.length; i++)
  130. {
  131. events[event.events[i]] = false;
  132. }
  133. break;
  134. default:
  135. console.error("Unknown action for event.");
  136. }
  137. }
  138. /**
  139. * Sends message to the external application.
  140. * @param object
  141. */
  142. function sendMessage(object) {
  143. window.parent.postMessage(JSON.stringify(object), "*");
  144. }
  145. /**
  146. * Processes a message event from the external application
  147. * @param event the message event
  148. */
  149. function processMessage(event)
  150. {
  151. var message;
  152. try {
  153. message = JSON.parse(event.data);
  154. } catch (e) {}
  155. if(!message.type)
  156. return;
  157. switch (message.type)
  158. {
  159. case "command":
  160. processCommand(message);
  161. break;
  162. case "event":
  163. processEvent(message);
  164. break;
  165. default:
  166. console.error("Unknown type of the message");
  167. return;
  168. }
  169. }
  170. function setupListeners() {
  171. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, function (from) {
  172. API.triggerEvent("participantJoined", {jid: from});
  173. });
  174. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid, stamp) {
  175. if (from != myjid)
  176. API.triggerEvent("incomingMessage",
  177. {"from": from, "nick": nick, "message": txt, "stamp": stamp});
  178. });
  179. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, function (jid) {
  180. API.triggerEvent("participantLeft", {jid: jid});
  181. });
  182. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {
  183. name = displayName[jid];
  184. if(!name || name != newDisplayName) {
  185. API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});
  186. displayName[jid] = newDisplayName;
  187. }
  188. });
  189. APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {
  190. APP.API.triggerEvent("outgoingMessage", {"message": body});
  191. });
  192. }
  193. var API = {
  194. /**
  195. * Check whether the API should be enabled or not.
  196. * @returns {boolean}
  197. */
  198. isEnabled: function () {
  199. var hash = location.hash;
  200. if(hash && hash.indexOf("external") > -1 && window.postMessage)
  201. return true;
  202. return false;
  203. },
  204. /**
  205. * Initializes the APIConnector. Setups message event listeners that will
  206. * receive information from external applications that embed Jitsi Meet.
  207. * It also sends a message to the external application that APIConnector
  208. * is initialized.
  209. */
  210. init: function () {
  211. initCommands();
  212. if (window.addEventListener)
  213. {
  214. window.addEventListener('message',
  215. processMessage, false);
  216. }
  217. else
  218. {
  219. window.attachEvent('onmessage', processMessage);
  220. }
  221. sendMessage({type: "system", loaded: true});
  222. setupListeners();
  223. },
  224. /**
  225. * Checks whether the event is enabled ot not.
  226. * @param name the name of the event.
  227. * @returns {*}
  228. */
  229. isEventEnabled: function (name) {
  230. return events[name];
  231. },
  232. /**
  233. * Sends event object to the external application that has been subscribed
  234. * for that event.
  235. * @param name the name event
  236. * @param object data associated with the event
  237. */
  238. triggerEvent: function (name, object) {
  239. if(this.isEnabled() && this.isEventEnabled(name))
  240. sendMessage({
  241. type: "event", action: "result", event: name, result: object});
  242. },
  243. /**
  244. * Removes the listeners.
  245. */
  246. dispose: function () {
  247. if(window.removeEventListener)
  248. {
  249. window.removeEventListener("message",
  250. processMessage, false);
  251. }
  252. else
  253. {
  254. window.detachEvent('onmessage', processMessage);
  255. }
  256. }
  257. };
  258. module.exports = API;
  259. },{"../../service/xmpp/XMPPEvents":108}],3:[function(require,module,exports){
  260. /* global APP */
  261. /**
  262. * A module for sending DTMF tones.
  263. */
  264. var DTMFSender;
  265. var initDtmfSender = function() {
  266. // TODO: This needs to reset this if the peerconnection changes
  267. // (e.g. the call is re-made)
  268. if (DTMFSender)
  269. return;
  270. var localAudio = APP.RTC.localAudio;
  271. if (localAudio && localAudio.getTracks().length > 0)
  272. {
  273. var peerconnection
  274. = APP.xmpp.getConnection().jingle.activecall.peerconnection;
  275. if (peerconnection) {
  276. DTMFSender =
  277. peerconnection.peerconnection
  278. .createDTMFSender(localAudio.getTracks()[0]);
  279. console.log("Initialized DTMFSender");
  280. }
  281. else {
  282. console.log("Failed to initialize DTMFSender: no PeerConnection.");
  283. }
  284. }
  285. else {
  286. console.log("Failed to initialize DTMFSender: no audio track.");
  287. }
  288. };
  289. var DTMF = {
  290. sendTones: function (tones, duration, pause) {
  291. if (!DTMFSender)
  292. initDtmfSender();
  293. if (DTMFSender){
  294. DTMFSender.insertDTMF(tones,
  295. (duration || 200),
  296. (pause || 200));
  297. }
  298. }
  299. };
  300. module.exports = DTMF;
  301. },{}],4:[function(require,module,exports){
  302. /* global Strophe, focusedVideoSrc*/
  303. // cache datachannels to avoid garbage collection
  304. // https://code.google.com/p/chromium/issues/detail?id=405545
  305. var RTCEvents = require("../../service/RTC/RTCEvents");
  306. var _dataChannels = [];
  307. var eventEmitter = null;
  308. var DataChannels =
  309. {
  310. /**
  311. * Callback triggered by PeerConnection when new data channel is opened
  312. * on the bridge.
  313. * @param event the event info object.
  314. */
  315. onDataChannel: function (event)
  316. {
  317. var dataChannel = event.channel;
  318. dataChannel.onopen = function () {
  319. console.info("Data channel opened by the Videobridge!", dataChannel);
  320. // Code sample for sending string and/or binary data
  321. // Sends String message to the bridge
  322. //dataChannel.send("Hello bridge!");
  323. // Sends 12 bytes binary message to the bridge
  324. //dataChannel.send(new ArrayBuffer(12));
  325. eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  326. };
  327. dataChannel.onerror = function (error) {
  328. console.error("Data Channel Error:", error, dataChannel);
  329. };
  330. dataChannel.onmessage = function (event) {
  331. var data = event.data;
  332. // JSON
  333. var obj;
  334. try {
  335. obj = JSON.parse(data);
  336. }
  337. catch (e) {
  338. console.error(
  339. "Failed to parse data channel message as JSON: ",
  340. data,
  341. dataChannel);
  342. }
  343. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  344. var colibriClass = obj.colibriClass;
  345. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  346. // Endpoint ID from the Videobridge.
  347. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  348. console.info(
  349. "Data channel new dominant speaker event: ",
  350. dominantSpeakerEndpoint);
  351. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  352. }
  353. else if ("InLastNChangeEvent" === colibriClass)
  354. {
  355. var oldValue = obj.oldValue;
  356. var newValue = obj.newValue;
  357. // Make sure that oldValue and newValue are of type boolean.
  358. var type;
  359. if ((type = typeof oldValue) !== 'boolean') {
  360. if (type === 'string') {
  361. oldValue = (oldValue == "true");
  362. } else {
  363. oldValue = new Boolean(oldValue).valueOf();
  364. }
  365. }
  366. if ((type = typeof newValue) !== 'boolean') {
  367. if (type === 'string') {
  368. newValue = (newValue == "true");
  369. } else {
  370. newValue = new Boolean(newValue).valueOf();
  371. }
  372. }
  373. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  374. }
  375. else if ("LastNEndpointsChangeEvent" === colibriClass)
  376. {
  377. // The new/latest list of last-n endpoint IDs.
  378. var lastNEndpoints = obj.lastNEndpoints;
  379. // The list of endpoint IDs which are entering the list of
  380. // last-n at this time i.e. were not in the old list of last-n
  381. // endpoint IDs.
  382. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  383. var stream = obj.stream;
  384. console.log(
  385. "Data channel new last-n event: ",
  386. lastNEndpoints, endpointsEnteringLastN, obj);
  387. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  388. lastNEndpoints, endpointsEnteringLastN, obj);
  389. }
  390. else
  391. {
  392. console.debug("Data channel JSON-formatted message: ", obj);
  393. }
  394. }
  395. };
  396. dataChannel.onclose = function ()
  397. {
  398. console.info("The Data Channel closed", dataChannel);
  399. var idx = _dataChannels.indexOf(dataChannel);
  400. if (idx > -1)
  401. _dataChannels = _dataChannels.splice(idx, 1);
  402. };
  403. _dataChannels.push(dataChannel);
  404. },
  405. /**
  406. * Binds "ondatachannel" event listener to given PeerConnection instance.
  407. * @param peerConnection WebRTC peer connection instance.
  408. */
  409. init: function (peerConnection, emitter) {
  410. if(!config.openSctp)
  411. return;
  412. peerConnection.ondatachannel = this.onDataChannel;
  413. eventEmitter = emitter;
  414. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  415. // Although it's not a requirement to open separate channels from both bridge
  416. // and peer as single channel can be used for sending and receiving data.
  417. // So either channel opened by the bridge or the one opened here is enough
  418. // for communication with the bridge.
  419. /*var dataChannelOptions =
  420. {
  421. reliable: true
  422. };
  423. var dataChannel
  424. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  425. // Can be used only when is in open state
  426. dataChannel.onopen = function ()
  427. {
  428. dataChannel.send("My channel !!!");
  429. };
  430. dataChannel.onmessage = function (event)
  431. {
  432. var msgData = event.data;
  433. console.info("Got My Data Channel Message:", msgData, dataChannel);
  434. };*/
  435. },
  436. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  437. handlePinnedEndpointEvent: onPinnedEndpointChanged
  438. };
  439. function onSelectedEndpointChanged(userResource)
  440. {
  441. console.log('selected endpoint changed: ', userResource);
  442. if (_dataChannels && _dataChannels.length != 0)
  443. {
  444. _dataChannels.some(function (dataChannel) {
  445. if (dataChannel.readyState == 'open')
  446. {
  447. console.log('sending selected endpoint changed '
  448. + 'notification to the bridge: ', userResource);
  449. dataChannel.send(JSON.stringify({
  450. 'colibriClass': 'SelectedEndpointChangedEvent',
  451. 'selectedEndpoint':
  452. (!userResource || userResource === null)?
  453. null : userResource
  454. }));
  455. return true;
  456. }
  457. });
  458. }
  459. }
  460. function onPinnedEndpointChanged(userResource)
  461. {
  462. console.log('pinned endpoint changed: ', userResource);
  463. if (_dataChannels && _dataChannels.length != 0)
  464. {
  465. _dataChannels.some(function (dataChannel) {
  466. if (dataChannel.readyState == 'open')
  467. {
  468. dataChannel.send(JSON.stringify({
  469. 'colibriClass': 'PinnedEndpointChangedEvent',
  470. 'pinnedEndpoint':
  471. (!userResource || userResource == null)?
  472. null : userResource
  473. }));
  474. return true;
  475. }
  476. });
  477. }
  478. }
  479. module.exports = DataChannels;
  480. },{"../../service/RTC/RTCEvents":99}],5:[function(require,module,exports){
  481. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  482. var RTCEvents = require("../../service/RTC/RTCEvents");
  483. function LocalStream(stream, type, eventEmitter, videoType, isGUMStream)
  484. {
  485. this.stream = stream;
  486. this.eventEmitter = eventEmitter;
  487. this.type = type;
  488. this.videoType = videoType;
  489. this.isGUMStream = true;
  490. if(isGUMStream === false)
  491. this.isGUMStream = isGUMStream;
  492. var self = this;
  493. if(type == "audio")
  494. {
  495. this.getTracks = function () {
  496. return self.stream.getAudioTracks();
  497. };
  498. }
  499. else
  500. {
  501. this.getTracks = function () {
  502. return self.stream.getVideoTracks();
  503. };
  504. }
  505. this.stream.onended = function()
  506. {
  507. self.streamEnded();
  508. };
  509. }
  510. LocalStream.prototype.streamEnded = function () {
  511. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  512. }
  513. LocalStream.prototype.getOriginalStream = function()
  514. {
  515. return this.stream;
  516. }
  517. LocalStream.prototype.isAudioStream = function () {
  518. return this.type === "audio";
  519. };
  520. LocalStream.prototype.setMute = function(mute)
  521. {
  522. if((window.location.protocol != "https:" && this.isGUMStream) ||
  523. (this.isAudioStream() && this.isGUMStream) || this.videoType === "screen")
  524. {
  525. var tracks = this.getTracks();
  526. for (var idx = 0; idx < tracks.length; idx++) {
  527. tracks[idx].enabled = mute;
  528. }
  529. this.eventEmitter.emit(
  530. (this.type == "audio"? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE),
  531. !mute);
  532. }
  533. else
  534. {
  535. if(mute === false) {
  536. APP.xmpp.removeStream(this.stream);
  537. this.stream.stop();
  538. this.eventEmitter.emit(
  539. (this.type == "audio"? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE),
  540. true);
  541. }
  542. else
  543. {
  544. var self = this;
  545. APP.RTC.rtcUtils.obtainAudioAndVideoPermissions(
  546. (this.isAudioStream() ? ["audio"] : ["video"]),
  547. function (stream) {
  548. if(self.isAudioStream())
  549. {
  550. APP.RTC.changeLocalAudio(stream,
  551. function () {
  552. self.eventEmitter.emit(
  553. (self.type == "audio"? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE),
  554. true);
  555. });
  556. }
  557. else
  558. {
  559. APP.RTC.changeLocalVideo(stream, false,
  560. function () {
  561. self.eventEmitter.emit(
  562. (self.type == "audio"? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE),
  563. true);
  564. });
  565. }
  566. });
  567. }
  568. }
  569. };
  570. LocalStream.prototype.isMuted = function () {
  571. var tracks = [];
  572. if(this.type == "audio")
  573. {
  574. tracks = this.stream.getAudioTracks();
  575. }
  576. else
  577. {
  578. if(this.stream.ended)
  579. return true;
  580. tracks = this.stream.getVideoTracks();
  581. }
  582. for (var idx = 0; idx < tracks.length; idx++) {
  583. if(tracks[idx].enabled)
  584. return false;
  585. }
  586. return true;
  587. }
  588. LocalStream.prototype.getId = function () {
  589. return this.stream.getTracks()[0].id;
  590. }
  591. module.exports = LocalStream;
  592. },{"../../service/RTC/RTCEvents":99,"../../service/RTC/StreamEventTypes.js":101}],6:[function(require,module,exports){
  593. ////These lines should be uncommented when require works in app.js
  594. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  595. var StreamEventType = require("../../service/RTC/StreamEventTypes");
  596. /**
  597. * Creates a MediaStream object for the given data, session id and ssrc.
  598. * It is a wrapper class for the MediaStream.
  599. *
  600. * @param data the data object from which we obtain the stream,
  601. * the peerjid, etc.
  602. * @param sid the session id
  603. * @param ssrc the ssrc corresponding to this MediaStream
  604. *
  605. * @constructor
  606. */
  607. function MediaStream(data, sid, ssrc, browser, eventEmitter) {
  608. // XXX(gp) to minimize headaches in the future, we should build our
  609. // abstractions around tracks and not streams. ORTC is track based API.
  610. // Mozilla expects m-lines to represent media tracks.
  611. //
  612. // Practically, what I'm saying is that we should have a MediaTrack class
  613. // and not a MediaStream class.
  614. //
  615. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  616. // a track might have an associated RTX and FEC sources.
  617. this.sid = sid;
  618. this.stream = data.stream;
  619. this.peerjid = data.peerjid;
  620. this.videoType = data.videoType;
  621. this.ssrc = ssrc;
  622. this.type = (this.stream.getVideoTracks().length > 0)?
  623. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  624. this.muted = false;
  625. this.eventEmitter = eventEmitter;
  626. }
  627. MediaStream.prototype.getOriginalStream = function()
  628. {
  629. return this.stream;
  630. };
  631. MediaStream.prototype.setMute = function (value)
  632. {
  633. this.stream.muted = value;
  634. this.muted = value;
  635. };
  636. module.exports = MediaStream;
  637. },{"../../service/RTC/MediaStreamTypes":98,"../../service/RTC/StreamEventTypes":101}],7:[function(require,module,exports){
  638. var EventEmitter = require("events");
  639. var RTCBrowserType = require("./RTCBrowserType");
  640. var RTCUtils = require("./RTCUtils.js");
  641. var LocalStream = require("./LocalStream.js");
  642. var DataChannels = require("./DataChannels");
  643. var MediaStream = require("./MediaStream.js");
  644. var DesktopSharingEventTypes
  645. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  646. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  647. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  648. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  649. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  650. var UIEvents = require("../../service/UI/UIEvents");
  651. var eventEmitter = new EventEmitter();
  652. function getMediaStreamUsage()
  653. {
  654. var result = {
  655. audio: true,
  656. video: true
  657. };
  658. /** There are some issues with the desktop sharing
  659. * when this property is enabled.
  660. * WARNING: We must change the implementation to start video/audio if we
  661. * receive from the focus that the peer is not muted.
  662. var isSecureConnection = window.location.protocol == "https:";
  663. if(config.disableEarlyMediaPermissionRequests || !isSecureConnection)
  664. {
  665. result = {
  666. audio: false,
  667. video: false
  668. };
  669. }
  670. **/
  671. return result;
  672. }
  673. var RTC = {
  674. rtcUtils: null,
  675. devices: {
  676. audio: true,
  677. video: true
  678. },
  679. localStreams: [],
  680. remoteStreams: {},
  681. localAudio: null,
  682. localVideo: null,
  683. addStreamListener: function (listener, eventType) {
  684. eventEmitter.on(eventType, listener);
  685. },
  686. addListener: function (type, listener) {
  687. eventEmitter.on(type, listener);
  688. },
  689. removeStreamListener: function (listener, eventType) {
  690. if(!(eventType instanceof StreamEventTypes))
  691. throw "Illegal argument";
  692. eventEmitter.removeListener(eventType, listener);
  693. },
  694. createLocalStream: function (stream, type, change, videoType, isMuted, isGUMStream) {
  695. var localStream = new LocalStream(stream, type, eventEmitter, videoType, isGUMStream);
  696. //in firefox we have only one stream object
  697. if(this.localStreams.length == 0 ||
  698. this.localStreams[0].getOriginalStream() != stream)
  699. this.localStreams.push(localStream);
  700. if(isMuted === true)
  701. localStream.setMute(false);
  702. if(type == "audio")
  703. {
  704. this.localAudio = localStream;
  705. }
  706. else
  707. {
  708. this.localVideo = localStream;
  709. }
  710. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  711. if(change)
  712. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  713. eventEmitter.emit(eventType, localStream, isMuted);
  714. return localStream;
  715. },
  716. removeLocalStream: function (stream) {
  717. for(var i = 0; i < this.localStreams.length; i++)
  718. {
  719. if(this.localStreams[i].getOriginalStream() === stream) {
  720. delete this.localStreams[i];
  721. return;
  722. }
  723. }
  724. },
  725. createRemoteStream: function (data, sid, thessrc) {
  726. var remoteStream = new MediaStream(data, sid, thessrc,
  727. RTCBrowserType.getBrowserType(), eventEmitter);
  728. var jid = data.peerjid || APP.xmpp.myJid();
  729. if(!this.remoteStreams[jid]) {
  730. this.remoteStreams[jid] = {};
  731. }
  732. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  733. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  734. return remoteStream;
  735. },
  736. getPCConstraints: function () {
  737. return this.rtcUtils.pc_constraints;
  738. },
  739. getUserMediaWithConstraints:function(um, success_callback,
  740. failure_callback, resolution,
  741. bandwidth, fps, desktopStream)
  742. {
  743. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  744. failure_callback, resolution, bandwidth, fps, desktopStream);
  745. },
  746. attachMediaStream: function (elSelector, stream) {
  747. this.rtcUtils.attachMediaStream(elSelector, stream);
  748. },
  749. getStreamID: function (stream) {
  750. return this.rtcUtils.getStreamID(stream);
  751. },
  752. getVideoSrc: function (element) {
  753. return this.rtcUtils.getVideoSrc(element);
  754. },
  755. setVideoSrc: function (element, src) {
  756. this.rtcUtils.setVideoSrc(element, src);
  757. },
  758. getVideoElementName: function () {
  759. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  760. },
  761. dispose: function() {
  762. if (this.rtcUtils) {
  763. this.rtcUtils = null;
  764. }
  765. },
  766. stop: function () {
  767. this.dispose();
  768. },
  769. start: function () {
  770. var self = this;
  771. APP.desktopsharing.addListener(
  772. function (stream, isUsingScreenStream, callback) {
  773. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  774. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  775. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  776. DataChannels.init(event.peerconnection, eventEmitter);
  777. });
  778. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  779. DataChannels.handleSelectedEndpointEvent);
  780. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  781. DataChannels.handlePinnedEndpointEvent);
  782. // In case of IE we continue from 'onReady' callback
  783. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  784. // once it is initialized.
  785. var onReady = function () {
  786. eventEmitter.emit(RTCEvents.RTC_READY, true);
  787. self.rtcUtils.obtainAudioAndVideoPermissions(
  788. null, null, getMediaStreamUsage());
  789. };
  790. this.rtcUtils = new RTCUtils(this, onReady);
  791. // Call onReady() if Temasys plugin is not used
  792. if (!RTCBrowserType.isTemasysPluginUsed()) {
  793. onReady();
  794. }
  795. },
  796. muteRemoteVideoStream: function (jid, value) {
  797. var stream;
  798. if(this.remoteStreams[jid] &&
  799. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE])
  800. {
  801. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  802. }
  803. if(!stream)
  804. return true;
  805. if (value != stream.muted) {
  806. stream.setMute(value);
  807. return true;
  808. }
  809. return false;
  810. },
  811. switchVideoStreams: function (new_stream) {
  812. this.localVideo.stream = new_stream;
  813. this.localStreams = [];
  814. //in firefox we have only one stream object
  815. if (this.localAudio.getOriginalStream() != new_stream)
  816. this.localStreams.push(this.localAudio);
  817. this.localStreams.push(this.localVideo);
  818. },
  819. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  820. var oldStream = this.localVideo.getOriginalStream();
  821. var type = (isUsingScreenStream? "screen" : "video");
  822. var localCallback = callback;
  823. if(this.localVideo.isMuted() && this.localVideo.videoType !== type)
  824. {
  825. localCallback = function() {
  826. APP.xmpp.setVideoMute(false, function(mute) {
  827. eventEmitter.emit(RTCEvents.VIDEO_MUTE, mute);
  828. });
  829. callback();
  830. };
  831. }
  832. // FIXME: Workaround for FF/IE/Safari
  833. if (stream && stream.videoStream) {
  834. stream = stream.videoStream;
  835. }
  836. var videoStream = this.rtcUtils.createStream(stream, true);
  837. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  838. // Stop the stream to trigger onended event for old stream
  839. oldStream.stop();
  840. this.switchVideoStreams(videoStream, oldStream);
  841. APP.xmpp.switchStreams(videoStream, oldStream,localCallback);
  842. },
  843. changeLocalAudio: function (stream, callback) {
  844. var oldStream = this.localAudio.getOriginalStream();
  845. var newStream = this.rtcUtils.createStream(stream);
  846. this.localAudio = this.createLocalStream(newStream, "audio", true);
  847. // Stop the stream to trigger onended event for old stream
  848. oldStream.stop();
  849. APP.xmpp.switchStreams(newStream, oldStream, callback, true);
  850. },
  851. isVideoMuted: function (jid) {
  852. if (jid === APP.xmpp.myJid()) {
  853. var localVideo = APP.RTC.localVideo;
  854. return (!localVideo || localVideo.isMuted());
  855. }
  856. else
  857. {
  858. if (!APP.RTC.remoteStreams[jid] || !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  859. return null;
  860. }
  861. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  862. }
  863. },
  864. /**
  865. * Checks if video identified by given src is desktop stream.
  866. * @param videoSrc eg.
  867. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  868. * @returns {boolean}
  869. */
  870. isVideoSrcDesktop: function (jid) {
  871. if(!jid)
  872. return false;
  873. var isDesktop = false;
  874. var stream = null;
  875. if (APP.xmpp.myJid() === jid) {
  876. // local video
  877. stream = this.localVideo;
  878. } else {
  879. var peerStreams = this.remoteStreams[jid];
  880. if(!peerStreams)
  881. return false;
  882. stream = peerStreams[MediaStreamType.VIDEO_TYPE];
  883. }
  884. if(stream)
  885. isDesktop = (stream.videoType === "screen");
  886. return isDesktop;
  887. },
  888. setVideoMute: function(mute, callback, options) {
  889. if(!this.localVideo)
  890. return;
  891. if (mute == APP.RTC.localVideo.isMuted())
  892. {
  893. APP.xmpp.sendVideoInfoPresence(mute);
  894. if(callback)
  895. callback(mute);
  896. }
  897. else
  898. {
  899. APP.RTC.localVideo.setMute(!mute);
  900. APP.xmpp.setVideoMute(
  901. mute,
  902. callback,
  903. options);
  904. }
  905. },
  906. setDeviceAvailability: function (devices) {
  907. if(!devices)
  908. return;
  909. if(devices.audio === true || devices.audio === false)
  910. this.devices.audio = devices.audio;
  911. if(devices.video === true || devices.video === false)
  912. this.devices.video = devices.video;
  913. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  914. }
  915. };
  916. module.exports = RTC;
  917. },{"../../service/RTC/MediaStreamTypes":98,"../../service/RTC/RTCEvents.js":99,"../../service/RTC/StreamEventTypes.js":101,"../../service/UI/UIEvents":102,"../../service/desktopsharing/DesktopSharingEventTypes":105,"../../service/xmpp/XMPPEvents":108,"./DataChannels":4,"./LocalStream.js":5,"./MediaStream.js":6,"./RTCBrowserType":8,"./RTCUtils.js":9,"events":109}],8:[function(require,module,exports){
  918. var currentBrowser;
  919. var browserVersion;
  920. var RTCBrowserType = {
  921. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  922. RTC_BROWSER_OPERA: "rtc_browser.opera",
  923. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  924. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  925. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  926. getBrowserType: function () {
  927. return currentBrowser;
  928. },
  929. isChrome: function () {
  930. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  931. },
  932. isOpera: function () {
  933. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  934. },
  935. isFirefox: function () {
  936. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  937. },
  938. isIExplorer: function () {
  939. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  940. },
  941. isSafari: function () {
  942. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  943. },
  944. isTemasysPluginUsed: function () {
  945. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  946. },
  947. getFirefoxVersion: function () {
  948. return RTCBrowserType.isFirefox() ? browserVersion : null;
  949. },
  950. getChromeVersion: function () {
  951. return RTCBrowserType.isChrome() ? browserVersion : null;
  952. },
  953. usesPlanB: function() {
  954. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  955. || RTCBrowserType.isTemasysPluginUsed();
  956. },
  957. usesUnifiedPlan: function() {
  958. return RTCBrowserType.isFirefox();
  959. }
  960. // Add version getters for other browsers when needed
  961. };
  962. // detectOpera() must be called before detectChrome() !!!
  963. // otherwise Opera wil be detected as Chrome
  964. function detectChrome() {
  965. if (navigator.webkitGetUserMedia) {
  966. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  967. var userAgent = navigator.userAgent.toLowerCase();
  968. // We can assume that user agent is chrome, because it's
  969. // enforced when 'ext' streaming method is set
  970. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  971. console.log("This appears to be Chrome, ver: " + ver);
  972. return ver;
  973. }
  974. return null;
  975. }
  976. function detectOpera() {
  977. var userAgent = navigator.userAgent;
  978. if (userAgent.match(/Opera|OPR/)) {
  979. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  980. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  981. console.info("This appears to be Opera, ver: " + version);
  982. return version;
  983. }
  984. return null;
  985. }
  986. function detectFirefox() {
  987. if (navigator.mozGetUserMedia) {
  988. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  989. var version = parseInt(
  990. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  991. console.log('This appears to be Firefox, ver: ' + version);
  992. return version;
  993. }
  994. return null;
  995. }
  996. function detectSafari() {
  997. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  998. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  999. console.info("This appears to be Safari");
  1000. // FIXME detect Safari version when needed
  1001. return 1;
  1002. }
  1003. return null;
  1004. }
  1005. function detectIE() {
  1006. var version;
  1007. var ua = window.navigator.userAgent;
  1008. var msie = ua.indexOf('MSIE ');
  1009. if (msie > 0) {
  1010. // IE 10 or older => return version number
  1011. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  1012. }
  1013. var trident = ua.indexOf('Trident/');
  1014. if (!version && trident > 0) {
  1015. // IE 11 => return version number
  1016. var rv = ua.indexOf('rv:');
  1017. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  1018. }
  1019. var edge = ua.indexOf('Edge/');
  1020. if (!version && edge > 0) {
  1021. // IE 12 => return version number
  1022. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  1023. }
  1024. if (version) {
  1025. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1026. console.info("This appears to be IExplorer, ver: " + version);
  1027. }
  1028. return version;
  1029. }
  1030. function detectBrowser() {
  1031. var version;
  1032. var detectors = [
  1033. detectOpera,
  1034. detectChrome,
  1035. detectFirefox,
  1036. detectIE,
  1037. detectSafari
  1038. ];
  1039. // Try all browser detectors
  1040. for (var i = 0; i < detectors.length; i++) {
  1041. version = detectors[i]();
  1042. if (version)
  1043. return version;
  1044. }
  1045. console.error("Failed to detect browser type");
  1046. return undefined;
  1047. }
  1048. browserVersion = detectBrowser();
  1049. module.exports = RTCBrowserType;
  1050. },{}],9:[function(require,module,exports){
  1051. var RTCBrowserType = require("./RTCBrowserType");
  1052. var Resolutions = require("../../service/RTC/Resolutions");
  1053. var AdapterJS = require("./adapter.screenshare");
  1054. var SDPUtil = require("../xmpp/SDPUtil");
  1055. var currentResolution = null;
  1056. function getPreviousResolution(resolution) {
  1057. if(!Resolutions[resolution])
  1058. return null;
  1059. var order = Resolutions[resolution].order;
  1060. var res = null;
  1061. var resName = null;
  1062. for(var i in Resolutions)
  1063. {
  1064. var tmp = Resolutions[i];
  1065. if(res == null || (res.order < tmp.order && tmp.order < order))
  1066. {
  1067. resName = i;
  1068. res = tmp;
  1069. }
  1070. }
  1071. return resName;
  1072. }
  1073. function setResolutionConstraints(constraints, resolution, isAndroid)
  1074. {
  1075. if (resolution && !constraints.video || isAndroid) {
  1076. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  1077. }
  1078. if(Resolutions[resolution])
  1079. {
  1080. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1081. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1082. }
  1083. else
  1084. {
  1085. if (isAndroid) {
  1086. constraints.video.mandatory.minWidth = 320;
  1087. constraints.video.mandatory.minHeight = 240;
  1088. constraints.video.mandatory.maxFrameRate = 15;
  1089. }
  1090. }
  1091. if (constraints.video.mandatory.minWidth)
  1092. constraints.video.mandatory.maxWidth = constraints.video.mandatory.minWidth;
  1093. if (constraints.video.mandatory.minHeight)
  1094. constraints.video.mandatory.maxHeight = constraints.video.mandatory.minHeight;
  1095. }
  1096. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  1097. {
  1098. var constraints = {audio: false, video: false};
  1099. if (um.indexOf('video') >= 0) {
  1100. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  1101. }
  1102. if (um.indexOf('audio') >= 0) {
  1103. constraints.audio = { mandatory: {}, optional: []};// same behaviour as true
  1104. }
  1105. if (um.indexOf('screen') >= 0) {
  1106. if (RTCBrowserType.isChrome()) {
  1107. constraints.video = {
  1108. mandatory: {
  1109. chromeMediaSource: "screen",
  1110. googLeakyBucket: true,
  1111. maxWidth: window.screen.width,
  1112. maxHeight: window.screen.height,
  1113. maxFrameRate: 3
  1114. },
  1115. optional: []
  1116. };
  1117. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  1118. constraints.video = {
  1119. optional: [
  1120. {
  1121. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  1122. }
  1123. ]
  1124. };
  1125. } else {
  1126. console.error(
  1127. "'screen' WebRTC media source is supported only in Chrome" +
  1128. " and with Temasys plugin");
  1129. }
  1130. }
  1131. if (um.indexOf('desktop') >= 0) {
  1132. constraints.video = {
  1133. mandatory: {
  1134. chromeMediaSource: "desktop",
  1135. chromeMediaSourceId: desktopStream,
  1136. googLeakyBucket: true,
  1137. maxWidth: window.screen.width,
  1138. maxHeight: window.screen.height,
  1139. maxFrameRate: 3
  1140. },
  1141. optional: []
  1142. };
  1143. }
  1144. if (constraints.audio) {
  1145. // if it is good enough for hangouts...
  1146. constraints.audio.optional.push(
  1147. {googEchoCancellation: true},
  1148. {googAutoGainControl: true},
  1149. {googNoiseSupression: true},
  1150. {googHighpassFilter: true},
  1151. {googNoisesuppression2: true},
  1152. {googEchoCancellation2: true},
  1153. {googAutoGainControl2: true}
  1154. );
  1155. }
  1156. if (constraints.video) {
  1157. constraints.video.optional.push(
  1158. {googNoiseReduction: false} // chrome 37 workaround for issue 3807, reenable in M38
  1159. );
  1160. if (um.indexOf('video') >= 0) {
  1161. constraints.video.optional.push(
  1162. {googLeakyBucket: true}
  1163. );
  1164. }
  1165. }
  1166. if (um.indexOf('video') >= 0) {
  1167. setResolutionConstraints(constraints, resolution, isAndroid);
  1168. }
  1169. if (bandwidth) { // doesn't work currently, see webrtc issue 1846
  1170. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};//same behaviour as true
  1171. constraints.video.optional.push({bandwidth: bandwidth});
  1172. }
  1173. if (fps) { // for some cameras it might be necessary to request 30fps
  1174. // so they choose 30fps mjpg over 10fps yuy2
  1175. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};// same behaviour as true;
  1176. constraints.video.mandatory.minFrameRate = fps;
  1177. }
  1178. return constraints;
  1179. }
  1180. function RTCUtils(RTCService, onTemasysPluginReady)
  1181. {
  1182. var self = this;
  1183. this.service = RTCService;
  1184. if (RTCBrowserType.isFirefox()) {
  1185. var FFversion = RTCBrowserType.getFirefoxVersion();
  1186. if (FFversion >= 40 && config.useBundle && config.useRtcpMux) {
  1187. this.peerconnection = mozRTCPeerConnection;
  1188. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1189. this.pc_constraints = {};
  1190. this.attachMediaStream = function (element, stream) {
  1191. // srcObject is being standardized and FF will eventually
  1192. // support that unprefixed. FF also supports the
  1193. // "element.src = URL.createObjectURL(...)" combo, but that
  1194. // will be deprecated in favour of srcObject.
  1195. //
  1196. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1197. // https://github.com/webrtc/samples/issues/302
  1198. if(!element[0])
  1199. return;
  1200. element[0].mozSrcObject = stream;
  1201. element[0].play();
  1202. };
  1203. this.getStreamID = function (stream) {
  1204. var id = stream.id;
  1205. if (!id) {
  1206. var tracks = stream.getVideoTracks();
  1207. if (!tracks || tracks.length === 0)
  1208. {
  1209. tracks = stream.getAudioTracks();
  1210. }
  1211. id = tracks[0].id;
  1212. }
  1213. return SDPUtil.filter_special_chars(id);
  1214. };
  1215. this.getVideoSrc = function (element) {
  1216. if(!element)
  1217. return null;
  1218. return element.mozSrcObject;
  1219. };
  1220. this.setVideoSrc = function (element, src) {
  1221. if(element)
  1222. element.mozSrcObject = src;
  1223. };
  1224. RTCSessionDescription = mozRTCSessionDescription;
  1225. RTCIceCandidate = mozRTCIceCandidate;
  1226. } else {
  1227. console.error(
  1228. "Firefox requirements not met, ver: " + FFversion +
  1229. ", bundle: " + config.useBundle +
  1230. ", rtcp-mux: " + config.useRtcpMux);
  1231. window.location.href = 'unsupported_browser.html';
  1232. return;
  1233. }
  1234. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  1235. this.peerconnection = webkitRTCPeerConnection;
  1236. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1237. this.attachMediaStream = function (element, stream) {
  1238. element.attr('src', webkitURL.createObjectURL(stream));
  1239. };
  1240. this.getStreamID = function (stream) {
  1241. // streams from FF endpoints have the characters '{' and '}'
  1242. // that make jQuery choke.
  1243. return SDPUtil.filter_special_chars(stream.id);
  1244. };
  1245. this.getVideoSrc = function (element) {
  1246. if(!element)
  1247. return null;
  1248. return element.getAttribute("src");
  1249. };
  1250. this.setVideoSrc = function (element, src) {
  1251. if(element)
  1252. element.setAttribute("src", src);
  1253. };
  1254. // DTLS should now be enabled by default but..
  1255. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  1256. if (navigator.userAgent.indexOf('Android') != -1) {
  1257. this.pc_constraints = {}; // disable DTLS on Android
  1258. }
  1259. if (!webkitMediaStream.prototype.getVideoTracks) {
  1260. webkitMediaStream.prototype.getVideoTracks = function () {
  1261. return this.videoTracks;
  1262. };
  1263. }
  1264. if (!webkitMediaStream.prototype.getAudioTracks) {
  1265. webkitMediaStream.prototype.getAudioTracks = function () {
  1266. return this.audioTracks;
  1267. };
  1268. }
  1269. }
  1270. // Detect IE/Safari
  1271. else if (RTCBrowserType.isTemasysPluginUsed()) {
  1272. //AdapterJS.WebRTCPlugin.setLogLevel(
  1273. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  1274. AdapterJS.webRTCReady(function (isPlugin) {
  1275. self.peerconnection = RTCPeerConnection;
  1276. self.getUserMedia = getUserMedia;
  1277. self.attachMediaStream = function (elSel, stream) {
  1278. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  1279. return;
  1280. }
  1281. attachMediaStream(elSel[0], stream);
  1282. };
  1283. self.getStreamID = function (stream) {
  1284. var id = SDPUtil.filter_special_chars(stream.label);
  1285. return id;
  1286. };
  1287. self.getVideoSrc = function (element) {
  1288. if (!element) {
  1289. console.warn("Attempt to get video SRC of null element");
  1290. return null;
  1291. }
  1292. var src = null;
  1293. var children = element.children;
  1294. for (var i = 0; i !== children.length; ++i) {
  1295. if (children[i].name === 'streamId') {
  1296. return children[i].value;
  1297. }
  1298. }
  1299. //console.info(element.id + " SRC: " + src);
  1300. return null;
  1301. };
  1302. self.setVideoSrc = function (element, src) {
  1303. //console.info("Set video src: ", element, src);
  1304. if (!src) {
  1305. console.warn("Not attaching video stream, 'src' is null");
  1306. return;
  1307. }
  1308. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  1309. var stream = AdapterJS.WebRTCPlugin.plugin
  1310. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  1311. attachMediaStream(element, stream);
  1312. };
  1313. onTemasysPluginReady(isPlugin);
  1314. });
  1315. } else {
  1316. try {
  1317. console.log('Browser does not appear to be WebRTC-capable');
  1318. } catch (e) { }
  1319. window.location.href = 'unsupported_browser.html';
  1320. }
  1321. }
  1322. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1323. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1324. desktopStream)
  1325. {
  1326. currentResolution = resolution;
  1327. // Check if we are running on Android device
  1328. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1329. var constraints = getConstraints(
  1330. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1331. console.info("Get media constraints", constraints);
  1332. var self = this;
  1333. try {
  1334. this.getUserMedia(constraints,
  1335. function (stream) {
  1336. console.log('onUserMediaSuccess');
  1337. self.setAvailableDevices(um, true);
  1338. success_callback(stream);
  1339. },
  1340. function (error) {
  1341. self.setAvailableDevices(um, false);
  1342. console.warn('Failed to get access to local media. Error ',
  1343. error, constraints);
  1344. if (failure_callback) {
  1345. failure_callback(error);
  1346. }
  1347. });
  1348. } catch (e) {
  1349. console.error('GUM failed: ', e);
  1350. if(failure_callback) {
  1351. failure_callback(e);
  1352. }
  1353. }
  1354. };
  1355. RTCUtils.prototype.setAvailableDevices = function (um, available) {
  1356. var devices = {};
  1357. if(um.indexOf("video") != -1)
  1358. {
  1359. devices.video = available;
  1360. }
  1361. if(um.indexOf("audio") != -1)
  1362. {
  1363. devices.audio = available;
  1364. }
  1365. this.service.setDeviceAvailability(devices);
  1366. }
  1367. /**
  1368. * We ask for audio and video combined stream in order to get permissions and
  1369. * not to ask twice.
  1370. */
  1371. RTCUtils.prototype.obtainAudioAndVideoPermissions =
  1372. function(devices, callback, usageOptions)
  1373. {
  1374. var self = this;
  1375. // Get AV
  1376. var successCallback = function (stream) {
  1377. if(callback)
  1378. callback(stream, usageOptions);
  1379. else
  1380. self.successCallback(stream, usageOptions);
  1381. };
  1382. if(!devices)
  1383. devices = ['audio', 'video'];
  1384. var newDevices = [];
  1385. if(usageOptions)
  1386. for(var i = 0; i < devices.length; i++)
  1387. {
  1388. var device = devices[i];
  1389. if(usageOptions[device] === true)
  1390. newDevices.push(device);
  1391. }
  1392. else
  1393. newDevices = devices;
  1394. if(newDevices.length === 0)
  1395. {
  1396. successCallback();
  1397. return;
  1398. }
  1399. if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {
  1400. // With FF/IE we can't split the stream into audio and video because FF
  1401. // doesn't support media stream constructors. So, we need to get the
  1402. // audio stream separately from the video stream using two distinct GUM
  1403. // calls. Not very user friendly :-( but we don't have many other
  1404. // options neither.
  1405. //
  1406. // Note that we pack those 2 streams in a single object and pass it to
  1407. // the successCallback method.
  1408. var obtainVideo = function (audioStream) {
  1409. self.getUserMediaWithConstraints(
  1410. ['video'],
  1411. function (videoStream) {
  1412. return successCallback({
  1413. audioStream: audioStream,
  1414. videoStream: videoStream
  1415. });
  1416. },
  1417. function (error) {
  1418. console.error(
  1419. 'failed to obtain video stream - stop', error);
  1420. self.errorCallback(error);
  1421. },
  1422. config.resolution || '360');
  1423. };
  1424. var obtainAudio = function () {
  1425. self.getUserMediaWithConstraints(
  1426. ['audio'],
  1427. function (audioStream) {
  1428. if (newDevices.indexOf('video') !== -1)
  1429. obtainVideo(audioStream);
  1430. },
  1431. function (error) {
  1432. console.error(
  1433. 'failed to obtain audio stream - stop', error);
  1434. self.errorCallback(error);
  1435. }
  1436. );
  1437. };
  1438. if (newDevices.indexOf('audio') !== -1) {
  1439. obtainAudio();
  1440. } else {
  1441. obtainVideo(null);
  1442. }
  1443. } else {
  1444. this.getUserMediaWithConstraints(
  1445. newDevices,
  1446. function (stream) {
  1447. successCallback(stream);
  1448. },
  1449. function (error) {
  1450. self.errorCallback(error);
  1451. },
  1452. config.resolution || '360');
  1453. }
  1454. };
  1455. RTCUtils.prototype.successCallback = function (stream, usageOptions) {
  1456. // If this is FF or IE, the stream parameter is *not* a MediaStream object,
  1457. // it's an object with two properties: audioStream, videoStream.
  1458. if (stream && stream.getAudioTracks && stream.getVideoTracks)
  1459. console.log('got', stream, stream.getAudioTracks().length,
  1460. stream.getVideoTracks().length);
  1461. this.handleLocalStream(stream, usageOptions);
  1462. };
  1463. RTCUtils.prototype.errorCallback = function (error) {
  1464. var self = this;
  1465. console.error('failed to obtain audio/video stream - trying audio only', error);
  1466. var resolution = getPreviousResolution(currentResolution);
  1467. if(typeof error == "object" && error.constraintName && error.name
  1468. && (error.name == "ConstraintNotSatisfiedError" ||
  1469. error.name == "OverconstrainedError") &&
  1470. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1471. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1472. && resolution != null)
  1473. {
  1474. self.getUserMediaWithConstraints(['audio', 'video'],
  1475. function (stream) {
  1476. return self.successCallback(stream);
  1477. }, function (error) {
  1478. return self.errorCallback(error);
  1479. }, resolution);
  1480. }
  1481. else
  1482. {
  1483. self.getUserMediaWithConstraints(
  1484. ['audio'],
  1485. function (stream) {
  1486. return self.successCallback(stream);
  1487. },
  1488. function (error) {
  1489. console.error('failed to obtain audio/video stream - stop',
  1490. error);
  1491. return self.successCallback(null);
  1492. }
  1493. );
  1494. }
  1495. }
  1496. RTCUtils.prototype.handleLocalStream = function(stream, usageOptions)
  1497. {
  1498. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1499. // an object with two properties: audioStream, videoStream.
  1500. var audioStream, videoStream;
  1501. if(window.webkitMediaStream)
  1502. {
  1503. audioStream = new webkitMediaStream();
  1504. videoStream = new webkitMediaStream();
  1505. if(stream) {
  1506. var audioTracks = stream.getAudioTracks();
  1507. for (var i = 0; i < audioTracks.length; i++) {
  1508. audioStream.addTrack(audioTracks[i]);
  1509. }
  1510. var videoTracks = stream.getVideoTracks();
  1511. for (i = 0; i < videoTracks.length; i++) {
  1512. videoStream.addTrack(videoTracks[i]);
  1513. }
  1514. }
  1515. }
  1516. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed())
  1517. { // Firefox and Temasys plugin
  1518. if (stream && stream.audioStream)
  1519. audioStream = stream.audioStream;
  1520. else
  1521. audioStream = new DummyMediaStream("dummyAudio");
  1522. if (stream && stream.videoStream)
  1523. videoStream = stream.videoStream;
  1524. else
  1525. videoStream = new DummyMediaStream("dummyVideo");
  1526. }
  1527. var audioMuted = (usageOptions && usageOptions.audio === false),
  1528. videoMuted = (usageOptions && usageOptions.video === false);
  1529. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  1530. videoGUM = (!usageOptions || usageOptions.video !== false);
  1531. this.service.createLocalStream(audioStream, "audio", null, null,
  1532. audioMuted, audioGUM);
  1533. this.service.createLocalStream(videoStream, "video", null, null,
  1534. videoMuted, videoGUM);
  1535. };
  1536. function DummyMediaStream(id) {
  1537. this.id = id;
  1538. this.label = id;
  1539. this.stop = function() { };
  1540. this.getAudioTracks = function() { return []; }
  1541. this.getVideoTracks = function() { return []; }
  1542. }
  1543. RTCUtils.prototype.createStream = function(stream, isVideo) {
  1544. var newStream = null;
  1545. if (window.webkitMediaStream) {
  1546. newStream = new webkitMediaStream();
  1547. if (newStream) {
  1548. var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());
  1549. for (i = 0; i < tracks.length; i++) {
  1550. newStream.addTrack(tracks[i]);
  1551. }
  1552. }
  1553. }
  1554. else {
  1555. // FIXME: this is duplicated with 'handleLocalStream' !!!
  1556. if (stream) {
  1557. newStream = stream;
  1558. } else {
  1559. newStream = new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  1560. }
  1561. }
  1562. return newStream;
  1563. };
  1564. module.exports = RTCUtils;
  1565. },{"../../service/RTC/Resolutions":100,"../xmpp/SDPUtil":56,"./RTCBrowserType":8,"./adapter.screenshare":10}],10:[function(require,module,exports){
  1566. /*! adapterjs - v0.11.0 - 2015-06-08 */
  1567. // Adapter's interface.
  1568. var AdapterJS = AdapterJS || {};
  1569. // Browserify compatibility
  1570. if(typeof exports !== 'undefined') {
  1571. module.exports = AdapterJS;
  1572. }
  1573. AdapterJS.options = AdapterJS.options || {};
  1574. // uncomment to get virtual webcams
  1575. // AdapterJS.options.getAllCams = true;
  1576. // uncomment to prevent the install prompt when the plugin in not yet installed
  1577. // AdapterJS.options.hidePluginInstallPrompt = true;
  1578. // AdapterJS version
  1579. AdapterJS.VERSION = '0.11.0';
  1580. // This function will be called when the WebRTC API is ready to be used
  1581. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  1582. // the plugin
  1583. // You may Override this function to synchronise the start of your application
  1584. // with the WebRTC API being ready.
  1585. // If you decide not to override use this synchronisation, it may result in
  1586. // an extensive CPU usage on the plugin start (once per tab loaded)
  1587. // Params:
  1588. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  1589. //
  1590. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  1591. // The WebRTC API is ready.
  1592. // Override me and do whatever you want here
  1593. };
  1594. // Sets a callback function to be called when the WebRTC interface is ready.
  1595. // The first argument is the function to callback.\
  1596. // Throws an error if the first argument is not a function
  1597. AdapterJS.webRTCReady = function (callback) {
  1598. if (typeof callback !== 'function') {
  1599. throw new Error('Callback provided is not a function');
  1600. }
  1601. if (true === AdapterJS.onwebrtcreadyDone) {
  1602. // All WebRTC interfaces are ready, just call the callback
  1603. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  1604. } else {
  1605. // will be triggered automatically when your browser/plugin is ready.
  1606. AdapterJS.onwebrtcready = callback;
  1607. }
  1608. };
  1609. // Plugin namespace
  1610. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  1611. // The object to store plugin information
  1612. AdapterJS.WebRTCPlugin.pluginInfo = {
  1613. prefix : 'Tem',
  1614. plugName : 'TemWebRTCPlugin',
  1615. pluginId : 'plugin0',
  1616. type : 'application/x-temwebrtcplugin',
  1617. onload : '__TemWebRTCReady0',
  1618. portalLink : 'http://skylink.io/plugin/',
  1619. downloadLink : null, //set below
  1620. companyName: 'Temasys'
  1621. };
  1622. if(!!navigator.platform.match(/^Mac/i)) {
  1623. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  1624. }
  1625. else if(!!navigator.platform.match(/^Win/i)) {
  1626. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  1627. }
  1628. // Unique identifier of each opened page
  1629. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  1630. // Use this whenever you want to call the plugin.
  1631. AdapterJS.WebRTCPlugin.plugin = null;
  1632. // Set log level for the plugin once it is ready.
  1633. // The different values are
  1634. // This is an asynchronous function that will run when the plugin is ready
  1635. AdapterJS.WebRTCPlugin.setLogLevel = null;
  1636. // Defines webrtc's JS interface according to the plugin's implementation.
  1637. // Define plugin Browsers as WebRTC Interface.
  1638. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  1639. // This function detects whether or not a plugin is installed.
  1640. // Checks if Not IE (firefox, for example), else if it's IE,
  1641. // we're running IE and do something. If not it is not supported.
  1642. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  1643. // Lets adapter.js wait until the the document is ready before injecting the plugin
  1644. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  1645. // Inject the HTML DOM object element into the page.
  1646. AdapterJS.WebRTCPlugin.injectPlugin = null;
  1647. // States of readiness that the plugin goes through when
  1648. // being injected and stated
  1649. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  1650. NONE : 0, // no plugin use
  1651. INITIALIZING : 1, // Detected need for plugin
  1652. INJECTING : 2, // Injecting plugin
  1653. INJECTED: 3, // Plugin element injected but not usable yet
  1654. READY: 4 // Plugin ready to be used
  1655. };
  1656. // Current state of the plugin. You cannot use the plugin before this is
  1657. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  1658. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  1659. // True is AdapterJS.onwebrtcready was already called, false otherwise
  1660. // Used to make sure AdapterJS.onwebrtcready is only called once
  1661. AdapterJS.onwebrtcreadyDone = false;
  1662. // Log levels for the plugin.
  1663. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  1664. /*
  1665. Log outputs are prefixed in some cases.
  1666. INFO: Information reported by the plugin.
  1667. ERROR: Errors originating from within the plugin.
  1668. WEBRTC: Error originating from within the libWebRTC library
  1669. */
  1670. // From the least verbose to the most verbose
  1671. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  1672. NONE : 'NONE',
  1673. ERROR : 'ERROR',
  1674. WARNING : 'WARNING',
  1675. INFO: 'INFO',
  1676. VERBOSE: 'VERBOSE',
  1677. SENSITIVE: 'SENSITIVE'
  1678. };
  1679. // Does a waiting check before proceeding to load the plugin.
  1680. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  1681. // This methid will use an interval to wait for the plugin to be ready.
  1682. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  1683. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  1684. // This function will be called when plugin is ready. It sends necessary
  1685. // details to the plugin.
  1686. // The function will wait for the document to be ready and the set the
  1687. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  1688. // indicating that it can start being requested.
  1689. // This function is not in the IE/Safari condition brackets so that
  1690. // TemPluginLoaded function might be called on Chrome/Firefox.
  1691. // This function is the only private function that is not encapsulated to
  1692. // allow the plugin method to be called.
  1693. __TemWebRTCReady0 = function () {
  1694. if (document.readyState === 'complete') {
  1695. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1696. AdapterJS.maybeThroughWebRTCReady();
  1697. } else {
  1698. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  1699. if (document.readyState === 'complete') {
  1700. // TODO: update comments, we wait for the document to be ready
  1701. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  1702. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1703. AdapterJS.maybeThroughWebRTCReady();
  1704. }
  1705. }, 100);
  1706. }
  1707. };
  1708. AdapterJS.maybeThroughWebRTCReady = function() {
  1709. if (!AdapterJS.onwebrtcreadyDone) {
  1710. AdapterJS.onwebrtcreadyDone = true;
  1711. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  1712. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  1713. }
  1714. }
  1715. };
  1716. // Text namespace
  1717. AdapterJS.TEXT = {
  1718. PLUGIN: {
  1719. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  1720. 'to work on this browser.',
  1721. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  1722. BUTTON: 'Install Now'
  1723. },
  1724. REFRESH: {
  1725. REQUIRE_REFRESH: 'Please refresh page',
  1726. BUTTON: 'Refresh Page'
  1727. }
  1728. };
  1729. // The result of ice connection states.
  1730. // - starting: Ice connection is starting.
  1731. // - checking: Ice connection is checking.
  1732. // - connected Ice connection is connected.
  1733. // - completed Ice connection is connected.
  1734. // - done Ice connection has been completed.
  1735. // - disconnected Ice connection has been disconnected.
  1736. // - failed Ice connection has failed.
  1737. // - closed Ice connection is closed.
  1738. AdapterJS._iceConnectionStates = {
  1739. starting : 'starting',
  1740. checking : 'checking',
  1741. connected : 'connected',
  1742. completed : 'connected',
  1743. done : 'completed',
  1744. disconnected : 'disconnected',
  1745. failed : 'failed',
  1746. closed : 'closed'
  1747. };
  1748. //The IceConnection states that has been fired for each peer.
  1749. AdapterJS._iceConnectionFiredStates = [];
  1750. // Check if WebRTC Interface is defined.
  1751. AdapterJS.isDefined = null;
  1752. // This function helps to retrieve the webrtc detected browser information.
  1753. // This sets:
  1754. // - webrtcDetectedBrowser: The browser agent name.
  1755. // - webrtcDetectedVersion: The browser version.
  1756. // - webrtcDetectedType: The types of webRTC support.
  1757. // - 'moz': Mozilla implementation of webRTC.
  1758. // - 'webkit': WebKit implementation of webRTC.
  1759. // - 'plugin': Using the plugin implementation.
  1760. AdapterJS.parseWebrtcDetectedBrowser = function () {
  1761. var hasMatch, checkMatch = navigator.userAgent.match(
  1762. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  1763. if (/trident/i.test(checkMatch[1])) {
  1764. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  1765. webrtcDetectedBrowser = 'IE';
  1766. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  1767. } else if (checkMatch[1] === 'Chrome') {
  1768. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  1769. if (hasMatch !== null) {
  1770. webrtcDetectedBrowser = 'opera';
  1771. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  1772. }
  1773. }
  1774. if (navigator.userAgent.indexOf('Safari')) {
  1775. if (typeof InstallTrigger !== 'undefined') {
  1776. webrtcDetectedBrowser = 'firefox';
  1777. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  1778. webrtcDetectedBrowser = 'IE';
  1779. } else if (
  1780. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  1781. webrtcDetectedBrowser = 'safari';
  1782. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  1783. webrtcDetectedBrowser = 'opera';
  1784. } else if (!!window.chrome) {
  1785. webrtcDetectedBrowser = 'chrome';
  1786. }
  1787. }
  1788. if (!webrtcDetectedBrowser) {
  1789. webrtcDetectedVersion = checkMatch[1];
  1790. }
  1791. if (!webrtcDetectedVersion) {
  1792. try {
  1793. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  1794. [navigator.appName, navigator.appVersion, '-?'];
  1795. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  1796. checkMatch.splice(1, 1, hasMatch[1]);
  1797. }
  1798. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  1799. } catch (error) { }
  1800. }
  1801. };
  1802. // To fix configuration as some browsers does not support
  1803. // the 'urls' attribute.
  1804. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  1805. if (pcConfig === null) {
  1806. return;
  1807. }
  1808. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  1809. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  1810. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  1811. delete pcConfig.iceServers[i].urls;
  1812. }
  1813. }
  1814. };
  1815. AdapterJS.addEvent = function(elem, evnt, func) {
  1816. if (elem.addEventListener) { // W3C DOM
  1817. elem.addEventListener(evnt, func, false);
  1818. } else if (elem.attachEvent) {// OLD IE DOM
  1819. elem.attachEvent('on'+evnt, func);
  1820. } else { // No much to do
  1821. elem[evnt] = func;
  1822. }
  1823. };
  1824. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  1825. // only inject once the page is ready
  1826. if (document.readyState !== 'complete') {
  1827. return;
  1828. }
  1829. var w = window;
  1830. var i = document.createElement('iframe');
  1831. i.style.position = 'fixed';
  1832. i.style.top = '-41px';
  1833. i.style.left = 0;
  1834. i.style.right = 0;
  1835. i.style.width = '100%';
  1836. i.style.height = '40px';
  1837. i.style.backgroundColor = '#ffffe1';
  1838. i.style.border = 'none';
  1839. i.style.borderBottom = '1px solid #888888';
  1840. i.style.zIndex = '9999999';
  1841. if(typeof i.style.webkitTransition === 'string') {
  1842. i.style.webkitTransition = 'all .5s ease-out';
  1843. } else if(typeof i.style.transition === 'string') {
  1844. i.style.transition = 'all .5s ease-out';
  1845. }
  1846. document.body.appendChild(i);
  1847. c = (i.contentWindow) ? i.contentWindow :
  1848. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  1849. c.document.open();
  1850. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  1851. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  1852. 'middle; cursor: default;">' + text + '</span>');
  1853. if(buttonText && buttonLink) {
  1854. c.document.write('<button id="okay">' + buttonText + '</button><button>Cancel</button>');
  1855. c.document.close();
  1856. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  1857. if (!!displayRefreshBar) {
  1858. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  1859. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  1860. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  1861. }
  1862. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  1863. e.preventDefault();
  1864. try {
  1865. event.cancelBubble = true;
  1866. } catch(error) { }
  1867. });
  1868. }
  1869. else {
  1870. c.document.close();
  1871. }
  1872. AdapterJS.addEvent(c.document, 'click', function() {
  1873. w.document.body.removeChild(i);
  1874. });
  1875. setTimeout(function() {
  1876. if(typeof i.style.webkitTransform === 'string') {
  1877. i.style.webkitTransform = 'translateY(40px)';
  1878. } else if(typeof i.style.transform === 'string') {
  1879. i.style.transform = 'translateY(40px)';
  1880. } else {
  1881. i.style.top = '0px';
  1882. }
  1883. }, 300);
  1884. };
  1885. // -----------------------------------------------------------
  1886. // Detected webrtc implementation. Types are:
  1887. // - 'moz': Mozilla implementation of webRTC.
  1888. // - 'webkit': WebKit implementation of webRTC.
  1889. // - 'plugin': Using the plugin implementation.
  1890. webrtcDetectedType = null;
  1891. // Detected webrtc datachannel support. Types are:
  1892. // - 'SCTP': SCTP datachannel support.
  1893. // - 'RTP': RTP datachannel support.
  1894. webrtcDetectedDCSupport = null;
  1895. // Set the settings for creating DataChannels, MediaStream for
  1896. // Cross-browser compability.
  1897. // - This is only for SCTP based support browsers.
  1898. // the 'urls' attribute.
  1899. checkMediaDataChannelSettings =
  1900. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  1901. if (typeof callback !== 'function') {
  1902. return;
  1903. }
  1904. var beOfferer = true;
  1905. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  1906. // Nightly version does not require MozDontOfferDataChannel for interop
  1907. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  1908. var isPeerFirefox = peerBrowserAgent === 'firefox';
  1909. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  1910. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  1911. // Resends an updated version of constraints for MozDataChannel to work
  1912. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  1913. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  1914. try {
  1915. delete constraints.mandatory.MozDontOfferDataChannel;
  1916. } catch (error) {
  1917. console.error('Failed deleting MozDontOfferDataChannel');
  1918. console.error(error);
  1919. }
  1920. } else if ((isLocalFirefox && !isPeerFirefox)) {
  1921. constraints.mandatory.MozDontOfferDataChannel = true;
  1922. }
  1923. if (!isLocalFirefox) {
  1924. // temporary measure to remove Moz* constraints in non Firefox browsers
  1925. for (var prop in constraints.mandatory) {
  1926. if (constraints.mandatory.hasOwnProperty(prop)) {
  1927. if (prop.indexOf('Moz') !== -1) {
  1928. delete constraints.mandatory[prop];
  1929. }
  1930. }
  1931. }
  1932. }
  1933. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  1934. // interopability of the media stream
  1935. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  1936. beOfferer = false;
  1937. }
  1938. callback(beOfferer, constraints);
  1939. };
  1940. // Handles the differences for all browsers ice connection state output.
  1941. // - Tested outcomes are:
  1942. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  1943. // - Chrome (answerer) : 'checking' > 'connected'
  1944. // - Firefox (offerer) : 'checking' > 'connected'
  1945. // - Firefox (answerer): 'checking' > 'connected'
  1946. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  1947. if (typeof callback !== 'function') {
  1948. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  1949. return;
  1950. }
  1951. peerId = (peerId) ? peerId : 'peer';
  1952. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  1953. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  1954. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  1955. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  1956. AdapterJS._iceConnectionFiredStates[peerId] = [];
  1957. }
  1958. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  1959. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  1960. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  1961. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  1962. setTimeout(function () {
  1963. AdapterJS._iceConnectionFiredStates[peerId]
  1964. .push(AdapterJS._iceConnectionStates.done);
  1965. callback(AdapterJS._iceConnectionStates.done);
  1966. }, 1000);
  1967. }
  1968. callback(iceConnectionState);
  1969. }
  1970. return;
  1971. };
  1972. // Firefox:
  1973. // - Creates iceServer from the url for Firefox.
  1974. // - Create iceServer with stun url.
  1975. // - Create iceServer with turn url.
  1976. // - Ignore the transport parameter from TURN url for FF version <=27.
  1977. // - Return null for createIceServer if transport=tcp.
  1978. // - FF 27 and above supports transport parameters in TURN url,
  1979. // - So passing in the full url to create iceServer.
  1980. // Chrome:
  1981. // - Creates iceServer from the url for Chrome M33 and earlier.
  1982. // - Create iceServer with stun url.
  1983. // - Chrome M28 & above uses below TURN format.
  1984. // Plugin:
  1985. // - Creates Ice Server for Plugin Browsers
  1986. // - If Stun - Create iceServer with stun url.
  1987. // - Else - Create iceServer with turn url
  1988. // - This is a WebRTC Function
  1989. createIceServer = null;
  1990. // Firefox:
  1991. // - Creates IceServers for Firefox
  1992. // - Use .url for FireFox.
  1993. // - Multiple Urls support
  1994. // Chrome:
  1995. // - Creates iceServers from the urls for Chrome M34 and above.
  1996. // - .urls is supported since Chrome M34.
  1997. // - Multiple Urls support
  1998. // Plugin:
  1999. // - Creates Ice Servers for Plugin Browsers
  2000. // - Multiple Urls support
  2001. // - This is a WebRTC Function
  2002. createIceServers = null;
  2003. //------------------------------------------------------------
  2004. //The RTCPeerConnection object.
  2005. RTCPeerConnection = null;
  2006. // Creates RTCSessionDescription object for Plugin Browsers
  2007. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  2008. RTCSessionDescription : null;
  2009. // Creates RTCIceCandidate object for Plugin Browsers
  2010. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  2011. RTCIceCandidate : null;
  2012. // Get UserMedia (only difference is the prefix).
  2013. // Code from Adam Barth.
  2014. getUserMedia = null;
  2015. // Attach a media stream to an element.
  2016. attachMediaStream = null;
  2017. // Re-attach a media stream to an element.
  2018. reattachMediaStream = null;
  2019. // Detected browser agent name. Types are:
  2020. // - 'firefox': Firefox browser.
  2021. // - 'chrome': Chrome browser.
  2022. // - 'opera': Opera browser.
  2023. // - 'safari': Safari browser.
  2024. // - 'IE' - Internet Explorer browser.
  2025. webrtcDetectedBrowser = null;
  2026. // Detected browser version.
  2027. webrtcDetectedVersion = null;
  2028. // Check for browser types and react accordingly
  2029. if (navigator.mozGetUserMedia) {
  2030. webrtcDetectedBrowser = 'firefox';
  2031. webrtcDetectedVersion = parseInt(navigator
  2032. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2033. webrtcDetectedType = 'moz';
  2034. webrtcDetectedDCSupport = 'SCTP';
  2035. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2036. AdapterJS.maybeFixConfiguration(pcConfig);
  2037. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  2038. };
  2039. // The RTCSessionDescription object.
  2040. RTCSessionDescription = mozRTCSessionDescription;
  2041. window.RTCSessionDescription = RTCSessionDescription;
  2042. // The RTCIceCandidate object.
  2043. RTCIceCandidate = mozRTCIceCandidate;
  2044. window.RTCIceCandidate = RTCIceCandidate;
  2045. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  2046. navigator.getUserMedia = window.getUserMedia;
  2047. // Shim for MediaStreamTrack.getSources.
  2048. MediaStreamTrack.getSources = function(successCb) {
  2049. setTimeout(function() {
  2050. var infos = [
  2051. { kind: 'audio', id: 'default', label:'', facing:'' },
  2052. { kind: 'video', id: 'default', label:'', facing:'' }
  2053. ];
  2054. successCb(infos);
  2055. }, 0);
  2056. };
  2057. createIceServer = function (url, username, password) {
  2058. var iceServer = null;
  2059. var url_parts = url.split(':');
  2060. if (url_parts[0].indexOf('stun') === 0) {
  2061. iceServer = { url : url };
  2062. } else if (url_parts[0].indexOf('turn') === 0) {
  2063. if (webrtcDetectedVersion < 27) {
  2064. var turn_url_parts = url.split('?');
  2065. if (turn_url_parts.length === 1 ||
  2066. turn_url_parts[1].indexOf('transport=udp') === 0) {
  2067. iceServer = {
  2068. url : turn_url_parts[0],
  2069. credential : password,
  2070. username : username
  2071. };
  2072. }
  2073. } else {
  2074. iceServer = {
  2075. url : url,
  2076. credential : password,
  2077. username : username
  2078. };
  2079. }
  2080. }
  2081. return iceServer;
  2082. };
  2083. createIceServers = function (urls, username, password) {
  2084. var iceServers = [];
  2085. for (i = 0; i < urls.length; i++) {
  2086. var iceServer = createIceServer(urls[i], username, password);
  2087. if (iceServer !== null) {
  2088. iceServers.push(iceServer);
  2089. }
  2090. }
  2091. return iceServers;
  2092. };
  2093. attachMediaStream = function (element, stream) {
  2094. element.mozSrcObject = stream;
  2095. if (stream !== null)
  2096. element.play();
  2097. return element;
  2098. };
  2099. reattachMediaStream = function (to, from) {
  2100. to.mozSrcObject = from.mozSrcObject;
  2101. to.play();
  2102. return to;
  2103. };
  2104. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  2105. if (!callback) {
  2106. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  2107. ': 1 argument required, but only 0 present.');
  2108. }
  2109. return callback([]);
  2110. };
  2111. // Fake get{Video,Audio}Tracks
  2112. if (!MediaStream.prototype.getVideoTracks) {
  2113. MediaStream.prototype.getVideoTracks = function () {
  2114. return [];
  2115. };
  2116. }
  2117. if (!MediaStream.prototype.getAudioTracks) {
  2118. MediaStream.prototype.getAudioTracks = function () {
  2119. return [];
  2120. };
  2121. }
  2122. AdapterJS.maybeThroughWebRTCReady();
  2123. } else if (navigator.webkitGetUserMedia) {
  2124. webrtcDetectedBrowser = 'chrome';
  2125. webrtcDetectedType = 'webkit';
  2126. webrtcDetectedVersion = parseInt(navigator
  2127. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  2128. // check if browser is opera 20+
  2129. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2130. if (checkIfOpera !== null) {
  2131. webrtcDetectedBrowser = 'opera';
  2132. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  2133. }
  2134. // check browser datachannel support
  2135. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  2136. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  2137. webrtcDetectedDCSupport = 'SCTP';
  2138. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  2139. webrtcDetectedVersion > 24) {
  2140. webrtcDetectedDCSupport = 'RTP';
  2141. } else {
  2142. webrtcDetectedDCSupport = '';
  2143. }
  2144. createIceServer = function (url, username, password) {
  2145. var iceServer = null;
  2146. var url_parts = url.split(':');
  2147. if (url_parts[0].indexOf('stun') === 0) {
  2148. iceServer = { 'url' : url };
  2149. } else if (url_parts[0].indexOf('turn') === 0) {
  2150. iceServer = {
  2151. 'url' : url,
  2152. 'credential' : password,
  2153. 'username' : username
  2154. };
  2155. }
  2156. return iceServer;
  2157. };
  2158. createIceServers = function (urls, username, password) {
  2159. var iceServers = [];
  2160. if (webrtcDetectedVersion >= 34) {
  2161. iceServers = {
  2162. 'urls' : urls,
  2163. 'credential' : password,
  2164. 'username' : username
  2165. };
  2166. } else {
  2167. for (i = 0; i < urls.length; i++) {
  2168. var iceServer = createIceServer(urls[i], username, password);
  2169. if (iceServer !== null) {
  2170. iceServers.push(iceServer);
  2171. }
  2172. }
  2173. }
  2174. return iceServers;
  2175. };
  2176. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2177. if (webrtcDetectedVersion < 34) {
  2178. AdapterJS.maybeFixConfiguration(pcConfig);
  2179. }
  2180. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  2181. };
  2182. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2183. navigator.getUserMedia = window.getUserMedia;
  2184. attachMediaStream = function (element, stream) {
  2185. if (typeof element.srcObject !== 'undefined') {
  2186. element.srcObject = stream;
  2187. } else if (typeof element.mozSrcObject !== 'undefined') {
  2188. element.mozSrcObject = stream;
  2189. } else if (typeof element.src !== 'undefined') {
  2190. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  2191. } else {
  2192. console.log('Error attaching stream to element.');
  2193. }
  2194. return element;
  2195. };
  2196. reattachMediaStream = function (to, from) {
  2197. to.src = from.src;
  2198. return to;
  2199. };
  2200. AdapterJS.maybeThroughWebRTCReady();
  2201. } else { // TRY TO USE PLUGIN
  2202. // IE 9 is not offering an implementation of console.log until you open a console
  2203. if (typeof console !== 'object' || typeof console.log !== 'function') {
  2204. /* jshint -W020 */
  2205. console = {} || console;
  2206. // Implemented based on console specs from MDN
  2207. // You may override these functions
  2208. console.log = function (arg) {};
  2209. console.info = function (arg) {};
  2210. console.error = function (arg) {};
  2211. console.dir = function (arg) {};
  2212. console.exception = function (arg) {};
  2213. console.trace = function (arg) {};
  2214. console.warn = function (arg) {};
  2215. console.count = function (arg) {};
  2216. console.debug = function (arg) {};
  2217. console.count = function (arg) {};
  2218. console.time = function (arg) {};
  2219. console.timeEnd = function (arg) {};
  2220. console.group = function (arg) {};
  2221. console.groupCollapsed = function (arg) {};
  2222. console.groupEnd = function (arg) {};
  2223. /* jshint +W020 */
  2224. }
  2225. webrtcDetectedType = 'plugin';
  2226. webrtcDetectedDCSupport = 'plugin';
  2227. AdapterJS.parseWebrtcDetectedBrowser();
  2228. isIE = webrtcDetectedBrowser === 'IE';
  2229. /* jshint -W035 */
  2230. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  2231. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2232. /* empty because it needs to prevent the function from running. */
  2233. }
  2234. };
  2235. /* jshint +W035 */
  2236. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  2237. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2238. // Call immediately if possible
  2239. // Once the plugin is set, the code will always take this path
  2240. callback();
  2241. } else {
  2242. // otherwise start a 100ms interval
  2243. var checkPluginReadyState = setInterval(function () {
  2244. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2245. clearInterval(checkPluginReadyState);
  2246. callback();
  2247. }
  2248. }, 100);
  2249. }
  2250. };
  2251. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  2252. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2253. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  2254. });
  2255. };
  2256. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  2257. // only inject once the page is ready
  2258. if (document.readyState !== 'complete') {
  2259. return;
  2260. }
  2261. // Prevent multiple injections
  2262. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  2263. return;
  2264. }
  2265. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  2266. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  2267. var frag = document.createDocumentFragment();
  2268. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  2269. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  2270. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  2271. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  2272. '<param name="pluginId" value="' +
  2273. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  2274. '<param name="windowless" value="false" /> ' +
  2275. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2276. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload +
  2277. '" />' +
  2278. // uncomment to be able to use virtual cams
  2279. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2280. '</object>';
  2281. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  2282. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  2283. }
  2284. document.body.appendChild(frag);
  2285. // Need to re-fetch the plugin
  2286. AdapterJS.WebRTCPlugin.plugin =
  2287. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  2288. } else {
  2289. // Load Plugin
  2290. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  2291. AdapterJS.WebRTCPlugin.plugin.id =
  2292. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  2293. // IE will only start the plugin if it's ACTUALLY visible
  2294. if (isIE) {
  2295. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  2296. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  2297. } else { // The size of the plugin on Safari should be 0x0px
  2298. // so that the autorisation prompt is at the top
  2299. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  2300. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  2301. }
  2302. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  2303. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  2304. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  2305. '<param name="pluginId" value="' +
  2306. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  2307. '<param name="windowless" value="false" /> ' +
  2308. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2309. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">';
  2310. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  2311. }
  2312. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  2313. };
  2314. AdapterJS.WebRTCPlugin.isPluginInstalled =
  2315. function (comName, plugName, installedCb, notInstalledCb) {
  2316. if (!isIE) {
  2317. var pluginArray = navigator.plugins;
  2318. for (var i = 0; i < pluginArray.length; i++) {
  2319. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  2320. installedCb();
  2321. return;
  2322. }
  2323. }
  2324. notInstalledCb();
  2325. } else {
  2326. try {
  2327. var axo = new ActiveXObject(comName + '.' + plugName);
  2328. } catch (e) {
  2329. notInstalledCb();
  2330. return;
  2331. }
  2332. installedCb();
  2333. }
  2334. };
  2335. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  2336. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  2337. AdapterJS.isDefined = function (variable) {
  2338. return variable !== null && variable !== undefined;
  2339. };
  2340. createIceServer = function (url, username, password) {
  2341. var iceServer = null;
  2342. var url_parts = url.split(':');
  2343. if (url_parts[0].indexOf('stun') === 0) {
  2344. iceServer = {
  2345. 'url' : url,
  2346. 'hasCredentials' : false
  2347. };
  2348. } else if (url_parts[0].indexOf('turn') === 0) {
  2349. iceServer = {
  2350. 'url' : url,
  2351. 'hasCredentials' : true,
  2352. 'credential' : password,
  2353. 'username' : username
  2354. };
  2355. }
  2356. return iceServer;
  2357. };
  2358. createIceServers = function (urls, username, password) {
  2359. var iceServers = [];
  2360. for (var i = 0; i < urls.length; ++i) {
  2361. iceServers.push(createIceServer(urls[i], username, password));
  2362. }
  2363. return iceServers;
  2364. };
  2365. RTCSessionDescription = function (info) {
  2366. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2367. return AdapterJS.WebRTCPlugin.plugin.
  2368. ConstructSessionDescription(info.type, info.sdp);
  2369. };
  2370. RTCPeerConnection = function (servers, constraints) {
  2371. var iceServers = null;
  2372. if (servers) {
  2373. iceServers = servers.iceServers;
  2374. for (var i = 0; i < iceServers.length; i++) {
  2375. if (iceServers[i].urls && !iceServers[i].url) {
  2376. iceServers[i].url = iceServers[i].urls;
  2377. }
  2378. iceServers[i].hasCredentials = AdapterJS.
  2379. isDefined(iceServers[i].username) &&
  2380. AdapterJS.isDefined(iceServers[i].credential);
  2381. }
  2382. }
  2383. var mandatory = (constraints && constraints.mandatory) ?
  2384. constraints.mandatory : null;
  2385. var optional = (constraints && constraints.optional) ?
  2386. constraints.optional : null;
  2387. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2388. return AdapterJS.WebRTCPlugin.plugin.
  2389. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  2390. iceServers, mandatory, optional);
  2391. };
  2392. MediaStreamTrack = {};
  2393. MediaStreamTrack.getSources = function (callback) {
  2394. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2395. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  2396. });
  2397. };
  2398. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  2399. constraints.audio = constraints.audio || false;
  2400. constraints.video = constraints.video || false;
  2401. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2402. AdapterJS.WebRTCPlugin.plugin.
  2403. getUserMedia(constraints, successCallback, failureCallback);
  2404. });
  2405. };
  2406. window.navigator.getUserMedia = window.getUserMedia;
  2407. attachMediaStream = function (element, stream) {
  2408. if (!element || !element.parentNode) {
  2409. return;
  2410. }
  2411. var streamId
  2412. if (stream === null) {
  2413. streamId = '';
  2414. }
  2415. else {
  2416. stream.enableSoundTracks(true);
  2417. streamId = stream.id;
  2418. }
  2419. if (element.nodeName.toLowerCase() !== 'audio') {
  2420. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  2421. if (!element.isWebRTCPlugin || !element.isWebRTCPlugin()) {
  2422. var frag = document.createDocumentFragment();
  2423. var temp = document.createElement('div');
  2424. var classHTML = '';
  2425. if (element.className) {
  2426. classHTML = 'class="' + element.className + '" ';
  2427. } else if (element.attributes && element.attributes['class']) {
  2428. classHTML = 'class="' + element.attributes['class'].value + '" ';
  2429. }
  2430. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  2431. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  2432. '<param name="pluginId" value="' + elementId + '" /> ' +
  2433. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2434. '<param name="windowless" value="true" /> ' +
  2435. '<param name="streamId" value="' + streamId + '" /> ' +
  2436. '</object>';
  2437. while (temp.firstChild) {
  2438. frag.appendChild(temp.firstChild);
  2439. }
  2440. var height = '';
  2441. var width = '';
  2442. if (element.getBoundingClientRect) {
  2443. var rectObject = element.getBoundingClientRect();
  2444. width = rectObject.width + 'px';
  2445. height = rectObject.height + 'px';
  2446. }
  2447. else if (element.width) {
  2448. width = element.width;
  2449. height = element.height;
  2450. } else {
  2451. // TODO: What scenario could bring us here?
  2452. }
  2453. element.parentNode.insertBefore(frag, element);
  2454. frag = document.getElementById(elementId);
  2455. frag.width = width;
  2456. frag.height = height;
  2457. element.parentNode.removeChild(element);
  2458. } else {
  2459. var children = element.children;
  2460. for (var i = 0; i !== children.length; ++i) {
  2461. if (children[i].name === 'streamId') {
  2462. children[i].value = streamId;
  2463. break;
  2464. }
  2465. }
  2466. element.setStreamId(streamId);
  2467. }
  2468. var newElement = document.getElementById(elementId);
  2469. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  2470. if (isIE) { // on IE the event needs to be plugged manually
  2471. newElement.attachEvent('onplaying', newElement.onplaying);
  2472. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  2473. newElement._TemOnClick = function (id) {
  2474. var arg = {
  2475. srcElement : document.getElementById(id)
  2476. };
  2477. newElement.onclick(arg);
  2478. };
  2479. }
  2480. return newElement;
  2481. } else {
  2482. return element;
  2483. }
  2484. };
  2485. reattachMediaStream = function (to, from) {
  2486. var stream = null;
  2487. var children = from.children;
  2488. for (var i = 0; i !== children.length; ++i) {
  2489. if (children[i].name === 'streamId') {
  2490. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2491. stream = AdapterJS.WebRTCPlugin.plugin
  2492. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  2493. break;
  2494. }
  2495. }
  2496. if (stream !== null) {
  2497. return attachMediaStream(to, stream);
  2498. } else {
  2499. console.log('Could not find the stream associated with this element');
  2500. }
  2501. };
  2502. RTCIceCandidate = function (candidate) {
  2503. if (!candidate.sdpMid) {
  2504. candidate.sdpMid = '';
  2505. }
  2506. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2507. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  2508. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  2509. );
  2510. };
  2511. // inject plugin
  2512. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  2513. AdapterJS.WebRTCPlugin.injectPlugin();
  2514. };
  2515. // This function will be called if the plugin is needed (browser different
  2516. // from Chrome or Firefox), but the plugin is not installed.
  2517. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  2518. function() {
  2519. AdapterJS.addEvent(document,
  2520. 'readystatechange',
  2521. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  2522. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  2523. };
  2524. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  2525. if (AdapterJS.options.hidePluginInstallPrompt) {
  2526. return;
  2527. }
  2528. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  2529. if(downloadLink) { // if download link
  2530. var popupString;
  2531. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  2532. popupString = 'This website requires you to install the ' +
  2533. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  2534. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  2535. ' WebRTC Plugin</a>' +
  2536. ' to work on this browser.';
  2537. } else { // no portal link, just print a generic explanation
  2538. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  2539. }
  2540. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  2541. } else { // no download link, just print a generic explanation
  2542. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  2543. }
  2544. };
  2545. // Try to detect the plugin and act accordingly
  2546. AdapterJS.WebRTCPlugin.isPluginInstalled(
  2547. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  2548. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  2549. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  2550. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  2551. }
  2552. (function () {
  2553. 'use strict';
  2554. var baseGetUserMedia = null;
  2555. AdapterJS.TEXT.EXTENSION = {
  2556. REQUIRE_INSTALLATION_FF: 'To enable screensharing you need to install the Skylink WebRTC tools Firefox Add-on.',
  2557. REQUIRE_INSTALLATION_CHROME: 'To enable screensharing you need to install the Skylink WebRTC tools Chrome Extension.',
  2558. REQUIRE_REFRESH: 'Please refresh this page after the Skylink WebRTC tools extension has been installed.',
  2559. BUTTON_FF: 'Install Now',
  2560. BUTTON_CHROME: 'Go to Chrome Web Store'
  2561. };
  2562. var clone = function(obj) {
  2563. if (null == obj || "object" != typeof obj) return obj;
  2564. var copy = obj.constructor();
  2565. for (var attr in obj) {
  2566. if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
  2567. }
  2568. return copy;
  2569. };
  2570. if (window.navigator.mozGetUserMedia) {
  2571. baseGetUserMedia = window.navigator.getUserMedia;
  2572. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2573. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2574. // intercepting screensharing requests
  2575. if (constraints.video.mediaSource !== 'screen' && constraints.video.mediaSource !== 'window') {
  2576. throw new Error('Only "screen" and "window" option is available as mediaSource');
  2577. }
  2578. var updatedConstraints = clone(constraints);
  2579. //constraints.video.mediaSource = constraints.video.mediaSource;
  2580. updatedConstraints.video.mozMediaSource = updatedConstraints.video.mediaSource;
  2581. // so generally, it requires for document.readyState to be completed before the getUserMedia could be invoked.
  2582. // strange but this works anyway
  2583. var checkIfReady = setInterval(function () {
  2584. if (document.readyState === 'complete') {
  2585. clearInterval(checkIfReady);
  2586. baseGetUserMedia(updatedConstraints, successCb, function (error) {
  2587. if (error.name === 'PermissionDeniedError' && window.parent.location.protocol === 'https:') {
  2588. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_FF,
  2589. AdapterJS.TEXT.EXTENSION.BUTTON_FF,
  2590. 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname, false, true);
  2591. //window.location.href = 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname;
  2592. } else {
  2593. failureCb(error);
  2594. }
  2595. });
  2596. }
  2597. }, 1);
  2598. } else { // regular GetUserMediaRequest
  2599. baseGetUserMedia(constraints, successCb, failureCb);
  2600. }
  2601. };
  2602. getUserMedia = navigator.getUserMedia;
  2603. } else if (window.navigator.webkitGetUserMedia) {
  2604. baseGetUserMedia = window.navigator.getUserMedia;
  2605. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2606. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2607. if (window.webrtcDetectedBrowser !== 'chrome') {
  2608. throw new Error('Current browser does not support screensharing');
  2609. }
  2610. // would be fine since no methods
  2611. var updatedConstraints = clone(constraints);
  2612. var chromeCallback = function(error, sourceId) {
  2613. if(!error) {
  2614. updatedConstraints.video.mandatory = updatedConstraints.video.mandatory || {};
  2615. updatedConstraints.video.mandatory.chromeMediaSource = 'desktop';
  2616. updatedConstraints.video.mandatory.maxWidth = window.screen.width > 1920 ? window.screen.width : 1920;
  2617. updatedConstraints.video.mandatory.maxHeight = window.screen.height > 1080 ? window.screen.height : 1080;
  2618. if (sourceId) {
  2619. updatedConstraints.video.mandatory.chromeMediaSourceId = sourceId;
  2620. }
  2621. delete updatedConstraints.video.mediaSource;
  2622. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2623. } else {
  2624. if (error === 'permission-denied') {
  2625. throw new Error('Permission denied for screen retrieval');
  2626. } else {
  2627. throw new Error('Failed retrieving selected screen');
  2628. }
  2629. }
  2630. };
  2631. var onIFrameCallback = function (event) {
  2632. if (!event.data) {
  2633. return;
  2634. }
  2635. if (event.data.chromeMediaSourceId) {
  2636. if (event.data.chromeMediaSourceId === 'PermissionDeniedError') {
  2637. chromeCallback('permission-denied');
  2638. } else {
  2639. chromeCallback(null, event.data.chromeMediaSourceId);
  2640. }
  2641. }
  2642. if (event.data.chromeExtensionStatus) {
  2643. if (event.data.chromeExtensionStatus === 'not-installed') {
  2644. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_CHROME,
  2645. AdapterJS.TEXT.EXTENSION.BUTTON_CHROME,
  2646. event.data.data, true, true);
  2647. } else {
  2648. chromeCallback(event.data.chromeExtensionStatus, null);
  2649. }
  2650. }
  2651. // this event listener is no more needed
  2652. window.removeEventListener('message', onIFrameCallback);
  2653. };
  2654. window.addEventListener('message', onIFrameCallback);
  2655. postFrameMessage({
  2656. captureSourceId: true
  2657. });
  2658. } else {
  2659. baseGetUserMedia(constraints, successCb, failureCb);
  2660. }
  2661. };
  2662. getUserMedia = navigator.getUserMedia;
  2663. } else {
  2664. baseGetUserMedia = window.navigator.getUserMedia;
  2665. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2666. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2667. // would be fine since no methods
  2668. var updatedConstraints = clone(constraints);
  2669. // wait for plugin to be ready
  2670. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2671. // check if screensharing feature is available
  2672. if (!!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature &&
  2673. !!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  2674. // set the constraints
  2675. updatedConstraints.video.optional = updatedConstraints.video.optional || [];
  2676. updatedConstraints.video.optional.push({
  2677. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey || 'Screensharing'
  2678. });
  2679. delete updatedConstraints.video.mediaSource;
  2680. } else {
  2681. throw new Error('Your WebRTC plugin does not support screensharing');
  2682. }
  2683. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2684. });
  2685. } else {
  2686. baseGetUserMedia(constraints, successCb, failureCb);
  2687. }
  2688. };
  2689. getUserMedia = window.navigator.getUserMedia;
  2690. }
  2691. if (window.webrtcDetectedBrowser === 'chrome') {
  2692. var iframe = document.createElement('iframe');
  2693. iframe.onload = function() {
  2694. iframe.isLoaded = true;
  2695. };
  2696. iframe.src = 'https://cdn.temasys.com.sg/skylink/extensions/detectRTC.html';
  2697. //'https://temasys-cdn.s3.amazonaws.com/skylink/extensions/detection-script-dev/detectRTC.html';
  2698. iframe.style.display = 'none';
  2699. (document.body || document.documentElement).appendChild(iframe);
  2700. var postFrameMessage = function (object) {
  2701. object = object || {};
  2702. if (!iframe.isLoaded) {
  2703. setTimeout(function () {
  2704. iframe.contentWindow.postMessage(object, '*');
  2705. }, 100);
  2706. return;
  2707. }
  2708. iframe.contentWindow.postMessage(object, '*');
  2709. };
  2710. }
  2711. })();
  2712. },{}],11:[function(require,module,exports){
  2713. var UI = {};
  2714. var VideoLayout = require("./videolayout/VideoLayout.js");
  2715. var AudioLevels = require("./audio_levels/AudioLevels.js");
  2716. var Prezi = require("./prezi/Prezi.js");
  2717. var Etherpad = require("./etherpad/Etherpad.js");
  2718. var Chat = require("./side_pannels/chat/Chat.js");
  2719. var Toolbar = require("./toolbars/Toolbar");
  2720. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  2721. var BottomToolbar = require("./toolbars/BottomToolbar");
  2722. var ContactList = require("./side_pannels/contactlist/ContactList");
  2723. var Avatar = require("./avatar/Avatar");
  2724. var EventEmitter = require("events");
  2725. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  2726. var Settings = require("./../settings/Settings");
  2727. var PanelToggler = require("./side_pannels/SidePanelToggler");
  2728. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  2729. UI.messageHandler = require("./util/MessageHandler");
  2730. var messageHandler = UI.messageHandler;
  2731. var Authentication = require("./authentication/Authentication");
  2732. var UIUtil = require("./util/UIUtil");
  2733. var NicknameHandler = require("./util/NicknameHandler");
  2734. var CQEvents = require("../../service/connectionquality/CQEvents");
  2735. var DesktopSharingEventTypes
  2736. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  2737. var RTCEvents = require("../../service/RTC/RTCEvents");
  2738. var RTCBrowserType = require("../RTC/RTCBrowserType");
  2739. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  2740. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  2741. var UIEvents = require("../../service/UI/UIEvents");
  2742. var MemberEvents = require("../../service/members/Events");
  2743. var eventEmitter = new EventEmitter();
  2744. var roomName = null;
  2745. function promptDisplayName() {
  2746. var message = '<h2 data-i18n="dialog.displayNameRequired">';
  2747. message += APP.translation.translateString(
  2748. "dialog.displayNameRequired");
  2749. message += '</h2>' +
  2750. '<input name="displayName" type="text" data-i18n=' +
  2751. '"[placeholder]defaultNickname" placeholder="' +
  2752. APP.translation.translateString(
  2753. "defaultNickname", {name: "Jane Pink"}) +
  2754. '" autofocus>';
  2755. var buttonTxt
  2756. = APP.translation.generateTranslationHTML("dialog.Ok");
  2757. var buttons = [];
  2758. buttons.push({title: buttonTxt, value: "ok"});
  2759. messageHandler.openDialog(null, message,
  2760. true,
  2761. buttons,
  2762. function (e, v, m, f) {
  2763. if (v == "ok") {
  2764. var displayName = f.displayName;
  2765. if (displayName) {
  2766. VideoLayout.inputDisplayNameHandler(displayName);
  2767. return true;
  2768. }
  2769. }
  2770. e.preventDefault();
  2771. },
  2772. function () {
  2773. var form = $.prompt.getPrompt();
  2774. var input = form.find("input[name='displayName']");
  2775. input.focus();
  2776. var button = form.find("button");
  2777. button.attr("disabled", "disabled");
  2778. input.keyup(function () {
  2779. if(!input.val())
  2780. button.attr("disabled", "disabled");
  2781. else
  2782. button.removeAttr("disabled");
  2783. });
  2784. }
  2785. );
  2786. }
  2787. function notifyForInitialMute()
  2788. {
  2789. messageHandler.notify(null, "notify.mutedTitle", "connected",
  2790. "notify.muted", null, {timeOut: 120000});
  2791. }
  2792. function setupPrezi()
  2793. {
  2794. $("#reloadPresentationLink").click(function()
  2795. {
  2796. Prezi.reloadPresentation();
  2797. });
  2798. }
  2799. function setupChat()
  2800. {
  2801. Chat.init();
  2802. $("#toggle_smileys").click(function() {
  2803. Chat.toggleSmileys();
  2804. });
  2805. }
  2806. function setupToolbars() {
  2807. Toolbar.init(UI);
  2808. Toolbar.setupButtonsFromConfig();
  2809. BottomToolbar.init();
  2810. }
  2811. function streamHandler(stream, isMuted) {
  2812. switch (stream.type)
  2813. {
  2814. case "audio":
  2815. VideoLayout.changeLocalAudio(stream, isMuted);
  2816. break;
  2817. case "video":
  2818. VideoLayout.changeLocalVideo(stream, isMuted);
  2819. break;
  2820. case "stream":
  2821. VideoLayout.changeLocalStream(stream, isMuted);
  2822. break;
  2823. }
  2824. }
  2825. function onXmppConnectionFailed(stropheErrorMsg) {
  2826. var title = APP.translation.generateTranslationHTML(
  2827. "dialog.error");
  2828. var message;
  2829. if (stropheErrorMsg) {
  2830. message = APP.translation.generateTranslationHTML(
  2831. "dialog.connectErrorWithMsg", {msg: stropheErrorMsg});
  2832. } else {
  2833. message = APP.translation.generateTranslationHTML(
  2834. "dialog.connectError");
  2835. }
  2836. messageHandler.openDialog(
  2837. title, message, true, {}, function (e, v, m, f) { return false; });
  2838. }
  2839. function onDisposeConference(unload) {
  2840. Toolbar.showAuthenticateButton(false);
  2841. }
  2842. function onDisplayNameChanged(jid, displayName) {
  2843. ContactList.onDisplayNameChange(jid, displayName);
  2844. SettingsMenu.onDisplayNameChange(jid, displayName);
  2845. VideoLayout.onDisplayNameChanged(jid, displayName);
  2846. }
  2847. function registerListeners() {
  2848. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  2849. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  2850. APP.RTC.addStreamListener(function (stream) {
  2851. VideoLayout.onRemoteStreamAdded(stream);
  2852. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  2853. APP.RTC.addStreamListener(function (jid) {
  2854. VideoLayout.onVideoTypeChanged(jid);
  2855. }, StreamEventTypes.EVENT_TYPE_REMOTE_CHANGED);
  2856. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  2857. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (resourceJid) {
  2858. VideoLayout.onDominantSpeakerChanged(resourceJid);
  2859. });
  2860. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  2861. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  2862. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  2863. endpointsEnteringLastN, stream);
  2864. });
  2865. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED,
  2866. function (devices) {
  2867. VideoLayout.setDeviceAvailabilityIcons(null, devices);
  2868. });
  2869. APP.RTC.addListener(RTCEvents.VIDEO_MUTE, UI.setVideoMuteButtonsState);
  2870. APP.RTC.addListener(RTCEvents.DATA_CHANNEL_OPEN, function() {
  2871. // when the data channel becomes available, tell the bridge about video
  2872. // selections so that it can do adaptive simulcast,
  2873. // we want the notification to trigger even if userJid is undefined,
  2874. // or null.
  2875. var userJid = APP.UI.getLargeVideoJid();
  2876. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT, userJid);
  2877. });
  2878. APP.statistics.addAudioLevelListener(function(jid, audioLevel)
  2879. {
  2880. var resourceJid;
  2881. if(jid === APP.statistics.LOCAL_JID)
  2882. {
  2883. resourceJid = AudioLevels.LOCAL_LEVEL;
  2884. if(APP.RTC.localAudio.isMuted())
  2885. {
  2886. audioLevel = 0;
  2887. }
  2888. }
  2889. else
  2890. {
  2891. resourceJid = Strophe.getResourceFromJid(jid);
  2892. }
  2893. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  2894. UI.getLargeVideoJid());
  2895. });
  2896. APP.desktopsharing.addListener(function () {
  2897. ToolbarToggler.showDesktopSharingButton();
  2898. }, DesktopSharingEventTypes.INIT);
  2899. APP.desktopsharing.addListener(
  2900. Toolbar.changeDesktopSharingButtonState,
  2901. DesktopSharingEventTypes.SWITCHING_DONE);
  2902. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  2903. VideoLayout.updateLocalConnectionStats);
  2904. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  2905. VideoLayout.updateConnectionStats);
  2906. APP.connectionquality.addListener(CQEvents.STOP,
  2907. VideoLayout.onStatsStop);
  2908. APP.xmpp.addListener(XMPPEvents.CONNECTION_FAILED, onXmppConnectionFailed);
  2909. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  2910. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  2911. messageHandler.openMessageDialog(
  2912. 'dialog.serviceUnavailable',
  2913. 'dialog.gracefulShutdown'
  2914. );
  2915. });
  2916. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  2917. var title = APP.translation.generateTranslationHTML(
  2918. "dialog.reservationError");
  2919. var message = APP.translation.generateTranslationHTML(
  2920. "dialog.reservationErrorMsg", {code: code, msg: msg});
  2921. messageHandler.openDialog(
  2922. title,
  2923. message,
  2924. true, {},
  2925. function (event, value, message, formVals)
  2926. {
  2927. return false;
  2928. }
  2929. );
  2930. });
  2931. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  2932. messageHandler.openMessageDialog("dialog.sessTerminated",
  2933. "dialog.kickMessage");
  2934. });
  2935. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  2936. //FIXME: use Session Terminated from translation, but
  2937. // 'reason' text comes from XMPP packet and is not translated
  2938. var title = APP.translation.generateTranslationHTML("dialog.sessTerminated");
  2939. messageHandler.openDialog(
  2940. title, reason, true, {},
  2941. function (event, value, message, formVals)
  2942. {
  2943. return false;
  2944. }
  2945. );
  2946. });
  2947. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  2948. messageHandler.showError("dialog.error",
  2949. "dialog.bridgeUnavailable");
  2950. });
  2951. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  2952. Avatar.setUserAvatar(from, id);
  2953. });
  2954. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  2955. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  2956. APP.xmpp.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, onLocalRoleChanged);
  2957. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  2958. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  2959. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  2960. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  2961. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  2962. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  2963. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordRequired);
  2964. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  2965. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  2966. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED,
  2967. onAuthenticationRequired);
  2968. APP.xmpp.addListener(XMPPEvents.DEVICE_AVAILABLE,
  2969. function (resource, devices) {
  2970. VideoLayout.setDeviceAvailabilityIcons(resource, devices);
  2971. });
  2972. APP.xmpp.addListener(XMPPEvents.AUDIO_MUTED, VideoLayout.onAudioMute);
  2973. APP.xmpp.addListener(XMPPEvents.VIDEO_MUTED, VideoLayout.onVideoMute);
  2974. APP.xmpp.addListener(XMPPEvents.AUDIO_MUTED_BY_FOCUS, function(doMuteAudio) {
  2975. UI.setAudioMuted(doMuteAudio);
  2976. });
  2977. APP.members.addListener(MemberEvents.DTMF_SUPPORT_CHANGED,
  2978. onDtmfSupportChanged);
  2979. APP.xmpp.addListener(XMPPEvents.START_MUTED_SETTING_CHANGED, function (audio, video) {
  2980. SettingsMenu.setStartMuted(audio, video);
  2981. });
  2982. APP.xmpp.addListener(XMPPEvents.START_MUTED_FROM_FOCUS, function (audio, video) {
  2983. UI.setInitialMuteFromFocus(audio, video);
  2984. });
  2985. APP.xmpp.addListener(XMPPEvents.JINGLE_FATAL_ERROR, function (session, error) {
  2986. UI.messageHandler.showError("dialog.sorry",
  2987. "dialog.internalError");
  2988. });
  2989. APP.xmpp.addListener(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR, function() {
  2990. messageHandler.showError("dialog.error",
  2991. "dialog.SLDFailure");
  2992. });
  2993. APP.xmpp.addListener(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR, function() {
  2994. messageHandler.showError("dialog.error",
  2995. "dialog.SRDFailure");
  2996. });
  2997. APP.xmpp.addListener(XMPPEvents.CREATE_ANSWER_ERROR, function() {
  2998. messageHandler.showError();
  2999. });
  3000. APP.xmpp.addListener(XMPPEvents.PROMPT_FOR_LOGIN, function() {
  3001. // FIXME: re-use LoginDialog which supports retries
  3002. UI.showLoginPopup(connect);
  3003. });
  3004. APP.xmpp.addListener(XMPPEvents.FOCUS_DISCONNECTED, function(focusComponent, retrySec) {
  3005. UI.messageHandler.notify(
  3006. null, "notify.focus",
  3007. 'disconnected', "notify.focusFail",
  3008. {component: focusComponent, ms: retrySec});
  3009. });
  3010. APP.xmpp.addListener(XMPPEvents.ROOM_JOIN_ERROR, function(pres) {
  3011. UI.messageHandler.openReportDialog(null,
  3012. "dialog.joinError", pres);
  3013. });
  3014. APP.xmpp.addListener(XMPPEvents.ROOM_CONNECT_ERROR, function(pres) {
  3015. UI.messageHandler.openReportDialog(null,
  3016. "dialog.connectError", pres);
  3017. });
  3018. APP.xmpp.addListener(XMPPEvents.READY_TO_JOIN, function() {
  3019. var roomName = UI.generateRoomName();
  3020. APP.xmpp.allocateConferenceFocus(roomName, UI.checkForNicknameAndJoin);
  3021. });
  3022. //NicknameHandler emits this event
  3023. UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  3024. APP.xmpp.addToPresence("displayName", nickname);
  3025. });
  3026. }
  3027. /**
  3028. * Mutes/unmutes the local video.
  3029. *
  3030. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  3031. * @param options an object which specifies optional arguments such as the
  3032. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  3033. * specifies whether the method was initiated in response to a user command (in
  3034. * contrast to an automatic decision taken by the application logic)
  3035. */
  3036. function setVideoMute(mute, options) {
  3037. APP.RTC.setVideoMute(mute,
  3038. UI.setVideoMuteButtonsState,
  3039. options);
  3040. }
  3041. function onResize()
  3042. {
  3043. Chat.resizeChat();
  3044. VideoLayout.resizeLargeVideoContainer();
  3045. }
  3046. function bindEvents()
  3047. {
  3048. /**
  3049. * Resizes and repositions videos in full screen mode.
  3050. */
  3051. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  3052. onResize);
  3053. $(window).resize(onResize);
  3054. }
  3055. UI.start = function (init) {
  3056. document.title = interfaceConfig.APP_NAME;
  3057. if(config.enableWelcomePage && window.location.pathname == "/" &&
  3058. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  3059. {
  3060. $("#videoconference_page").hide();
  3061. var setupWelcomePage = require("./welcome_page/WelcomePage");
  3062. setupWelcomePage();
  3063. return;
  3064. }
  3065. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  3066. var leftWatermarkDiv
  3067. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  3068. leftWatermarkDiv.css({display: 'block'});
  3069. leftWatermarkDiv.parent().get(0).href
  3070. = interfaceConfig.JITSI_WATERMARK_LINK;
  3071. }
  3072. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  3073. var rightWatermarkDiv
  3074. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  3075. rightWatermarkDiv.css({display: 'block'});
  3076. rightWatermarkDiv.parent().get(0).href
  3077. = interfaceConfig.BRAND_WATERMARK_LINK;
  3078. rightWatermarkDiv.get(0).style.backgroundImage
  3079. = "url(images/rightwatermark.png)";
  3080. }
  3081. if (interfaceConfig.SHOW_POWERED_BY) {
  3082. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  3083. }
  3084. $("#welcome_page").hide();
  3085. $("#videospace").mousemove(function () {
  3086. return ToolbarToggler.showToolbar();
  3087. });
  3088. // Set the defaults for prompt dialogs.
  3089. jQuery.prompt.setDefaults({persistent: false});
  3090. VideoLayout.init(eventEmitter);
  3091. AudioLevels.init();
  3092. NicknameHandler.init(eventEmitter);
  3093. registerListeners();
  3094. bindEvents();
  3095. setupPrezi();
  3096. setupToolbars();
  3097. setupChat();
  3098. document.title = interfaceConfig.APP_NAME;
  3099. $("#downloadlog").click(function (event) {
  3100. dump(event.target);
  3101. });
  3102. if(config.enableWelcomePage && window.location.pathname == "/" &&
  3103. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  3104. {
  3105. $("#videoconference_page").hide();
  3106. var setupWelcomePage = require("./welcome_page/WelcomePage");
  3107. setupWelcomePage();
  3108. return;
  3109. }
  3110. $("#welcome_page").hide();
  3111. // Display notice message at the top of the toolbar
  3112. if (config.noticeMessage) {
  3113. $('#noticeText').text(config.noticeMessage);
  3114. $('#notice').css({display: 'block'});
  3115. }
  3116. if (!RTCBrowserType.isIExplorer()) {
  3117. document.getElementById('largeVideo').volume = 0;
  3118. }
  3119. if(config.requireDisplayName) {
  3120. var currentSettings = Settings.getSettings();
  3121. if (!currentSettings.displayName) {
  3122. promptDisplayName();
  3123. }
  3124. }
  3125. init();
  3126. toastr.options = {
  3127. "closeButton": true,
  3128. "debug": false,
  3129. "positionClass": "notification-bottom-right",
  3130. "onclick": null,
  3131. "showDuration": "300",
  3132. "hideDuration": "1000",
  3133. "timeOut": "2000",
  3134. "extendedTimeOut": "1000",
  3135. "showEasing": "swing",
  3136. "hideEasing": "linear",
  3137. "showMethod": "fadeIn",
  3138. "hideMethod": "fadeOut",
  3139. "reposition": function() {
  3140. if(PanelToggler.isVisible()) {
  3141. $("#toast-container").addClass("notification-bottom-right-center");
  3142. } else {
  3143. $("#toast-container").removeClass("notification-bottom-right-center");
  3144. }
  3145. },
  3146. "newestOnTop": false
  3147. };
  3148. SettingsMenu.init();
  3149. };
  3150. function chatAddError(errorMessage, originalText)
  3151. {
  3152. return Chat.chatAddError(errorMessage, originalText);
  3153. };
  3154. function chatSetSubject(text)
  3155. {
  3156. return Chat.chatSetSubject(text);
  3157. };
  3158. function updateChatConversation(from, displayName, message, myjid, stamp) {
  3159. return Chat.updateChatConversation(from, displayName, message, myjid, stamp);
  3160. }
  3161. function onMucJoined(jid, info) {
  3162. Toolbar.updateRoomUrl(window.location.href);
  3163. var meHTML = APP.translation.generateTranslationHTML("me");
  3164. $("#localNick").html(Strophe.getResourceFromJid(jid) + " (" + meHTML + ")");
  3165. var settings = Settings.getSettings();
  3166. // Make sure we configure our avatar id, before creating avatar for us
  3167. Avatar.setUserAvatar(jid, settings.email || settings.uid);
  3168. // Add myself to the contact list.
  3169. ContactList.addContact(jid);
  3170. // Once we've joined the muc show the toolbar
  3171. ToolbarToggler.showToolbar();
  3172. var displayName = !config.displayJids
  3173. ? info.displayName : Strophe.getResourceFromJid(jid);
  3174. if (displayName)
  3175. onDisplayNameChanged('localVideoContainer', displayName);
  3176. VideoLayout.mucJoined();
  3177. }
  3178. function initEtherpad(name) {
  3179. Etherpad.init(name);
  3180. }
  3181. function onMucMemberLeft(jid) {
  3182. console.log('left.muc', jid);
  3183. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  3184. '>.displayname').html();
  3185. messageHandler.notify(displayName,'notify.somebody',
  3186. 'disconnected',
  3187. 'notify.disconnected');
  3188. if(!config.startAudioMuted ||
  3189. config.startAudioMuted > APP.members.size())
  3190. UIUtil.playSoundNotification('userLeft');
  3191. // Need to call this with a slight delay, otherwise the element couldn't be
  3192. // found for some reason.
  3193. // XXX(gp) it works fine without the timeout for me (with Chrome 38).
  3194. window.setTimeout(function () {
  3195. var container = document.getElementById(
  3196. 'participant_' + Strophe.getResourceFromJid(jid));
  3197. if (container) {
  3198. ContactList.removeContact(jid);
  3199. VideoLayout.removeConnectionIndicator(jid);
  3200. // hide here, wait for video to close before removing
  3201. $(container).hide();
  3202. VideoLayout.resizeThumbnails();
  3203. }
  3204. }, 10);
  3205. VideoLayout.participantLeft(jid);
  3206. };
  3207. function onLocalRoleChanged(jid, info, pres, isModerator)
  3208. {
  3209. console.info("My role changed, new role: " + info.role);
  3210. onModeratorStatusChanged(isModerator);
  3211. VideoLayout.showModeratorIndicator();
  3212. SettingsMenu.onRoleChanged();
  3213. if (isModerator) {
  3214. Authentication.closeAuthenticationWindow();
  3215. messageHandler.notify(null, "notify.me",
  3216. 'connected', "notify.moderator");
  3217. }
  3218. }
  3219. function onModeratorStatusChanged(isModerator) {
  3220. Toolbar.showSipCallButton(isModerator);
  3221. Toolbar.showRecordingButton(
  3222. isModerator); //&&
  3223. // FIXME:
  3224. // Recording visible if
  3225. // there are at least 2(+ 1 focus) participants
  3226. //Object.keys(connection.emuc.members).length >= 3);
  3227. }
  3228. function onPasswordRequired(callback) {
  3229. // password is required
  3230. Toolbar.lockLockButton();
  3231. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3232. message += APP.translation.translateString(
  3233. "dialog.passwordRequired");
  3234. message += '</h2>' +
  3235. '<input name="lockKey" type="text" data-i18n=' +
  3236. '"[placeholder]dialog.password" placeholder="' +
  3237. APP.translation.translateString("dialog.password") +
  3238. '" autofocus>';
  3239. messageHandler.openTwoButtonDialog(null, null, null, message,
  3240. true,
  3241. "dialog.Ok",
  3242. function (e, v, m, f) {},
  3243. null,
  3244. function (e, v, m, f) {
  3245. if (v) {
  3246. var lockKey = f.lockKey;
  3247. if (lockKey) {
  3248. Toolbar.setSharedKey(lockKey);
  3249. callback(lockKey);
  3250. }
  3251. }
  3252. },
  3253. ':input:first'
  3254. );
  3255. }
  3256. /**
  3257. * The dialpad button is shown iff there is at least one member that supports
  3258. * DTMF (e.g. jigasi).
  3259. */
  3260. function onDtmfSupportChanged(dtmfSupport) {
  3261. //TODO: enable when the UI is ready
  3262. //Toolbar.showDialPadButton(dtmfSupport);
  3263. }
  3264. function onMucMemberJoined(jid, id, displayName) {
  3265. messageHandler.notify(displayName,'notify.somebody',
  3266. 'connected',
  3267. 'notify.connected');
  3268. if(!config.startAudioMuted ||
  3269. config.startAudioMuted > APP.members.size())
  3270. UIUtil.playSoundNotification('userJoined');
  3271. // Configure avatar
  3272. Avatar.setUserAvatar(jid, id);
  3273. // Add Peer's container
  3274. VideoLayout.ensurePeerContainerExists(jid);
  3275. }
  3276. function onMucPresenceStatus(jid, info) {
  3277. VideoLayout.setPresenceStatus(Strophe.getResourceFromJid(jid), info.status);
  3278. }
  3279. function onMucRoleChanged(role, displayName) {
  3280. VideoLayout.showModeratorIndicator();
  3281. if (role === 'moderator') {
  3282. var messageKey, messageOptions = {};
  3283. if (!displayName) {
  3284. messageKey = "notify.grantedToUnknown";
  3285. }
  3286. else
  3287. {
  3288. messageKey = "notify.grantedTo";
  3289. messageOptions = {to: displayName};
  3290. }
  3291. messageHandler.notify(
  3292. displayName,'notify.somebody',
  3293. 'connected', messageKey,
  3294. messageOptions);
  3295. }
  3296. }
  3297. function onAuthenticationRequired(intervalCallback) {
  3298. Authentication.openAuthenticationDialog(
  3299. roomName, intervalCallback, function () {
  3300. Toolbar.authenticateClicked();
  3301. });
  3302. };
  3303. function onLastNChanged(oldValue, newValue) {
  3304. if (config.muteLocalVideoIfNotInLastN) {
  3305. setVideoMute(!newValue, { 'byUser': false });
  3306. }
  3307. }
  3308. UI.toggleSmileys = function () {
  3309. Chat.toggleSmileys();
  3310. };
  3311. UI.getSettings = function () {
  3312. return Settings.getSettings();
  3313. };
  3314. UI.toggleFilmStrip = function () {
  3315. return BottomToolbar.toggleFilmStrip();
  3316. };
  3317. UI.toggleChat = function () {
  3318. return BottomToolbar.toggleChat();
  3319. };
  3320. UI.toggleContactList = function () {
  3321. return BottomToolbar.toggleContactList();
  3322. };
  3323. UI.inputDisplayNameHandler = function (value) {
  3324. VideoLayout.inputDisplayNameHandler(value);
  3325. };
  3326. UI.getLargeVideoJid = function()
  3327. {
  3328. return VideoLayout.getLargeVideoJid();
  3329. };
  3330. UI.generateRoomName = function() {
  3331. if(roomName)
  3332. return roomName;
  3333. var roomnode = null;
  3334. var path = window.location.pathname;
  3335. // determinde the room node from the url
  3336. // TODO: just the roomnode or the whole bare jid?
  3337. if (config.getroomnode && typeof config.getroomnode === 'function') {
  3338. // custom function might be responsible for doing the pushstate
  3339. roomnode = config.getroomnode(path);
  3340. } else {
  3341. /* fall back to default strategy
  3342. * this is making assumptions about how the URL->room mapping happens.
  3343. * It currently assumes deployment at root, with a rewrite like the
  3344. * following one (for nginx):
  3345. location ~ ^/([a-zA-Z0-9]+)$ {
  3346. rewrite ^/(.*)$ / break;
  3347. }
  3348. */
  3349. if (path.length > 1) {
  3350. roomnode = path.substr(1).toLowerCase();
  3351. } else {
  3352. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  3353. roomnode = word.toLowerCase();
  3354. window.history.pushState('VideoChat',
  3355. 'Room: ' + word, window.location.pathname + word);
  3356. }
  3357. }
  3358. roomName = roomnode + '@' + config.hosts.muc;
  3359. return roomName;
  3360. };
  3361. UI.connectionIndicatorShowMore = function(jid)
  3362. {
  3363. return VideoLayout.showMore(jid);
  3364. };
  3365. UI.showLoginPopup = function(callback)
  3366. {
  3367. console.log('password is required');
  3368. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3369. message += APP.translation.translateString(
  3370. "dialog.passwordRequired");
  3371. message += '</h2>' +
  3372. '<input name="username" type="text" ' +
  3373. 'placeholder="user@domain.net" autofocus>' +
  3374. '<input name="password" ' +
  3375. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  3376. ' placeholder="user password">';
  3377. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  3378. true,
  3379. "dialog.Ok",
  3380. function (e, v, m, f) {
  3381. if (v) {
  3382. if (f.username !== null && f.password != null) {
  3383. callback(f.username, f.password);
  3384. }
  3385. }
  3386. },
  3387. null, null, ':input:first'
  3388. );
  3389. }
  3390. UI.checkForNicknameAndJoin = function () {
  3391. Authentication.closeAuthenticationDialog();
  3392. Authentication.stopInterval();
  3393. var nick = null;
  3394. if (config.useNicks) {
  3395. nick = window.prompt('Your nickname (optional)');
  3396. }
  3397. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  3398. };
  3399. function dump(elem, filename) {
  3400. elem = elem.parentNode;
  3401. elem.download = filename || 'meetlog.json';
  3402. elem.href = 'data:application/json;charset=utf-8,\n';
  3403. var data = APP.xmpp.populateData();
  3404. var metadata = {};
  3405. metadata.time = new Date();
  3406. metadata.url = window.location.href;
  3407. metadata.ua = navigator.userAgent;
  3408. var log = APP.xmpp.getLogger();
  3409. if (log) {
  3410. metadata.xmpp = log;
  3411. }
  3412. data.metadata = metadata;
  3413. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  3414. return false;
  3415. }
  3416. UI.getRoomName = function () {
  3417. return roomName;
  3418. };
  3419. UI.setInitialMuteFromFocus = function (muteAudio, muteVideo) {
  3420. if(muteAudio || muteVideo) notifyForInitialMute();
  3421. if(muteAudio) UI.setAudioMuted(true);
  3422. if(muteVideo) UI.setVideoMute(true);
  3423. }
  3424. /**
  3425. * Mutes/unmutes the local video.
  3426. */
  3427. UI.toggleVideo = function () {
  3428. setVideoMute(!APP.RTC.localVideo.isMuted());
  3429. };
  3430. /**
  3431. * Mutes / unmutes audio for the local participant.
  3432. */
  3433. UI.toggleAudio = function() {
  3434. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  3435. };
  3436. /**
  3437. * Sets muted audio state for the local participant.
  3438. */
  3439. UI.setAudioMuted = function (mute, earlyMute) {
  3440. var audioMute = null;
  3441. if(earlyMute)
  3442. audioMute = function (mute, cb) {
  3443. return APP.xmpp.sendAudioInfoPresence(mute, cb);
  3444. };
  3445. else
  3446. audioMute = function (mute, cb) {
  3447. return APP.xmpp.setAudioMute(mute, cb);
  3448. }
  3449. if(!audioMute(mute, function () {
  3450. VideoLayout.showLocalAudioIndicator(mute);
  3451. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  3452. }))
  3453. {
  3454. // We still click the button.
  3455. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  3456. return;
  3457. }
  3458. }
  3459. UI.addListener = function (type, listener) {
  3460. eventEmitter.on(type, listener);
  3461. }
  3462. UI.clickOnVideo = function (videoNumber) {
  3463. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  3464. if (remoteVideos.length > videoNumber) {
  3465. remoteVideos[videoNumber].click();
  3466. }
  3467. }
  3468. //Used by torture
  3469. UI.showToolbar = function () {
  3470. return ToolbarToggler.showToolbar();
  3471. }
  3472. //Used by torture
  3473. UI.dockToolbar = function (isDock) {
  3474. return ToolbarToggler.dockToolbar(isDock);
  3475. }
  3476. UI.setVideoMuteButtonsState = function (mute) {
  3477. var video = $('#video');
  3478. var communicativeClass = "icon-camera";
  3479. var muteClass = "icon-camera icon-camera-disabled";
  3480. if (mute) {
  3481. video.removeClass(communicativeClass);
  3482. video.addClass(muteClass);
  3483. } else {
  3484. video.removeClass(muteClass);
  3485. video.addClass(communicativeClass);
  3486. }
  3487. }
  3488. UI.userAvatarChanged = function (resourceJid, thumbUrl, contactListUrl) {
  3489. VideoLayout.userAvatarChanged(resourceJid, thumbUrl);
  3490. ContactList.userAvatarChanged(resourceJid, contactListUrl);
  3491. if(resourceJid === APP.xmpp.myResource())
  3492. SettingsMenu.changeAvatar(thumbUrl);
  3493. }
  3494. UI.setVideoMute = setVideoMute;
  3495. module.exports = UI;
  3496. },{"../../service/RTC/RTCEvents":99,"../../service/RTC/StreamEventTypes":101,"../../service/UI/UIEvents":102,"../../service/connectionquality/CQEvents":104,"../../service/desktopsharing/DesktopSharingEventTypes":105,"../../service/members/Events":106,"../../service/xmpp/XMPPEvents":108,"../RTC/RTCBrowserType":8,"./../settings/Settings":47,"./audio_levels/AudioLevels.js":12,"./authentication/Authentication":14,"./avatar/Avatar":16,"./etherpad/Etherpad.js":17,"./prezi/Prezi.js":18,"./side_pannels/SidePanelToggler":20,"./side_pannels/chat/Chat.js":21,"./side_pannels/contactlist/ContactList":25,"./side_pannels/settings/SettingsMenu":26,"./toolbars/BottomToolbar":27,"./toolbars/Toolbar":28,"./toolbars/ToolbarToggler":29,"./util/MessageHandler":31,"./util/NicknameHandler":32,"./util/UIUtil":33,"./videolayout/VideoLayout.js":39,"./welcome_page/RoomnameGenerator":40,"./welcome_page/WelcomePage":41,"events":109}],12:[function(require,module,exports){
  3497. var CanvasUtil = require("./CanvasUtils");
  3498. var ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  3499. function initActiveSpeakerAudioLevels() {
  3500. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  3501. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  3502. // Draw a circle.
  3503. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  3504. // Add a shadow around the circle
  3505. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  3506. ASDrawContext.shadowOffsetX = 0;
  3507. ASDrawContext.shadowOffsetY = 0;
  3508. }
  3509. /**
  3510. * The audio Levels plugin.
  3511. */
  3512. var AudioLevels = (function(my) {
  3513. var audioLevelCanvasCache = {};
  3514. my.LOCAL_LEVEL = 'local';
  3515. my.init = function () {
  3516. initActiveSpeakerAudioLevels();
  3517. }
  3518. /**
  3519. * Updates the audio level canvas for the given peerJid. If the canvas
  3520. * didn't exist we create it.
  3521. */
  3522. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  3523. var resourceJid = null;
  3524. var videoSpanId = null;
  3525. if (!peerJid)
  3526. videoSpanId = 'localVideoContainer';
  3527. else {
  3528. resourceJid = Strophe.getResourceFromJid(peerJid);
  3529. videoSpanId = 'participant_' + resourceJid;
  3530. }
  3531. var videoSpan = document.getElementById(videoSpanId);
  3532. if (!videoSpan) {
  3533. if (resourceJid)
  3534. console.error("No video element for jid", resourceJid);
  3535. else
  3536. console.error("No video element for local video.");
  3537. return;
  3538. }
  3539. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  3540. var videoSpaceWidth = $('#remoteVideos').width();
  3541. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  3542. var thumbnailWidth = thumbnailSize[0];
  3543. var thumbnailHeight = thumbnailSize[1];
  3544. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  3545. audioLevelCanvas = document.createElement('canvas');
  3546. audioLevelCanvas.className = "audiolevel";
  3547. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3548. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3549. resizeAudioLevelCanvas( audioLevelCanvas,
  3550. thumbnailWidth,
  3551. thumbnailHeight);
  3552. videoSpan.appendChild(audioLevelCanvas);
  3553. } else {
  3554. audioLevelCanvas = audioLevelCanvas.get(0);
  3555. resizeAudioLevelCanvas( audioLevelCanvas,
  3556. thumbnailWidth,
  3557. thumbnailHeight);
  3558. }
  3559. };
  3560. /**
  3561. * Updates the audio level UI for the given resourceJid.
  3562. *
  3563. * @param resourceJid the resource jid indicating the video element for
  3564. * which we draw the audio level
  3565. * @param audioLevel the newAudio level to render
  3566. */
  3567. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  3568. drawAudioLevelCanvas(resourceJid, audioLevel);
  3569. var videoSpanId = getVideoSpanId(resourceJid);
  3570. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  3571. if (!audioLevelCanvas)
  3572. return;
  3573. var drawContext = audioLevelCanvas.getContext('2d');
  3574. var canvasCache = audioLevelCanvasCache[resourceJid];
  3575. drawContext.clearRect (0, 0,
  3576. audioLevelCanvas.width, audioLevelCanvas.height);
  3577. drawContext.drawImage(canvasCache, 0, 0);
  3578. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  3579. if(!APP.xmpp.myJid()) {
  3580. return;
  3581. }
  3582. resourceJid = APP.xmpp.myResource();
  3583. }
  3584. if(resourceJid === largeVideoResourceJid) {
  3585. window.requestAnimationFrame(function () {
  3586. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  3587. });
  3588. }
  3589. };
  3590. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  3591. if($("#activeSpeaker").css("visibility") == "hidden")
  3592. return;
  3593. ASDrawContext.clearRect(0, 0, 300, 300);
  3594. if(audioLevel == 0)
  3595. return;
  3596. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  3597. // Fill the shape.
  3598. ASDrawContext.fill();
  3599. };
  3600. /**
  3601. * Resizes the given audio level canvas to match the given thumbnail size.
  3602. */
  3603. function resizeAudioLevelCanvas(audioLevelCanvas,
  3604. thumbnailWidth,
  3605. thumbnailHeight) {
  3606. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  3607. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  3608. }
  3609. /**
  3610. * Draws the audio level canvas into the cached canvas object.
  3611. *
  3612. * @param resourceJid the resource jid indicating the video element for
  3613. * which we draw the audio level
  3614. * @param audioLevel the newAudio level to render
  3615. */
  3616. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  3617. if (!audioLevelCanvasCache[resourceJid]) {
  3618. var videoSpanId = getVideoSpanId(resourceJid);
  3619. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  3620. /*
  3621. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  3622. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  3623. * error. Since audio levels are frequently updated, the errors have
  3624. * been observed to pile into the console, strain the CPU.
  3625. */
  3626. if (audioLevelCanvasOrig)
  3627. {
  3628. audioLevelCanvasCache[resourceJid]
  3629. = CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  3630. }
  3631. }
  3632. var canvas = audioLevelCanvasCache[resourceJid];
  3633. if (!canvas)
  3634. return;
  3635. var drawContext = canvas.getContext('2d');
  3636. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  3637. var shadowLevel = getShadowLevel(audioLevel);
  3638. if (shadowLevel > 0)
  3639. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  3640. CanvasUtil.drawRoundRectGlow( drawContext,
  3641. interfaceConfig.CANVAS_EXTRA/2, interfaceConfig.CANVAS_EXTRA/2,
  3642. canvas.width - interfaceConfig.CANVAS_EXTRA,
  3643. canvas.height - interfaceConfig.CANVAS_EXTRA,
  3644. interfaceConfig.CANVAS_RADIUS,
  3645. interfaceConfig.SHADOW_COLOR,
  3646. shadowLevel);
  3647. }
  3648. /**
  3649. * Returns the shadow/glow level for the given audio level.
  3650. *
  3651. * @param audioLevel the audio level from which we determine the shadow
  3652. * level
  3653. */
  3654. function getShadowLevel (audioLevel) {
  3655. var shadowLevel = 0;
  3656. if (audioLevel <= 0.3) {
  3657. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  3658. }
  3659. else if (audioLevel <= 0.6) {
  3660. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  3661. }
  3662. else {
  3663. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  3664. }
  3665. return shadowLevel;
  3666. }
  3667. /**
  3668. * Returns the video span id corresponding to the given resourceJid or local
  3669. * user.
  3670. */
  3671. function getVideoSpanId(resourceJid) {
  3672. var videoSpanId = null;
  3673. if (resourceJid === AudioLevels.LOCAL_LEVEL
  3674. || (APP.xmpp.myResource() && resourceJid
  3675. === APP.xmpp.myResource()))
  3676. videoSpanId = 'localVideoContainer';
  3677. else
  3678. videoSpanId = 'participant_' + resourceJid;
  3679. return videoSpanId;
  3680. }
  3681. /**
  3682. * Indicates that the remote video has been resized.
  3683. */
  3684. $(document).bind('remotevideo.resized', function (event, width, height) {
  3685. var resized = false;
  3686. $('#remoteVideos>span>canvas').each(function() {
  3687. var canvas = $(this).get(0);
  3688. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  3689. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  3690. resized = true;
  3691. }
  3692. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  3693. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  3694. resized = true;
  3695. }
  3696. });
  3697. if (resized)
  3698. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  3699. audioLevelCanvasCache[resourceJid].width
  3700. = width + interfaceConfig.CANVAS_EXTRA;
  3701. audioLevelCanvasCache[resourceJid].height
  3702. = height + interfaceConfig.CANVAS_EXTRA;
  3703. });
  3704. });
  3705. return my;
  3706. })(AudioLevels || {});
  3707. module.exports = AudioLevels;
  3708. },{"./CanvasUtils":13}],13:[function(require,module,exports){
  3709. /**
  3710. * Utility class for drawing canvas shapes.
  3711. */
  3712. var CanvasUtil = (function(my) {
  3713. /**
  3714. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  3715. * of the glow.
  3716. *
  3717. * @param drawContext the context of the canvas to draw to
  3718. * @param x the x coordinate of the round rectangle
  3719. * @param y the y coordinate of the round rectangle
  3720. * @param w the width of the round rectangle
  3721. * @param h the height of the round rectangle
  3722. * @param glowColor the color of the glow
  3723. * @param glowWidth the width of the glow
  3724. */
  3725. my.drawRoundRectGlow
  3726. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  3727. // Save the previous state of the context.
  3728. drawContext.save();
  3729. if (w < 2 * r) r = w / 2;
  3730. if (h < 2 * r) r = h / 2;
  3731. // Draw a round rectangle.
  3732. drawContext.beginPath();
  3733. drawContext.moveTo(x+r, y);
  3734. drawContext.arcTo(x+w, y, x+w, y+h, r);
  3735. drawContext.arcTo(x+w, y+h, x, y+h, r);
  3736. drawContext.arcTo(x, y+h, x, y, r);
  3737. drawContext.arcTo(x, y, x+w, y, r);
  3738. drawContext.closePath();
  3739. // Add a shadow around the rectangle
  3740. drawContext.shadowColor = glowColor;
  3741. drawContext.shadowBlur = glowWidth;
  3742. drawContext.shadowOffsetX = 0;
  3743. drawContext.shadowOffsetY = 0;
  3744. // Fill the shape.
  3745. drawContext.fill();
  3746. drawContext.save();
  3747. drawContext.restore();
  3748. // 1) Uncomment this line to use Composite Operation, which is doing the
  3749. // same as the clip function below and is also antialiasing the round
  3750. // border, but is said to be less fast performance wise.
  3751. // drawContext.globalCompositeOperation='destination-out';
  3752. drawContext.beginPath();
  3753. drawContext.moveTo(x+r, y);
  3754. drawContext.arcTo(x+w, y, x+w, y+h, r);
  3755. drawContext.arcTo(x+w, y+h, x, y+h, r);
  3756. drawContext.arcTo(x, y+h, x, y, r);
  3757. drawContext.arcTo(x, y, x+w, y, r);
  3758. drawContext.closePath();
  3759. // 2) Uncomment this line to use Composite Operation, which is doing the
  3760. // same as the clip function below and is also antialiasing the round
  3761. // border, but is said to be less fast performance wise.
  3762. // drawContext.fill();
  3763. // Comment these two lines if choosing to do the same with composite
  3764. // operation above 1 and 2.
  3765. drawContext.clip();
  3766. drawContext.clearRect(0, 0, 277, 200);
  3767. // Restore the previous context state.
  3768. drawContext.restore();
  3769. };
  3770. /**
  3771. * Clones the given canvas.
  3772. *
  3773. * @return the new cloned canvas.
  3774. */
  3775. my.cloneCanvas = function (oldCanvas) {
  3776. /*
  3777. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  3778. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  3779. * levels are frequently updated, the errors have been observed to pile
  3780. * into the console, strain the CPU.
  3781. */
  3782. if (!oldCanvas)
  3783. return oldCanvas;
  3784. //create a new canvas
  3785. var newCanvas = document.createElement('canvas');
  3786. var context = newCanvas.getContext('2d');
  3787. //set dimensions
  3788. newCanvas.width = oldCanvas.width;
  3789. newCanvas.height = oldCanvas.height;
  3790. //apply the old canvas to the new one
  3791. context.drawImage(oldCanvas, 0, 0);
  3792. //return the new canvas
  3793. return newCanvas;
  3794. };
  3795. return my;
  3796. })(CanvasUtil || {});
  3797. module.exports = CanvasUtil;
  3798. },{}],14:[function(require,module,exports){
  3799. /* global $, APP*/
  3800. var LoginDialog = require('./LoginDialog');
  3801. var Moderator = require('../../xmpp/moderator');
  3802. /* Initial "authentication required" dialog */
  3803. var authDialog = null;
  3804. /* Loop retry ID that wits for other user to create the room */
  3805. var authRetryId = null;
  3806. var authenticationWindow = null;
  3807. var Authentication = {
  3808. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  3809. // This is the loop that will wait for the room to be created by
  3810. // someone else. 'auth_required.moderator' will bring us back here.
  3811. authRetryId = window.setTimeout(intervalCallback, 5000);
  3812. // Show prompt only if it's not open
  3813. if (authDialog !== null) {
  3814. return;
  3815. }
  3816. // extract room name from 'room@muc.server.net'
  3817. var room = roomName.substr(0, roomName.indexOf('@'));
  3818. var title
  3819. = APP.translation.generateTranslationHTML("dialog.WaitingForHost");
  3820. var msg
  3821. = APP.translation.generateTranslationHTML(
  3822. "dialog.WaitForHostMsg", {room: room});
  3823. var buttonTxt
  3824. = APP.translation.generateTranslationHTML("dialog.IamHost");
  3825. var buttons = [];
  3826. buttons.push({title: buttonTxt, value: "authNow"});
  3827. authDialog = APP.UI.messageHandler.openDialog(
  3828. title,
  3829. msg,
  3830. true,
  3831. buttons,
  3832. function (onSubmitEvent, submitValue) {
  3833. // Do not close the dialog yet
  3834. onSubmitEvent.preventDefault();
  3835. // Open login popup
  3836. if (submitValue === 'authNow') {
  3837. callback();
  3838. }
  3839. }
  3840. );
  3841. },
  3842. closeAuthenticationWindow: function () {
  3843. if (authenticationWindow) {
  3844. authenticationWindow.close();
  3845. authenticationWindow = null;
  3846. }
  3847. },
  3848. xmppAuthenticate: function () {
  3849. var loginDialog = LoginDialog.show(
  3850. function (connection, state) {
  3851. if (!state) {
  3852. // User cancelled
  3853. loginDialog.close();
  3854. return;
  3855. } else if (state == APP.xmpp.Status.CONNECTED) {
  3856. loginDialog.close();
  3857. Authentication.stopInterval();
  3858. Authentication.closeAuthenticationDialog();
  3859. // Close the connection as anonymous one will be used
  3860. // to create the conference. Session-id will authorize
  3861. // the request.
  3862. connection.disconnect();
  3863. var roomName = APP.UI.generateRoomName();
  3864. Moderator.allocateConferenceFocus(roomName, function () {
  3865. // If it's not "on the fly" authentication now join
  3866. // the conference room
  3867. if (!APP.xmpp.getMUCJoined()) {
  3868. APP.UI.checkForNicknameAndJoin();
  3869. }
  3870. });
  3871. }
  3872. }, true);
  3873. },
  3874. focusAuthenticationWindow: function () {
  3875. // If auth window exists just bring it to the front
  3876. if (authenticationWindow) {
  3877. authenticationWindow.focus();
  3878. return;
  3879. }
  3880. },
  3881. closeAuthenticationDialog: function () {
  3882. // Close authentication dialog if opened
  3883. if (authDialog) {
  3884. authDialog.close();
  3885. authDialog = null;
  3886. }
  3887. },
  3888. createAuthenticationWindow: function (callback, url) {
  3889. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  3890. url, 910, 660,
  3891. // On closed
  3892. function () {
  3893. // Close authentication dialog if opened
  3894. Authentication.closeAuthenticationDialog();
  3895. callback();
  3896. authenticationWindow = null;
  3897. });
  3898. return authenticationWindow;
  3899. },
  3900. stopInterval: function () {
  3901. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  3902. if (authRetryId) {
  3903. window.clearTimeout(authRetryId);
  3904. authRetryId = null;
  3905. }
  3906. }
  3907. };
  3908. module.exports = Authentication;
  3909. },{"../../xmpp/moderator":58,"./LoginDialog":15}],15:[function(require,module,exports){
  3910. /* global $, APP, config*/
  3911. var XMPP = require('../../xmpp/xmpp');
  3912. var Moderator = require('../../xmpp/moderator');
  3913. //FIXME: use LoginDialog to add retries to XMPP.connect method used when
  3914. // anonymous domain is not enabled
  3915. /**
  3916. * Creates new <tt>Dialog</tt> instance.
  3917. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt> called
  3918. * when we either fail to connect or succeed(check Strophe.Status).
  3919. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to Jicofo
  3920. * in order to create session-id after the connection is established.
  3921. * @constructor
  3922. */
  3923. function Dialog(callback, obtainSession) {
  3924. var self = this;
  3925. var stop = false;
  3926. var connection = APP.xmpp.createConnection();
  3927. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3928. message += APP.translation.translateString("dialog.passwordRequired");
  3929. message += '</h2>' +
  3930. '<input name="username" type="text" ' +
  3931. 'placeholder="user@domain.net" autofocus>' +
  3932. '<input name="password" ' +
  3933. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  3934. ' placeholder="user password">';
  3935. var okButton = APP.translation.generateTranslationHTML("dialog.Ok");
  3936. var cancelButton = APP.translation.generateTranslationHTML("dialog.Cancel");
  3937. var states = {
  3938. login: {
  3939. html: message,
  3940. buttons: [
  3941. { title: okButton, value: true},
  3942. { title: cancelButton, value: false}
  3943. ],
  3944. focus: ':input:first',
  3945. submit: function (e, v, m, f) {
  3946. e.preventDefault();
  3947. if (v) {
  3948. var jid = f.username;
  3949. var password = f.password;
  3950. if (jid && password) {
  3951. stop = false;
  3952. connection.reset();
  3953. connDialog.goToState('connecting');
  3954. connection.connect(jid, password, stateHandler);
  3955. }
  3956. } else {
  3957. // User cancelled
  3958. stop = true;
  3959. callback();
  3960. }
  3961. }
  3962. },
  3963. connecting: {
  3964. title: APP.translation.translateString('dialog.connecting'),
  3965. html: '<div id="connectionStatus"></div>',
  3966. buttons: [],
  3967. defaultButton: 0
  3968. },
  3969. finished: {
  3970. title: APP.translation.translateString('dialog.error'),
  3971. html: '<div id="errorMessage"></div>',
  3972. buttons: [
  3973. {
  3974. title: APP.translation.translateString('dialog.retry'),
  3975. value: 'retry'
  3976. },
  3977. {
  3978. title: APP.translation.translateString('dialog.Cancel'),
  3979. value: 'cancel'
  3980. },
  3981. ],
  3982. defaultButton: 0,
  3983. submit: function (e, v, m, f) {
  3984. e.preventDefault();
  3985. if (v === 'retry')
  3986. connDialog.goToState('login');
  3987. else
  3988. callback();
  3989. }
  3990. }
  3991. };
  3992. var connDialog
  3993. = APP.UI.messageHandler.openDialogWithStates(states,
  3994. { persistent: true, closeText: '' }, null);
  3995. var stateHandler = function (status, message) {
  3996. if (stop) {
  3997. return;
  3998. }
  3999. var translateKey = "connection." + XMPP.getStatusString(status);
  4000. var statusStr = APP.translation.translateString(translateKey);
  4001. // Display current state
  4002. var connectionStatus =
  4003. connDialog.getState('connecting').find('#connectionStatus');
  4004. connectionStatus.text(statusStr);
  4005. switch (status) {
  4006. case XMPP.Status.CONNECTED:
  4007. stop = true;
  4008. if (!obtainSession) {
  4009. callback(connection, status);
  4010. return;
  4011. }
  4012. // Obtaining session-id status
  4013. connectionStatus.text(
  4014. APP.translation.translateString(
  4015. 'connection.FETCH_SESSION_ID'));
  4016. // Authenticate with Jicofo and obtain session-id
  4017. var roomName = APP.UI.generateRoomName();
  4018. // Jicofo will return new session-id when connected
  4019. // from authenticated domain
  4020. connection.sendIQ(
  4021. Moderator.createConferenceIq(roomName),
  4022. function (result) {
  4023. connectionStatus.text(
  4024. APP.translation.translateString(
  4025. 'connection.GOT_SESSION_ID'));
  4026. stop = true;
  4027. // Parse session-id
  4028. Moderator.parseSessionId(result);
  4029. callback(connection, status);
  4030. },
  4031. function (error) {
  4032. console.error("Auth on the fly failed", error);
  4033. stop = true;
  4034. var errorMsg =
  4035. APP.translation.translateString(
  4036. 'connection.GET_SESSION_ID_ERROR') +
  4037. $(error).find('>error').attr('code');
  4038. self.displayError(errorMsg);
  4039. connection.disconnect();
  4040. });
  4041. break;
  4042. case XMPP.Status.AUTHFAIL:
  4043. case XMPP.Status.CONNFAIL:
  4044. case XMPP.Status.DISCONNECTED:
  4045. stop = true;
  4046. callback(connection, status);
  4047. var errorMessage = statusStr;
  4048. if (message)
  4049. {
  4050. errorMessage += ': ' + message;
  4051. }
  4052. self.displayError(errorMessage);
  4053. break;
  4054. default:
  4055. break;
  4056. }
  4057. };
  4058. /**
  4059. * Displays error message in 'finished' state which allows either to cancel
  4060. * or retry.
  4061. * @param message the final message to be displayed.
  4062. */
  4063. this.displayError = function (message) {
  4064. var finishedState = connDialog.getState('finished');
  4065. var errorMessageElem = finishedState.find('#errorMessage');
  4066. errorMessageElem.text(message);
  4067. connDialog.goToState('finished');
  4068. };
  4069. /**
  4070. * Closes LoginDialog.
  4071. */
  4072. this.close = function () {
  4073. stop = true;
  4074. connDialog.close();
  4075. };
  4076. }
  4077. var LoginDialog = {
  4078. /**
  4079. * Displays login prompt used to establish new XMPP connection. Given
  4080. * <tt>callback(Strophe.Connection, Strophe.Status)</tt> function will be
  4081. * called when we connect successfully(status === CONNECTED) or when we fail
  4082. * to do so. On connection failure program can call Dialog.close() method in
  4083. * order to cancel or do nothing to let the user retry.
  4084. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt>
  4085. * called when we either fail to connect or succeed(check
  4086. * Strophe.Status).
  4087. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to
  4088. * Jicofo in order to create session-id after the connection is
  4089. * established.
  4090. * @returns {Dialog}
  4091. */
  4092. show: function (callback, obtainSession) {
  4093. return new Dialog(callback, obtainSession);
  4094. }
  4095. };
  4096. module.exports = LoginDialog;
  4097. },{"../../xmpp/moderator":58,"../../xmpp/xmpp":66}],16:[function(require,module,exports){
  4098. var Settings = require("../../settings/Settings");
  4099. var users = {};
  4100. var Avatar = {
  4101. /**
  4102. * Sets the user's avatar in the settings menu(if local user), contact list
  4103. * and thumbnail
  4104. * @param jid jid of the user
  4105. * @param id email or userID to be used as a hash
  4106. */
  4107. setUserAvatar: function (jid, id) {
  4108. if (id) {
  4109. if (users[jid] === id) {
  4110. return;
  4111. }
  4112. users[jid] = id;
  4113. }
  4114. var thumbUrl = this.getThumbUrl(jid);
  4115. var contactListUrl = this.getContactListUrl(jid);
  4116. var resourceJid = Strophe.getResourceFromJid(jid);
  4117. APP.UI.userAvatarChanged(resourceJid, thumbUrl, contactListUrl);
  4118. },
  4119. /**
  4120. * Returns image URL for the avatar to be displayed on large video area
  4121. * where current active speaker is presented.
  4122. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4123. */
  4124. getActiveSpeakerUrl: function (jid) {
  4125. return this.getGravatarUrl(jid, 100);
  4126. },
  4127. /**
  4128. * Returns image URL for the avatar to be displayed on small video thumbnail
  4129. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4130. */
  4131. getThumbUrl: function (jid) {
  4132. return this.getGravatarUrl(jid, 100);
  4133. },
  4134. /**
  4135. * Returns the URL for the avatar to be displayed as contactlist item
  4136. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4137. */
  4138. getContactListUrl: function (jid) {
  4139. return this.getGravatarUrl(jid, 30);
  4140. },
  4141. getGravatarUrl: function (jid, size) {
  4142. if (!jid) {
  4143. console.error("Get gravatar - jid is undefined");
  4144. return null;
  4145. }
  4146. var id = users[jid];
  4147. if (!id) {
  4148. console.warn("No avatar stored yet for " + jid);
  4149. return null;
  4150. }
  4151. return 'https://www.gravatar.com/avatar/' +
  4152. MD5.hexdigest(id.trim().toLowerCase()) +
  4153. "?d=wavatar&size=" + (size || "30");
  4154. }
  4155. };
  4156. module.exports = Avatar;
  4157. },{"../../settings/Settings":47}],17:[function(require,module,exports){
  4158. /* global $, config,
  4159. setLargeVideoVisible, Util */
  4160. var VideoLayout = require("../videolayout/VideoLayout");
  4161. var Prezi = require("../prezi/Prezi");
  4162. var UIUtil = require("../util/UIUtil");
  4163. var etherpadName = null;
  4164. var etherpadIFrame = null;
  4165. var domain = null;
  4166. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  4167. /**
  4168. * Resizes the etherpad.
  4169. */
  4170. function resize() {
  4171. if ($('#etherpad>iframe').length) {
  4172. var remoteVideos = $('#remoteVideos');
  4173. var availableHeight
  4174. = window.innerHeight - remoteVideos.outerHeight();
  4175. var availableWidth = UIUtil.getAvailableVideoWidth();
  4176. $('#etherpad>iframe').width(availableWidth);
  4177. $('#etherpad>iframe').height(availableHeight);
  4178. }
  4179. }
  4180. /**
  4181. * Creates the Etherpad button and adds it to the toolbar.
  4182. */
  4183. function enableEtherpadButton() {
  4184. if (!$('#etherpadButton').is(":visible"))
  4185. $('#etherpadButton').css({display: 'inline-block'});
  4186. }
  4187. /**
  4188. * Creates the IFrame for the etherpad.
  4189. */
  4190. function createIFrame() {
  4191. etherpadIFrame = document.createElement('iframe');
  4192. etherpadIFrame.src = domain + etherpadName + options;
  4193. etherpadIFrame.frameBorder = 0;
  4194. etherpadIFrame.scrolling = "no";
  4195. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  4196. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  4197. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  4198. document.getElementById('etherpad').appendChild(etherpadIFrame);
  4199. etherpadIFrame.onload = function() {
  4200. document.domain = document.domain;
  4201. bubbleIframeMouseMove(etherpadIFrame);
  4202. setTimeout(function() {
  4203. // the iframes inside of the etherpad are
  4204. // not yet loaded when the etherpad iframe is loaded
  4205. var outer = etherpadIFrame.
  4206. contentDocument.getElementsByName("ace_outer")[0];
  4207. bubbleIframeMouseMove(outer);
  4208. var inner = outer.
  4209. contentDocument.getElementsByName("ace_inner")[0];
  4210. bubbleIframeMouseMove(inner);
  4211. }, 2000);
  4212. };
  4213. }
  4214. function bubbleIframeMouseMove(iframe){
  4215. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  4216. iframe.contentWindow.onmousemove = function(e){
  4217. if(existingOnMouseMove) existingOnMouseMove(e);
  4218. var evt = document.createEvent("MouseEvents");
  4219. var boundingClientRect = iframe.getBoundingClientRect();
  4220. evt.initMouseEvent(
  4221. "mousemove",
  4222. true, // bubbles
  4223. false, // not cancelable
  4224. window,
  4225. e.detail,
  4226. e.screenX,
  4227. e.screenY,
  4228. e.clientX + boundingClientRect.left,
  4229. e.clientY + boundingClientRect.top,
  4230. e.ctrlKey,
  4231. e.altKey,
  4232. e.shiftKey,
  4233. e.metaKey,
  4234. e.button,
  4235. null // no related element
  4236. );
  4237. iframe.dispatchEvent(evt);
  4238. };
  4239. }
  4240. /**
  4241. * On video selected event.
  4242. */
  4243. $(document).bind('video.selected', function (event, isPresentation) {
  4244. if (config.etherpad_base && etherpadIFrame && etherpadIFrame.style.visibility !== 'hidden')
  4245. Etherpad.toggleEtherpad(isPresentation);
  4246. });
  4247. var Etherpad = {
  4248. /**
  4249. * Initializes the etherpad.
  4250. */
  4251. init: function (name) {
  4252. if (config.etherpad_base && !etherpadName && name) {
  4253. domain = config.etherpad_base;
  4254. etherpadName = name;
  4255. enableEtherpadButton();
  4256. /**
  4257. * Resizes the etherpad, when the window is resized.
  4258. */
  4259. $(window).resize(function () {
  4260. resize();
  4261. });
  4262. }
  4263. },
  4264. /**
  4265. * Opens/hides the Etherpad.
  4266. */
  4267. toggleEtherpad: function (isPresentation) {
  4268. if (!etherpadIFrame)
  4269. createIFrame();
  4270. var largeVideo = null;
  4271. if (Prezi.isPresentationVisible())
  4272. largeVideo = $('#presentation>iframe');
  4273. else
  4274. largeVideo = $('#largeVideo');
  4275. if ($('#etherpad>iframe').css('visibility') === 'hidden') {
  4276. $('#activeSpeaker').css('visibility', 'hidden');
  4277. largeVideo.fadeOut(300, function () {
  4278. if (Prezi.isPresentationVisible()) {
  4279. largeVideo.css({opacity: '0'});
  4280. } else {
  4281. VideoLayout.setLargeVideoVisible(false);
  4282. }
  4283. });
  4284. $('#etherpad>iframe').fadeIn(300, function () {
  4285. document.body.style.background = '#eeeeee';
  4286. $('#etherpad>iframe').css({visibility: 'visible'});
  4287. $('#etherpad').css({zIndex: 2});
  4288. });
  4289. }
  4290. else if ($('#etherpad>iframe')) {
  4291. $('#etherpad>iframe').fadeOut(300, function () {
  4292. $('#etherpad>iframe').css({visibility: 'hidden'});
  4293. $('#etherpad').css({zIndex: 0});
  4294. document.body.style.background = 'black';
  4295. });
  4296. if (!isPresentation) {
  4297. $('#largeVideo').fadeIn(300, function () {
  4298. VideoLayout.setLargeVideoVisible(true);
  4299. });
  4300. }
  4301. }
  4302. resize();
  4303. },
  4304. isVisible: function() {
  4305. var etherpadIframe = $('#etherpad>iframe');
  4306. return etherpadIframe && etherpadIframe.is(':visible');
  4307. }
  4308. };
  4309. module.exports = Etherpad;
  4310. },{"../prezi/Prezi":18,"../util/UIUtil":33,"../videolayout/VideoLayout":39}],18:[function(require,module,exports){
  4311. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  4312. var UIUtil = require("../util/UIUtil");
  4313. var VideoLayout = require("../videolayout/VideoLayout");
  4314. var messageHandler = require("../util/MessageHandler");
  4315. var PreziPlayer = require("./PreziPlayer");
  4316. var preziPlayer = null;
  4317. var Prezi = {
  4318. /**
  4319. * Reloads the current presentation.
  4320. */
  4321. reloadPresentation: function() {
  4322. var iframe = document.getElementById(preziPlayer.options.preziId);
  4323. iframe.src = iframe.src;
  4324. },
  4325. /**
  4326. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  4327. * otherwise.
  4328. */
  4329. isPresentationVisible: function () {
  4330. return ($('#presentation>iframe') != null
  4331. && $('#presentation>iframe').css('opacity') == 1);
  4332. },
  4333. /**
  4334. * Opens the Prezi dialog, from which the user could choose a presentation
  4335. * to load.
  4336. */
  4337. openPreziDialog: function() {
  4338. var myprezi = APP.xmpp.getPrezi();
  4339. if (myprezi) {
  4340. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  4341. null,
  4342. "dialog.removePreziMsg",
  4343. null,
  4344. false,
  4345. "dialog.Remove",
  4346. function(e,v,m,f) {
  4347. if(v) {
  4348. APP.xmpp.removePreziFromPresence();
  4349. }
  4350. }
  4351. );
  4352. }
  4353. else if (preziPlayer != null) {
  4354. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  4355. null, "dialog.sharePreziMsg",
  4356. null,
  4357. false,
  4358. "dialog.Ok",
  4359. function(e,v,m,f) {
  4360. $.prompt.close();
  4361. }
  4362. );
  4363. }
  4364. else {
  4365. var html = APP.translation.generateTranslationHTML(
  4366. "dialog.sharePreziTitle");
  4367. var cancelButton = APP.translation.generateTranslationHTML(
  4368. "dialog.Cancel");
  4369. var shareButton = APP.translation.generateTranslationHTML(
  4370. "dialog.Share");
  4371. var backButton = APP.translation.generateTranslationHTML(
  4372. "dialog.Back");
  4373. var buttons = [];
  4374. var buttons1 = [];
  4375. // Cancel button to both states
  4376. buttons.push({title: cancelButton, value: false});
  4377. buttons1.push({title: cancelButton, value: false});
  4378. // Share button
  4379. buttons.push({title: shareButton, value: true});
  4380. // Back button
  4381. buttons1.push({title: backButton, value: true});
  4382. var linkError = APP.translation.generateTranslationHTML(
  4383. "dialog.preziLinkError");
  4384. var defaultUrl = APP.translation.translateString("defaultPreziLink",
  4385. {url: "http://prezi.com/wz7vhjycl7e6/my-prezi"});
  4386. var openPreziState = {
  4387. state0: {
  4388. html: '<h2>' + html + '</h2>' +
  4389. '<input name="preziUrl" type="text" ' +
  4390. 'data-i18n="[placeholder]defaultPreziLink" data-i18n-options=\'' +
  4391. JSON.stringify({"url": "http://prezi.com/wz7vhjycl7e6/my-prezi"}) +
  4392. '\' placeholder="' + defaultUrl + '" autofocus>',
  4393. persistent: false,
  4394. buttons: buttons,
  4395. focus: ':input:first',
  4396. defaultButton: 0,
  4397. submit: function (e, v, m, f) {
  4398. e.preventDefault();
  4399. if(v)
  4400. {
  4401. var preziUrl = f.preziUrl;
  4402. if (preziUrl)
  4403. {
  4404. var urlValue
  4405. = encodeURI(UIUtil.escapeHtml(preziUrl));
  4406. if (urlValue.indexOf('http://prezi.com/') != 0
  4407. && urlValue.indexOf('https://prezi.com/') != 0)
  4408. {
  4409. $.prompt.goToState('state1');
  4410. return false;
  4411. }
  4412. else {
  4413. var presIdTmp = urlValue.substring(
  4414. urlValue.indexOf("prezi.com/") + 10);
  4415. if (!isAlphanumeric(presIdTmp)
  4416. || presIdTmp.indexOf('/') < 2) {
  4417. $.prompt.goToState('state1');
  4418. return false;
  4419. }
  4420. else {
  4421. APP.xmpp.addToPresence("prezi", urlValue);
  4422. $.prompt.close();
  4423. }
  4424. }
  4425. }
  4426. }
  4427. else
  4428. $.prompt.close();
  4429. }
  4430. },
  4431. state1: {
  4432. html: '<h2>' + html + '</h2>' +
  4433. linkError,
  4434. persistent: false,
  4435. buttons: buttons1,
  4436. focus: ':input:first',
  4437. defaultButton: 1,
  4438. submit: function (e, v, m, f) {
  4439. e.preventDefault();
  4440. if (v === 0)
  4441. $.prompt.close();
  4442. else
  4443. $.prompt.goToState('state0');
  4444. }
  4445. }
  4446. };
  4447. messageHandler.openDialogWithStates(openPreziState);
  4448. }
  4449. }
  4450. };
  4451. /**
  4452. * A new presentation has been added.
  4453. *
  4454. * @param event the event indicating the add of a presentation
  4455. * @param jid the jid from which the presentation was added
  4456. * @param presUrl url of the presentation
  4457. * @param currentSlide the current slide to which we should move
  4458. */
  4459. function presentationAdded(event, jid, presUrl, currentSlide) {
  4460. console.log("presentation added", presUrl);
  4461. var presId = getPresentationId(presUrl);
  4462. var elementId = 'participant_'
  4463. + Strophe.getResourceFromJid(jid)
  4464. + '_' + presId;
  4465. VideoLayout.addPreziContainer(elementId);
  4466. VideoLayout.resizeThumbnails();
  4467. var controlsEnabled = false;
  4468. if (jid === APP.xmpp.myJid())
  4469. controlsEnabled = true;
  4470. setPresentationVisible(true);
  4471. $('#largeVideoContainer').hover(
  4472. function (event) {
  4473. if (Prezi.isPresentationVisible()) {
  4474. var reloadButtonRight = window.innerWidth
  4475. - $('#presentation>iframe').offset().left
  4476. - $('#presentation>iframe').width();
  4477. $('#reloadPresentation').css({ right: reloadButtonRight,
  4478. display:'inline-block'});
  4479. }
  4480. },
  4481. function (event) {
  4482. if (!Prezi.isPresentationVisible())
  4483. $('#reloadPresentation').css({display:'none'});
  4484. else {
  4485. var e = event.toElement || event.relatedTarget;
  4486. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  4487. $('#reloadPresentation').css({display:'none'});
  4488. }
  4489. });
  4490. preziPlayer = new PreziPlayer(
  4491. 'presentation',
  4492. {preziId: presId,
  4493. width: getPresentationWidth(),
  4494. height: getPresentationHeihgt(),
  4495. controls: controlsEnabled,
  4496. debug: true
  4497. });
  4498. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  4499. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  4500. console.log("prezi status", event.value);
  4501. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  4502. if (jid != APP.xmpp.myJid())
  4503. preziPlayer.flyToStep(currentSlide);
  4504. }
  4505. });
  4506. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  4507. console.log("event value", event.value);
  4508. APP.xmpp.addToPresence("preziSlide", event.value);
  4509. });
  4510. $("#" + elementId).css( 'background-image',
  4511. 'url(../images/avatarprezi.png)');
  4512. $("#" + elementId).click(
  4513. function () {
  4514. setPresentationVisible(true);
  4515. }
  4516. );
  4517. };
  4518. /**
  4519. * A presentation has been removed.
  4520. *
  4521. * @param event the event indicating the remove of a presentation
  4522. * @param jid the jid for which the presentation was removed
  4523. * @param the url of the presentation
  4524. */
  4525. function presentationRemoved(event, jid, presUrl) {
  4526. console.log('presentation removed', presUrl);
  4527. var presId = getPresentationId(presUrl);
  4528. setPresentationVisible(false);
  4529. $('#participant_'
  4530. + Strophe.getResourceFromJid(jid)
  4531. + '_' + presId).remove();
  4532. $('#presentation>iframe').remove();
  4533. if (preziPlayer != null) {
  4534. preziPlayer.destroy();
  4535. preziPlayer = null;
  4536. }
  4537. };
  4538. /**
  4539. * Indicates if the given string is an alphanumeric string.
  4540. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  4541. * purpose of checking URIs.
  4542. */
  4543. function isAlphanumeric(unsafeText) {
  4544. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  4545. return regex.test(unsafeText);
  4546. }
  4547. /**
  4548. * Returns the presentation id from the given url.
  4549. */
  4550. function getPresentationId (presUrl) {
  4551. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  4552. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  4553. }
  4554. /**
  4555. * Returns the presentation width.
  4556. */
  4557. function getPresentationWidth() {
  4558. var availableWidth = UIUtil.getAvailableVideoWidth();
  4559. var availableHeight = getPresentationHeihgt();
  4560. var aspectRatio = 16.0 / 9.0;
  4561. if (availableHeight < availableWidth / aspectRatio) {
  4562. availableWidth = Math.floor(availableHeight * aspectRatio);
  4563. }
  4564. return availableWidth;
  4565. }
  4566. /**
  4567. * Returns the presentation height.
  4568. */
  4569. function getPresentationHeihgt() {
  4570. var remoteVideos = $('#remoteVideos');
  4571. return window.innerHeight - remoteVideos.outerHeight();
  4572. }
  4573. /**
  4574. * Resizes the presentation iframe.
  4575. */
  4576. function resize() {
  4577. if ($('#presentation>iframe')) {
  4578. $('#presentation>iframe').width(getPresentationWidth());
  4579. $('#presentation>iframe').height(getPresentationHeihgt());
  4580. }
  4581. }
  4582. /**
  4583. * Shows/hides a presentation.
  4584. */
  4585. function setPresentationVisible(visible) {
  4586. var prezi = $('#presentation>iframe');
  4587. if (visible) {
  4588. // Trigger the video.selected event to indicate a change in the
  4589. // large video.
  4590. $(document).trigger("video.selected", [true]);
  4591. $('#largeVideo').fadeOut(300);
  4592. prezi.fadeIn(300, function() {
  4593. prezi.css({opacity:'1'});
  4594. ToolbarToggler.dockToolbar(true);
  4595. VideoLayout.setLargeVideoVisible(false);
  4596. });
  4597. $('#activeSpeaker').css('visibility', 'hidden');
  4598. }
  4599. else {
  4600. if (prezi.css('opacity') == '1') {
  4601. prezi.fadeOut(300, function () {
  4602. prezi.css({opacity:'0'});
  4603. $('#reloadPresentation').css({display:'none'});
  4604. $('#largeVideo').fadeIn(300, function() {
  4605. VideoLayout.setLargeVideoVisible(true);
  4606. ToolbarToggler.dockToolbar(false);
  4607. });
  4608. });
  4609. }
  4610. }
  4611. }
  4612. /**
  4613. * Presentation has been removed.
  4614. */
  4615. $(document).bind('presentationremoved.muc', presentationRemoved);
  4616. /**
  4617. * Presentation has been added.
  4618. */
  4619. $(document).bind('presentationadded.muc', presentationAdded);
  4620. /*
  4621. * Indicates presentation slide change.
  4622. */
  4623. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  4624. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  4625. preziPlayer.flyToStep(current);
  4626. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  4627. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  4628. preziPlayer.flyToStep(current, i);
  4629. }
  4630. }
  4631. });
  4632. /**
  4633. * On video selected event.
  4634. */
  4635. $(document).bind('video.selected', function (event, isPresentation) {
  4636. if (!isPresentation && $('#presentation>iframe')) {
  4637. setPresentationVisible(false);
  4638. }
  4639. });
  4640. $(window).resize(function () {
  4641. resize();
  4642. });
  4643. module.exports = Prezi;
  4644. },{"../toolbars/ToolbarToggler":29,"../util/MessageHandler":31,"../util/UIUtil":33,"../videolayout/VideoLayout":39,"./PreziPlayer":19}],19:[function(require,module,exports){
  4645. (function() {
  4646. "use strict";
  4647. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  4648. window.PreziPlayer = (function() {
  4649. PreziPlayer.API_VERSION = 1;
  4650. PreziPlayer.CURRENT_STEP = 'currentStep';
  4651. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  4652. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  4653. PreziPlayer.STATUS_LOADING = 'loading';
  4654. PreziPlayer.STATUS_READY = 'ready';
  4655. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  4656. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  4657. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  4658. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  4659. PreziPlayer.EVENT_STATUS = "statusChange";
  4660. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  4661. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  4662. PreziPlayer.domain = "https://prezi.com";
  4663. PreziPlayer.path = "/player/";
  4664. PreziPlayer.players = {};
  4665. PreziPlayer.binded_methods = ['changesHandler'];
  4666. PreziPlayer.createMultiplePlayers = function(optionArray){
  4667. for(var i=0; i<optionArray.length; i++) {
  4668. var optionSet = optionArray[i];
  4669. new PreziPlayer(optionSet.id, optionSet);
  4670. };
  4671. };
  4672. PreziPlayer.messageReceived = function(event){
  4673. var message, item, player;
  4674. try {
  4675. message = JSON.parse(event.data);
  4676. if (message.id && (player = PreziPlayer.players[message.id])) {
  4677. if (player.options.debug === true) {
  4678. if (console && console.log)
  4679. console.log('received', message);
  4680. }
  4681. if (message.type === "changes") {
  4682. player.changesHandler(message);
  4683. }
  4684. for (var i = 0; i < player.callbacks.length; i++) {
  4685. item = player.callbacks[i];
  4686. if (item && message.type === item.event) {
  4687. item.callback(message);
  4688. }
  4689. }
  4690. }
  4691. } catch (e) { }
  4692. };
  4693. function PreziPlayer(id, options) {
  4694. var params, paramString = "", _this = this;
  4695. if (PreziPlayer.players[id]){
  4696. PreziPlayer.players[id].destroy();
  4697. }
  4698. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  4699. var method_name = PreziPlayer.binded_methods[i];
  4700. _this[method_name] = __bind(_this[method_name], _this);
  4701. };
  4702. options = options || {};
  4703. this.options = options;
  4704. this.values = {'status': PreziPlayer.STATUS_LOADING};
  4705. this.values[PreziPlayer.CURRENT_STEP] = 0;
  4706. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  4707. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  4708. this.callbacks = [];
  4709. this.id = id;
  4710. this.embedTo = document.getElementById(id);
  4711. if (!this.embedTo) {
  4712. throw "The element id is not available.";
  4713. }
  4714. this.iframe = document.createElement('iframe');
  4715. params = [
  4716. { name: 'oid', value: options.preziId },
  4717. { name: 'explorable', value: options.explorable ? 1 : 0 },
  4718. { name: 'controls', value: options.controls ? 1 : 0 }
  4719. ];
  4720. for(var i=0; i<params.length; i++) {
  4721. var param = params[i];
  4722. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  4723. };
  4724. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  4725. this.iframe.frameBorder = 0;
  4726. this.iframe.scrolling = "no";
  4727. this.iframe.width = options.width || 640;
  4728. this.iframe.height = options.height || 480;
  4729. this.embedTo.innerHTML = '';
  4730. // JITSI: IN CASE SOMETHING GOES WRONG.
  4731. try {
  4732. this.embedTo.appendChild(this.iframe);
  4733. }
  4734. catch (err) {
  4735. console.log("CATCH ERROR");
  4736. }
  4737. // JITSI: Increase interval from 200 to 500, which fixes prezi
  4738. // crashes for us.
  4739. this.initPollInterval = setInterval(function(){
  4740. _this.sendMessage({'action': 'init'});
  4741. }, 500);
  4742. PreziPlayer.players[id] = this;
  4743. }
  4744. PreziPlayer.prototype.changesHandler = function(message) {
  4745. var key, value, j, item;
  4746. if (this.initPollInterval) {
  4747. clearInterval(this.initPollInterval);
  4748. this.initPollInterval = false;
  4749. }
  4750. for (key in message.data) {
  4751. if (message.data.hasOwnProperty(key)){
  4752. value = message.data[key];
  4753. this.values[key] = value;
  4754. for (j=0; j<this.callbacks.length; j++) {
  4755. item = this.callbacks[j];
  4756. if (item && item.event === key + "Change"){
  4757. item.callback({type: item.event, value: value});
  4758. }
  4759. }
  4760. }
  4761. }
  4762. };
  4763. PreziPlayer.prototype.destroy = function() {
  4764. if (this.initPollInterval) {
  4765. clearInterval(this.initPollInterval);
  4766. this.initPollInterval = false;
  4767. }
  4768. this.embedTo.innerHTML = '';
  4769. };
  4770. PreziPlayer.prototype.sendMessage = function(message) {
  4771. if (this.options.debug === true) {
  4772. if (console && console.log) console.log('sent', message);
  4773. }
  4774. message.version = PreziPlayer.API_VERSION;
  4775. message.id = this.id;
  4776. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  4777. };
  4778. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  4779. PreziPlayer.prototype.flyToNextStep = function() {
  4780. return this.sendMessage({
  4781. 'action': 'present',
  4782. 'data': ['moveToNextStep']
  4783. });
  4784. };
  4785. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  4786. PreziPlayer.prototype.flyToPreviousStep = function() {
  4787. return this.sendMessage({
  4788. 'action': 'present',
  4789. 'data': ['moveToPrevStep']
  4790. });
  4791. };
  4792. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  4793. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  4794. var obj = this;
  4795. // check animation_step
  4796. if (animation_step > 0 &&
  4797. obj.values.animationCountOnSteps &&
  4798. obj.values.animationCountOnSteps[step] <= animation_step) {
  4799. animation_step = obj.values.animationCountOnSteps[step];
  4800. }
  4801. // jump to animation steps by calling flyToNextStep()
  4802. function doAnimationSteps() {
  4803. if (obj.values.isMoving == true) {
  4804. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  4805. return;
  4806. }
  4807. while (animation_step-- > 0) {
  4808. obj.flyToNextStep(); // do the animation steps
  4809. }
  4810. }
  4811. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  4812. // jump to the step
  4813. return this.sendMessage({
  4814. 'action': 'present',
  4815. 'data': ['moveToStep', step]
  4816. });
  4817. };
  4818. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  4819. PreziPlayer.prototype.flyToObject = function(objectId) {
  4820. return this.sendMessage({
  4821. 'action': 'present',
  4822. 'data': ['moveToObject', objectId]
  4823. });
  4824. };
  4825. PreziPlayer.prototype.play = function(defaultDelay) {
  4826. return this.sendMessage({
  4827. 'action': 'present',
  4828. 'data': ['startAutoPlay', defaultDelay]
  4829. });
  4830. };
  4831. PreziPlayer.prototype.stop = function() {
  4832. return this.sendMessage({
  4833. 'action': 'present',
  4834. 'data': ['stopAutoPlay']
  4835. });
  4836. };
  4837. PreziPlayer.prototype.pause = function(defaultDelay) {
  4838. return this.sendMessage({
  4839. 'action': 'present',
  4840. 'data': ['pauseAutoPlay', defaultDelay]
  4841. });
  4842. };
  4843. PreziPlayer.prototype.getCurrentStep = function() {
  4844. return this.values.currentStep;
  4845. };
  4846. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  4847. return this.values.currentAnimationStep;
  4848. };
  4849. PreziPlayer.prototype.getCurrentObject = function() {
  4850. return this.values.currentObject;
  4851. };
  4852. PreziPlayer.prototype.getStatus = function() {
  4853. return this.values.status;
  4854. };
  4855. PreziPlayer.prototype.isPlaying = function() {
  4856. return this.values.isAutoPlaying;
  4857. };
  4858. PreziPlayer.prototype.getStepCount = function() {
  4859. return this.values.stepCount;
  4860. };
  4861. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  4862. return this.values.animationCountOnSteps;
  4863. };
  4864. PreziPlayer.prototype.getTitle = function() {
  4865. return this.values.title;
  4866. };
  4867. PreziPlayer.prototype.setDimensions = function(dims) {
  4868. for (var parameter in dims) {
  4869. this.iframe[parameter] = dims[parameter];
  4870. }
  4871. }
  4872. PreziPlayer.prototype.getDimensions = function() {
  4873. return {
  4874. width: parseInt(this.iframe.width, 10),
  4875. height: parseInt(this.iframe.height, 10)
  4876. }
  4877. }
  4878. PreziPlayer.prototype.on = function(event, callback) {
  4879. this.callbacks.push({
  4880. event: event,
  4881. callback: callback
  4882. });
  4883. };
  4884. PreziPlayer.prototype.off = function(event, callback) {
  4885. var j, item;
  4886. if (event === undefined) {
  4887. this.callbacks = [];
  4888. }
  4889. j = this.callbacks.length;
  4890. while (j--) {
  4891. item = this.callbacks[j];
  4892. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  4893. this.callbacks.splice(j, 1);
  4894. }
  4895. }
  4896. };
  4897. if (window.addEventListener) {
  4898. window.addEventListener('message', PreziPlayer.messageReceived, false);
  4899. } else {
  4900. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  4901. }
  4902. return PreziPlayer;
  4903. })();
  4904. })();
  4905. module.exports = PreziPlayer;
  4906. },{}],20:[function(require,module,exports){
  4907. var Chat = require("./chat/Chat");
  4908. var ContactList = require("./contactlist/ContactList");
  4909. var Settings = require("./../../settings/Settings");
  4910. var SettingsMenu = require("./settings/SettingsMenu");
  4911. var VideoLayout = require("../videolayout/VideoLayout");
  4912. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  4913. var UIUtil = require("../util/UIUtil");
  4914. var LargeVideo = require("../videolayout/LargeVideo");
  4915. /**
  4916. * Toggler for the chat, contact list, settings menu, etc..
  4917. */
  4918. var PanelToggler = (function(my) {
  4919. var currentlyOpen = null;
  4920. var buttons = {
  4921. '#chatspace': '#chatBottomButton',
  4922. '#contactlist': '#contactListButton',
  4923. '#settingsmenu': '#settingsButton'
  4924. };
  4925. /**
  4926. * Toggles the windows in the side panel
  4927. * @param object the window that should be shown
  4928. * @param selector the selector for the element containing the panel
  4929. * @param onOpenComplete function to be called when the panel is opened
  4930. * @param onOpen function to be called if the window is going to be opened
  4931. * @param onClose function to be called if the window is going to be closed
  4932. */
  4933. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  4934. UIUtil.buttonClick(buttons[selector], "active");
  4935. if (object.isVisible()) {
  4936. $("#toast-container").animate({
  4937. right: '5px'
  4938. },
  4939. {
  4940. queue: false,
  4941. duration: 500
  4942. });
  4943. $(selector).hide("slide", {
  4944. direction: "right",
  4945. queue: false,
  4946. duration: 500
  4947. });
  4948. if(typeof onClose === "function") {
  4949. onClose();
  4950. }
  4951. currentlyOpen = null;
  4952. }
  4953. else {
  4954. // Undock the toolbar when the chat is shown and if we're in a
  4955. // video mode.
  4956. if (LargeVideo.isLargeVideoVisible()) {
  4957. ToolbarToggler.dockToolbar(false);
  4958. }
  4959. if(currentlyOpen) {
  4960. var current = $(currentlyOpen);
  4961. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  4962. current.css('z-index', 4);
  4963. setTimeout(function () {
  4964. current.css('display', 'none');
  4965. current.css('z-index', 5);
  4966. }, 500);
  4967. }
  4968. $("#toast-container").animate({
  4969. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  4970. },
  4971. {
  4972. queue: false,
  4973. duration: 500
  4974. });
  4975. $(selector).show("slide", {
  4976. direction: "right",
  4977. queue: false,
  4978. duration: 500,
  4979. complete: onOpenComplete
  4980. });
  4981. if(typeof onOpen === "function") {
  4982. onOpen();
  4983. }
  4984. currentlyOpen = selector;
  4985. }
  4986. };
  4987. /**
  4988. * Opens / closes the chat area.
  4989. */
  4990. my.toggleChat = function() {
  4991. var chatCompleteFunction = Chat.isVisible() ?
  4992. function() {} : function () {
  4993. Chat.scrollChatToBottom();
  4994. $('#chatspace').trigger('shown');
  4995. };
  4996. VideoLayout.resizeVideoArea(!Chat.isVisible(), chatCompleteFunction);
  4997. toggle(Chat,
  4998. '#chatspace',
  4999. function () {
  5000. // Request the focus in the nickname field or the chat input field.
  5001. if ($('#nickname').css('visibility') === 'visible') {
  5002. $('#nickinput').focus();
  5003. } else {
  5004. $('#usermsg').focus();
  5005. }
  5006. },
  5007. null,
  5008. Chat.resizeChat,
  5009. null);
  5010. };
  5011. /**
  5012. * Opens / closes the contact list area.
  5013. */
  5014. my.toggleContactList = function () {
  5015. var completeFunction = ContactList.isVisible() ?
  5016. function() {} : function () { $('#contactlist').trigger('shown');};
  5017. VideoLayout.resizeVideoArea(!ContactList.isVisible(), completeFunction);
  5018. toggle(ContactList,
  5019. '#contactlist',
  5020. null,
  5021. function() {
  5022. ContactList.setVisualNotification(false);
  5023. },
  5024. null);
  5025. };
  5026. /**
  5027. * Opens / closes the settings menu
  5028. */
  5029. my.toggleSettingsMenu = function() {
  5030. VideoLayout.resizeVideoArea(!SettingsMenu.isVisible(), function (){});
  5031. toggle(SettingsMenu,
  5032. '#settingsmenu',
  5033. null,
  5034. function() {
  5035. var settings = Settings.getSettings();
  5036. $('#setDisplayName').get(0).value = settings.displayName;
  5037. $('#setEmail').get(0).value = settings.email;
  5038. },
  5039. null);
  5040. };
  5041. /**
  5042. * Returns the size of the side panel.
  5043. */
  5044. my.getPanelSize = function () {
  5045. var availableHeight = window.innerHeight;
  5046. var availableWidth = window.innerWidth;
  5047. var panelWidth = 200;
  5048. if (availableWidth * 0.2 < 200) {
  5049. panelWidth = availableWidth * 0.2;
  5050. }
  5051. return [panelWidth, availableHeight];
  5052. };
  5053. my.isVisible = function() {
  5054. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  5055. };
  5056. return my;
  5057. }(PanelToggler || {}));
  5058. module.exports = PanelToggler;
  5059. },{"../toolbars/ToolbarToggler":29,"../util/UIUtil":33,"../videolayout/LargeVideo":35,"../videolayout/VideoLayout":39,"./../../settings/Settings":47,"./chat/Chat":21,"./contactlist/ContactList":25,"./settings/SettingsMenu":26}],21:[function(require,module,exports){
  5060. /* global $, Util, nickname:true */
  5061. var Replacement = require("./Replacement");
  5062. var CommandsProcessor = require("./Commands");
  5063. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  5064. var smileys = require("./smileys.json").smileys;
  5065. var NicknameHandler = require("../../util/NicknameHandler");
  5066. var UIUtil = require("../../util/UIUtil");
  5067. var UIEvents = require("../../../../service/UI/UIEvents");
  5068. var notificationInterval = false;
  5069. var unreadMessages = 0;
  5070. /**
  5071. * Shows/hides a visual notification, indicating that a message has arrived.
  5072. */
  5073. function setVisualNotification(show) {
  5074. var unreadMsgElement = document.getElementById('unreadMessages');
  5075. var unreadMsgBottomElement
  5076. = document.getElementById('bottomUnreadMessages');
  5077. var glower = $('#chatButton');
  5078. var bottomGlower = $('#chatBottomButton');
  5079. if (unreadMessages) {
  5080. unreadMsgElement.innerHTML = unreadMessages.toString();
  5081. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  5082. ToolbarToggler.dockToolbar(true);
  5083. var chatButtonElement
  5084. = document.getElementById('chatButton').parentNode;
  5085. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  5086. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  5087. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  5088. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  5089. unreadMsgElement.setAttribute(
  5090. 'style',
  5091. 'top:' + topIndent +
  5092. '; left:' + leftIndent + ';');
  5093. var chatBottomButtonElement
  5094. = document.getElementById('chatBottomButton').parentNode;
  5095. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  5096. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  5097. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  5098. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  5099. unreadMsgBottomElement.setAttribute(
  5100. 'style',
  5101. 'top:' + bottomTopIndent +
  5102. '; left:' + bottomLeftIndent + ';');
  5103. if (!glower.hasClass('icon-chat-simple')) {
  5104. glower.removeClass('icon-chat');
  5105. glower.addClass('icon-chat-simple');
  5106. }
  5107. }
  5108. else {
  5109. unreadMsgElement.innerHTML = '';
  5110. unreadMsgBottomElement.innerHTML = '';
  5111. glower.removeClass('icon-chat-simple');
  5112. glower.addClass('icon-chat');
  5113. }
  5114. if (show && !notificationInterval) {
  5115. notificationInterval = window.setInterval(function () {
  5116. glower.toggleClass('active');
  5117. bottomGlower.toggleClass('active glowing');
  5118. }, 800);
  5119. }
  5120. else if (!show && notificationInterval) {
  5121. window.clearInterval(notificationInterval);
  5122. notificationInterval = false;
  5123. glower.removeClass('active');
  5124. bottomGlower.removeClass('glowing');
  5125. bottomGlower.addClass('active');
  5126. }
  5127. }
  5128. /**
  5129. * Returns the current time in the format it is shown to the user
  5130. * @returns {string}
  5131. */
  5132. function getCurrentTime(stamp) {
  5133. var now = (stamp? new Date(stamp): new Date());
  5134. var hour = now.getHours();
  5135. var minute = now.getMinutes();
  5136. var second = now.getSeconds();
  5137. if(hour.toString().length === 1) {
  5138. hour = '0'+hour;
  5139. }
  5140. if(minute.toString().length === 1) {
  5141. minute = '0'+minute;
  5142. }
  5143. if(second.toString().length === 1) {
  5144. second = '0'+second;
  5145. }
  5146. return hour+':'+minute+':'+second;
  5147. }
  5148. function toggleSmileys()
  5149. {
  5150. var smileys = $('#smileysContainer');
  5151. if(!smileys.is(':visible')) {
  5152. smileys.show("slide", { direction: "down", duration: 300});
  5153. } else {
  5154. smileys.hide("slide", { direction: "down", duration: 300});
  5155. }
  5156. $('#usermsg').focus();
  5157. }
  5158. function addClickFunction(smiley, number) {
  5159. smiley.onclick = function addSmileyToMessage() {
  5160. var usermsg = $('#usermsg');
  5161. var message = usermsg.val();
  5162. message += smileys['smiley' + number];
  5163. usermsg.val(message);
  5164. usermsg.get(0).setSelectionRange(message.length, message.length);
  5165. toggleSmileys();
  5166. usermsg.focus();
  5167. };
  5168. }
  5169. /**
  5170. * Adds the smileys container to the chat
  5171. */
  5172. function addSmileys() {
  5173. var smileysContainer = document.createElement('div');
  5174. smileysContainer.id = 'smileysContainer';
  5175. for(var i = 1; i <= 21; i++) {
  5176. var smileyContainer = document.createElement('div');
  5177. smileyContainer.id = 'smiley' + i;
  5178. smileyContainer.className = 'smileyContainer';
  5179. var smiley = document.createElement('img');
  5180. smiley.src = 'images/smileys/smiley' + i + '.svg';
  5181. smiley.className = 'smiley';
  5182. addClickFunction(smiley, i);
  5183. smileyContainer.appendChild(smiley);
  5184. smileysContainer.appendChild(smileyContainer);
  5185. }
  5186. $("#chatspace").append(smileysContainer);
  5187. }
  5188. /**
  5189. * Resizes the chat conversation.
  5190. */
  5191. function resizeChatConversation() {
  5192. var msgareaHeight = $('#usermsg').outerHeight();
  5193. var chatspace = $('#chatspace');
  5194. var width = chatspace.width();
  5195. var chat = $('#chatconversation');
  5196. var smileys = $('#smileysarea');
  5197. smileys.height(msgareaHeight);
  5198. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  5199. $('#smileysContainer').css('bottom', msgareaHeight);
  5200. chat.width(width - 10);
  5201. chat.height(window.innerHeight - 15 - msgareaHeight);
  5202. }
  5203. /**
  5204. * Chat related user interface.
  5205. */
  5206. var Chat = (function (my) {
  5207. /**
  5208. * Initializes chat related interface.
  5209. */
  5210. my.init = function () {
  5211. if(NicknameHandler.getNickname())
  5212. Chat.setChatConversationMode(true);
  5213. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  5214. function (nickname) {
  5215. Chat.setChatConversationMode(true);
  5216. });
  5217. $('#nickinput').keydown(function (event) {
  5218. if (event.keyCode === 13) {
  5219. event.preventDefault();
  5220. var val = UIUtil.escapeHtml(this.value);
  5221. this.value = '';
  5222. if (!NicknameHandler.getNickname()) {
  5223. NicknameHandler.setNickname(val);
  5224. return;
  5225. }
  5226. }
  5227. });
  5228. $('#usermsg').keydown(function (event) {
  5229. if (event.keyCode === 13) {
  5230. event.preventDefault();
  5231. var value = this.value;
  5232. $('#usermsg').val('').trigger('autosize.resize');
  5233. this.focus();
  5234. var command = new CommandsProcessor(value);
  5235. if(command.isCommand())
  5236. {
  5237. command.processCommand();
  5238. }
  5239. else
  5240. {
  5241. var message = UIUtil.escapeHtml(value);
  5242. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  5243. }
  5244. }
  5245. });
  5246. var onTextAreaResize = function () {
  5247. resizeChatConversation();
  5248. Chat.scrollChatToBottom();
  5249. };
  5250. $('#usermsg').autosize({callback: onTextAreaResize});
  5251. $("#chatspace").bind("shown",
  5252. function () {
  5253. unreadMessages = 0;
  5254. setVisualNotification(false);
  5255. });
  5256. addSmileys();
  5257. };
  5258. /**
  5259. * Appends the given message to the chat conversation.
  5260. */
  5261. my.updateChatConversation = function (from, displayName, message, myjid, stamp) {
  5262. var divClassName = '';
  5263. if (APP.xmpp.myJid() === from) {
  5264. divClassName = "localuser";
  5265. }
  5266. else {
  5267. divClassName = "remoteuser";
  5268. if (!Chat.isVisible()) {
  5269. unreadMessages++;
  5270. UIUtil.playSoundNotification('chatNotification');
  5271. setVisualNotification(true);
  5272. }
  5273. }
  5274. // replace links and smileys
  5275. // Strophe already escapes special symbols on sending,
  5276. // so we escape here only tags to avoid double &amp;
  5277. var escMessage = message.replace(/</g, '&lt;').
  5278. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  5279. var escDisplayName = UIUtil.escapeHtml(displayName);
  5280. message = Replacement.processReplacements(escMessage);
  5281. var messageContainer =
  5282. '<div class="chatmessage">'+
  5283. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  5284. '<div class="username ' + divClassName +'">' + escDisplayName +
  5285. '</div>' + '<div class="timestamp">' + getCurrentTime(stamp) +
  5286. '</div>' + '<div class="usermessage">' + message + '</div>' +
  5287. '</div>';
  5288. $('#chatconversation').append(messageContainer);
  5289. $('#chatconversation').animate(
  5290. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5291. };
  5292. /**
  5293. * Appends error message to the conversation
  5294. * @param errorMessage the received error message.
  5295. * @param originalText the original message.
  5296. */
  5297. my.chatAddError = function(errorMessage, originalText)
  5298. {
  5299. errorMessage = UIUtil.escapeHtml(errorMessage);
  5300. originalText = UIUtil.escapeHtml(originalText);
  5301. $('#chatconversation').append(
  5302. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  5303. (originalText? (' \"'+ originalText + '\"') : "") +
  5304. ' was not sent.' +
  5305. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  5306. $('#chatconversation').animate(
  5307. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5308. };
  5309. /**
  5310. * Sets the subject to the UI
  5311. * @param subject the subject
  5312. */
  5313. my.chatSetSubject = function(subject)
  5314. {
  5315. if(subject)
  5316. subject = subject.trim();
  5317. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  5318. if(subject === "")
  5319. {
  5320. $("#subject").css({display: "none"});
  5321. }
  5322. else
  5323. {
  5324. $("#subject").css({display: "block"});
  5325. }
  5326. };
  5327. /**
  5328. * Sets the chat conversation mode.
  5329. */
  5330. my.setChatConversationMode = function (isConversationMode) {
  5331. if (isConversationMode) {
  5332. $('#nickname').css({visibility: 'hidden'});
  5333. $('#chatconversation').css({visibility: 'visible'});
  5334. $('#usermsg').css({visibility: 'visible'});
  5335. $('#smileysarea').css({visibility: 'visible'});
  5336. $('#usermsg').focus();
  5337. }
  5338. };
  5339. /**
  5340. * Resizes the chat area.
  5341. */
  5342. my.resizeChat = function () {
  5343. var chatSize = require("../SidePanelToggler").getPanelSize();
  5344. $('#chatspace').width(chatSize[0]);
  5345. $('#chatspace').height(chatSize[1]);
  5346. resizeChatConversation();
  5347. };
  5348. /**
  5349. * Indicates if the chat is currently visible.
  5350. */
  5351. my.isVisible = function () {
  5352. return $('#chatspace').is(":visible");
  5353. };
  5354. /**
  5355. * Shows and hides the window with the smileys
  5356. */
  5357. my.toggleSmileys = toggleSmileys;
  5358. /**
  5359. * Scrolls chat to the bottom.
  5360. */
  5361. my.scrollChatToBottom = function() {
  5362. setTimeout(function () {
  5363. $('#chatconversation').scrollTop(
  5364. $('#chatconversation')[0].scrollHeight);
  5365. }, 5);
  5366. };
  5367. return my;
  5368. }(Chat || {}));
  5369. module.exports = Chat;
  5370. },{"../../../../service/UI/UIEvents":102,"../../toolbars/ToolbarToggler":29,"../../util/NicknameHandler":32,"../../util/UIUtil":33,"../SidePanelToggler":20,"./Commands":22,"./Replacement":23,"./smileys.json":24}],22:[function(require,module,exports){
  5371. var UIUtil = require("../../util/UIUtil");
  5372. /**
  5373. * List with supported commands. The keys are the names of the commands and
  5374. * the value is the function that processes the message.
  5375. * @type {{String: function}}
  5376. */
  5377. var commands = {
  5378. "topic" : processTopic
  5379. };
  5380. /**
  5381. * Extracts the command from the message.
  5382. * @param message the received message
  5383. * @returns {string} the command
  5384. */
  5385. function getCommand(message)
  5386. {
  5387. if(message)
  5388. {
  5389. for(var command in commands)
  5390. {
  5391. if(message.indexOf("/" + command) == 0)
  5392. return command;
  5393. }
  5394. }
  5395. return "";
  5396. };
  5397. /**
  5398. * Processes the data for topic command.
  5399. * @param commandArguments the arguments of the topic command.
  5400. */
  5401. function processTopic(commandArguments)
  5402. {
  5403. var topic = UIUtil.escapeHtml(commandArguments);
  5404. APP.xmpp.setSubject(topic);
  5405. }
  5406. /**
  5407. * Constructs new CommandProccessor instance from a message that
  5408. * handles commands received via chat messages.
  5409. * @param message the message
  5410. * @constructor
  5411. */
  5412. function CommandsProcessor(message)
  5413. {
  5414. var command = getCommand(message);
  5415. /**
  5416. * Returns the name of the command.
  5417. * @returns {String} the command
  5418. */
  5419. this.getCommand = function()
  5420. {
  5421. return command;
  5422. };
  5423. var messageArgument = message.substr(command.length + 2);
  5424. /**
  5425. * Returns the arguments of the command.
  5426. * @returns {string}
  5427. */
  5428. this.getArgument = function()
  5429. {
  5430. return messageArgument;
  5431. };
  5432. }
  5433. /**
  5434. * Checks whether this instance is valid command or not.
  5435. * @returns {boolean}
  5436. */
  5437. CommandsProcessor.prototype.isCommand = function()
  5438. {
  5439. if(this.getCommand())
  5440. return true;
  5441. return false;
  5442. };
  5443. /**
  5444. * Processes the command.
  5445. */
  5446. CommandsProcessor.prototype.processCommand = function()
  5447. {
  5448. if(!this.isCommand())
  5449. return;
  5450. commands[this.getCommand()](this.getArgument());
  5451. };
  5452. module.exports = CommandsProcessor;
  5453. },{"../../util/UIUtil":33}],23:[function(require,module,exports){
  5454. var Smileys = require("./smileys.json");
  5455. /**
  5456. * Processes links and smileys in "body"
  5457. */
  5458. function processReplacements(body)
  5459. {
  5460. //make links clickable
  5461. body = linkify(body);
  5462. //add smileys
  5463. body = smilify(body);
  5464. return body;
  5465. }
  5466. /**
  5467. * Finds and replaces all links in the links in "body"
  5468. * with their <a href=""></a>
  5469. */
  5470. function linkify(inputText)
  5471. {
  5472. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  5473. //URLs starting with http://, https://, or ftp://
  5474. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  5475. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  5476. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  5477. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  5478. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  5479. //Change email addresses to mailto:: links.
  5480. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  5481. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  5482. return replacedText;
  5483. }
  5484. /**
  5485. * Replaces common smiley strings with images
  5486. */
  5487. function smilify(body)
  5488. {
  5489. if(!body) {
  5490. return body;
  5491. }
  5492. var regexs = Smileys["regexs"];
  5493. for(var smiley in regexs) {
  5494. if(regexs.hasOwnProperty(smiley)) {
  5495. body = body.replace(regexs[smiley],
  5496. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  5497. }
  5498. }
  5499. return body;
  5500. }
  5501. module.exports = {
  5502. processReplacements: processReplacements,
  5503. linkify: linkify
  5504. };
  5505. },{"./smileys.json":24}],24:[function(require,module,exports){
  5506. module.exports={
  5507. "smileys": {
  5508. "smiley1": ":)",
  5509. "smiley2": ":(",
  5510. "smiley3": ":D",
  5511. "smiley4": "(y)",
  5512. "smiley5": " :P",
  5513. "smiley6": "(wave)",
  5514. "smiley7": "(blush)",
  5515. "smiley8": "(chuckle)",
  5516. "smiley9": "(shocked)",
  5517. "smiley10": ":*",
  5518. "smiley11": "(n)",
  5519. "smiley12": "(search)",
  5520. "smiley13": " <3",
  5521. "smiley14": "(oops)",
  5522. "smiley15": "(angry)",
  5523. "smiley16": "(angel)",
  5524. "smiley17": "(sick)",
  5525. "smiley18": ";(",
  5526. "smiley19": "(bomb)",
  5527. "smiley20": "(clap)",
  5528. "smiley21": " ;)"
  5529. },
  5530. "regexs": {
  5531. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  5532. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  5533. "smiley1": /(:-\)|:\))/gi,
  5534. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  5535. "smiley5": /(:-P|:P|:-p|:p)/gi,
  5536. "smiley6": /(\(wave\))/gi,
  5537. "smiley7": /(\(blush\))/gi,
  5538. "smiley8": /(\(chuckle\))/gi,
  5539. "smiley9": /(:-0|\(shocked\))/gi,
  5540. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  5541. "smiley11": /(\(n\))/gi,
  5542. "smiley12": /(\(search\))/g,
  5543. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  5544. "smiley14": /(\(oops\))/gi,
  5545. "smiley15": /(\(angry\))/gi,
  5546. "smiley16": /(\(angel\))/gi,
  5547. "smiley17": /(\(sick\))/gi,
  5548. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  5549. "smiley19": /(\(bomb\))/gi,
  5550. "smiley20": /(\(clap\))/gi,
  5551. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  5552. }
  5553. }
  5554. },{}],25:[function(require,module,exports){
  5555. var Avatar = require('../../avatar/Avatar');
  5556. var numberOfContacts = 0;
  5557. var notificationInterval;
  5558. /**
  5559. * Updates the number of participants in the contact list button and sets
  5560. * the glow
  5561. * @param delta indicates whether a new user has joined (1) or someone has
  5562. * left(-1)
  5563. */
  5564. function updateNumberOfParticipants(delta) {
  5565. numberOfContacts += delta;
  5566. if (numberOfContacts === 1) {
  5567. // when the user is alone we don't show the number of participants
  5568. $("#numberOfParticipants").text('');
  5569. ContactList.setVisualNotification(false);
  5570. } else if (numberOfContacts > 1) {
  5571. ContactList.setVisualNotification(!ContactList.isVisible());
  5572. $("#numberOfParticipants").text(numberOfContacts);
  5573. } else {
  5574. console.error("Invalid number of participants: " + numberOfContacts);
  5575. }
  5576. }
  5577. /**
  5578. * Creates the avatar element.
  5579. *
  5580. * @return the newly created avatar element
  5581. */
  5582. function createAvatar(jid) {
  5583. var avatar = document.createElement('img');
  5584. avatar.className = "icon-avatar avatar";
  5585. avatar.src = Avatar.getContactListUrl(jid);
  5586. return avatar;
  5587. }
  5588. /**
  5589. * Creates the display name paragraph.
  5590. *
  5591. * @param displayName the display name to set
  5592. */
  5593. function createDisplayNameParagraph(key, displayName) {
  5594. var p = document.createElement('p');
  5595. if(displayName)
  5596. p.innerText = displayName;
  5597. else if(key)
  5598. {
  5599. p.setAttribute("data-i18n",key);
  5600. p.innerText = APP.translation.translateString(key);
  5601. }
  5602. return p;
  5603. }
  5604. function stopGlowing(glower) {
  5605. window.clearInterval(notificationInterval);
  5606. notificationInterval = false;
  5607. glower.removeClass('glowing');
  5608. if (!ContactList.isVisible()) {
  5609. glower.removeClass('active');
  5610. }
  5611. }
  5612. /**
  5613. * Contact list.
  5614. */
  5615. var ContactList = {
  5616. /**
  5617. * Indicates if the chat is currently visible.
  5618. *
  5619. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  5620. * otherwise
  5621. */
  5622. isVisible: function () {
  5623. return $('#contactlist').is(":visible");
  5624. },
  5625. /**
  5626. * Adds a contact for the given peerJid if such doesn't yet exist.
  5627. *
  5628. * @param peerJid the peerJid corresponding to the contact
  5629. */
  5630. ensureAddContact: function (peerJid) {
  5631. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5632. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5633. if (!contact || contact.length <= 0)
  5634. ContactList.addContact(peerJid);
  5635. },
  5636. /**
  5637. * Adds a contact for the given peer jid.
  5638. *
  5639. * @param peerJid the jid of the contact to add
  5640. */
  5641. addContact: function (peerJid) {
  5642. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5643. var contactlist = $('#contacts');
  5644. var newContact = document.createElement('li');
  5645. newContact.id = resourceJid;
  5646. newContact.className = "clickable";
  5647. newContact.onclick = function (event) {
  5648. if (event.currentTarget.className === "clickable") {
  5649. $(ContactList).trigger('contactclicked', [peerJid]);
  5650. }
  5651. };
  5652. newContact.appendChild(createAvatar(peerJid));
  5653. newContact.appendChild(createDisplayNameParagraph("participant"));
  5654. if (resourceJid === APP.xmpp.myResource()) {
  5655. contactlist.prepend(newContact);
  5656. }
  5657. else {
  5658. contactlist.append(newContact);
  5659. }
  5660. updateNumberOfParticipants(1);
  5661. },
  5662. /**
  5663. * Removes a contact for the given peer jid.
  5664. *
  5665. * @param peerJid the peerJid corresponding to the contact to remove
  5666. */
  5667. removeContact: function (peerJid) {
  5668. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5669. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5670. if (contact && contact.length > 0) {
  5671. var contactlist = $('#contactlist>ul');
  5672. contactlist.get(0).removeChild(contact.get(0));
  5673. updateNumberOfParticipants(-1);
  5674. }
  5675. },
  5676. setVisualNotification: function (show, stopGlowingIn) {
  5677. var glower = $('#contactListButton');
  5678. if (show && !notificationInterval) {
  5679. notificationInterval = window.setInterval(function () {
  5680. glower.toggleClass('active glowing');
  5681. }, 800);
  5682. }
  5683. else if (!show && notificationInterval) {
  5684. stopGlowing(glower);
  5685. }
  5686. if (stopGlowingIn) {
  5687. setTimeout(function () {
  5688. stopGlowing(glower);
  5689. }, stopGlowingIn);
  5690. }
  5691. },
  5692. setClickable: function (resourceJid, isClickable) {
  5693. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5694. if (isClickable) {
  5695. contact.addClass('clickable');
  5696. } else {
  5697. contact.removeClass('clickable');
  5698. }
  5699. },
  5700. onDisplayNameChange: function (peerJid, displayName) {
  5701. if (peerJid === 'localVideoContainer')
  5702. peerJid = APP.xmpp.myJid();
  5703. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5704. var contactName = $('#contacts #' + resourceJid + '>p');
  5705. if (contactName && displayName && displayName.length > 0)
  5706. contactName.html(displayName);
  5707. },
  5708. userAvatarChanged: function (resourceJid, contactListUrl) {
  5709. // set the avatar in the contact list
  5710. var contact = $('#' + resourceJid + '>img');
  5711. if (contact && contact.length > 0) {
  5712. contact.get(0).src = contactListUrl;
  5713. }
  5714. }
  5715. };
  5716. module.exports = ContactList;
  5717. },{"../../avatar/Avatar":16}],26:[function(require,module,exports){
  5718. var Avatar = require("../../avatar/Avatar");
  5719. var Settings = require("./../../../settings/Settings");
  5720. var UIUtil = require("../../util/UIUtil");
  5721. var languages = require("../../../../service/translation/languages");
  5722. function generateLanguagesSelectBox()
  5723. {
  5724. var currentLang = APP.translation.getCurrentLanguage();
  5725. var html = "<select id=\"languages_selectbox\">";
  5726. var langArray = languages.getLanguages();
  5727. for(var i = 0; i < langArray.length; i++)
  5728. {
  5729. var lang = langArray[i];
  5730. html += "<option ";
  5731. if(lang === currentLang)
  5732. html += "selected ";
  5733. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  5734. html += "</option>";
  5735. }
  5736. return html + "</select>";
  5737. }
  5738. var SettingsMenu = {
  5739. init: function () {
  5740. $("#startMutedOptions").before(generateLanguagesSelectBox());
  5741. APP.translation.translateElement($("#languages_selectbox"));
  5742. $('#settingsmenu>input').keyup(function(event){
  5743. if(event.keyCode === 13) {//enter
  5744. SettingsMenu.update();
  5745. }
  5746. });
  5747. if(APP.xmpp.isModerator())
  5748. {
  5749. $("#startMutedOptions").css("display", "block");
  5750. }
  5751. else
  5752. {
  5753. $("#startMutedOptions").css("display", "none");
  5754. }
  5755. $("#updateSettings").click(function () {
  5756. SettingsMenu.update();
  5757. });
  5758. },
  5759. onRoleChanged: function () {
  5760. if(APP.xmpp.isModerator())
  5761. {
  5762. $("#startMutedOptions").css("display", "block");
  5763. }
  5764. else
  5765. {
  5766. $("#startMutedOptions").css("display", "none");
  5767. }
  5768. },
  5769. setStartMuted: function (audio, video) {
  5770. $("#startAudioMuted").attr("checked", audio);
  5771. $("#startVideoMuted").attr("checked", video);
  5772. },
  5773. update: function() {
  5774. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  5775. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  5776. if(newDisplayName) {
  5777. var displayName = Settings.setDisplayName(newDisplayName);
  5778. APP.xmpp.addToPresence("displayName", displayName, true);
  5779. }
  5780. var language = $("#languages_selectbox").val();
  5781. APP.translation.setLanguage(language);
  5782. Settings.setLanguage(language);
  5783. APP.xmpp.addToPresence("email", newEmail);
  5784. var email = Settings.setEmail(newEmail);
  5785. var startAudioMuted = ($("#startAudioMuted").is(":checked"));
  5786. var startVideoMuted = ($("#startVideoMuted").is(":checked"));
  5787. APP.xmpp.addToPresence("startMuted",
  5788. [startAudioMuted, startVideoMuted]);
  5789. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  5790. },
  5791. isVisible: function() {
  5792. return $('#settingsmenu').is(':visible');
  5793. },
  5794. setDisplayName: function(newDisplayName) {
  5795. var displayName = Settings.setDisplayName(newDisplayName);
  5796. $('#setDisplayName').get(0).value = displayName;
  5797. },
  5798. onDisplayNameChange: function(peerJid, newDisplayName) {
  5799. if(peerJid === 'localVideoContainer' ||
  5800. peerJid === APP.xmpp.myJid()) {
  5801. this.setDisplayName(newDisplayName);
  5802. }
  5803. },
  5804. changeAvatar: function (thumbUrl) {
  5805. $('#avatar').get(0).src = thumbUrl;
  5806. }
  5807. };
  5808. module.exports = SettingsMenu;
  5809. },{"../../../../service/translation/languages":107,"../../avatar/Avatar":16,"../../util/UIUtil":33,"./../../../settings/Settings":47}],27:[function(require,module,exports){
  5810. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5811. var buttonHandlers = {
  5812. "bottom_toolbar_contact_list": function () {
  5813. BottomToolbar.toggleContactList();
  5814. },
  5815. "bottom_toolbar_film_strip": function () {
  5816. BottomToolbar.toggleFilmStrip();
  5817. },
  5818. "bottom_toolbar_chat": function () {
  5819. BottomToolbar.toggleChat();
  5820. }
  5821. };
  5822. var BottomToolbar = (function (my) {
  5823. my.init = function () {
  5824. for(var k in buttonHandlers)
  5825. $("#" + k).click(buttonHandlers[k]);
  5826. };
  5827. my.toggleChat = function() {
  5828. PanelToggler.toggleChat();
  5829. };
  5830. my.toggleContactList = function() {
  5831. PanelToggler.toggleContactList();
  5832. };
  5833. my.toggleFilmStrip = function() {
  5834. var filmstrip = $("#remoteVideos");
  5835. filmstrip.toggleClass("hidden");
  5836. };
  5837. $(document).bind("remotevideo.resized", function (event, width, height) {
  5838. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  5839. $('#bottomToolbar').css({bottom: bottom + 'px'});
  5840. });
  5841. return my;
  5842. }(BottomToolbar || {}));
  5843. module.exports = BottomToolbar;
  5844. },{"../side_pannels/SidePanelToggler":20}],28:[function(require,module,exports){
  5845. /* global APP,$, buttonClick, config, lockRoom,
  5846. setSharedKey, Util */
  5847. var messageHandler = require("../util/MessageHandler");
  5848. var BottomToolbar = require("./BottomToolbar");
  5849. var Prezi = require("../prezi/Prezi");
  5850. var Etherpad = require("../etherpad/Etherpad");
  5851. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5852. var Authentication = require("../authentication/Authentication");
  5853. var UIUtil = require("../util/UIUtil");
  5854. var AuthenticationEvents
  5855. = require("../../../service/authentication/AuthenticationEvents");
  5856. var roomUrl = null;
  5857. var sharedKey = '';
  5858. var UI = null;
  5859. var buttonHandlers =
  5860. {
  5861. "toolbar_button_mute": function () {
  5862. return APP.UI.toggleAudio();
  5863. },
  5864. "toolbar_button_camera": function () {
  5865. return APP.UI.toggleVideo();
  5866. },
  5867. /*"toolbar_button_authentication": function () {
  5868. return Toolbar.authenticateClicked();
  5869. },*/
  5870. "toolbar_button_record": function () {
  5871. return toggleRecording();
  5872. },
  5873. "toolbar_button_security": function () {
  5874. return Toolbar.openLockDialog();
  5875. },
  5876. "toolbar_button_link": function () {
  5877. return Toolbar.openLinkDialog();
  5878. },
  5879. "toolbar_button_chat": function () {
  5880. return BottomToolbar.toggleChat();
  5881. },
  5882. "toolbar_button_prezi": function () {
  5883. return Prezi.openPreziDialog();
  5884. },
  5885. "toolbar_button_etherpad": function () {
  5886. return Etherpad.toggleEtherpad(0);
  5887. },
  5888. "toolbar_button_desktopsharing": function () {
  5889. return APP.desktopsharing.toggleScreenSharing();
  5890. },
  5891. "toolbar_button_fullScreen": function()
  5892. {
  5893. UIUtil.buttonClick("#fullScreen", "icon-full-screen icon-exit-full-screen");
  5894. return Toolbar.toggleFullScreen();
  5895. },
  5896. "toolbar_button_sip": function () {
  5897. return callSipButtonClicked();
  5898. },
  5899. "toolbar_button_dialpad": function () {
  5900. return dialpadButtonClicked();
  5901. },
  5902. "toolbar_button_settings": function () {
  5903. PanelToggler.toggleSettingsMenu();
  5904. },
  5905. "toolbar_button_hangup": function () {
  5906. return hangup();
  5907. },
  5908. "toolbar_button_login": function () {
  5909. Toolbar.authenticateClicked();
  5910. },
  5911. "toolbar_button_logout": function () {
  5912. // Ask for confirmation
  5913. messageHandler.openTwoButtonDialog(
  5914. "dialog.logoutTitle",
  5915. null,
  5916. "dialog.logoutQuestion",
  5917. null,
  5918. false,
  5919. "dialog.Yes",
  5920. function (evt, yes) {
  5921. if (yes) {
  5922. APP.xmpp.logout(function (url) {
  5923. if (url) {
  5924. window.location.href = url;
  5925. } else {
  5926. hangup();
  5927. }
  5928. });
  5929. }
  5930. });
  5931. }
  5932. };
  5933. function hangup() {
  5934. APP.xmpp.disposeConference();
  5935. if(config.enableWelcomePage)
  5936. {
  5937. setTimeout(function()
  5938. {
  5939. window.localStorage.welcomePageDisabled = false;
  5940. window.location.pathname = "/";
  5941. }, 10000);
  5942. }
  5943. var title = APP.translation.generateTranslationHTML(
  5944. "dialog.sessTerminated");
  5945. var msg = APP.translation.generateTranslationHTML(
  5946. "dialog.hungUp");
  5947. var button = APP.translation.generateTranslationHTML(
  5948. "dialog.joinAgain");
  5949. var buttons = [];
  5950. buttons.push({title: button, value: true});
  5951. UI.messageHandler.openDialog(
  5952. title,
  5953. msg,
  5954. true,
  5955. buttons,
  5956. function(event, value, message, formVals)
  5957. {
  5958. window.location.reload();
  5959. return false;
  5960. }
  5961. );
  5962. }
  5963. /**
  5964. * Starts or stops the recording for the conference.
  5965. */
  5966. function toggleRecording() {
  5967. APP.xmpp.toggleRecording(function (callback) {
  5968. var msg = APP.translation.generateTranslationHTML(
  5969. "dialog.recordingToken");
  5970. var token = APP.translation.translateString("dialog.token");
  5971. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  5972. '<h2>' + msg + '</h2>' +
  5973. '<input name="recordingToken" type="text" ' +
  5974. ' data-i18n="[placeholder]dialog.token" ' +
  5975. 'placeholder="' + token + '" autofocus>',
  5976. false,
  5977. "dialog.Save",
  5978. function (e, v, m, f) {
  5979. if (v) {
  5980. var token = f.recordingToken;
  5981. if (token) {
  5982. callback(UIUtil.escapeHtml(token));
  5983. }
  5984. }
  5985. },
  5986. null,
  5987. function () { },
  5988. ':input:first'
  5989. );
  5990. }, Toolbar.setRecordingButtonState, Toolbar.setRecordingButtonState);
  5991. }
  5992. /**
  5993. * Locks / unlocks the room.
  5994. */
  5995. function lockRoom(lock) {
  5996. var currentSharedKey = '';
  5997. if (lock)
  5998. currentSharedKey = sharedKey;
  5999. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  6000. // password is required
  6001. if (sharedKey)
  6002. {
  6003. console.log('set room password');
  6004. Toolbar.lockLockButton();
  6005. }
  6006. else
  6007. {
  6008. console.log('removed room password');
  6009. Toolbar.unlockLockButton();
  6010. }
  6011. }, function (err) {
  6012. console.warn('setting password failed', err);
  6013. messageHandler.showError("dialog.lockTitle",
  6014. "dialog.lockMessage");
  6015. Toolbar.setSharedKey('');
  6016. }, function () {
  6017. console.warn('room passwords not supported');
  6018. messageHandler.showError("dialog.warning",
  6019. "dialog.passwordNotSupported");
  6020. Toolbar.setSharedKey('');
  6021. });
  6022. };
  6023. /**
  6024. * Invite participants to conference.
  6025. */
  6026. function inviteParticipants() {
  6027. if (roomUrl === null)
  6028. return;
  6029. var sharedKeyText = "";
  6030. if (sharedKey && sharedKey.length > 0) {
  6031. sharedKeyText =
  6032. APP.translation.translateString("email.sharedKey",
  6033. {sharedKey: sharedKey});
  6034. sharedKeyText = sharedKeyText.replace(/\n/g, "%0D%0A");
  6035. }
  6036. var supportedBrowsers = "Chromium, Google Chrome " +
  6037. APP.translation.translateString("email.and") + " Opera";
  6038. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  6039. var subject = APP.translation.translateString("email.subject",
  6040. {appName:interfaceConfig.APP_NAME, conferenceName: conferenceName});
  6041. var body = APP.translation.translateString("email.body",
  6042. {appName:interfaceConfig.APP_NAME, sharedKeyText: sharedKeyText,
  6043. roomUrl: roomUrl, supportedBrowsers: supportedBrowsers});
  6044. body = body.replace(/\n/g, "%0D%0A");
  6045. if (window.localStorage.displayname) {
  6046. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  6047. }
  6048. if (interfaceConfig.INVITATION_POWERED_BY) {
  6049. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  6050. }
  6051. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  6052. }
  6053. function dialpadButtonClicked()
  6054. {
  6055. //TODO show the dialpad window
  6056. }
  6057. function callSipButtonClicked()
  6058. {
  6059. var defaultNumber
  6060. = config.defaultSipNumber ? config.defaultSipNumber : '';
  6061. var sipMsg = APP.translation.generateTranslationHTML(
  6062. "dialog.sipMsg");
  6063. messageHandler.openTwoButtonDialog(null, null, null,
  6064. '<h2>' + sipMsg + '</h2>' +
  6065. '<input name="sipNumber" type="text"' +
  6066. ' value="' + defaultNumber + '" autofocus>',
  6067. false,
  6068. "dialog.Dial",
  6069. function (e, v, m, f) {
  6070. if (v) {
  6071. var numberInput = f.sipNumber;
  6072. if (numberInput) {
  6073. APP.xmpp.dial(
  6074. numberInput, 'fromnumber', UI.getRoomName(), sharedKey);
  6075. }
  6076. }
  6077. },
  6078. null, null, ':input:first'
  6079. );
  6080. }
  6081. var Toolbar = (function (my) {
  6082. my.init = function (ui) {
  6083. for(var k in buttonHandlers)
  6084. $("#" + k).click(buttonHandlers[k]);
  6085. UI = ui;
  6086. // Update login info
  6087. APP.xmpp.addListener(
  6088. AuthenticationEvents.IDENTITY_UPDATED,
  6089. function (authenticationEnabled, userIdentity) {
  6090. var loggedIn = false;
  6091. if (userIdentity) {
  6092. loggedIn = true;
  6093. }
  6094. Toolbar.showAuthenticateButton(authenticationEnabled);
  6095. if (authenticationEnabled) {
  6096. Toolbar.setAuthenticatedIdentity(userIdentity);
  6097. Toolbar.showLoginButton(!loggedIn);
  6098. Toolbar.showLogoutButton(loggedIn);
  6099. }
  6100. }
  6101. );
  6102. },
  6103. /**
  6104. * Sets shared key
  6105. * @param sKey the shared key
  6106. */
  6107. my.setSharedKey = function (sKey) {
  6108. sharedKey = sKey;
  6109. };
  6110. my.authenticateClicked = function () {
  6111. Authentication.focusAuthenticationWindow();
  6112. if (!APP.xmpp.isExternalAuthEnabled()) {
  6113. Authentication.xmppAuthenticate();
  6114. return;
  6115. }
  6116. // Get authentication URL
  6117. if (!APP.xmpp.getMUCJoined()) {
  6118. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  6119. // If conference has not been started yet - redirect to login page
  6120. window.location.href = url;
  6121. });
  6122. } else {
  6123. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  6124. // Otherwise - open popup with authentication URL
  6125. var authenticationWindow = Authentication.createAuthenticationWindow(
  6126. function () {
  6127. // On popup closed - retry room allocation
  6128. APP.xmpp.allocateConferenceFocus(
  6129. APP.UI.getRoomName(),
  6130. function () { console.info("AUTH DONE"); }
  6131. );
  6132. }, url);
  6133. if (!authenticationWindow) {
  6134. messageHandler.openMessageDialog(
  6135. null, "dialog.popupError");
  6136. }
  6137. });
  6138. }
  6139. };
  6140. /**
  6141. * Updates the room invite url.
  6142. */
  6143. my.updateRoomUrl = function (newRoomUrl) {
  6144. roomUrl = newRoomUrl;
  6145. // If the invite dialog has been already opened we update the information.
  6146. var inviteLink = document.getElementById('inviteLinkRef');
  6147. if (inviteLink) {
  6148. inviteLink.value = roomUrl;
  6149. inviteLink.select();
  6150. $('#inviteLinkRef').parent()
  6151. .find('button[value=true]').prop('disabled', false);
  6152. }
  6153. };
  6154. /**
  6155. * Disables and enables some of the buttons.
  6156. */
  6157. my.setupButtonsFromConfig = function () {
  6158. if (config.disablePrezi)
  6159. {
  6160. $("#prezi_button").css({display: "none"});
  6161. }
  6162. };
  6163. /**
  6164. * Opens the lock room dialog.
  6165. */
  6166. my.openLockDialog = function () {
  6167. // Only the focus is able to set a shared key.
  6168. if (!APP.xmpp.isModerator()) {
  6169. if (sharedKey) {
  6170. messageHandler.openMessageDialog(null,
  6171. "dialog.passwordError");
  6172. } else {
  6173. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  6174. }
  6175. } else {
  6176. if (sharedKey) {
  6177. messageHandler.openTwoButtonDialog(null, null,
  6178. "dialog.passwordCheck",
  6179. null,
  6180. false,
  6181. "dialog.Remove",
  6182. function (e, v) {
  6183. if (v) {
  6184. Toolbar.setSharedKey('');
  6185. lockRoom(false);
  6186. }
  6187. });
  6188. } else {
  6189. var msg = APP.translation.generateTranslationHTML(
  6190. "dialog.passwordMsg");
  6191. var yourPassword = APP.translation.translateString(
  6192. "dialog.yourPassword");
  6193. messageHandler.openTwoButtonDialog(null, null, null,
  6194. '<h2>' + msg + '</h2>' +
  6195. '<input name="lockKey" type="text"' +
  6196. ' data-i18n="[placeholder]dialog.yourPassword" ' +
  6197. 'placeholder="' + yourPassword + '" autofocus>',
  6198. false,
  6199. "dialog.Save",
  6200. function (e, v, m, f) {
  6201. if (v) {
  6202. var lockKey = f.lockKey;
  6203. if (lockKey) {
  6204. Toolbar.setSharedKey(
  6205. UIUtil.escapeHtml(lockKey));
  6206. lockRoom(true);
  6207. }
  6208. }
  6209. },
  6210. null, null, 'input:first'
  6211. );
  6212. }
  6213. }
  6214. };
  6215. /**
  6216. * Opens the invite link dialog.
  6217. */
  6218. my.openLinkDialog = function () {
  6219. var inviteAttreibutes;
  6220. if (roomUrl === null) {
  6221. inviteAttreibutes = 'data-i18n="[value]roomUrlDefaultMsg" value="' +
  6222. APP.translation.translateString("roomUrlDefaultMsg") + '"';
  6223. } else {
  6224. inviteAttreibutes = "value=\"" + encodeURI(roomUrl) + "\"";
  6225. }
  6226. messageHandler.openTwoButtonDialog("dialog.shareLink",
  6227. null, null,
  6228. '<input id="inviteLinkRef" type="text" ' +
  6229. inviteAttreibutes + ' onclick="this.select();" readonly>',
  6230. false,
  6231. "dialog.Invite",
  6232. function (e, v) {
  6233. if (v) {
  6234. if (roomUrl) {
  6235. inviteParticipants();
  6236. }
  6237. }
  6238. },
  6239. function (event) {
  6240. if (roomUrl) {
  6241. document.getElementById('inviteLinkRef').select();
  6242. } else {
  6243. if (event && event.target)
  6244. $(event.target)
  6245. .find('button[value=true]').prop('disabled', true);
  6246. }
  6247. }
  6248. );
  6249. };
  6250. /**
  6251. * Opens the settings dialog.
  6252. * FIXME: not used ?
  6253. */
  6254. my.openSettingsDialog = function () {
  6255. var settings1 = APP.translation.generateTranslationHTML(
  6256. "dialog.settings1");
  6257. var settings2 = APP.translation.generateTranslationHTML(
  6258. "dialog.settings2");
  6259. var settings3 = APP.translation.generateTranslationHTML(
  6260. "dialog.settings3");
  6261. var yourPassword = APP.translation.translateString(
  6262. "dialog.yourPassword");
  6263. messageHandler.openTwoButtonDialog(null,
  6264. '<h2>' + settings1 + '</h2>' +
  6265. '<input type="checkbox" id="initMuted">' +
  6266. settings2 + '<br/>' +
  6267. '<input type="checkbox" id="requireNicknames">' +
  6268. settings3 +
  6269. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  6270. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  6271. null,
  6272. null,
  6273. false,
  6274. "dialog.Save",
  6275. function () {
  6276. document.getElementById('lockKey').focus();
  6277. },
  6278. function (e, v) {
  6279. if (v) {
  6280. if ($('#initMuted').is(":checked")) {
  6281. // it is checked
  6282. }
  6283. if ($('#requireNicknames').is(":checked")) {
  6284. // it is checked
  6285. }
  6286. /*
  6287. var lockKey = document.getElementById('lockKey');
  6288. if (lockKey.value) {
  6289. setSharedKey(lockKey.value);
  6290. lockRoom(true);
  6291. }
  6292. */
  6293. }
  6294. }
  6295. );
  6296. };
  6297. /**
  6298. * Toggles the application in and out of full screen mode
  6299. * (a.k.a. presentation mode in Chrome).
  6300. */
  6301. my.toggleFullScreen = function () {
  6302. var fsElement = document.documentElement;
  6303. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  6304. //Enter Full Screen
  6305. if (fsElement.mozRequestFullScreen) {
  6306. fsElement.mozRequestFullScreen();
  6307. }
  6308. else {
  6309. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  6310. }
  6311. } else {
  6312. //Exit Full Screen
  6313. if (document.mozCancelFullScreen) {
  6314. document.mozCancelFullScreen();
  6315. } else {
  6316. document.webkitCancelFullScreen();
  6317. }
  6318. }
  6319. };
  6320. /**
  6321. * Unlocks the lock button state.
  6322. */
  6323. my.unlockLockButton = function () {
  6324. if ($("#lockIcon").hasClass("icon-security-locked"))
  6325. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  6326. };
  6327. /**
  6328. * Updates the lock button state to locked.
  6329. */
  6330. my.lockLockButton = function () {
  6331. if ($("#lockIcon").hasClass("icon-security"))
  6332. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  6333. };
  6334. /**
  6335. * Shows or hides authentication button
  6336. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  6337. */
  6338. my.showAuthenticateButton = function (show) {
  6339. if (show) {
  6340. $('#authentication').css({display: "inline"});
  6341. }
  6342. else {
  6343. $('#authentication').css({display: "none"});
  6344. }
  6345. };
  6346. // Shows or hides the 'recording' button.
  6347. my.showRecordingButton = function (show) {
  6348. if (!config.enableRecording) {
  6349. return;
  6350. }
  6351. if (show) {
  6352. $('#recording').css({display: "inline"});
  6353. }
  6354. else {
  6355. $('#recording').css({display: "none"});
  6356. }
  6357. };
  6358. // Sets the state of the recording button
  6359. my.setRecordingButtonState = function (isRecording) {
  6360. var selector = $('#recordButton');
  6361. if (isRecording) {
  6362. selector.removeClass("icon-recEnable");
  6363. selector.addClass("icon-recEnable active");
  6364. } else {
  6365. selector.removeClass("icon-recEnable active");
  6366. selector.addClass("icon-recEnable");
  6367. }
  6368. };
  6369. // Shows or hides SIP calls button
  6370. my.showSipCallButton = function (show) {
  6371. if (APP.xmpp.isSipGatewayEnabled() && show) {
  6372. $('#sipCallButton').css({display: "inline-block"});
  6373. } else {
  6374. $('#sipCallButton').css({display: "none"});
  6375. }
  6376. };
  6377. // Shows or hides the dialpad button
  6378. my.showDialPadButton = function (show) {
  6379. if (show) {
  6380. $('#dialPadButton').css({display: "inline-block"});
  6381. } else {
  6382. $('#dialPadButton').css({display: "none"});
  6383. }
  6384. };
  6385. /**
  6386. * Displays user authenticated identity name(login).
  6387. * @param authIdentity identity name to be displayed.
  6388. */
  6389. my.setAuthenticatedIdentity = function (authIdentity) {
  6390. if (authIdentity) {
  6391. var selector = $('#toolbar_auth_identity');
  6392. selector.css({display: "list-item"});
  6393. selector.text(authIdentity);
  6394. } else {
  6395. $('#toolbar_auth_identity').css({display: "none"});
  6396. }
  6397. };
  6398. /**
  6399. * Shows/hides login button.
  6400. * @param show <tt>true</tt> to show
  6401. */
  6402. my.showLoginButton = function (show) {
  6403. if (show) {
  6404. $('#toolbar_button_login').css({display: "list-item"});
  6405. } else {
  6406. $('#toolbar_button_login').css({display: "none"});
  6407. }
  6408. };
  6409. /**
  6410. * Shows/hides logout button.
  6411. * @param show <tt>true</tt> to show
  6412. */
  6413. my.showLogoutButton = function (show) {
  6414. if (show) {
  6415. $('#toolbar_button_logout').css({display: "list-item"});
  6416. } else {
  6417. $('#toolbar_button_logout').css({display: "none"});
  6418. }
  6419. };
  6420. /**
  6421. * Sets the state of the button. The button has blue glow if desktop
  6422. * streaming is active.
  6423. * @param active the state of the desktop streaming.
  6424. */
  6425. my.changeDesktopSharingButtonState = function (active) {
  6426. var button = $("#desktopsharing > a");
  6427. if (active)
  6428. {
  6429. button.addClass("glow");
  6430. }
  6431. else
  6432. {
  6433. button.removeClass("glow");
  6434. }
  6435. };
  6436. return my;
  6437. }(Toolbar || {}));
  6438. module.exports = Toolbar;
  6439. },{"../../../service/authentication/AuthenticationEvents":103,"../authentication/Authentication":14,"../etherpad/Etherpad":17,"../prezi/Prezi":18,"../side_pannels/SidePanelToggler":20,"../util/MessageHandler":31,"../util/UIUtil":33,"./BottomToolbar":27}],29:[function(require,module,exports){
  6440. /* global $, interfaceConfig, Moderator, DesktopStreaming.showDesktopSharingButton */
  6441. var toolbarTimeoutObject,
  6442. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  6443. function showDesktopSharingButton() {
  6444. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  6445. $('#desktopsharing').css({display: "inline"});
  6446. } else {
  6447. $('#desktopsharing').css({display: "none"});
  6448. }
  6449. }
  6450. /**
  6451. * Hides the toolbar.
  6452. */
  6453. function hideToolbar() {
  6454. if(config.alwaysVisibleToolbar)
  6455. return;
  6456. var header = $("#header"),
  6457. bottomToolbar = $("#bottomToolbar");
  6458. var isToolbarHover = false;
  6459. header.find('*').each(function () {
  6460. var id = $(this).attr('id');
  6461. if ($("#" + id + ":hover").length > 0) {
  6462. isToolbarHover = true;
  6463. }
  6464. });
  6465. if ($("#bottomToolbar:hover").length > 0) {
  6466. isToolbarHover = true;
  6467. }
  6468. clearTimeout(toolbarTimeoutObject);
  6469. toolbarTimeoutObject = null;
  6470. if (!isToolbarHover) {
  6471. header.hide("slide", { direction: "up", duration: 300});
  6472. $('#subject').animate({top: "-=40"}, 300);
  6473. if ($("#remoteVideos").hasClass("hidden")) {
  6474. bottomToolbar.hide(
  6475. "slide", {direction: "right", duration: 300});
  6476. }
  6477. }
  6478. else {
  6479. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6480. }
  6481. }
  6482. var ToolbarToggler = {
  6483. /**
  6484. * Shows the main toolbar.
  6485. */
  6486. showToolbar: function () {
  6487. var header = $("#header"),
  6488. bottomToolbar = $("#bottomToolbar");
  6489. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  6490. header.show("slide", { direction: "up", duration: 300});
  6491. $('#subject').animate({top: "+=40"}, 300);
  6492. if (!bottomToolbar.is(":visible")) {
  6493. bottomToolbar.show(
  6494. "slide", {direction: "right", duration: 300});
  6495. }
  6496. if (toolbarTimeoutObject) {
  6497. clearTimeout(toolbarTimeoutObject);
  6498. toolbarTimeoutObject = null;
  6499. }
  6500. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6501. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  6502. }
  6503. if (APP.xmpp.isModerator())
  6504. {
  6505. // TODO: Enable settings functionality.
  6506. // Need to uncomment the settings button in index.html.
  6507. // $('#settingsButton').css({visibility:"visible"});
  6508. }
  6509. // Show/hide desktop sharing button
  6510. showDesktopSharingButton();
  6511. },
  6512. /**
  6513. * Docks/undocks the toolbar.
  6514. *
  6515. * @param isDock indicates what operation to perform
  6516. */
  6517. dockToolbar: function (isDock) {
  6518. if (isDock) {
  6519. // First make sure the toolbar is shown.
  6520. if (!$('#header').is(':visible')) {
  6521. this.showToolbar();
  6522. }
  6523. // Then clear the time out, to dock the toolbar.
  6524. if (toolbarTimeoutObject) {
  6525. clearTimeout(toolbarTimeoutObject);
  6526. toolbarTimeoutObject = null;
  6527. }
  6528. }
  6529. else {
  6530. if (!$('#header').is(':visible')) {
  6531. this.showToolbar();
  6532. }
  6533. else {
  6534. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6535. }
  6536. }
  6537. },
  6538. showDesktopSharingButton: showDesktopSharingButton
  6539. };
  6540. module.exports = ToolbarToggler;
  6541. },{}],30:[function(require,module,exports){
  6542. var JitsiPopover = (function () {
  6543. /**
  6544. * Constructs new JitsiPopover and attaches it to the element
  6545. * @param element jquery selector
  6546. * @param options the options for the popover.
  6547. * @constructor
  6548. */
  6549. function JitsiPopover(element, options)
  6550. {
  6551. this.options = {
  6552. skin: "white",
  6553. content: ""
  6554. };
  6555. if(options)
  6556. {
  6557. if(options.skin)
  6558. this.options.skin = options.skin;
  6559. if(options.content)
  6560. this.options.content = options.content;
  6561. }
  6562. this.elementIsHovered = false;
  6563. this.popoverIsHovered = false;
  6564. this.popoverShown = false;
  6565. element.data("jitsi_popover", this);
  6566. this.element = element;
  6567. this.template = ' <div class="jitsipopover ' + this.options.skin +
  6568. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  6569. '<div class="jitsiPopupmenuPadding"></div></div>';
  6570. var self = this;
  6571. this.element.on("mouseenter", function () {
  6572. self.elementIsHovered = true;
  6573. self.show();
  6574. }).on("mouseleave", function () {
  6575. self.elementIsHovered = false;
  6576. setTimeout(function () {
  6577. self.hide();
  6578. }, 10);
  6579. });
  6580. }
  6581. /**
  6582. * Shows the popover
  6583. */
  6584. JitsiPopover.prototype.show = function () {
  6585. this.createPopover();
  6586. this.popoverShown = true;
  6587. };
  6588. /**
  6589. * Hides the popover
  6590. */
  6591. JitsiPopover.prototype.hide = function () {
  6592. if(!this.elementIsHovered && !this.popoverIsHovered && this.popoverShown)
  6593. {
  6594. this.forceHide();
  6595. }
  6596. };
  6597. /**
  6598. * Hides the popover
  6599. */
  6600. JitsiPopover.prototype.forceHide = function () {
  6601. $(".jitsipopover").remove();
  6602. this.popoverShown = false;
  6603. };
  6604. /**
  6605. * Creates the popover html
  6606. */
  6607. JitsiPopover.prototype.createPopover = function () {
  6608. $("body").append(this.template);
  6609. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  6610. var self = this;
  6611. $(".jitsipopover").on("mouseenter", function () {
  6612. self.popoverIsHovered = true;
  6613. }).on("mouseleave", function () {
  6614. self.popoverIsHovered = false;
  6615. self.hide();
  6616. });
  6617. this.refreshPosition();
  6618. };
  6619. /**
  6620. * Refreshes the position of the popover
  6621. */
  6622. JitsiPopover.prototype.refreshPosition = function () {
  6623. $(".jitsipopover").position({
  6624. my: "bottom",
  6625. at: "top",
  6626. collision: "fit",
  6627. of: this.element,
  6628. using: function (position, elements) {
  6629. var calcLeft = elements.target.left - elements.element.left + elements.target.width/2;
  6630. $(".jitsipopover").css({top: position.top, left: position.left, display: "table"});
  6631. $(".jitsipopover > .arrow").css({left: calcLeft});
  6632. $(".jitsipopover > .jitsiPopupmenuPadding").css({left: calcLeft - 50});
  6633. }
  6634. });
  6635. };
  6636. /**
  6637. * Updates the content of popover.
  6638. * @param content new content
  6639. */
  6640. JitsiPopover.prototype.updateContent = function (content) {
  6641. this.options.content = content;
  6642. if(!this.popoverShown)
  6643. return;
  6644. $(".jitsipopover").remove();
  6645. this.createPopover();
  6646. };
  6647. return JitsiPopover;
  6648. })();
  6649. module.exports = JitsiPopover;
  6650. },{}],31:[function(require,module,exports){
  6651. /* global $, APP, jQuery, toastr */
  6652. var messageHandler = (function(my) {
  6653. /**
  6654. * Shows a message to the user.
  6655. *
  6656. * @param titleString the title of the message
  6657. * @param messageString the text of the message
  6658. */
  6659. my.openMessageDialog = function(titleKey, messageKey) {
  6660. var title = null;
  6661. if(titleKey)
  6662. {
  6663. title = APP.translation.generateTranslationHTML(titleKey);
  6664. }
  6665. var message = APP.translation.generateTranslationHTML(messageKey);
  6666. $.prompt(message,
  6667. {
  6668. title: title,
  6669. persistent: false
  6670. }
  6671. );
  6672. };
  6673. /**
  6674. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  6675. *
  6676. * @param titleString the title of the message
  6677. * @param msgString the text of the message
  6678. * @param persistent boolean value which determines whether the message is persistent or not
  6679. * @param leftButton the fist button's text
  6680. * @param submitFunction function to be called on submit
  6681. * @param loadedFunction function to be called after the prompt is fully loaded
  6682. * @param closeFunction function to be called after the prompt is closed
  6683. * @param focus optional focus selector or button index to be focused after
  6684. * the dialog is opened
  6685. * @param defaultButton index of default button which will be activated when
  6686. * the user press 'enter'. Indexed from 0.
  6687. */
  6688. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  6689. persistent, leftButtonKey, submitFunction, loadedFunction,
  6690. closeFunction, focus, defaultButton)
  6691. {
  6692. var buttons = [];
  6693. var leftButton = APP.translation.generateTranslationHTML(leftButtonKey);
  6694. buttons.push({ title: leftButton, value: true});
  6695. var cancelButton
  6696. = APP.translation.generateTranslationHTML("dialog.Cancel");
  6697. buttons.push({title: cancelButton, value: false});
  6698. var message = msgString, title = titleString;
  6699. if (titleKey)
  6700. {
  6701. title = APP.translation.generateTranslationHTML(titleKey);
  6702. }
  6703. if (msgKey) {
  6704. message = APP.translation.generateTranslationHTML(msgKey);
  6705. }
  6706. $.prompt(message, {
  6707. title: title,
  6708. persistent: false,
  6709. buttons: buttons,
  6710. defaultButton: defaultButton,
  6711. focus: focus,
  6712. loaded: loadedFunction,
  6713. submit: submitFunction,
  6714. close: closeFunction
  6715. });
  6716. };
  6717. /**
  6718. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  6719. *
  6720. * @param titleString the title of the message
  6721. * @param msgString the text of the message
  6722. * @param persistent boolean value which determines whether the message is persistent or not
  6723. * @param buttons object with the buttons. The keys must be the name of the button and value is the value
  6724. * that will be passed to submitFunction
  6725. * @param submitFunction function to be called on submit
  6726. * @param loadedFunction function to be called after the prompt is fully loaded
  6727. */
  6728. my.openDialog = function (titleString, msgString, persistent, buttons,
  6729. submitFunction, loadedFunction) {
  6730. var args = {
  6731. title: titleString,
  6732. persistent: persistent,
  6733. buttons: buttons,
  6734. defaultButton: 1,
  6735. loaded: loadedFunction,
  6736. submit: submitFunction
  6737. };
  6738. if (persistent) {
  6739. args.closeText = '';
  6740. }
  6741. return new Impromptu(msgString, args);
  6742. };
  6743. /**
  6744. * Closes currently opened dialog.
  6745. */
  6746. my.closeDialog = function () {
  6747. $.prompt.close();
  6748. };
  6749. /**
  6750. * Shows a dialog with different states to the user.
  6751. *
  6752. * @param statesObject object containing all the states of the dialog
  6753. */
  6754. my.openDialogWithStates = function (statesObject, options) {
  6755. return new Impromptu(statesObject, options);
  6756. };
  6757. /**
  6758. * Opens new popup window for given <tt>url</tt> centered over current
  6759. * window.
  6760. *
  6761. * @param url the URL to be displayed in the popup window
  6762. * @param w the width of the popup window
  6763. * @param h the height of the popup window
  6764. * @param onPopupClosed optional callback function called when popup window
  6765. * has been closed.
  6766. *
  6767. * @returns popup window object if opened successfully or undefined
  6768. * in case we failed to open it(popup blocked)
  6769. */
  6770. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  6771. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  6772. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  6773. var popup = window.open(
  6774. url, '_blank',
  6775. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  6776. if (popup && onPopupClosed) {
  6777. var pollTimer = window.setInterval(function () {
  6778. if (popup.closed !== false) {
  6779. window.clearInterval(pollTimer);
  6780. onPopupClosed();
  6781. }
  6782. }, 200);
  6783. }
  6784. return popup;
  6785. };
  6786. /**
  6787. * Shows a dialog prompting the user to send an error report.
  6788. *
  6789. * @param titleString the title of the message
  6790. * @param msgString the text of the message
  6791. * @param error the error that is being reported
  6792. */
  6793. my.openReportDialog = function(titleKey, msgKey, error) {
  6794. my.openMessageDialog(titleKey, msgKey);
  6795. console.log(error);
  6796. //FIXME send the error to the server
  6797. };
  6798. /**
  6799. * Shows an error dialog to the user.
  6800. * @param title the title of the message
  6801. * @param message the text of the messafe
  6802. */
  6803. my.showError = function(titleKey, msgKey) {
  6804. if(!titleKey) {
  6805. titleKey = "dialog.oops";
  6806. }
  6807. if(!msgKey)
  6808. {
  6809. msgKey = "dialog.defaultError";
  6810. }
  6811. messageHandler.openMessageDialog(titleKey, msgKey);
  6812. };
  6813. my.notify = function(displayName, displayNameKey,
  6814. cls, messageKey, messageArguments, options) {
  6815. var displayNameSpan = '<span class="nickname" ';
  6816. if(displayName)
  6817. {
  6818. displayNameSpan += ">" + displayName;
  6819. }
  6820. else
  6821. {
  6822. displayNameSpan += "data-i18n='" + displayNameKey +
  6823. "'>" + APP.translation.translateString(displayNameKey);
  6824. }
  6825. displayNameSpan += "</span>";
  6826. toastr.info(
  6827. displayNameSpan + '<br>' +
  6828. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  6829. (messageArguments?
  6830. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  6831. : "") + ">" +
  6832. APP.translation.translateString(messageKey,
  6833. messageArguments) +
  6834. '</span>', null, options);
  6835. };
  6836. return my;
  6837. }(messageHandler || {}));
  6838. module.exports = messageHandler;
  6839. },{}],32:[function(require,module,exports){
  6840. var UIEvents = require("../../../service/UI/UIEvents");
  6841. var nickname = null;
  6842. var eventEmitter = null;
  6843. var NickanameHandler = {
  6844. init: function (emitter) {
  6845. eventEmitter = emitter;
  6846. var storedDisplayName = window.localStorage.displayname;
  6847. if (storedDisplayName) {
  6848. nickname = storedDisplayName;
  6849. }
  6850. },
  6851. setNickname: function (newNickname) {
  6852. if (!newNickname || nickname === newNickname)
  6853. return;
  6854. nickname = newNickname;
  6855. window.localStorage.displayname = nickname;
  6856. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  6857. },
  6858. getNickname: function () {
  6859. return nickname;
  6860. },
  6861. addListener: function (type, listener) {
  6862. eventEmitter.on(type, listener);
  6863. }
  6864. };
  6865. module.exports = NickanameHandler;
  6866. },{"../../../service/UI/UIEvents":102}],33:[function(require,module,exports){
  6867. /**
  6868. * Created by hristo on 12/22/14.
  6869. */
  6870. module.exports = {
  6871. /**
  6872. * Returns the available video width.
  6873. */
  6874. getAvailableVideoWidth: function (isVisible) {
  6875. var PanelToggler = require("../side_pannels/SidePanelToggler");
  6876. if(typeof isVisible === "undefined" || isVisible === null)
  6877. isVisible = PanelToggler.isVisible();
  6878. var rightPanelWidth
  6879. = isVisible ? PanelToggler.getPanelSize()[0] : 0;
  6880. return window.innerWidth - rightPanelWidth;
  6881. },
  6882. /**
  6883. * Changes the style class of the element given by id.
  6884. */
  6885. buttonClick: function(id, classname) {
  6886. $(id).toggleClass(classname); // add the class to the clicked element
  6887. },
  6888. /**
  6889. * Returns the text width for the given element.
  6890. *
  6891. * @param el the element
  6892. */
  6893. getTextWidth: function (el) {
  6894. return (el.clientWidth + 1);
  6895. },
  6896. /**
  6897. * Returns the text height for the given element.
  6898. *
  6899. * @param el the element
  6900. */
  6901. getTextHeight: function (el) {
  6902. return (el.clientHeight + 1);
  6903. },
  6904. /**
  6905. * Plays the sound given by id.
  6906. *
  6907. * @param id the identifier of the audio element.
  6908. */
  6909. playSoundNotification: function (id) {
  6910. document.getElementById(id).play();
  6911. },
  6912. /**
  6913. * Escapes the given text.
  6914. */
  6915. escapeHtml: function (unsafeText) {
  6916. return $('<div/>').text(unsafeText).html();
  6917. },
  6918. imageToGrayScale: function (canvas) {
  6919. var context = canvas.getContext('2d');
  6920. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  6921. var pixels = imgData.data;
  6922. for (var i = 0, n = pixels.length; i < n; i += 4) {
  6923. var grayscale
  6924. = pixels[i] * .3 + pixels[i+1] * .59 + pixels[i+2] * .11;
  6925. pixels[i ] = grayscale; // red
  6926. pixels[i+1] = grayscale; // green
  6927. pixels[i+2] = grayscale; // blue
  6928. // pixels[i+3] is alpha
  6929. }
  6930. // redraw the image in black & white
  6931. context.putImageData(imgData, 0, 0);
  6932. },
  6933. setTooltip: function (element, key, position) {
  6934. element.setAttribute("data-i18n", "[data-content]" + key);
  6935. element.setAttribute("data-toggle", "popover");
  6936. element.setAttribute("data-placement", position);
  6937. element.setAttribute("data-html", true);
  6938. element.setAttribute("data-container", "body");
  6939. }
  6940. };
  6941. },{"../side_pannels/SidePanelToggler":20}],34:[function(require,module,exports){
  6942. var JitsiPopover = require("../util/JitsiPopover");
  6943. /**
  6944. * Constructs new connection indicator.
  6945. * @param videoContainer the video container associated with the indicator.
  6946. * @constructor
  6947. */
  6948. function ConnectionIndicator(videoContainer, jid)
  6949. {
  6950. this.videoContainer = videoContainer;
  6951. this.bandwidth = null;
  6952. this.packetLoss = null;
  6953. this.bitrate = null;
  6954. this.showMoreValue = false;
  6955. this.resolution = null;
  6956. this.transport = [];
  6957. this.popover = null;
  6958. this.jid = jid;
  6959. this.create();
  6960. }
  6961. /**
  6962. * Values for the connection quality
  6963. * @type {{98: string,
  6964. * 81: string,
  6965. * 64: string,
  6966. * 47: string,
  6967. * 30: string,
  6968. * 0: string}}
  6969. */
  6970. ConnectionIndicator.connectionQualityValues = {
  6971. 98: "18px", //full
  6972. 81: "15px",//4 bars
  6973. 64: "11px",//3 bars
  6974. 47: "7px",//2 bars
  6975. 30: "3px",//1 bar
  6976. 0: "0px"//empty
  6977. };
  6978. ConnectionIndicator.getIP = function(value)
  6979. {
  6980. return value.substring(0, value.lastIndexOf(":"));
  6981. };
  6982. ConnectionIndicator.getPort = function(value)
  6983. {
  6984. return value.substring(value.lastIndexOf(":") + 1, value.length);
  6985. };
  6986. ConnectionIndicator.getStringFromArray = function (array) {
  6987. var res = "";
  6988. for(var i = 0; i < array.length; i++)
  6989. {
  6990. res += (i === 0? "" : ", ") + array[i];
  6991. }
  6992. return res;
  6993. };
  6994. /**
  6995. * Generates the html content.
  6996. * @returns {string} the html content.
  6997. */
  6998. ConnectionIndicator.prototype.generateText = function () {
  6999. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  7000. var translate = APP.translation.translateString;
  7001. if(this.bitrate === null)
  7002. {
  7003. downloadBitrate = "N/A";
  7004. uploadBitrate = "N/A";
  7005. }
  7006. else
  7007. {
  7008. downloadBitrate =
  7009. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  7010. uploadBitrate =
  7011. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  7012. }
  7013. if(this.packetLoss === null)
  7014. {
  7015. packetLoss = "N/A";
  7016. }
  7017. else
  7018. {
  7019. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  7020. (this.packetLoss.download !== null? this.packetLoss.download : "N/A") +
  7021. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  7022. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") + "%";
  7023. }
  7024. var resolutionValue = null;
  7025. if(this.resolution && this.jid != null)
  7026. {
  7027. var keys = Object.keys(this.resolution);
  7028. for(var ssrc in this.resolution)
  7029. {
  7030. resolutionValue = this.resolution[ssrc];
  7031. }
  7032. }
  7033. if(this.jid === null)
  7034. {
  7035. resolution = "";
  7036. if(this.resolution === null || !Object.keys(this.resolution) ||
  7037. Object.keys(this.resolution).length === 0)
  7038. {
  7039. resolution = "N/A";
  7040. }
  7041. else
  7042. for(i in this.resolution)
  7043. {
  7044. resolutionValue = this.resolution[i];
  7045. if(resolutionValue)
  7046. {
  7047. if(resolutionValue.height &&
  7048. resolutionValue.width)
  7049. {
  7050. resolution += (resolution === ""? "" : ", ") +
  7051. resolutionValue.width + "x" +
  7052. resolutionValue.height;
  7053. }
  7054. }
  7055. }
  7056. }
  7057. else if(!resolutionValue ||
  7058. !resolutionValue.height ||
  7059. !resolutionValue.width)
  7060. {
  7061. resolution = "N/A";
  7062. }
  7063. else
  7064. {
  7065. resolution = resolutionValue.width + "x" + resolutionValue.height;
  7066. }
  7067. var result = "<table style='width:100%'>" +
  7068. "<tr>" +
  7069. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  7070. translate("connectionindicator.bitrate") + "</span></td>" +
  7071. "<td><span class='jitsipopover_green'>&darr;</span>" +
  7072. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  7073. uploadBitrate + "</td>" +
  7074. "</tr><tr>" +
  7075. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  7076. translate("connectionindicator.packetloss") + "</span></td>" +
  7077. "<td>" + packetLoss + "</td>" +
  7078. "</tr><tr>" +
  7079. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  7080. translate("connectionindicator.resolution") + "</span></td>" +
  7081. "<td>" + resolution + "</td></tr></table>";
  7082. if(this.videoContainer.videoSpanId == "localVideoContainer") {
  7083. result += "<div class=\"jitsipopover_showmore\" " +
  7084. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  7085. // FIXME: we do not know local jid when this text is generated
  7086. //this.jid + "')\" data-i18n='connectionindicator." +
  7087. "local')\" data-i18n='connectionindicator." +
  7088. (this.showMoreValue ? "less" : "more") + "'>" +
  7089. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  7090. "</div><br />";
  7091. }
  7092. if(this.showMoreValue)
  7093. {
  7094. var downloadBandwidth, uploadBandwidth, transport;
  7095. if(this.bandwidth === null)
  7096. {
  7097. downloadBandwidth = "N/A";
  7098. uploadBandwidth = "N/A";
  7099. }
  7100. else
  7101. {
  7102. downloadBandwidth = this.bandwidth.download?
  7103. this.bandwidth.download + " Kbps" :
  7104. "N/A";
  7105. uploadBandwidth = this.bandwidth.upload?
  7106. this.bandwidth.upload + " Kbps" :
  7107. "N/A";
  7108. }
  7109. if(!this.transport || this.transport.length === 0)
  7110. {
  7111. transport = "<tr>" +
  7112. "<td><span class='jitsipopover_blue' " +
  7113. "data-i18n='connectionindicator.address'>" +
  7114. translate("connectionindicator.address") + "</span></td>" +
  7115. "<td> N/A</td></tr>";
  7116. }
  7117. else
  7118. {
  7119. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  7120. for(i = 0; i < this.transport.length; i++)
  7121. {
  7122. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  7123. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  7124. var localIP =
  7125. ConnectionIndicator.getIP(this.transport[i].localip);
  7126. var localPort =
  7127. ConnectionIndicator.getPort(this.transport[i].localip);
  7128. if(data.remoteIP.indexOf(ip) == -1)
  7129. {
  7130. data.remoteIP.push(ip);
  7131. }
  7132. if(data.remotePort.indexOf(port) == -1)
  7133. {
  7134. data.remotePort.push(port);
  7135. }
  7136. if(data.localIP.indexOf(localIP) == -1)
  7137. {
  7138. data.localIP.push(localIP);
  7139. }
  7140. if(data.localPort.indexOf(localPort) == -1)
  7141. {
  7142. data.localPort.push(localPort);
  7143. }
  7144. }
  7145. var local_address_key = "connectionindicator.localaddress";
  7146. var remote_address_key = "connectionindicator.remoteaddress";
  7147. var localTransport =
  7148. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  7149. local_address_key +"' data-i18n-options='" +
  7150. JSON.stringify({count: data.localIP.length}) + "'>" +
  7151. translate(local_address_key, {count: data.localIP.length}) +
  7152. "</span></td><td> " +
  7153. ConnectionIndicator.getStringFromArray(data.localIP) +
  7154. "</td></tr>";
  7155. transport =
  7156. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  7157. remote_address_key + "' data-i18n-options='" +
  7158. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  7159. translate(remote_address_key,
  7160. {count: data.remoteIP.length}) +
  7161. "</span></td><td> " +
  7162. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  7163. "</td></tr>";
  7164. var key_remote = "connectionindicator.remoteport",
  7165. key_local = "connectionindicator.localport";
  7166. transport += "<tr>" +
  7167. "<td>" +
  7168. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  7169. "' data-i18n-options='" +
  7170. JSON.stringify({count: this.transport.length}) + "'>" +
  7171. translate(key_remote, {count: this.transport.length}) +
  7172. "</span></td><td>";
  7173. localTransport += "<tr>" +
  7174. "<td>" +
  7175. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  7176. "' data-i18n-options='" +
  7177. JSON.stringify({count: this.transport.length}) + "'>" +
  7178. translate(key_local, {count: this.transport.length}) +
  7179. "</span></td><td>";
  7180. transport +=
  7181. ConnectionIndicator.getStringFromArray(data.remotePort);
  7182. localTransport +=
  7183. ConnectionIndicator.getStringFromArray(data.localPort);
  7184. transport += "</td></tr>";
  7185. transport += localTransport + "</td></tr>";
  7186. transport +="<tr>" +
  7187. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  7188. translate("connectionindicator.transport") + "</span></td>" +
  7189. "<td>" + this.transport[0].type + "</td></tr>";
  7190. }
  7191. result += "<table style='width:100%'>" +
  7192. "<tr>" +
  7193. "<td>" +
  7194. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  7195. translate("connectionindicator.bandwidth") + "</span>" +
  7196. "</td><td>" +
  7197. "<span class='jitsipopover_green'>&darr;</span>" +
  7198. downloadBandwidth +
  7199. " <span class='jitsipopover_orange'>&uarr;</span>" +
  7200. uploadBandwidth + "</td></tr>";
  7201. result += transport + "</table>";
  7202. }
  7203. return result;
  7204. };
  7205. /**
  7206. * Shows or hide the additional information.
  7207. */
  7208. ConnectionIndicator.prototype.showMore = function () {
  7209. this.showMoreValue = !this.showMoreValue;
  7210. this.updatePopoverData();
  7211. };
  7212. function createIcon(classes)
  7213. {
  7214. var icon = document.createElement("span");
  7215. for(var i in classes)
  7216. {
  7217. icon.classList.add(classes[i]);
  7218. }
  7219. icon.appendChild(
  7220. document.createElement("i")).classList.add("icon-connection");
  7221. return icon;
  7222. }
  7223. /**
  7224. * Creates the indicator
  7225. */
  7226. ConnectionIndicator.prototype.create = function () {
  7227. this.connectionIndicatorContainer = document.createElement("div");
  7228. this.connectionIndicatorContainer.className = "connectionindicator";
  7229. this.connectionIndicatorContainer.style.display = "none";
  7230. this.videoContainer.container.appendChild(this.connectionIndicatorContainer);
  7231. this.popover = new JitsiPopover(
  7232. $("#" + this.videoContainer.videoSpanId + " > .connectionindicator"),
  7233. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  7234. APP.translation.translateString("connectionindicator.na") + "</div>",
  7235. skin: "black"});
  7236. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  7237. createIcon(["connection", "connection_empty"]));
  7238. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  7239. createIcon(["connection", "connection_full"]));
  7240. };
  7241. /**
  7242. * Removes the indicator
  7243. */
  7244. ConnectionIndicator.prototype.remove = function()
  7245. {
  7246. if (this.connectionIndicatorContainer.parentNode) {
  7247. this.connectionIndicatorContainer.parentNode.removeChild(
  7248. this.connectionIndicatorContainer);
  7249. }
  7250. this.popover.forceHide();
  7251. };
  7252. /**
  7253. * Updates the data of the indicator
  7254. * @param percent the percent of connection quality
  7255. * @param object the statistics data.
  7256. */
  7257. ConnectionIndicator.prototype.updateConnectionQuality =
  7258. function (percent, object) {
  7259. if(percent === null)
  7260. {
  7261. this.connectionIndicatorContainer.style.display = "none";
  7262. this.popover.forceHide();
  7263. return;
  7264. }
  7265. else
  7266. {
  7267. if(this.connectionIndicatorContainer.style.display == "none") {
  7268. this.connectionIndicatorContainer.style.display = "block";
  7269. this.videoContainer.updateIconPositions();
  7270. }
  7271. }
  7272. this.bandwidth = object.bandwidth;
  7273. this.bitrate = object.bitrate;
  7274. this.packetLoss = object.packetLoss;
  7275. this.transport = object.transport;
  7276. if(object.resolution)
  7277. {
  7278. this.resolution = object.resolution;
  7279. }
  7280. for(var quality in ConnectionIndicator.connectionQualityValues)
  7281. {
  7282. if(percent >= quality)
  7283. {
  7284. this.fullIcon.style.width =
  7285. ConnectionIndicator.connectionQualityValues[quality];
  7286. }
  7287. }
  7288. this.updatePopoverData();
  7289. };
  7290. /**
  7291. * Updates the resolution
  7292. * @param resolution the new resolution
  7293. */
  7294. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  7295. this.resolution = resolution;
  7296. this.updatePopoverData();
  7297. };
  7298. /**
  7299. * Updates the content of the popover
  7300. */
  7301. ConnectionIndicator.prototype.updatePopoverData = function () {
  7302. this.popover.updateContent(
  7303. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  7304. APP.translation.translateElement($(".connection_info"));
  7305. };
  7306. /**
  7307. * Hides the popover
  7308. */
  7309. ConnectionIndicator.prototype.hide = function () {
  7310. this.popover.forceHide();
  7311. };
  7312. /**
  7313. * Hides the indicator
  7314. */
  7315. ConnectionIndicator.prototype.hideIndicator = function () {
  7316. this.connectionIndicatorContainer.style.display = "none";
  7317. if(this.popover)
  7318. this.popover.forceHide();
  7319. };
  7320. module.exports = ConnectionIndicator;
  7321. },{"../util/JitsiPopover":30}],35:[function(require,module,exports){
  7322. var Avatar = require("../avatar/Avatar");
  7323. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7324. var UIUtil = require("../util/UIUtil");
  7325. var UIEvents = require("../../../service/UI/UIEvents");
  7326. var xmpp = require("../../xmpp/xmpp");
  7327. // FIXME: With Temasys we have to re-select everytime
  7328. //var video = $('#largeVideo');
  7329. var currentVideoWidth = null;
  7330. var currentVideoHeight = null;
  7331. // By default we use camera
  7332. var getVideoSize = getCameraVideoSize;
  7333. var getVideoPosition = getCameraVideoPosition;
  7334. var currentSmallVideo = null;
  7335. /**
  7336. * Sets the size and position of the given video element.
  7337. *
  7338. * @param video the video element to position
  7339. * @param width the desired video width
  7340. * @param height the desired video height
  7341. * @param horizontalIndent the left and right indent
  7342. * @param verticalIndent the top and bottom indent
  7343. */
  7344. function positionVideo(video,
  7345. width,
  7346. height,
  7347. horizontalIndent,
  7348. verticalIndent,
  7349. animate) {
  7350. if(animate)
  7351. {
  7352. video.animate({
  7353. width: width,
  7354. height: height,
  7355. top: verticalIndent,
  7356. bottom: verticalIndent,
  7357. left: horizontalIndent,
  7358. right: horizontalIndent
  7359. },
  7360. {
  7361. queue: false,
  7362. duration: 500
  7363. });
  7364. }
  7365. else
  7366. {
  7367. video.width(width);
  7368. video.height(height);
  7369. video.css({ top: verticalIndent + 'px',
  7370. bottom: verticalIndent + 'px',
  7371. left: horizontalIndent + 'px',
  7372. right: horizontalIndent + 'px'});
  7373. }
  7374. }
  7375. /**
  7376. * Returns an array of the video dimensions, so that it keeps it's aspect
  7377. * ratio and fits available area with it's larger dimension. This method
  7378. * ensures that whole video will be visible and can leave empty areas.
  7379. *
  7380. * @return an array with 2 elements, the video width and the video height
  7381. */
  7382. function getDesktopVideoSize(videoWidth,
  7383. videoHeight,
  7384. videoSpaceWidth,
  7385. videoSpaceHeight) {
  7386. if (!videoWidth)
  7387. videoWidth = currentVideoWidth;
  7388. if (!videoHeight)
  7389. videoHeight = currentVideoHeight;
  7390. var aspectRatio = videoWidth / videoHeight;
  7391. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7392. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7393. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  7394. if (availableWidth / aspectRatio >= videoSpaceHeight)
  7395. {
  7396. availableHeight = videoSpaceHeight;
  7397. availableWidth = availableHeight * aspectRatio;
  7398. }
  7399. if (availableHeight * aspectRatio >= videoSpaceWidth)
  7400. {
  7401. availableWidth = videoSpaceWidth;
  7402. availableHeight = availableWidth / aspectRatio;
  7403. }
  7404. return [availableWidth, availableHeight];
  7405. }
  7406. /**
  7407. * Returns an array of the video horizontal and vertical indents,
  7408. * so that if fits its parent.
  7409. *
  7410. * @return an array with 2 elements, the horizontal indent and the vertical
  7411. * indent
  7412. */
  7413. function getCameraVideoPosition(videoWidth,
  7414. videoHeight,
  7415. videoSpaceWidth,
  7416. videoSpaceHeight) {
  7417. // Parent height isn't completely calculated when we position the video in
  7418. // full screen mode and this is why we use the screen height in this case.
  7419. // Need to think it further at some point and implement it properly.
  7420. var isFullScreen = document.fullScreen ||
  7421. document.mozFullScreen ||
  7422. document.webkitIsFullScreen;
  7423. if (isFullScreen)
  7424. videoSpaceHeight = window.innerHeight;
  7425. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7426. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  7427. return [horizontalIndent, verticalIndent];
  7428. }
  7429. /**
  7430. * Returns an array of the video horizontal and vertical indents.
  7431. * Centers horizontally and top aligns vertically.
  7432. *
  7433. * @return an array with 2 elements, the horizontal indent and the vertical
  7434. * indent
  7435. */
  7436. function getDesktopVideoPosition(videoWidth,
  7437. videoHeight,
  7438. videoSpaceWidth,
  7439. videoSpaceHeight) {
  7440. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7441. var verticalIndent = 0;// Top aligned
  7442. return [horizontalIndent, verticalIndent];
  7443. }
  7444. /**
  7445. * Returns an array of the video dimensions, so that it covers the screen.
  7446. * It leaves no empty areas, but some parts of the video might not be visible.
  7447. *
  7448. * @return an array with 2 elements, the video width and the video height
  7449. */
  7450. function getCameraVideoSize(videoWidth,
  7451. videoHeight,
  7452. videoSpaceWidth,
  7453. videoSpaceHeight) {
  7454. if (!videoWidth)
  7455. videoWidth = currentVideoWidth;
  7456. if (!videoHeight)
  7457. videoHeight = currentVideoHeight;
  7458. var aspectRatio = videoWidth / videoHeight;
  7459. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7460. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7461. if (availableWidth / aspectRatio < videoSpaceHeight) {
  7462. availableHeight = videoSpaceHeight;
  7463. availableWidth = availableHeight * aspectRatio;
  7464. }
  7465. if (availableHeight * aspectRatio < videoSpaceWidth) {
  7466. availableWidth = videoSpaceWidth;
  7467. availableHeight = availableWidth / aspectRatio;
  7468. }
  7469. return [availableWidth, availableHeight];
  7470. }
  7471. /**
  7472. * Updates the src of the active speaker avatar
  7473. * @param jid of the current active speaker
  7474. */
  7475. function updateActiveSpeakerAvatarSrc() {
  7476. var avatar = $("#activeSpeakerAvatar")[0];
  7477. var jid = currentSmallVideo.peerJid;
  7478. var url = Avatar.getActiveSpeakerUrl(jid);
  7479. if (avatar.src === url)
  7480. return;
  7481. var isMuted = null;
  7482. if (!currentSmallVideo.isLocal &&
  7483. !LargeVideo.VideoLayout.isInLastN(currentSmallVideo.getResourceJid())) {
  7484. isMuted = true;
  7485. }
  7486. else
  7487. {
  7488. isMuted = APP.RTC.isVideoMuted(jid);
  7489. }
  7490. if (jid && isMuted !== null) {
  7491. avatar.src = url;
  7492. $("#largeVideo").css("visibility", isMuted ? "hidden" : "visible");
  7493. currentSmallVideo.showAvatar(isMuted);
  7494. }
  7495. }
  7496. function changeVideo(isVisible) {
  7497. updateActiveSpeakerAvatarSrc();
  7498. APP.RTC.setVideoSrc($('#largeVideo')[0], currentSmallVideo.getSrc());
  7499. var videoTransform = document.getElementById('largeVideo')
  7500. .style.webkitTransform;
  7501. var flipX = currentSmallVideo.flipX;
  7502. if (flipX && videoTransform !== 'scaleX(-1)') {
  7503. document.getElementById('largeVideo').style.webkitTransform
  7504. = "scaleX(-1)";
  7505. }
  7506. else if (!flipX && videoTransform === 'scaleX(-1)') {
  7507. document.getElementById('largeVideo').style.webkitTransform
  7508. = "none";
  7509. }
  7510. var isDesktop = APP.RTC.isVideoSrcDesktop(currentSmallVideo.peerJid);
  7511. // Change the way we'll be measuring and positioning large video
  7512. getVideoSize = isDesktop
  7513. ? getDesktopVideoSize
  7514. : getCameraVideoSize;
  7515. getVideoPosition = isDesktop
  7516. ? getDesktopVideoPosition
  7517. : getCameraVideoPosition;
  7518. // Only if the large video is currently visible.
  7519. if (isVisible) {
  7520. LargeVideo.VideoLayout.largeVideoUpdated(currentSmallVideo);
  7521. $('#largeVideo').fadeIn(300);
  7522. }
  7523. }
  7524. var LargeVideo = {
  7525. init: function (VideoLayout, emitter) {
  7526. this.VideoLayout = VideoLayout;
  7527. this.eventEmitter = emitter;
  7528. var self = this;
  7529. // Listen for large video size updates
  7530. var largeVideo = $('#largeVideo')[0];
  7531. var onplaying = function (arg1, arg2, arg3) {
  7532. // re-select
  7533. if (RTCBrowserType.isTemasysPluginUsed())
  7534. largeVideo = $('#largeVideo')[0];
  7535. currentVideoWidth = largeVideo.videoWidth;
  7536. currentVideoHeight = largeVideo.videoHeight;
  7537. self.position(currentVideoWidth, currentVideoHeight);
  7538. };
  7539. largeVideo.onplaying = onplaying;
  7540. },
  7541. /**
  7542. * Indicates if the large video is currently visible.
  7543. *
  7544. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  7545. */
  7546. isLargeVideoVisible: function() {
  7547. return $('#largeVideo').is(':visible');
  7548. },
  7549. /**
  7550. * Returns <tt>true</tt> if the user is currently displayed on large video.
  7551. */
  7552. isCurrentlyOnLarge: function (resourceJid) {
  7553. return currentSmallVideo && resourceJid &&
  7554. currentSmallVideo.getResourceJid() === resourceJid;
  7555. },
  7556. /**
  7557. * Updates the large video with the given new video source.
  7558. */
  7559. updateLargeVideo: function (resourceJid, forceUpdate) {
  7560. var newSmallVideo = this.VideoLayout.getSmallVideo(resourceJid);
  7561. console.log('hover in ' + resourceJid + ', video: ', newSmallVideo);
  7562. if (!LargeVideo.isCurrentlyOnLarge(resourceJid) || forceUpdate) {
  7563. $('#activeSpeaker').css('visibility', 'hidden');
  7564. var oldSmallVideo = null;
  7565. if (currentSmallVideo) {
  7566. oldSmallVideo = currentSmallVideo;
  7567. }
  7568. currentSmallVideo = newSmallVideo;
  7569. var oldJid = null;
  7570. if (oldSmallVideo)
  7571. oldJid = oldSmallVideo.peerJid;
  7572. if (oldJid !== resourceJid) {
  7573. // we want the notification to trigger even if userJid is undefined,
  7574. // or null.
  7575. this.eventEmitter.emit(UIEvents.SELECTED_ENDPOINT, resourceJid);
  7576. }
  7577. if (RTCBrowserType.isSafari()) {
  7578. // FIXME In Safari fadeOut works only for the first time
  7579. changeVideo(this.isLargeVideoVisible());
  7580. } else {
  7581. $('#largeVideo').fadeOut(300,
  7582. changeVideo.bind($('#largeVideo'), this.isLargeVideoVisible()));
  7583. }
  7584. } else {
  7585. if (currentSmallVideo) {
  7586. currentSmallVideo.showAvatar();
  7587. }
  7588. }
  7589. },
  7590. /**
  7591. * Shows/hides the large video.
  7592. */
  7593. setLargeVideoVisible: function(isVisible) {
  7594. if (isVisible) {
  7595. $('#largeVideo').css({visibility: 'visible'});
  7596. $('.watermark').css({visibility: 'visible'});
  7597. if(currentSmallVideo)
  7598. currentSmallVideo.enableDominantSpeaker(true);
  7599. }
  7600. else {
  7601. $('#largeVideo').css({visibility: 'hidden'});
  7602. $('#activeSpeaker').css('visibility', 'hidden');
  7603. $('.watermark').css({visibility: 'hidden'});
  7604. if(currentSmallVideo)
  7605. currentSmallVideo.enableDominantSpeaker(false);
  7606. }
  7607. },
  7608. onVideoTypeChanged: function (jid) {
  7609. var resourceJid = Strophe.getResourceFromJid(jid);
  7610. if (LargeVideo.isCurrentlyOnLarge(resourceJid))
  7611. {
  7612. var isDesktop = APP.RTC.isVideoSrcDesktop(jid);
  7613. getVideoSize = isDesktop
  7614. ? getDesktopVideoSize
  7615. : getCameraVideoSize;
  7616. getVideoPosition = isDesktop
  7617. ? getDesktopVideoPosition
  7618. : getCameraVideoPosition;
  7619. this.position(null, null);
  7620. }
  7621. },
  7622. /**
  7623. * Positions the large video.
  7624. *
  7625. * @param videoWidth the stream video width
  7626. * @param videoHeight the stream video height
  7627. */
  7628. position: function (videoWidth, videoHeight,
  7629. videoSpaceWidth, videoSpaceHeight, animate) {
  7630. if(!videoSpaceWidth)
  7631. videoSpaceWidth = $('#videospace').width();
  7632. if(!videoSpaceHeight)
  7633. videoSpaceHeight = window.innerHeight;
  7634. var videoSize = getVideoSize(videoWidth,
  7635. videoHeight,
  7636. videoSpaceWidth,
  7637. videoSpaceHeight);
  7638. var largeVideoWidth = videoSize[0];
  7639. var largeVideoHeight = videoSize[1];
  7640. var videoPosition = getVideoPosition(largeVideoWidth,
  7641. largeVideoHeight,
  7642. videoSpaceWidth,
  7643. videoSpaceHeight);
  7644. var horizontalIndent = videoPosition[0];
  7645. var verticalIndent = videoPosition[1];
  7646. positionVideo($('#largeVideo'),
  7647. largeVideoWidth,
  7648. largeVideoHeight,
  7649. horizontalIndent, verticalIndent, animate);
  7650. },
  7651. isLargeVideoOnTop: function () {
  7652. var Etherpad = require("../etherpad/Etherpad");
  7653. var Prezi = require("../prezi/Prezi");
  7654. return !Prezi.isPresentationVisible() && !Etherpad.isVisible();
  7655. },
  7656. resize: function (animate, isVisible, completeFunction) {
  7657. var availableHeight = window.innerHeight;
  7658. var availableWidth = UIUtil.getAvailableVideoWidth(isVisible);
  7659. if (availableWidth < 0 || availableHeight < 0) return;
  7660. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  7661. var top = availableHeight / 2 - avatarSize / 4 * 3;
  7662. $('#activeSpeaker').css('top', top);
  7663. if(animate)
  7664. {
  7665. $('#videospace').animate({
  7666. right: window.innerWidth - availableWidth,
  7667. width: availableWidth,
  7668. height: availableHeight
  7669. },
  7670. {
  7671. queue: false,
  7672. duration: 500,
  7673. complete: completeFunction
  7674. });
  7675. $('#largeVideoContainer').animate({
  7676. width: availableWidth,
  7677. height: availableHeight
  7678. },
  7679. {
  7680. queue: false,
  7681. duration: 500
  7682. });
  7683. }
  7684. else
  7685. {
  7686. $('#videospace').width(availableWidth);
  7687. $('#videospace').height(availableHeight);
  7688. $('#largeVideoContainer').width(availableWidth);
  7689. $('#largeVideoContainer').height(availableHeight);
  7690. }
  7691. return [availableWidth, availableHeight];
  7692. },
  7693. resizeVideoAreaAnimated: function (isVisible, completeFunction) {
  7694. var size = this.resize(true, isVisible, completeFunction);
  7695. this.position(null, null, size[0], size[1], true);
  7696. },
  7697. getResourceJid: function () {
  7698. return currentSmallVideo ? currentSmallVideo.getResourceJid() : null;
  7699. },
  7700. updateAvatar: function (resourceJid) {
  7701. if (resourceJid === this.getResourceJid()) {
  7702. updateActiveSpeakerAvatarSrc();
  7703. }
  7704. },
  7705. showAvatar: function (resourceJid, show) {
  7706. if(this.getResourceJid() === resourceJid
  7707. && LargeVideo.isLargeVideoOnTop())
  7708. {
  7709. $("#largeVideo").css("visibility", show ? "hidden" : "visible");
  7710. $('#activeSpeaker').css("visibility", show ? "visible" : "hidden");
  7711. return true;
  7712. }
  7713. return false;
  7714. }
  7715. }
  7716. module.exports = LargeVideo;
  7717. },{"../../../service/UI/UIEvents":102,"../../RTC/RTCBrowserType":8,"../../xmpp/xmpp":66,"../avatar/Avatar":16,"../etherpad/Etherpad":17,"../prezi/Prezi":18,"../util/UIUtil":33}],36:[function(require,module,exports){
  7718. var SmallVideo = require("./SmallVideo");
  7719. var ConnectionIndicator = require("./ConnectionIndicator");
  7720. var NicknameHandler = require("../util/NicknameHandler");
  7721. var UIUtil = require("../util/UIUtil");
  7722. var LargeVideo = require("./LargeVideo");
  7723. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7724. function LocalVideo(VideoLayout)
  7725. {
  7726. this.videoSpanId = "localVideoContainer";
  7727. this.container = $("#localVideoContainer").get(0);
  7728. this.VideoLayout = VideoLayout;
  7729. this.flipX = true;
  7730. this.isLocal = true;
  7731. this.peerJid = null;
  7732. }
  7733. LocalVideo.prototype = Object.create(SmallVideo.prototype);
  7734. LocalVideo.prototype.constructor = LocalVideo;
  7735. /**
  7736. * Creates the edit display name button.
  7737. *
  7738. * @returns the edit button
  7739. */
  7740. function createEditDisplayNameButton() {
  7741. var editButton = document.createElement('a');
  7742. editButton.className = 'displayname';
  7743. UIUtil.setTooltip(editButton,
  7744. "videothumbnail.editnickname",
  7745. "top");
  7746. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  7747. return editButton;
  7748. }
  7749. /**
  7750. * Sets the display name for the given video span id.
  7751. */
  7752. LocalVideo.prototype.setDisplayName = function(displayName, key) {
  7753. if (!this.container) {
  7754. console.warn(
  7755. "Unable to set displayName - " + this.videoSpanId + " does not exist");
  7756. return;
  7757. }
  7758. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  7759. var defaultLocalDisplayName = APP.translation.generateTranslationHTML(
  7760. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  7761. // If we already have a display name for this video.
  7762. if (nameSpan.length > 0) {
  7763. if (nameSpan.text() !== displayName) {
  7764. if (displayName && displayName.length > 0)
  7765. {
  7766. var meHTML = APP.translation.generateTranslationHTML("me");
  7767. $('#localDisplayName').html(displayName + ' (' + meHTML + ')');
  7768. }
  7769. else
  7770. $('#localDisplayName').html(defaultLocalDisplayName);
  7771. }
  7772. } else {
  7773. var editButton = createEditDisplayNameButton();
  7774. nameSpan = document.createElement('span');
  7775. nameSpan.className = 'displayname';
  7776. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  7777. if (displayName && displayName.length > 0) {
  7778. var meHTML = APP.translation.generateTranslationHTML("me");
  7779. nameSpan.innerHTML = displayName + meHTML;
  7780. }
  7781. else {
  7782. nameSpan.innerHTML = defaultLocalDisplayName;
  7783. }
  7784. nameSpan.id = 'localDisplayName';
  7785. this.container.appendChild(editButton);
  7786. //translates popover of edit button
  7787. APP.translation.translateElement($("a.displayname"));
  7788. var editableText = document.createElement('input');
  7789. editableText.className = 'displayname';
  7790. editableText.type = 'text';
  7791. editableText.id = 'editDisplayName';
  7792. if (displayName && displayName.length) {
  7793. editableText.value = displayName;
  7794. }
  7795. var defaultNickname = APP.translation.translateString(
  7796. "defaultNickname", {name: "Jane Pink"});
  7797. editableText.setAttribute('style', 'display:none;');
  7798. editableText.setAttribute('data-18n',
  7799. '[placeholder]defaultNickname');
  7800. editableText.setAttribute("data-i18n-options",
  7801. JSON.stringify({name: "Jane Pink"}));
  7802. editableText.setAttribute("placeholder", defaultNickname);
  7803. this.container.appendChild(editableText);
  7804. var self = this;
  7805. $('#localVideoContainer .displayname')
  7806. .bind("click", function (e) {
  7807. e.preventDefault();
  7808. e.stopPropagation();
  7809. $('#localDisplayName').hide();
  7810. $('#editDisplayName').show();
  7811. $('#editDisplayName').focus();
  7812. $('#editDisplayName').select();
  7813. $('#editDisplayName').one("focusout", function (e) {
  7814. self.VideoLayout.inputDisplayNameHandler(this.value);
  7815. });
  7816. $('#editDisplayName').on('keydown', function (e) {
  7817. if (e.keyCode === 13) {
  7818. e.preventDefault();
  7819. self.VideoLayout.inputDisplayNameHandler(this.value);
  7820. }
  7821. });
  7822. });
  7823. }
  7824. }
  7825. LocalVideo.prototype.inputDisplayNameHandler = function (name) {
  7826. NicknameHandler.setNickname(name);
  7827. if (!$('#localDisplayName').is(":visible")) {
  7828. if (NicknameHandler.getNickname())
  7829. {
  7830. var meHTML = APP.translation.generateTranslationHTML("me");
  7831. $('#localDisplayName').html(NicknameHandler.getNickname() + " (" + meHTML + ")");
  7832. }
  7833. else
  7834. {
  7835. var defaultHTML = APP.translation.generateTranslationHTML(
  7836. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  7837. $('#localDisplayName')
  7838. .html(defaultHTML);
  7839. }
  7840. $('#localDisplayName').show();
  7841. }
  7842. $('#editDisplayName').hide();
  7843. }
  7844. LocalVideo.prototype.createConnectionIndicator = function()
  7845. {
  7846. if(this.connectionIndicator)
  7847. return;
  7848. this.connectionIndicator
  7849. = new ConnectionIndicator(this, null);
  7850. }
  7851. LocalVideo.prototype.changeVideo = function (stream, isMuted) {
  7852. var self = this;
  7853. function localVideoClick(event) {
  7854. // FIXME: with Temasys plugin event arg is not an event, but
  7855. // the clicked object itself, so we have to skip this call
  7856. if (event.stopPropagation) {
  7857. event.stopPropagation();
  7858. }
  7859. self.VideoLayout.handleVideoThumbClicked(
  7860. false,
  7861. APP.xmpp.myResource());
  7862. }
  7863. $('#localVideoContainer').off('click');
  7864. $('#localVideoContainer').on('click', localVideoClick);
  7865. // Add hover handler
  7866. $('#localVideoContainer').hover(
  7867. function() {
  7868. self.showDisplayName(true);
  7869. },
  7870. function() {
  7871. if (!LargeVideo.isLargeVideoVisible() ||
  7872. !LargeVideo.isCurrentlyOnLarge(self.getResourceJid()))
  7873. self.showDisplayName(false);
  7874. }
  7875. );
  7876. if(isMuted)
  7877. {
  7878. APP.UI.setVideoMute(true);
  7879. return;
  7880. }
  7881. this.flipX = (stream.videoType == "screen")? false : true;
  7882. var localVideo = document.createElement('video');
  7883. localVideo.id = 'localVideo_' +
  7884. APP.RTC.getStreamID(stream.getOriginalStream());
  7885. if (!RTCBrowserType.isIExplorer()) {
  7886. localVideo.autoplay = true;
  7887. localVideo.volume = 0; // is it required if audio is separated ?
  7888. }
  7889. localVideo.oncontextmenu = function () { return false; };
  7890. var localVideoContainer = document.getElementById('localVideoWrapper');
  7891. localVideoContainer.appendChild(localVideo);
  7892. var localVideoSelector = $('#' + localVideo.id);
  7893. // Add click handler to both video and video wrapper elements in case
  7894. // there's no video.
  7895. // onclick has to be used with Temasys plugin
  7896. localVideo.onclick = localVideoClick;
  7897. if (this.flipX) {
  7898. localVideoSelector.addClass("flipVideoX");
  7899. }
  7900. // Attach WebRTC stream
  7901. APP.RTC.attachMediaStream(localVideoSelector, stream.getOriginalStream());
  7902. // Add stream ended handler
  7903. stream.getOriginalStream().onended = function () {
  7904. // We have to re-select after attach when Temasys plugin is used,
  7905. // because <video> element is replaced with <object>
  7906. localVideo = $('#' + localVideo.id)[0];
  7907. localVideoContainer.removeChild(localVideo);
  7908. self.VideoLayout.updateRemovedVideo(APP.xmpp.myResource());
  7909. };
  7910. };
  7911. LocalVideo.prototype.joined = function (jid) {
  7912. this.peerJid = jid;
  7913. };
  7914. LocalVideo.prototype.getResourceJid = function () {
  7915. var myResource = APP.xmpp.myResource();
  7916. if (!myResource) {
  7917. console.error("Requested local resource before we're in the MUC");
  7918. }
  7919. return myResource;
  7920. };
  7921. module.exports = LocalVideo;
  7922. },{"../../RTC/RTCBrowserType":8,"../util/NicknameHandler":32,"../util/UIUtil":33,"./ConnectionIndicator":34,"./LargeVideo":35,"./SmallVideo":38}],37:[function(require,module,exports){
  7923. var ConnectionIndicator = require("./ConnectionIndicator");
  7924. var SmallVideo = require("./SmallVideo");
  7925. var AudioLevels = require("../audio_levels/AudioLevels");
  7926. var LargeVideo = require("./LargeVideo");
  7927. var Avatar = require("../avatar/Avatar");
  7928. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7929. function RemoteVideo(peerJid, VideoLayout)
  7930. {
  7931. this.peerJid = peerJid;
  7932. this.resourceJid = Strophe.getResourceFromJid(peerJid);
  7933. this.videoSpanId = 'participant_' + this.resourceJid;
  7934. this.VideoLayout = VideoLayout;
  7935. this.addRemoteVideoContainer();
  7936. this.connectionIndicator = new ConnectionIndicator(
  7937. this, this.peerJid);
  7938. this.setDisplayName();
  7939. var nickfield = document.createElement('span');
  7940. nickfield.className = "nick";
  7941. nickfield.appendChild(document.createTextNode(this.resourceJid));
  7942. this.container.appendChild(nickfield);
  7943. this.flipX = false;
  7944. this.isLocal = false;
  7945. }
  7946. RemoteVideo.prototype = Object.create(SmallVideo.prototype);
  7947. RemoteVideo.prototype.constructor = RemoteVideo;
  7948. RemoteVideo.prototype.addRemoteVideoContainer = function() {
  7949. this.container = RemoteVideo.createContainer(this.videoSpanId);
  7950. if (APP.xmpp.isModerator())
  7951. this.addRemoteVideoMenu();
  7952. AudioLevels.updateAudioLevelCanvas(this.peerJid, this.VideoLayout);
  7953. return this.container;
  7954. };
  7955. /**
  7956. * Adds the remote video menu element for the given <tt>jid</tt> in the
  7957. * given <tt>parentElement</tt>.
  7958. *
  7959. * @param jid the jid indicating the video for which we're adding a menu.
  7960. * @param parentElement the parent element where this menu will be added
  7961. */
  7962. RemoteVideo.prototype.addRemoteVideoMenu = function () {
  7963. var spanElement = document.createElement('span');
  7964. spanElement.className = 'remotevideomenu';
  7965. this.container.appendChild(spanElement);
  7966. var menuElement = document.createElement('i');
  7967. menuElement.className = 'fa fa-angle-down';
  7968. menuElement.title = 'Remote user controls';
  7969. spanElement.appendChild(menuElement);
  7970. var popupmenuElement = document.createElement('ul');
  7971. popupmenuElement.className = 'popupmenu';
  7972. popupmenuElement.id
  7973. = 'remote_popupmenu_' + this.getResourceJid();
  7974. spanElement.appendChild(popupmenuElement);
  7975. var muteMenuItem = document.createElement('li');
  7976. var muteLinkItem = document.createElement('a');
  7977. var mutedIndicator = "<i style='float:left;' class='icon-mic-disabled'></i>";
  7978. if (!this.isMuted) {
  7979. muteLinkItem.innerHTML = mutedIndicator +
  7980. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  7981. muteLinkItem.className = 'mutelink';
  7982. }
  7983. else {
  7984. muteLinkItem.innerHTML = mutedIndicator +
  7985. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  7986. muteLinkItem.className = 'mutelink disabled';
  7987. }
  7988. var self = this;
  7989. muteLinkItem.onclick = function(){
  7990. if ($(this).attr('disabled') != undefined) {
  7991. event.preventDefault();
  7992. }
  7993. var isMute = self.isMuted == true;
  7994. APP.xmpp.setMute(self.peerJid, !isMute);
  7995. popupmenuElement.setAttribute('style', 'display:none;');
  7996. if (isMute) {
  7997. this.innerHTML = mutedIndicator +
  7998. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  7999. this.className = 'mutelink disabled';
  8000. }
  8001. else {
  8002. this.innerHTML = mutedIndicator +
  8003. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  8004. this.className = 'mutelink';
  8005. }
  8006. };
  8007. muteMenuItem.appendChild(muteLinkItem);
  8008. popupmenuElement.appendChild(muteMenuItem);
  8009. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  8010. var ejectMenuItem = document.createElement('li');
  8011. var ejectLinkItem = document.createElement('a');
  8012. var ejectText = "<div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.kick'>&nbsp;</div>";
  8013. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  8014. ejectLinkItem.onclick = function(){
  8015. APP.xmpp.eject(self.peerJid);
  8016. popupmenuElement.setAttribute('style', 'display:none;');
  8017. };
  8018. ejectMenuItem.appendChild(ejectLinkItem);
  8019. popupmenuElement.appendChild(ejectMenuItem);
  8020. var paddingSpan = document.createElement('span');
  8021. paddingSpan.className = 'popupmenuPadding';
  8022. popupmenuElement.appendChild(paddingSpan);
  8023. APP.translation.translateElement($("#" + popupmenuElement.id + " > li > a > div"));
  8024. }
  8025. /**
  8026. * Removes the remote stream element corresponding to the given stream and
  8027. * parent container.
  8028. *
  8029. * @param stream the stream
  8030. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  8031. * @param container
  8032. */
  8033. RemoteVideo.prototype.removeRemoteStreamElement = function (stream, isVideo, id) {
  8034. if (!this.container)
  8035. return false;
  8036. var select = null;
  8037. if (isVideo) {
  8038. select = $('#' + id);
  8039. }
  8040. else
  8041. select = $('#' + this.videoSpanId + '>audio');
  8042. // Mark video as removed to cancel waiting loop(if video is removed
  8043. // before has started)
  8044. select.removed = true;
  8045. select.remove();
  8046. var audioCount = $('#' + this.videoSpanId + '>audio').length;
  8047. var videoCount = $('#' + this.videoSpanId + '>' + APP.RTC.getVideoElementName()).length;
  8048. if (!audioCount && !videoCount) {
  8049. console.log("Remove whole user", this.videoSpanId);
  8050. if(this.connectionIndicator)
  8051. this.connectionIndicator.remove();
  8052. // Remove whole container
  8053. if (this.container.parentNode)
  8054. this.container.parentNode.removeChild(this.container);
  8055. this.VideoLayout.resizeThumbnails();
  8056. }
  8057. if (isVideo)
  8058. this.VideoLayout.updateRemovedVideo(this.getResourceJid());
  8059. };
  8060. RemoteVideo.prototype.waitForPlayback = function (sel, stream) {
  8061. var isVideo = stream.getVideoTracks().length > 0;
  8062. if (!isVideo || stream.id === 'mixedmslabel') {
  8063. return;
  8064. }
  8065. var self = this;
  8066. var resourceJid = this.getResourceJid();
  8067. // Register 'onplaying' listener to trigger 'videoactive' on VideoLayout
  8068. // when video playback starts
  8069. var onPlayingHandler = function () {
  8070. // FIXME: why do i have to do this for FF?
  8071. if (RTCBrowserType.isFirefox()) {
  8072. APP.RTC.attachMediaStream(sel, stream);
  8073. }
  8074. if (RTCBrowserType.isTemasysPluginUsed()) {
  8075. sel = self.VideoLayout.getPeerVideoSel(resourceJid);
  8076. }
  8077. self.VideoLayout.videoactive(sel, resourceJid);
  8078. sel[0].onplaying = null;
  8079. if (RTCBrowserType.isTemasysPluginUsed()) {
  8080. // 'currentTime' is used to check if the video has started
  8081. // and the value is not set by the plugin, so we do it
  8082. sel[0].currentTime = 1;
  8083. }
  8084. };
  8085. sel[0].onplaying = onPlayingHandler;
  8086. };
  8087. RemoteVideo.prototype.addRemoteStreamElement = function (sid, stream, thessrc) {
  8088. if (!this.container)
  8089. return;
  8090. var self = this;
  8091. var isVideo = stream.getVideoTracks().length > 0;
  8092. var streamElement = SmallVideo.createStreamElement(sid, stream);
  8093. var newElementId = streamElement.id;
  8094. this.container.appendChild(streamElement);
  8095. var sel = $('#' + newElementId);
  8096. sel.hide();
  8097. // If the container is currently visible we attach the stream.
  8098. if (!isVideo || (this.container.offsetParent !== null && isVideo)) {
  8099. this.waitForPlayback(sel, stream);
  8100. APP.RTC.attachMediaStream(sel, stream);
  8101. }
  8102. stream.onended = function () {
  8103. console.log('stream ended', this);
  8104. self.removeRemoteStreamElement(stream, isVideo, newElementId);
  8105. };
  8106. // Name of video element name is different for IE/Safari
  8107. var videoElem = APP.RTC.getVideoElementName();
  8108. // Add click handler.
  8109. var onClickHandler = function (event) {
  8110. self.VideoLayout.handleVideoThumbClicked(false, self.getResourceJid());
  8111. // On IE we need to populate this handler on video <object>
  8112. // and it does not give event instance as an argument,
  8113. // so we check here for methods.
  8114. if (event.stopPropagation && event.preventDefault) {
  8115. event.stopPropagation();
  8116. event.preventDefault();
  8117. }
  8118. return false;
  8119. };
  8120. this.container.onclick = onClickHandler;
  8121. // reselect
  8122. if (RTCBrowserType.isTemasysPluginUsed())
  8123. sel = $('#' + newElementId);
  8124. sel[0].onclick = onClickHandler;
  8125. //FIXME
  8126. // Add hover handler
  8127. $(this.container).hover(
  8128. function() {
  8129. self.showDisplayName(true);
  8130. },
  8131. function() {
  8132. // If the video has been "pinned" by the user we want to
  8133. // keep the display name on place.
  8134. if (!LargeVideo.isLargeVideoVisible() ||
  8135. !LargeVideo.isCurrentlyOnLarge(self.getResourceJid()))
  8136. self.showDisplayName(false);
  8137. }
  8138. );
  8139. },
  8140. /**
  8141. * Show/hide peer container for the given resourceJid.
  8142. */
  8143. RemoteVideo.prototype.showPeerContainer = function (state) {
  8144. if (!this.container)
  8145. return;
  8146. var isHide = state === 'hide';
  8147. var resizeThumbnails = false;
  8148. if (!isHide) {
  8149. if (!$(this.container).is(':visible')) {
  8150. resizeThumbnails = true;
  8151. $(this.container).show();
  8152. }
  8153. this.showAvatar(state !== 'show');
  8154. }
  8155. else if ($(this.container).is(':visible') && isHide)
  8156. {
  8157. resizeThumbnails = true;
  8158. $(this.container).hide();
  8159. if(this.connectionIndicator)
  8160. this.connectionIndicator.hide();
  8161. }
  8162. if (resizeThumbnails) {
  8163. this.VideoLayout.resizeThumbnails();
  8164. }
  8165. // We want to be able to pin a participant from the contact list, even
  8166. // if he's not in the lastN set!
  8167. // ContactList.setClickable(resourceJid, !isHide);
  8168. };
  8169. RemoteVideo.prototype.removeConnectionIndicator = function () {
  8170. if(this.connectionIndicator)
  8171. this.connectionIndicator.remove();
  8172. }
  8173. RemoteVideo.prototype.hideConnectionIndicator = function () {
  8174. if(this.connectionIndicator)
  8175. this.connectionIndicator.hide();
  8176. }
  8177. /**
  8178. * Updates the remote video menu.
  8179. *
  8180. * @param jid the jid indicating the video for which we're adding a menu.
  8181. * @param isMuted indicates the current mute state
  8182. */
  8183. RemoteVideo.prototype.updateRemoteVideoMenu = function (isMuted) {
  8184. var muteMenuItem
  8185. = $('#remote_popupmenu_' + this.getResourceJid() + '>li>a.mutelink');
  8186. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  8187. if (muteMenuItem.length) {
  8188. var muteLink = muteMenuItem.get(0);
  8189. if (isMuted === 'true') {
  8190. muteLink.innerHTML = mutedIndicator + ' Muted';
  8191. muteLink.className = 'mutelink disabled';
  8192. }
  8193. else {
  8194. muteLink.innerHTML = mutedIndicator + ' Mute';
  8195. muteLink.className = 'mutelink';
  8196. }
  8197. }
  8198. };
  8199. /**
  8200. * Sets the display name for the given video span id.
  8201. */
  8202. RemoteVideo.prototype.setDisplayName = function(displayName, key) {
  8203. if (!this.container) {
  8204. console.warn(
  8205. "Unable to set displayName - " + this.videoSpanId + " does not exist");
  8206. return;
  8207. }
  8208. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8209. // If we already have a display name for this video.
  8210. if (nameSpan.length > 0) {
  8211. if (displayName && displayName.length > 0)
  8212. {
  8213. $('#' + this.videoSpanId + '_name').html(displayName);
  8214. }
  8215. else if (key && key.length > 0)
  8216. {
  8217. var nameHtml = APP.translation.generateTranslationHTML(key);
  8218. $('#' + this.videoSpanId + '_name').html(nameHtml);
  8219. }
  8220. else
  8221. $('#' + this.videoSpanId + '_name').text(
  8222. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  8223. } else {
  8224. nameSpan = document.createElement('span');
  8225. nameSpan.className = 'displayname';
  8226. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  8227. if (displayName && displayName.length > 0) {
  8228. nameSpan.innerText = displayName;
  8229. }
  8230. else
  8231. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  8232. nameSpan.id = this.videoSpanId + '_name';
  8233. }
  8234. }
  8235. /**
  8236. * Removes remote video menu element from video element identified by
  8237. * given <tt>videoElementId</tt>.
  8238. *
  8239. * @param videoElementId the id of local or remote video element.
  8240. */
  8241. RemoteVideo.prototype.removeRemoteVideoMenu = function() {
  8242. var menuSpan = $('#' + this.videoSpanId + '>span.remotevideomenu');
  8243. if (menuSpan.length) {
  8244. menuSpan.remove();
  8245. }
  8246. };
  8247. RemoteVideo.prototype.getResourceJid = function () {
  8248. if (!this.resourceJid) {
  8249. console.error("Undefined resource jid");
  8250. }
  8251. return this.resourceJid;
  8252. };
  8253. RemoteVideo.createContainer = function (spanId) {
  8254. var container = document.createElement('span');
  8255. container.id = spanId;
  8256. container.className = 'videocontainer';
  8257. var remotes = document.getElementById('remoteVideos');
  8258. return remotes.appendChild(container);
  8259. };
  8260. module.exports = RemoteVideo;
  8261. },{"../../RTC/RTCBrowserType":8,"../audio_levels/AudioLevels":12,"../avatar/Avatar":16,"./ConnectionIndicator":34,"./LargeVideo":35,"./SmallVideo":38}],38:[function(require,module,exports){
  8262. var Avatar = require("../avatar/Avatar");
  8263. var UIUtil = require("../util/UIUtil");
  8264. var LargeVideo = require("./LargeVideo");
  8265. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  8266. function SmallVideo(){
  8267. this.isMuted = false;
  8268. this.hasAvatar = false;
  8269. }
  8270. function setVisibility(selector, show) {
  8271. if (selector && selector.length > 0) {
  8272. selector.css("visibility", show ? "visible" : "hidden");
  8273. }
  8274. }
  8275. SmallVideo.prototype.showDisplayName = function(isShow) {
  8276. var nameSpan = $('#' + this.videoSpanId + '>span.displayname').get(0);
  8277. if (isShow) {
  8278. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  8279. nameSpan.setAttribute("style", "display:inline-block;");
  8280. }
  8281. else {
  8282. if (nameSpan)
  8283. nameSpan.setAttribute("style", "display:none;");
  8284. }
  8285. };
  8286. SmallVideo.prototype.setDeviceAvailabilityIcons = function (devices) {
  8287. if(!this.container)
  8288. return;
  8289. $("#" + this.videoSpanId + " > .noMic").remove();
  8290. $("#" + this.videoSpanId + " > .noVideo").remove();
  8291. if(!devices.audio)
  8292. {
  8293. this.container.appendChild(
  8294. document.createElement("div")).setAttribute("class","noMic");
  8295. }
  8296. if(!devices.video)
  8297. {
  8298. this.container.appendChild(
  8299. document.createElement("div")).setAttribute("class","noVideo");
  8300. }
  8301. if(!devices.audio && !devices.video)
  8302. {
  8303. $("#" + this.videoSpanId + " > .noMic").css("background-position", "75%");
  8304. $("#" + this.videoSpanId + " > .noVideo").css("background-position", "25%");
  8305. $("#" + this.videoSpanId + " > .noVideo").css("background-color", "transparent");
  8306. }
  8307. }
  8308. /**
  8309. * Shows the presence status message for the given video.
  8310. */
  8311. SmallVideo.prototype.setPresenceStatus = function (statusMsg) {
  8312. if (!this.container) {
  8313. // No container
  8314. return;
  8315. }
  8316. var statusSpan = $('#' + this.videoSpanId + '>span.status');
  8317. if (!statusSpan.length) {
  8318. //Add status span
  8319. statusSpan = document.createElement('span');
  8320. statusSpan.className = 'status';
  8321. statusSpan.id = this.videoSpanId + '_status';
  8322. $('#' + this.videoSpanId)[0].appendChild(statusSpan);
  8323. statusSpan = $('#' + this.videoSpanId + '>span.status');
  8324. }
  8325. // Display status
  8326. if (statusMsg && statusMsg.length) {
  8327. $('#' + this.videoSpanId + '_status').text(statusMsg);
  8328. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  8329. }
  8330. else {
  8331. // Hide
  8332. statusSpan.get(0).setAttribute("style", "display:none;");
  8333. }
  8334. };
  8335. /**
  8336. * Creates an audio or video stream element.
  8337. */
  8338. SmallVideo.createStreamElement = function (sid, stream) {
  8339. var isVideo = stream.getVideoTracks().length > 0;
  8340. var element = isVideo
  8341. ? document.createElement('video')
  8342. : document.createElement('audio');
  8343. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_')
  8344. + sid + '_' + APP.RTC.getStreamID(stream);
  8345. element.id = id;
  8346. if (!RTCBrowserType.isIExplorer()) {
  8347. element.autoplay = true;
  8348. }
  8349. element.oncontextmenu = function () { return false; };
  8350. return element;
  8351. };
  8352. /**
  8353. * Updates the data for the indicator
  8354. * @param id the id of the indicator
  8355. * @param percent the percent for connection quality
  8356. * @param object the data
  8357. */
  8358. SmallVideo.prototype.updateStatsIndicator = function (percent, object) {
  8359. if(this.connectionIndicator)
  8360. this.connectionIndicator.updateConnectionQuality(percent, object);
  8361. }
  8362. SmallVideo.prototype.hideIndicator = function () {
  8363. if(this.connectionIndicator)
  8364. this.connectionIndicator.hideIndicator();
  8365. }
  8366. /**
  8367. * Shows audio muted indicator over small videos.
  8368. * @param {string} isMuted
  8369. */
  8370. SmallVideo.prototype.showAudioIndicator = function(isMuted) {
  8371. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8372. if (!isMuted) {
  8373. if (audioMutedSpan.length > 0) {
  8374. audioMutedSpan.popover('hide');
  8375. audioMutedSpan.remove();
  8376. }
  8377. }
  8378. else {
  8379. if(audioMutedSpan.length == 0 ) {
  8380. audioMutedSpan = document.createElement('span');
  8381. audioMutedSpan.className = 'audioMuted';
  8382. UIUtil.setTooltip(audioMutedSpan,
  8383. "videothumbnail.mute",
  8384. "top");
  8385. this.container.appendChild(audioMutedSpan);
  8386. APP.translation.translateElement($('#' + this.videoSpanId + " > span"));
  8387. var mutedIndicator = document.createElement('i');
  8388. mutedIndicator.className = 'icon-mic-disabled';
  8389. audioMutedSpan.appendChild(mutedIndicator);
  8390. }
  8391. this.updateIconPositions();
  8392. }
  8393. this.isMuted = isMuted;
  8394. };
  8395. /**
  8396. * Shows video muted indicator over small videos.
  8397. */
  8398. SmallVideo.prototype.showVideoIndicator = function(isMuted) {
  8399. this.showAvatar(isMuted);
  8400. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8401. if (isMuted === false) {
  8402. if (videoMutedSpan.length > 0) {
  8403. videoMutedSpan.remove();
  8404. }
  8405. }
  8406. else {
  8407. if(videoMutedSpan.length == 0) {
  8408. videoMutedSpan = document.createElement('span');
  8409. videoMutedSpan.className = 'videoMuted';
  8410. this.container.appendChild(videoMutedSpan);
  8411. var mutedIndicator = document.createElement('i');
  8412. mutedIndicator.className = 'icon-camera-disabled';
  8413. UIUtil.setTooltip(mutedIndicator,
  8414. "videothumbnail.videomute",
  8415. "top");
  8416. videoMutedSpan.appendChild(mutedIndicator);
  8417. //translate texts for muted indicator
  8418. APP.translation.translateElement($('#' + this.videoSpanId + " > span > i"));
  8419. }
  8420. this.updateIconPositions();
  8421. }
  8422. };
  8423. SmallVideo.prototype.enableDominantSpeaker = function (isEnable)
  8424. {
  8425. var resourceJid = this.getResourceJid();
  8426. var displayName = resourceJid;
  8427. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8428. if (nameSpan.length > 0)
  8429. displayName = nameSpan.html();
  8430. console.log("UI enable dominant speaker",
  8431. displayName,
  8432. resourceJid,
  8433. isEnable);
  8434. if (!this.container) {
  8435. return;
  8436. }
  8437. if (isEnable) {
  8438. this.showDisplayName(LargeVideo.isLargeVideoOnTop());
  8439. if (!this.container.classList.contains("dominantspeaker"))
  8440. this.container.classList.add("dominantspeaker");
  8441. }
  8442. else {
  8443. this.showDisplayName(false);
  8444. if (this.container.classList.contains("dominantspeaker"))
  8445. this.container.classList.remove("dominantspeaker");
  8446. }
  8447. this.showAvatar();
  8448. };
  8449. SmallVideo.prototype.updateIconPositions = function () {
  8450. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8451. var connectionIndicator = $('#' + this.videoSpanId + '>div.connectionindicator');
  8452. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8453. if(connectionIndicator.length > 0
  8454. && connectionIndicator[0].style.display != "none") {
  8455. audioMutedSpan.css({right: "23px"});
  8456. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  8457. }
  8458. else
  8459. {
  8460. audioMutedSpan.css({right: "0px"});
  8461. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  8462. }
  8463. }
  8464. /**
  8465. * Creates the element indicating the moderator(owner) of the conference.
  8466. *
  8467. * @param parentElement the parent element where the owner indicator will
  8468. * be added
  8469. */
  8470. SmallVideo.prototype.createModeratorIndicatorElement = function () {
  8471. // Show moderator indicator
  8472. var indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8473. if (!indicatorSpan || indicatorSpan.length === 0) {
  8474. indicatorSpan = document.createElement('span');
  8475. indicatorSpan.className = 'focusindicator';
  8476. this.container.appendChild(indicatorSpan);
  8477. indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8478. }
  8479. if (indicatorSpan.children().length !== 0)
  8480. return;
  8481. var moderatorIndicator = document.createElement('i');
  8482. moderatorIndicator.className = 'fa fa-star';
  8483. indicatorSpan[0].appendChild(moderatorIndicator);
  8484. UIUtil.setTooltip(indicatorSpan[0],
  8485. "videothumbnail.moderator",
  8486. "top");
  8487. //translates text in focus indicators
  8488. APP.translation.translateElement($('#' + this.videoSpanId + ' .focusindicator'));
  8489. }
  8490. SmallVideo.prototype.getSrc = function () {
  8491. var videoElement = APP.RTC.getVideoElementName();
  8492. return APP.RTC.getVideoSrc(
  8493. $('#' + this.videoSpanId).find(videoElement).get(0));
  8494. },
  8495. SmallVideo.prototype.focus = function(isFocused)
  8496. {
  8497. if(!isFocused) {
  8498. this.container.classList.remove("videoContainerFocused");
  8499. }
  8500. else
  8501. {
  8502. this.container.classList.add("videoContainerFocused");
  8503. }
  8504. }
  8505. SmallVideo.prototype.hasVideo = function () {
  8506. return $("#" + this.videoSpanId).find(
  8507. APP.RTC.getVideoElementName()).length !== 0;
  8508. }
  8509. /**
  8510. * Hides or shows the user's avatar
  8511. * @param show whether we should show the avatar or not
  8512. * video because there is no dominant speaker and no focused speaker
  8513. */
  8514. SmallVideo.prototype.showAvatar = function (show) {
  8515. if (!this.hasAvatar) {
  8516. if (this.peerJid) {
  8517. // Init avatar
  8518. this.avatarChanged(Avatar.getThumbUrl(this.peerJid));
  8519. } else {
  8520. console.error("Unable to init avatar - no peerjid", this);
  8521. return;
  8522. }
  8523. }
  8524. var resourceJid = this.getResourceJid();
  8525. var videoElem = APP.RTC.getVideoElementName();
  8526. var video = $('#' + this.videoSpanId).find(videoElem);
  8527. var avatar = $('#avatar_' + resourceJid);
  8528. if (show === undefined || show === null) {
  8529. if (!this.isLocal &&
  8530. !this.VideoLayout.isInLastN(resourceJid)) {
  8531. show = true;
  8532. }
  8533. else
  8534. {
  8535. show = APP.RTC.isVideoMuted(this.peerJid);
  8536. }
  8537. }
  8538. if (LargeVideo.showAvatar(resourceJid, show))
  8539. {
  8540. setVisibility(avatar, false);
  8541. setVisibility(video, false);
  8542. } else {
  8543. if (video && video.length > 0) {
  8544. setVisibility(video, !show);
  8545. }
  8546. setVisibility(avatar, show);
  8547. }
  8548. };
  8549. SmallVideo.prototype.avatarChanged = function (thumbUrl) {
  8550. var thumbnail = $('#' + this.videoSpanId);
  8551. var resourceJid = this.getResourceJid();
  8552. var avatar = $('#avatar_' + resourceJid);
  8553. this.hasAvatar = true;
  8554. // set the avatar in the thumbnail
  8555. if (avatar && avatar.length > 0) {
  8556. avatar[0].src = thumbUrl;
  8557. } else {
  8558. if (thumbnail && thumbnail.length > 0) {
  8559. avatar = document.createElement('img');
  8560. avatar.id = 'avatar_' + resourceJid;
  8561. avatar.className = 'userAvatar';
  8562. avatar.src = thumbUrl;
  8563. thumbnail.append(avatar);
  8564. }
  8565. }
  8566. }
  8567. module.exports = SmallVideo;
  8568. },{"../../RTC/RTCBrowserType":8,"../avatar/Avatar":16,"../util/UIUtil":33,"./LargeVideo":35}],39:[function(require,module,exports){
  8569. var AudioLevels = require("../audio_levels/AudioLevels");
  8570. var Avatar = require("../avatar/Avatar");
  8571. var ContactList = require("../side_pannels/contactlist/ContactList");
  8572. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  8573. var UIEvents = require("../../../service/UI/UIEvents");
  8574. var RTC = require("../../RTC/RTC");
  8575. var RTCBrowserType = require('../../RTC/RTCBrowserType');
  8576. var RemoteVideo = require("./RemoteVideo");
  8577. var LargeVideo = require("./LargeVideo");
  8578. var LocalVideo = require("./LocalVideo");
  8579. var remoteVideos = {};
  8580. var localVideoThumbnail = null;
  8581. var currentDominantSpeaker = null;
  8582. var lastNCount = config.channelLastN;
  8583. var localLastNCount = config.channelLastN;
  8584. var localLastNSet = [];
  8585. var lastNEndpointsCache = [];
  8586. var lastNPickupJid = null;
  8587. var eventEmitter = null;
  8588. /**
  8589. * Currently focused video jid
  8590. * @type {String}
  8591. */
  8592. var focusedVideoResourceJid = null;
  8593. var VideoLayout = (function (my) {
  8594. my.init = function (emitter) {
  8595. eventEmitter = emitter;
  8596. localVideoThumbnail = new LocalVideo(VideoLayout);
  8597. VideoLayout.resizeLargeVideoContainer();
  8598. LargeVideo.init(VideoLayout, emitter);
  8599. };
  8600. my.isInLastN = function(resource) {
  8601. return lastNCount < 0 // lastN is disabled, return true
  8602. || (lastNCount > 0 && lastNEndpointsCache.length == 0) // lastNEndpoints cache not built yet, return true
  8603. || (lastNEndpointsCache && lastNEndpointsCache.indexOf(resource) !== -1);
  8604. };
  8605. my.changeLocalStream = function (stream, isMuted) {
  8606. VideoLayout.changeLocalVideo(stream, isMuted);
  8607. };
  8608. my.changeLocalAudio = function(stream, isMuted) {
  8609. if (isMuted)
  8610. APP.UI.setAudioMuted(true, true);
  8611. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  8612. var localAudio = document.getElementById('localAudio');
  8613. // Writing volume not allowed in IE
  8614. if (!RTCBrowserType.isIExplorer()) {
  8615. localAudio.autoplay = true;
  8616. localAudio.volume = 0;
  8617. }
  8618. };
  8619. my.changeLocalVideo = function(stream, isMuted) {
  8620. // Set default display name.
  8621. localVideoThumbnail.setDisplayName();
  8622. localVideoThumbnail.createConnectionIndicator();
  8623. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  8624. localVideoThumbnail.changeVideo(stream, isMuted);
  8625. /* force update if we're currently being displayed */
  8626. if (LargeVideo.isCurrentlyOnLarge(APP.xmpp.myResource())) {
  8627. LargeVideo.updateLargeVideo(APP.xmpp.myResource(), true);
  8628. }
  8629. };
  8630. my.mucJoined = function () {
  8631. var myResourceJid = APP.xmpp.myResource();
  8632. localVideoThumbnail.joined(APP.xmpp.myJid());
  8633. if (!LargeVideo.getResourceJid())
  8634. LargeVideo.updateLargeVideo(myResourceJid, true);
  8635. };
  8636. /**
  8637. * Adds or removes icons for not available camera and microphone.
  8638. * @param resourceJid the jid of user
  8639. * @param devices available devices
  8640. */
  8641. my.setDeviceAvailabilityIcons = function (resourceJid, devices) {
  8642. if(!devices)
  8643. return;
  8644. if(!resourceJid)
  8645. {
  8646. localVideoThumbnail.setDeviceAvailabilityIcons(devices);
  8647. }
  8648. else
  8649. {
  8650. if(remoteVideos[resourceJid])
  8651. remoteVideos[resourceJid].setDeviceAvailabilityIcons(devices);
  8652. }
  8653. }
  8654. /**
  8655. * Checks if removed video is currently displayed and tries to display
  8656. * another one instead.
  8657. * @param removedVideoSrc src stream identifier of the video.
  8658. */
  8659. my.updateRemovedVideo = function(resourceJid) {
  8660. if (resourceJid === LargeVideo.getResourceJid()) {
  8661. var newResourceJid;
  8662. // We'll show user's avatar if he is the dominant speaker or if
  8663. // his video thumbnail is pinned
  8664. if (resourceJid === focusedVideoResourceJid ||
  8665. resourceJid === currentDominantSpeaker) {
  8666. newResourceJid = resourceJid;
  8667. } else {
  8668. // Otherwise select last visible video
  8669. newResourceJid = this.electLastVisibleVideo();
  8670. }
  8671. LargeVideo.updateLargeVideo(newResourceJid);
  8672. }
  8673. };
  8674. my.electLastVisibleVideo = function() {
  8675. // pick the last visible video in the row
  8676. // if nobody else is left, this picks the local video
  8677. var jid;
  8678. var videoElem = RTC.getVideoElementName();
  8679. var pick = $('#remoteVideos>span[id!="mixedstream"]:visible:last>' + videoElem);
  8680. if (pick.length && APP.RTC.getVideoSrc(pick[0])) {
  8681. return VideoLayout.getPeerContainerResourceJid(pick[0].parentNode);
  8682. } else {
  8683. console.info("Last visible video no longer exists");
  8684. pick = $('#remoteVideos>span[id!="mixedstream"]>' + videoElem);
  8685. if (pick.length && APP.RTC.getVideoSrc(pick[0])) {
  8686. return VideoLayout.getPeerContainerResourceJid(pick[0].parentNode);
  8687. } else {
  8688. // Try local video
  8689. console.info("Fallback to local video...");
  8690. return APP.xmpp.myResource();
  8691. }
  8692. }
  8693. };
  8694. my.onRemoteStreamAdded = function (stream) {
  8695. if (stream.peerjid) {
  8696. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  8697. var resourceJid = Strophe.getResourceFromJid(stream.peerjid);
  8698. remoteVideos[resourceJid].addRemoteStreamElement(
  8699. stream.sid,
  8700. stream.getOriginalStream(),
  8701. stream.ssrc);
  8702. }
  8703. };
  8704. my.getLargeVideoJid = function () {
  8705. return LargeVideo.getResourceJid();
  8706. };
  8707. /**
  8708. * Called when large video update is finished
  8709. * @param currentSmallVideo small video currently displayed on large video
  8710. */
  8711. my.largeVideoUpdated = function (currentSmallVideo) {
  8712. // Makes sure that dominant speaker UI
  8713. // is enabled only on current small video
  8714. localVideoThumbnail.enableDominantSpeaker(
  8715. localVideoThumbnail === currentSmallVideo);
  8716. Object.keys(remoteVideos).forEach(
  8717. function (resourceJid) {
  8718. var remoteVideo = remoteVideos[resourceJid];
  8719. if (remoteVideo) {
  8720. remoteVideo.enableDominantSpeaker(
  8721. remoteVideo === currentSmallVideo);
  8722. }
  8723. }
  8724. );
  8725. };
  8726. my.handleVideoThumbClicked = function(noPinnedEndpointChangedEvent,
  8727. resourceJid) {
  8728. if(focusedVideoResourceJid) {
  8729. var oldSmallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  8730. if(oldSmallVideo)
  8731. oldSmallVideo.focus(false);
  8732. }
  8733. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  8734. // Unlock current focused.
  8735. if (focusedVideoResourceJid === resourceJid)
  8736. {
  8737. focusedVideoResourceJid = null;
  8738. // Enable the currently set dominant speaker.
  8739. if (currentDominantSpeaker) {
  8740. if(smallVideo && smallVideo.hasVideo())
  8741. {
  8742. LargeVideo.updateLargeVideo(currentDominantSpeaker);
  8743. }
  8744. }
  8745. if (!noPinnedEndpointChangedEvent) {
  8746. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  8747. }
  8748. return;
  8749. }
  8750. // Lock new video
  8751. focusedVideoResourceJid = resourceJid;
  8752. // Update focused/pinned interface.
  8753. if (resourceJid)
  8754. {
  8755. if(smallVideo)
  8756. smallVideo.focus(true);
  8757. if (!noPinnedEndpointChangedEvent) {
  8758. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  8759. }
  8760. }
  8761. // Triggers a "video.selected" event. The "false" parameter indicates
  8762. // this isn't a prezi.
  8763. $(document).trigger("video.selected", [false]);
  8764. LargeVideo.updateLargeVideo(resourceJid);
  8765. // Writing volume not allowed in IE
  8766. if (!RTCBrowserType.isIExplorer()) {
  8767. $('audio').each(function (idx, el) {
  8768. el.volume = 0;
  8769. el.volume = 1;
  8770. });
  8771. }
  8772. };
  8773. /**
  8774. * Checks if container for participant identified by given peerJid exists
  8775. * in the document and creates it eventually.
  8776. *
  8777. * @param peerJid peer Jid to check.
  8778. *
  8779. * @return Returns <tt>true</tt> if the peer container exists,
  8780. * <tt>false</tt> - otherwise
  8781. */
  8782. my.ensurePeerContainerExists = function(peerJid) {
  8783. ContactList.ensureAddContact(peerJid);
  8784. var resourceJid = Strophe.getResourceFromJid(peerJid);
  8785. if(!remoteVideos[resourceJid])
  8786. {
  8787. remoteVideos[resourceJid] = new RemoteVideo(peerJid, VideoLayout);
  8788. // In case this is not currently in the last n we don't show it.
  8789. if (localLastNCount
  8790. && localLastNCount > 0
  8791. && $('#remoteVideos>span').length >= localLastNCount + 2) {
  8792. remoteVideos[resourceJid].showPeerContainer('hide');
  8793. }
  8794. else
  8795. VideoLayout.resizeThumbnails();
  8796. }
  8797. };
  8798. my.inputDisplayNameHandler = function (name) {
  8799. localVideoThumbnail.inputDisplayNameHandler(name);
  8800. };
  8801. my.videoactive = function (videoelem, resourceJid) {
  8802. console.info(resourceJid + " video is now active");
  8803. videoelem.show();
  8804. VideoLayout.resizeThumbnails();
  8805. // Update the large video to the last added video only if there's no
  8806. // current dominant, focused speaker or prezi playing or update it to
  8807. // the current dominant speaker.
  8808. if ((!focusedVideoResourceJid &&
  8809. !currentDominantSpeaker &&
  8810. !require("../prezi/Prezi").isPresentationVisible()) ||
  8811. focusedVideoResourceJid === resourceJid ||
  8812. (resourceJid &&
  8813. currentDominantSpeaker === resourceJid)) {
  8814. LargeVideo.updateLargeVideo(resourceJid, true);
  8815. }
  8816. }
  8817. /**
  8818. * Shows the presence status message for the given video.
  8819. */
  8820. my.setPresenceStatus = function (resourceJid, statusMsg) {
  8821. remoteVideos[resourceJid].setPresenceStatus(statusMsg);
  8822. };
  8823. /**
  8824. * Shows a visual indicator for the moderator of the conference.
  8825. */
  8826. my.showModeratorIndicator = function () {
  8827. var isModerator = APP.xmpp.isModerator();
  8828. if (isModerator) {
  8829. localVideoThumbnail.createModeratorIndicatorElement();
  8830. }
  8831. var members = APP.xmpp.getMembers();
  8832. Object.keys(members).forEach(function (jid) {
  8833. if (Strophe.getResourceFromJid(jid) === 'focus') {
  8834. // Skip server side focus
  8835. return;
  8836. }
  8837. var resourceJid = Strophe.getResourceFromJid(jid);
  8838. var member = members[jid];
  8839. if (member.role === 'moderator') {
  8840. remoteVideos[resourceJid].removeRemoteVideoMenu();
  8841. remoteVideos[resourceJid].createModeratorIndicatorElement();
  8842. } else if (isModerator) {
  8843. // We are moderator, but user is not - add menu
  8844. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  8845. remoteVideos[resourceJid].addRemoteVideoMenu();
  8846. }
  8847. }
  8848. });
  8849. };
  8850. /*
  8851. * Shows or hides the audio muted indicator over the local thumbnail video.
  8852. * @param {boolean} isMuted
  8853. */
  8854. my.showLocalAudioIndicator = function(isMuted) {
  8855. localVideoThumbnail.showAudioIndicator(isMuted);
  8856. };
  8857. /**
  8858. * Resizes the large video container.
  8859. */
  8860. my.resizeLargeVideoContainer = function () {
  8861. LargeVideo.resize();
  8862. VideoLayout.resizeThumbnails();
  8863. LargeVideo.position();
  8864. };
  8865. /**
  8866. * Resizes thumbnails.
  8867. */
  8868. my.resizeThumbnails = function(animate) {
  8869. var videoSpaceWidth = $('#remoteVideos').width();
  8870. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  8871. var width = thumbnailSize[0];
  8872. var height = thumbnailSize[1];
  8873. $('.userAvatar').css('left', (width - height) / 2);
  8874. if(animate)
  8875. {
  8876. $('#remoteVideos').animate({
  8877. height: height
  8878. },
  8879. {
  8880. queue: false,
  8881. duration: 500
  8882. });
  8883. $('#remoteVideos>span').animate({
  8884. height: height,
  8885. width: width
  8886. },
  8887. {
  8888. queue: false,
  8889. duration: 500,
  8890. complete: function () {
  8891. $(document).trigger(
  8892. "remotevideo.resized",
  8893. [width,
  8894. height]);
  8895. }
  8896. });
  8897. }
  8898. else
  8899. {
  8900. // size videos so that while keeping AR and max height, we have a
  8901. // nice fit
  8902. $('#remoteVideos').height(height);
  8903. $('#remoteVideos>span').width(width);
  8904. $('#remoteVideos>span').height(height);
  8905. $(document).trigger("remotevideo.resized", [width, height]);
  8906. }
  8907. };
  8908. /**
  8909. * Calculates the thumbnail size.
  8910. *
  8911. * @param videoSpaceWidth the width of the video space
  8912. */
  8913. my.calculateThumbnailSize = function (videoSpaceWidth) {
  8914. // Calculate the available height, which is the inner window height minus
  8915. // 39px for the header minus 2px for the delimiter lines on the top and
  8916. // bottom of the large video, minus the 36px space inside the remoteVideos
  8917. // container used for highlighting shadow.
  8918. var availableHeight = 100;
  8919. var numvids = $('#remoteVideos>span:visible').length;
  8920. if (localLastNCount && localLastNCount > 0) {
  8921. numvids = Math.min(localLastNCount + 1, numvids);
  8922. }
  8923. // Remove the 3px borders arround videos and border around the remote
  8924. // videos area and the 4 pixels between the local video and the others
  8925. //TODO: Find out where the 4 pixels come from and remove them
  8926. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  8927. var availableWidth = availableWinWidth / numvids;
  8928. var aspectRatio = 16.0 / 9.0;
  8929. var maxHeight = Math.min(160, availableHeight);
  8930. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  8931. if (availableHeight < availableWidth / aspectRatio) {
  8932. availableWidth = Math.floor(availableHeight * aspectRatio);
  8933. }
  8934. return [availableWidth, availableHeight];
  8935. };
  8936. /**
  8937. * Returns the corresponding resource jid to the given peer container
  8938. * DOM element.
  8939. *
  8940. * @return the corresponding resource jid to the given peer container
  8941. * DOM element
  8942. */
  8943. my.getPeerContainerResourceJid = function (containerElement) {
  8944. var i = containerElement.id.indexOf('participant_');
  8945. if (i >= 0)
  8946. return containerElement.id.substring(i + 12);
  8947. };
  8948. my.getPeerVideoSel = function (peerResourceJid) {
  8949. return $('#participant_' + peerResourceJid +
  8950. '>' + APP.RTC.getVideoElementName());
  8951. };
  8952. /**
  8953. * On contact list item clicked.
  8954. */
  8955. $(ContactList).bind('contactclicked', function(event, jid) {
  8956. if (!jid) {
  8957. return;
  8958. }
  8959. if (jid === APP.xmpp.myJid()) {
  8960. $("#localVideoContainer").click();
  8961. return;
  8962. }
  8963. var resource = Strophe.getResourceFromJid(jid);
  8964. var videoSel = VideoLayout.getPeerVideoSel(resource);
  8965. if (videoSel.length > 0) {
  8966. var videoThumb = videoSel[0];
  8967. // It is not always the case that a videoThumb exists (if there is
  8968. // no actual video).
  8969. if (RTC.getVideoSrc(videoThumb)) {
  8970. // We have a video src, great! Let's update the large video
  8971. // now.
  8972. VideoLayout.handleVideoThumbClicked(
  8973. false,
  8974. Strophe.getResourceFromJid(jid));
  8975. } else {
  8976. // If we don't have a video src for jid, there's absolutely
  8977. // no point in calling handleVideoThumbClicked; Quite
  8978. // simply, it won't work because it needs an src to attach
  8979. // to the large video.
  8980. //
  8981. // Instead, we trigger the pinned endpoint changed event to
  8982. // let the bridge adjust its lastN set for myjid and store
  8983. // the pinned user in the lastNPickupJid variable to be
  8984. // picked up later by the lastN changed event handler.
  8985. lastNPickupJid = jid;
  8986. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  8987. Strophe.getResourceFromJid(jid));
  8988. }
  8989. }
  8990. });
  8991. /**
  8992. * On audio muted event.
  8993. */
  8994. my.onAudioMute = function (jid, isMuted) {
  8995. var resourceJid = Strophe.getResourceFromJid(jid);
  8996. if (resourceJid === APP.xmpp.myResource()) {
  8997. localVideoThumbnail.showAudioIndicator(isMuted);
  8998. } else {
  8999. VideoLayout.ensurePeerContainerExists(jid);
  9000. remoteVideos[resourceJid].showAudioIndicator(isMuted);
  9001. if (APP.xmpp.isModerator()) {
  9002. remoteVideos[resourceJid].updateRemoteVideoMenu(isMuted);
  9003. }
  9004. }
  9005. };
  9006. /**
  9007. * On video muted event.
  9008. */
  9009. my.onVideoMute = function (jid, value) {
  9010. if(jid !== APP.xmpp.myJid() && !APP.RTC.muteRemoteVideoStream(jid, value))
  9011. return;
  9012. if (jid === APP.xmpp.myJid()) {
  9013. localVideoThumbnail.showVideoIndicator(value);
  9014. } else {
  9015. var resource = Strophe.getResourceFromJid(jid);
  9016. VideoLayout.ensurePeerContainerExists(jid);
  9017. remoteVideos[resource].showVideoIndicator(value);
  9018. var el = VideoLayout.getPeerVideoSel(resource);
  9019. if (!value)
  9020. el.show();
  9021. else
  9022. el.hide();
  9023. }
  9024. };
  9025. /**
  9026. * Display name changed.
  9027. */
  9028. my.onDisplayNameChanged =
  9029. function (jid, displayName, status) {
  9030. if (jid === 'localVideoContainer'
  9031. || jid === APP.xmpp.myJid()) {
  9032. localVideoThumbnail.setDisplayName(displayName);
  9033. } else {
  9034. VideoLayout.ensurePeerContainerExists(jid);
  9035. remoteVideos[Strophe.getResourceFromJid(jid)].setDisplayName(
  9036. displayName,
  9037. status);
  9038. }
  9039. };
  9040. /**
  9041. * On dominant speaker changed event.
  9042. */
  9043. my.onDominantSpeakerChanged = function (resourceJid) {
  9044. // We ignore local user events.
  9045. if (resourceJid === APP.xmpp.myResource())
  9046. return;
  9047. var members = APP.xmpp.getMembers();
  9048. // Update the current dominant speaker.
  9049. if (resourceJid !== currentDominantSpeaker) {
  9050. var currentJID = APP.xmpp.findJidFromResource(currentDominantSpeaker);
  9051. var newJID = APP.xmpp.findJidFromResource(resourceJid);
  9052. if(currentDominantSpeaker && (!members || !members[currentJID] ||
  9053. !members[currentJID].displayName)) {
  9054. remoteVideos[resourceJid].setDisplayName(null);
  9055. }
  9056. if(resourceJid && (!members || !members[newJID] ||
  9057. !members[newJID].displayName)) {
  9058. remoteVideos[resourceJid].setDisplayName(null,
  9059. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  9060. }
  9061. currentDominantSpeaker = resourceJid;
  9062. } else {
  9063. return;
  9064. }
  9065. // Obtain container for new dominant speaker.
  9066. var videoSel = VideoLayout.getPeerVideoSel(resourceJid);
  9067. // Local video will not have container found, but that's ok
  9068. // since we don't want to switch to local video.
  9069. if (!focusedVideoResourceJid && videoSel.length)
  9070. {
  9071. // Update the large video if the video source is already available,
  9072. // otherwise wait for the "videoactive.jingle" event.
  9073. if (videoSel[0].currentTime > 0) {
  9074. LargeVideo.updateLargeVideo(resourceJid);
  9075. }
  9076. }
  9077. };
  9078. /**
  9079. * On last N change event.
  9080. *
  9081. * @param lastNEndpoints the list of last N endpoints
  9082. * @param endpointsEnteringLastN the list currently entering last N
  9083. * endpoints
  9084. */
  9085. my.onLastNEndpointsChanged = function ( lastNEndpoints,
  9086. endpointsEnteringLastN,
  9087. stream) {
  9088. if (lastNCount !== lastNEndpoints.length)
  9089. lastNCount = lastNEndpoints.length;
  9090. lastNEndpointsCache = lastNEndpoints;
  9091. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  9092. //
  9093. // If LastN drops to, say, 2, because of adaptivity, then E should see
  9094. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  9095. // so E sees them. C is only in E's local LastN set.
  9096. //
  9097. // If F starts talking and LastN = 3, then E should see thumbnails for
  9098. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  9099. // enters E's local LastN ejecting C.
  9100. // Increase the local LastN set size, if necessary.
  9101. if (lastNCount > localLastNCount) {
  9102. localLastNCount = lastNCount;
  9103. }
  9104. // Update the local LastN set preserving the order in which the
  9105. // endpoints appeared in the LastN/local LastN set.
  9106. var nextLocalLastNSet = lastNEndpoints.slice(0);
  9107. for (var i = 0; i < localLastNSet.length; i++) {
  9108. if (nextLocalLastNSet.length >= localLastNCount) {
  9109. break;
  9110. }
  9111. var resourceJid = localLastNSet[i];
  9112. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  9113. nextLocalLastNSet.push(resourceJid);
  9114. }
  9115. }
  9116. localLastNSet = nextLocalLastNSet;
  9117. var updateLargeVideo = false;
  9118. // Handle LastN/local LastN changes.
  9119. $('#remoteVideos>span').each(function( index, element ) {
  9120. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  9121. var isReceived = true;
  9122. if (resourceJid
  9123. && lastNEndpoints.indexOf(resourceJid) < 0
  9124. && localLastNSet.indexOf(resourceJid) < 0) {
  9125. console.log("Remove from last N", resourceJid);
  9126. remoteVideos[resourceJid].showPeerContainer('hide');
  9127. isReceived = false;
  9128. } else if (resourceJid
  9129. && $('#participant_' + resourceJid).is(':visible')
  9130. && lastNEndpoints.indexOf(resourceJid) < 0
  9131. && localLastNSet.indexOf(resourceJid) >= 0) {
  9132. remoteVideos[resourceJid].showPeerContainer('avatar');
  9133. isReceived = false;
  9134. }
  9135. if (!isReceived) {
  9136. // resourceJid has dropped out of the server side lastN set, so
  9137. // it is no longer being received. If resourceJid was being
  9138. // displayed in the large video we have to switch to another
  9139. // user.
  9140. if (!updateLargeVideo && resourceJid === LargeVideo.getResourceJid()) {
  9141. updateLargeVideo = true;
  9142. }
  9143. }
  9144. });
  9145. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  9146. endpointsEnteringLastN = lastNEndpoints;
  9147. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  9148. endpointsEnteringLastN.forEach(function (resourceJid) {
  9149. var isVisible = $('#participant_' + resourceJid).is(':visible');
  9150. remoteVideos[resourceJid].showPeerContainer('show');
  9151. if (!isVisible) {
  9152. console.log("Add to last N", resourceJid);
  9153. var jid = APP.xmpp.findJidFromResource(resourceJid);
  9154. var mediaStream = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  9155. var sel = VideoLayout.getPeerVideoSel(resourceJid);
  9156. APP.RTC.attachMediaStream(sel, mediaStream.stream);
  9157. if (lastNPickupJid == mediaStream.peerjid) {
  9158. // Clean up the lastN pickup jid.
  9159. lastNPickupJid = null;
  9160. // Don't fire the events again, they've already
  9161. // been fired in the contact list click handler.
  9162. VideoLayout.handleVideoThumbClicked(
  9163. false,
  9164. Strophe.getResourceFromJid(mediaStream.peerjid));
  9165. updateLargeVideo = false;
  9166. }
  9167. remoteVideos[resourceJid].waitForPlayback(sel, mediaStream.stream);
  9168. }
  9169. });
  9170. }
  9171. // The endpoint that was being shown in the large video has dropped out
  9172. // of the lastN set and there was no lastN pickup jid. We need to update
  9173. // the large video now.
  9174. if (updateLargeVideo) {
  9175. var resource, container, src;
  9176. var myResource
  9177. = APP.xmpp.myResource();
  9178. // Find out which endpoint to show in the large video.
  9179. for (var i = 0; i < lastNEndpoints.length; i++) {
  9180. resource = lastNEndpoints[i];
  9181. if (!resource || resource === myResource)
  9182. continue;
  9183. // videoSrcToSsrc needs to be update for this call to succeed.
  9184. LargeVideo.updateLargeVideo(resource);
  9185. break;
  9186. }
  9187. }
  9188. };
  9189. /**
  9190. * Updates local stats
  9191. * @param percent
  9192. * @param object
  9193. */
  9194. my.updateLocalConnectionStats = function (percent, object) {
  9195. var resolution = null;
  9196. if(object.resolution !== null)
  9197. {
  9198. resolution = object.resolution;
  9199. object.resolution = resolution[APP.xmpp.myJid()];
  9200. delete resolution[APP.xmpp.myJid()];
  9201. }
  9202. localVideoThumbnail.updateStatsIndicator(percent, object);
  9203. for(var jid in resolution)
  9204. {
  9205. if(resolution[jid] === null)
  9206. continue;
  9207. var resourceJid = Strophe.getResourceFromJid(jid);
  9208. if(remoteVideos[resourceJid] && remoteVideos[resourceJid].connectionIndicator)
  9209. {
  9210. remoteVideos[resourceJid].connectionIndicator.updateResolution(resolution[jid]);
  9211. }
  9212. }
  9213. };
  9214. /**
  9215. * Updates remote stats.
  9216. * @param jid the jid associated with the stats
  9217. * @param percent the connection quality percent
  9218. * @param object the stats data
  9219. */
  9220. my.updateConnectionStats = function (jid, percent, object) {
  9221. var resourceJid = Strophe.getResourceFromJid(jid);
  9222. if(remoteVideos[resourceJid])
  9223. remoteVideos[resourceJid].updateStatsIndicator(percent, object);
  9224. };
  9225. /**
  9226. * Removes the connection
  9227. * @param jid
  9228. */
  9229. my.removeConnectionIndicator = function (jid) {
  9230. remoteVideos[Strophe.getResourceFromJid(jid)].removeConnectionIndicator();
  9231. };
  9232. /**
  9233. * Hides the connection indicator
  9234. * @param jid
  9235. */
  9236. my.hideConnectionIndicator = function (jid) {
  9237. remoteVideos[Strophe.getResourceFromJid(jid)].hideConnectionIndicator();
  9238. };
  9239. /**
  9240. * Hides all the indicators
  9241. */
  9242. my.onStatsStop = function () {
  9243. for(var video in remoteVideos)
  9244. {
  9245. remoteVideos[video].hideIndicator();
  9246. }
  9247. localVideoThumbnail.hideIndicator();
  9248. };
  9249. my.participantLeft = function (jid) {
  9250. // Unlock large video
  9251. var resourceJid = Strophe.getResourceFromJid(jid);
  9252. if (focusedVideoResourceJid === resourceJid)
  9253. {
  9254. console.info("Focused video owner has left the conference");
  9255. focusedVideoResourceJid = null;
  9256. }
  9257. };
  9258. my.onVideoTypeChanged = function (jid) {
  9259. LargeVideo.onVideoTypeChanged(jid);
  9260. };
  9261. my.showMore = function (jid) {
  9262. if (jid === 'local')
  9263. {
  9264. localVideoThumbnail.connectionIndicator.showMore();
  9265. }
  9266. else
  9267. {
  9268. var remoteVideo = remoteVideos[Strophe.getResourceFromJid(jid)];
  9269. if (remoteVideo) {
  9270. remoteVideo.connectionIndicator.showMore();
  9271. } else {
  9272. console.info("Error - no remote video for jid: " + jid);
  9273. }
  9274. }
  9275. };
  9276. my.addPreziContainer = function (id) {
  9277. return RemoteVideo.createContainer(id);
  9278. };
  9279. my.setLargeVideoVisible = function (isVisible) {
  9280. LargeVideo.setLargeVideoVisible(isVisible);
  9281. if(!isVisible && focusedVideoResourceJid)
  9282. {
  9283. var smallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  9284. if(smallVideo)
  9285. smallVideo.focus(false);
  9286. smallVideo.showAvatar();
  9287. focusedVideoResourceJid = null;
  9288. }
  9289. };
  9290. /**
  9291. * Resizes the video area
  9292. * @param completeFunction a function to be called when the video space is resized
  9293. */
  9294. my.resizeVideoArea = function(isVisible, completeFunction) {
  9295. LargeVideo.resizeVideoAreaAnimated(isVisible, completeFunction);
  9296. VideoLayout.resizeThumbnails(true);
  9297. };
  9298. my.getSmallVideo = function (resourceJid) {
  9299. if(resourceJid == APP.xmpp.myResource())
  9300. {
  9301. return localVideoThumbnail;
  9302. }
  9303. else
  9304. {
  9305. if(!remoteVideos[resourceJid])
  9306. return null;
  9307. return remoteVideos[resourceJid];
  9308. }
  9309. };
  9310. my.userAvatarChanged = function(resourceJid, thumbUrl)
  9311. {
  9312. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  9313. if(smallVideo)
  9314. smallVideo.avatarChanged(thumbUrl);
  9315. else
  9316. console.warn(
  9317. "Missed avatar update - no small video yet for " + resourceJid);
  9318. LargeVideo.updateAvatar(resourceJid, thumbUrl);
  9319. };
  9320. return my;
  9321. }(VideoLayout || {}));
  9322. module.exports = VideoLayout;
  9323. },{"../../../service/RTC/MediaStreamTypes":98,"../../../service/UI/UIEvents":102,"../../RTC/RTC":7,"../../RTC/RTCBrowserType":8,"../audio_levels/AudioLevels":12,"../avatar/Avatar":16,"../prezi/Prezi":18,"../side_pannels/contactlist/ContactList":25,"./LargeVideo":35,"./LocalVideo":36,"./RemoteVideo":37}],40:[function(require,module,exports){
  9324. //var nouns = [
  9325. //];
  9326. var pluralNouns = [
  9327. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  9328. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  9329. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  9330. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  9331. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  9332. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  9333. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  9334. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  9335. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  9336. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  9337. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  9338. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  9339. ];
  9340. //var places = [
  9341. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  9342. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  9343. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  9344. // "Bridge"
  9345. //];
  9346. var verbs = [
  9347. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  9348. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  9349. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  9350. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  9351. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  9352. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  9353. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  9354. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  9355. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  9356. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  9357. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  9358. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  9359. ];
  9360. var adverbs = [
  9361. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  9362. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  9363. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  9364. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  9365. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  9366. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  9367. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  9368. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  9369. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  9370. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  9371. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  9372. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  9373. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  9374. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  9375. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly", "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  9376. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  9377. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  9378. ];
  9379. var adjectives = [
  9380. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  9381. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  9382. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  9383. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  9384. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  9385. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  9386. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  9387. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  9388. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  9389. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  9390. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  9391. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  9392. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  9393. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  9394. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  9395. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  9396. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  9397. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  9398. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  9399. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  9400. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  9401. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  9402. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  9403. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  9404. "Zealous"
  9405. ];
  9406. //var pronouns = [
  9407. //];
  9408. //var conjunctions = [
  9409. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  9410. //];
  9411. /*
  9412. * Maps a string (category name) to the array of words from that category.
  9413. */
  9414. var CATEGORIES =
  9415. {
  9416. //"_NOUN_": nouns,
  9417. "_PLURALNOUN_": pluralNouns,
  9418. //"_PLACE_": places,
  9419. "_VERB_": verbs,
  9420. "_ADVERB_": adverbs,
  9421. "_ADJECTIVE_": adjectives
  9422. //"_PRONOUN_": pronouns,
  9423. //"_CONJUNCTION_": conjunctions,
  9424. };
  9425. var PATTERNS = [
  9426. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  9427. // BeautifulFungiOrSpaghetti
  9428. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  9429. // AmazinglyScaryToy
  9430. //"_ADVERB__ADJECTIVE__NOUN_",
  9431. // NeitherTrashNorRifle
  9432. //"Neither_NOUN_Nor_NOUN_",
  9433. //"Either_NOUN_Or_NOUN_",
  9434. // EitherCopulateOrInvestigate
  9435. //"Either_VERB_Or_VERB_",
  9436. //"Neither_VERB_Nor_VERB_",
  9437. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  9438. //"The_ADVERB__ADJECTIVE__NOUN_",
  9439. //"The_ADVERB__ADJECTIVE__NOUN_s",
  9440. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  9441. // WolvesComputeBadly
  9442. //"_PLURALNOUN__VERB__ADVERB_",
  9443. // UniteFacilitateAndMerge
  9444. //"_VERB__VERB_And_VERB_",
  9445. //NastyWitchesAtThePub
  9446. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  9447. ];
  9448. /*
  9449. * Returns a random element from the array 'arr'
  9450. */
  9451. function randomElement(arr)
  9452. {
  9453. return arr[Math.floor(Math.random() * arr.length)];
  9454. }
  9455. /*
  9456. * Returns true if the string 's' contains one of the
  9457. * template strings.
  9458. */
  9459. function hasTemplate(s)
  9460. {
  9461. for (var template in CATEGORIES){
  9462. if (s.indexOf(template) >= 0){
  9463. return true;
  9464. }
  9465. }
  9466. }
  9467. /**
  9468. * Generates new room name.
  9469. */
  9470. var RoomNameGenerator = {
  9471. generateRoomWithoutSeparator: function()
  9472. {
  9473. // Note that if more than one pattern is available, the choice of 'name' won't be random (names from patterns
  9474. // with fewer options will have higher probability of being chosen that names from patterns with more options).
  9475. var name = randomElement(PATTERNS);
  9476. var word;
  9477. while (hasTemplate(name)){
  9478. for (var template in CATEGORIES){
  9479. word = randomElement(CATEGORIES[template]);
  9480. name = name.replace(template, word);
  9481. }
  9482. }
  9483. return name;
  9484. }
  9485. }
  9486. module.exports = RoomNameGenerator;
  9487. },{}],41:[function(require,module,exports){
  9488. var animateTimeout, updateTimeout;
  9489. var RoomNameGenerator = require("./RoomnameGenerator");
  9490. function enter_room()
  9491. {
  9492. var val = $("#enter_room_field").val();
  9493. if(!val) {
  9494. val = $("#enter_room_field").attr("room_name");
  9495. }
  9496. if (val) {
  9497. window.location.pathname = "/" + val;
  9498. }
  9499. }
  9500. function animate(word) {
  9501. var currentVal = $("#enter_room_field").attr("placeholder");
  9502. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  9503. animateTimeout = setTimeout(function() {
  9504. animate(word.substring(1, word.length))
  9505. }, 70);
  9506. }
  9507. function update_roomname()
  9508. {
  9509. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  9510. $("#enter_room_field").attr("room_name", word);
  9511. $("#enter_room_field").attr("placeholder", "");
  9512. clearTimeout(animateTimeout);
  9513. animate(word);
  9514. updateTimeout = setTimeout(update_roomname, 10000);
  9515. }
  9516. function setupWelcomePage()
  9517. {
  9518. $("#videoconference_page").hide();
  9519. $("#domain_name").text(
  9520. window.location.protocol + "//" + window.location.host + "/");
  9521. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  9522. var leftWatermarkDiv
  9523. = $("#welcome_page_header div[class='watermark leftwatermark']");
  9524. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  9525. {
  9526. leftWatermarkDiv.css({display: 'block'});
  9527. leftWatermarkDiv.parent().get(0).href
  9528. = interfaceConfig.JITSI_WATERMARK_LINK;
  9529. }
  9530. }
  9531. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  9532. var rightWatermarkDiv
  9533. = $("#welcome_page_header div[class='watermark rightwatermark']");
  9534. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  9535. rightWatermarkDiv.css({display: 'block'});
  9536. rightWatermarkDiv.parent().get(0).href
  9537. = interfaceConfig.BRAND_WATERMARK_LINK;
  9538. rightWatermarkDiv.get(0).style.backgroundImage
  9539. = "url(images/rightwatermark.png)";
  9540. }
  9541. }
  9542. if (interfaceConfig.SHOW_POWERED_BY) {
  9543. $("#welcome_page_header>a[class='poweredby']")
  9544. .css({display: 'block'});
  9545. }
  9546. $("#enter_room_button").click(function()
  9547. {
  9548. enter_room();
  9549. });
  9550. $("#enter_room_field").keydown(function (event) {
  9551. if (event.keyCode === 13 /* enter */) {
  9552. enter_room();
  9553. }
  9554. });
  9555. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  9556. var updateTimeout;
  9557. var animateTimeout;
  9558. $("#reload_roomname").click(function () {
  9559. clearTimeout(updateTimeout);
  9560. clearTimeout(animateTimeout);
  9561. update_roomname();
  9562. });
  9563. $("#reload_roomname").show();
  9564. update_roomname();
  9565. }
  9566. $("#disable_welcome").click(function () {
  9567. window.localStorage.welcomePageDisabled
  9568. = $("#disable_welcome").is(":checked");
  9569. });
  9570. }
  9571. module.exports = setupWelcomePage;
  9572. },{"./RoomnameGenerator":40}],42:[function(require,module,exports){
  9573. var params = {};
  9574. function getConfigParamsFromUrl() {
  9575. if(!location.hash)
  9576. return {};
  9577. var hash = location.hash.substr(1);
  9578. var result = {};
  9579. hash.split("&").forEach(function(part) {
  9580. var item = part.split("=");
  9581. result[item[0]] = JSON.parse(
  9582. decodeURIComponent(item[1]).replace(/\\&/, "&"));
  9583. });
  9584. return result;
  9585. }
  9586. params = getConfigParamsFromUrl();
  9587. var URLProcessor = {
  9588. setConfigParametersFromUrl: function () {
  9589. for(var k in params)
  9590. {
  9591. if(typeof k !== "string" || k.indexOf("config.") === -1)
  9592. continue;
  9593. var v = params[k];
  9594. var confKey = k.substr(7);
  9595. if(config[confKey] && typeof config[confKey] !== typeof v)
  9596. {
  9597. console.warn("The type of " + k +
  9598. " is wrong. That parameter won't be updated in config.js.");
  9599. continue;
  9600. }
  9601. config[confKey] = v;
  9602. }
  9603. }
  9604. };
  9605. module.exports = URLProcessor;
  9606. },{}],43:[function(require,module,exports){
  9607. var EventEmitter = require("events");
  9608. var eventEmitter = new EventEmitter();
  9609. var CQEvents = require("../../service/connectionquality/CQEvents");
  9610. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9611. /**
  9612. * local stats
  9613. * @type {{}}
  9614. */
  9615. var stats = {};
  9616. /**
  9617. * remote stats
  9618. * @type {{}}
  9619. */
  9620. var remoteStats = {};
  9621. /**
  9622. * Interval for sending statistics to other participants
  9623. * @type {null}
  9624. */
  9625. var sendIntervalId = null;
  9626. /**
  9627. * Start statistics sending.
  9628. */
  9629. function startSendingStats() {
  9630. sendStats();
  9631. sendIntervalId = setInterval(sendStats, 10000);
  9632. }
  9633. /**
  9634. * Sends statistics to other participants
  9635. */
  9636. function sendStats() {
  9637. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  9638. }
  9639. /**
  9640. * Converts statistics to format for sending through XMPP
  9641. * @param stats the statistics
  9642. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  9643. */
  9644. function convertToMUCStats(stats) {
  9645. return {
  9646. "bitrate_download": stats.bitrate.download,
  9647. "bitrate_upload": stats.bitrate.upload,
  9648. "packetLoss_total": stats.packetLoss.total,
  9649. "packetLoss_download": stats.packetLoss.download,
  9650. "packetLoss_upload": stats.packetLoss.upload
  9651. };
  9652. }
  9653. /**
  9654. * Converts statitistics to format used by VideoLayout
  9655. * @param stats
  9656. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  9657. */
  9658. function parseMUCStats(stats) {
  9659. return {
  9660. bitrate: {
  9661. download: stats.bitrate_download,
  9662. upload: stats.bitrate_upload
  9663. },
  9664. packetLoss: {
  9665. total: stats.packetLoss_total,
  9666. download: stats.packetLoss_download,
  9667. upload: stats.packetLoss_upload
  9668. }
  9669. };
  9670. }
  9671. var ConnectionQuality = {
  9672. init: function () {
  9673. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  9674. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  9675. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  9676. },
  9677. /**
  9678. * Updates the local statistics
  9679. * @param data new statistics
  9680. */
  9681. updateLocalStats: function (data) {
  9682. stats = data;
  9683. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  9684. if (sendIntervalId == null) {
  9685. startSendingStats();
  9686. }
  9687. },
  9688. /**
  9689. * Updates remote statistics
  9690. * @param jid the jid associated with the statistics
  9691. * @param data the statistics
  9692. */
  9693. updateRemoteStats: function (jid, data) {
  9694. if (data == null || data.packetLoss_total == null) {
  9695. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  9696. return;
  9697. }
  9698. remoteStats[jid] = parseMUCStats(data);
  9699. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  9700. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  9701. },
  9702. /**
  9703. * Stops statistics sending.
  9704. */
  9705. stopSendingStats: function () {
  9706. clearInterval(sendIntervalId);
  9707. sendIntervalId = null;
  9708. //notify UI about stopping statistics gathering
  9709. eventEmitter.emit(CQEvents.STOP);
  9710. },
  9711. /**
  9712. * Returns the local statistics.
  9713. */
  9714. getStats: function () {
  9715. return stats;
  9716. },
  9717. addListener: function (type, listener) {
  9718. eventEmitter.on(type, listener);
  9719. }
  9720. };
  9721. module.exports = ConnectionQuality;
  9722. },{"../../service/connectionquality/CQEvents":104,"../../service/xmpp/XMPPEvents":108,"events":109}],44:[function(require,module,exports){
  9723. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  9724. getUserMediaWithConstraints */
  9725. /**
  9726. * Indicates that desktop stream is currently in use(for toggle purpose).
  9727. * @type {boolean}
  9728. */
  9729. var isUsingScreenStream = false;
  9730. /**
  9731. * Indicates that switch stream operation is in progress and prevent from
  9732. * triggering new events.
  9733. * @type {boolean}
  9734. */
  9735. var switchInProgress = false;
  9736. /**
  9737. * Method used to get screen sharing stream.
  9738. *
  9739. * @type {function (stream_callback, failure_callback}
  9740. */
  9741. var obtainDesktopStream = null;
  9742. /**
  9743. * Indicates whether desktop sharing extension is installed.
  9744. * @type {boolean}
  9745. */
  9746. var extInstalled = false;
  9747. /**
  9748. * Indicates whether update of desktop sharing extension is required.
  9749. * @type {boolean}
  9750. */
  9751. var extUpdateRequired = false;
  9752. var AdapterJS = require("../RTC/adapter.screenshare");
  9753. var EventEmitter = require("events");
  9754. var eventEmitter = new EventEmitter();
  9755. var DesktopSharingEventTypes
  9756. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  9757. var RTCBrowserType = require("../RTC/RTCBrowserType");
  9758. var RTCEvents = require("../../service/RTC/RTCEvents");
  9759. /**
  9760. * Method obtains desktop stream from WebRTC 'screen' source.
  9761. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  9762. */
  9763. function obtainWebRTCScreen(streamCallback, failCallback) {
  9764. APP.RTC.getUserMediaWithConstraints(
  9765. ['screen'],
  9766. streamCallback,
  9767. failCallback
  9768. );
  9769. }
  9770. /**
  9771. * Constructs inline install URL for Chrome desktop streaming extension.
  9772. * The 'chromeExtensionId' must be defined in config.js.
  9773. * @returns {string}
  9774. */
  9775. function getWebStoreInstallUrl()
  9776. {
  9777. return "https://chrome.google.com/webstore/detail/" +
  9778. config.chromeExtensionId;
  9779. }
  9780. /**
  9781. * Checks whether extension update is required.
  9782. * @param minVersion minimal required version
  9783. * @param extVersion current extension version
  9784. * @returns {boolean}
  9785. */
  9786. function isUpdateRequired(minVersion, extVersion)
  9787. {
  9788. try
  9789. {
  9790. var s1 = minVersion.split('.');
  9791. var s2 = extVersion.split('.');
  9792. var len = Math.max(s1.length, s2.length);
  9793. for (var i = 0; i < len; i++)
  9794. {
  9795. var n1 = 0,
  9796. n2 = 0;
  9797. if (i < s1.length)
  9798. n1 = parseInt(s1[i]);
  9799. if (i < s2.length)
  9800. n2 = parseInt(s2[i]);
  9801. if (isNaN(n1) || isNaN(n2))
  9802. {
  9803. return true;
  9804. }
  9805. else if (n1 !== n2)
  9806. {
  9807. return n1 > n2;
  9808. }
  9809. }
  9810. // will happen if boths version has identical numbers in
  9811. // their components (even if one of them is longer, has more components)
  9812. return false;
  9813. }
  9814. catch (e)
  9815. {
  9816. console.error("Failed to parse extension version", e);
  9817. APP.UI.messageHandler.showError("dialog.error",
  9818. "dialog.detectext");
  9819. return true;
  9820. }
  9821. }
  9822. function checkChromeExtInstalled(callback) {
  9823. if (!chrome.runtime) {
  9824. // No API, so no extension for sure
  9825. callback(false, false);
  9826. return;
  9827. }
  9828. chrome.runtime.sendMessage(
  9829. config.chromeExtensionId,
  9830. { getVersion: true },
  9831. function (response) {
  9832. if (!response || !response.version) {
  9833. // Communication failure - assume that no endpoint exists
  9834. console.warn(
  9835. "Extension not installed?: ", chrome.runtime.lastError);
  9836. callback(false, false);
  9837. return;
  9838. }
  9839. // Check installed extension version
  9840. var extVersion = response.version;
  9841. console.log('Extension version is: ' + extVersion);
  9842. var updateRequired
  9843. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  9844. callback(!updateRequired, updateRequired);
  9845. }
  9846. );
  9847. }
  9848. function doGetStreamFromExtension(streamCallback, failCallback) {
  9849. // Sends 'getStream' msg to the extension.
  9850. // Extension id must be defined in the config.
  9851. chrome.runtime.sendMessage(
  9852. config.chromeExtensionId,
  9853. { getStream: true, sources: config.desktopSharingSources },
  9854. function (response) {
  9855. if (!response) {
  9856. failCallback(chrome.runtime.lastError);
  9857. return;
  9858. }
  9859. console.log("Response from extension: " + response);
  9860. if (response.streamId) {
  9861. APP.RTC.getUserMediaWithConstraints(
  9862. ['desktop'],
  9863. function (stream) {
  9864. streamCallback(stream);
  9865. },
  9866. failCallback,
  9867. null, null, null,
  9868. response.streamId);
  9869. } else {
  9870. failCallback("Extension failed to get the stream");
  9871. }
  9872. }
  9873. );
  9874. }
  9875. /**
  9876. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  9877. * stream for returned stream token.
  9878. */
  9879. function obtainScreenFromExtension(streamCallback, failCallback) {
  9880. if (extInstalled) {
  9881. doGetStreamFromExtension(streamCallback, failCallback);
  9882. } else {
  9883. if (extUpdateRequired) {
  9884. alert(
  9885. 'Jitsi Desktop Streamer requires update. ' +
  9886. 'Changes will take effect after next Chrome restart.');
  9887. }
  9888. chrome.webstore.install(
  9889. getWebStoreInstallUrl(),
  9890. function (arg) {
  9891. console.log("Extension installed successfully", arg);
  9892. extInstalled = true;
  9893. // We need to give a moment for the endpoint to become available
  9894. window.setTimeout(function () {
  9895. doGetStreamFromExtension(streamCallback, failCallback);
  9896. }, 500);
  9897. },
  9898. function (arg) {
  9899. console.log("Failed to install the extension", arg);
  9900. failCallback(arg);
  9901. APP.UI.messageHandler.showError("dialog.error",
  9902. "dialog.failtoinstall");
  9903. }
  9904. );
  9905. }
  9906. }
  9907. /**
  9908. * Call this method to toggle desktop sharing feature.
  9909. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  9910. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  9911. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  9912. * enabled), pass any other string or nothing in order to disable this
  9913. * feature completely.
  9914. */
  9915. function setDesktopSharing(method) {
  9916. obtainDesktopStream = null;
  9917. // When TemasysWebRTC plugin is used we always use getUserMedia, so we don't
  9918. // care about 'method' parameter
  9919. if (RTCBrowserType.isTemasysPluginUsed()) {
  9920. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  9921. console.info("Screensharing not supported by this plugin version");
  9922. } else if (!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  9923. console.info(
  9924. "Screensharing not available with Temasys plugin on this site");
  9925. } else {
  9926. obtainDesktopStream = obtainWebRTCScreen;
  9927. console.info("Using Temasys plugin for desktop sharing");
  9928. }
  9929. } else if (RTCBrowserType.isChrome()) {
  9930. if (method == "ext") {
  9931. if (RTCBrowserType.getChromeVersion() >= 34) {
  9932. obtainDesktopStream = obtainScreenFromExtension;
  9933. console.info("Using Chrome extension for desktop sharing");
  9934. initChromeExtension();
  9935. } else {
  9936. console.info("Chrome extension not supported until ver 34");
  9937. }
  9938. } else if (method == "webrtc") {
  9939. obtainDesktopStream = obtainWebRTCScreen;
  9940. console.info("Using Chrome WebRTC for desktop sharing");
  9941. }
  9942. }
  9943. if (!obtainDesktopStream) {
  9944. console.info("Desktop sharing disabled");
  9945. }
  9946. }
  9947. /**
  9948. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  9949. * config.js to support inline installs. Host site must be selected as main
  9950. * website of published extension.
  9951. */
  9952. function initInlineInstalls()
  9953. {
  9954. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  9955. }
  9956. function initChromeExtension() {
  9957. // Initialize Chrome extension inline installs
  9958. initInlineInstalls();
  9959. // Check if extension is installed
  9960. checkChromeExtInstalled(function (installed, updateRequired) {
  9961. extInstalled = installed;
  9962. extUpdateRequired = updateRequired;
  9963. console.info(
  9964. "Chrome extension installed: " + extInstalled +
  9965. " updateRequired: " + extUpdateRequired);
  9966. });
  9967. }
  9968. function getVideoStreamFailed(error) {
  9969. console.error("Failed to obtain the stream to switch to", error);
  9970. switchInProgress = false;
  9971. isUsingScreenStream = false;
  9972. newStreamCreated(null);
  9973. }
  9974. function getDesktopStreamFailed(error) {
  9975. console.error("Failed to obtain the stream to switch to", error);
  9976. switchInProgress = false;
  9977. }
  9978. function streamSwitchDone() {
  9979. switchInProgress = false;
  9980. eventEmitter.emit(
  9981. DesktopSharingEventTypes.SWITCHING_DONE,
  9982. isUsingScreenStream);
  9983. }
  9984. function newStreamCreated(stream)
  9985. {
  9986. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  9987. stream, isUsingScreenStream, streamSwitchDone);
  9988. }
  9989. function onEndedHandler(stream) {
  9990. if (!switchInProgress && isUsingScreenStream) {
  9991. APP.desktopsharing.toggleScreenSharing();
  9992. }
  9993. //FIXME: to be verified
  9994. if (stream.removeEventListener) {
  9995. stream.removeEventListener('ended', onEndedHandler);
  9996. } else {
  9997. stream.detachEvent('ended', onEndedHandler);
  9998. }
  9999. }
  10000. // Called when RTC finishes initialization
  10001. function onWebRtcReady() {
  10002. setDesktopSharing(config.desktopSharing);
  10003. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  10004. }
  10005. module.exports = {
  10006. isUsingScreenStream: function () {
  10007. return isUsingScreenStream;
  10008. },
  10009. /**
  10010. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  10011. * and enabled.
  10012. */
  10013. isDesktopSharingEnabled: function () { return !!obtainDesktopStream; },
  10014. init: function () {
  10015. APP.RTC.addListener(RTCEvents.RTC_READY, onWebRtcReady);
  10016. },
  10017. addListener: function (listener, type)
  10018. {
  10019. eventEmitter.on(type, listener);
  10020. },
  10021. removeListener: function (listener, type) {
  10022. eventEmitter.removeListener(type, listener);
  10023. },
  10024. /*
  10025. * Toggles screen sharing.
  10026. */
  10027. toggleScreenSharing: function () {
  10028. if (switchInProgress || !obtainDesktopStream) {
  10029. console.warn("Switch in progress or no method defined");
  10030. return;
  10031. }
  10032. switchInProgress = true;
  10033. if (!isUsingScreenStream)
  10034. {
  10035. // Switch to desktop stream
  10036. obtainDesktopStream(
  10037. function (stream) {
  10038. // We now use screen stream
  10039. isUsingScreenStream = true;
  10040. // Hook 'ended' event to restore camera
  10041. // when screen stream stops
  10042. //FIXME: to be verified
  10043. if (stream.addEventListener) {
  10044. stream.addEventListener('ended', function () {
  10045. onEndedHandler(stream);
  10046. });
  10047. } else {
  10048. stream.attachEvent('ended', function () {
  10049. onEndedHandler(stream);
  10050. });
  10051. }
  10052. newStreamCreated(stream);
  10053. },
  10054. getDesktopStreamFailed);
  10055. } else {
  10056. // Disable screen stream
  10057. APP.RTC.getUserMediaWithConstraints(
  10058. ['video'],
  10059. function (stream) {
  10060. // We are now using camera stream
  10061. isUsingScreenStream = false;
  10062. newStreamCreated(stream);
  10063. },
  10064. getVideoStreamFailed, config.resolution || '360'
  10065. );
  10066. }
  10067. }
  10068. };
  10069. },{"../../service/RTC/RTCEvents":99,"../../service/desktopsharing/DesktopSharingEventTypes":105,"../RTC/RTCBrowserType":8,"../RTC/adapter.screenshare":10,"events":109}],45:[function(require,module,exports){
  10070. //maps keycode to character, id of popover for given function and function
  10071. var shortcuts = {};
  10072. function initShortcutHandlers() {
  10073. shortcuts = {
  10074. 67: {
  10075. character: "C",
  10076. id: "toggleChatPopover",
  10077. function: APP.UI.toggleChat
  10078. },
  10079. 70: {
  10080. character: "F",
  10081. id: "filmstripPopover",
  10082. function: APP.UI.toggleFilmStrip
  10083. },
  10084. 77: {
  10085. character: "M",
  10086. id: "mutePopover",
  10087. function: APP.UI.toggleAudio
  10088. },
  10089. 84: {
  10090. character: "T",
  10091. function: function() {
  10092. if(!APP.RTC.localAudio.isMuted()) {
  10093. APP.UI.toggleAudio();
  10094. }
  10095. }
  10096. },
  10097. 86: {
  10098. character: "V",
  10099. id: "toggleVideoPopover",
  10100. function: APP.UI.toggleVideo
  10101. }
  10102. };
  10103. }
  10104. var KeyboardShortcut = {
  10105. init: function () {
  10106. initShortcutHandlers();
  10107. window.onkeyup = function(e) {
  10108. var keycode = e.which;
  10109. if(!($(":focus").is("input[type=text]") ||
  10110. $(":focus").is("input[type=password]") ||
  10111. $(":focus").is("textarea"))) {
  10112. if (typeof shortcuts[keycode] === "object") {
  10113. shortcuts[keycode].function();
  10114. }
  10115. else if (keycode >= "0".charCodeAt(0) &&
  10116. keycode <= "9".charCodeAt(0)) {
  10117. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  10118. }
  10119. //esc while the smileys are visible hides them
  10120. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  10121. APP.UI.toggleSmileys();
  10122. }
  10123. };
  10124. window.onkeydown = function(e) {
  10125. if(!($(":focus").is("input[type=text]") ||
  10126. $(":focus").is("input[type=password]") ||
  10127. $(":focus").is("textarea"))) {
  10128. if(e.which === "T".charCodeAt(0)) {
  10129. if(APP.RTC.localAudio.isMuted()) {
  10130. APP.UI.toggleAudio();
  10131. }
  10132. }
  10133. }
  10134. };
  10135. var self = this;
  10136. $('body').popover({ selector: '[data-toggle=popover]',
  10137. trigger: 'click hover',
  10138. content: function() {
  10139. return this.getAttribute("content") +
  10140. self.getShortcut(this.getAttribute("shortcut"));
  10141. }
  10142. });
  10143. },
  10144. /**
  10145. *
  10146. * @param id indicates the popover associated with the shortcut
  10147. * @returns {string} the keyboard shortcut used for the id given
  10148. */
  10149. getShortcut: function (id) {
  10150. for (var keycode in shortcuts) {
  10151. if (shortcuts.hasOwnProperty(keycode)) {
  10152. if (shortcuts[keycode].id === id) {
  10153. return " (" + shortcuts[keycode].character + ")";
  10154. }
  10155. }
  10156. }
  10157. return "";
  10158. }
  10159. };
  10160. module.exports = KeyboardShortcut;
  10161. },{}],46:[function(require,module,exports){
  10162. /* global APP */
  10163. /**
  10164. * This module is meant to (eventually) contain and manage all information
  10165. * about members/participants of the conference, so that other modules don't
  10166. * have to do it on their own, and so that other modules can access members'
  10167. * information from a single place.
  10168. *
  10169. * Currently this module only manages information about the support of jingle
  10170. * DTMF of the members. Other fields, as well as accessor methods are meant to
  10171. * be added as needed.
  10172. */
  10173. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10174. var Events = require("../../service/members/Events");
  10175. var EventEmitter = require("events");
  10176. var eventEmitter = new EventEmitter();
  10177. /**
  10178. * The actual container.
  10179. */
  10180. var members = {};
  10181. /**
  10182. * There is at least one member that supports DTMF (i.e. is jigasi).
  10183. */
  10184. var atLeastOneDtmf = false;
  10185. function registerListeners() {
  10186. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  10187. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  10188. }
  10189. /**
  10190. * Handles a new member joining the MUC.
  10191. */
  10192. function onMucMemberJoined(jid, id, displayName) {
  10193. var member = {
  10194. displayName: displayName
  10195. };
  10196. APP.xmpp.getConnection().disco.info(
  10197. jid, "" /* node */, function(iq) { onDiscoInfoReceived(jid, iq); });
  10198. members[jid] = member;
  10199. }
  10200. /**
  10201. * Handles a member leaving the MUC.
  10202. */
  10203. function onMucMemberLeft(jid) {
  10204. delete members[jid];
  10205. updateAtLeastOneDtmf();
  10206. }
  10207. /**
  10208. * Handles the reception of a disco#info packet from a particular JID.
  10209. * @param jid the JID sending the packet.
  10210. * @param iq the packet.
  10211. */
  10212. function onDiscoInfoReceived(jid, iq) {
  10213. if (!members[jid])
  10214. return;
  10215. var supportsDtmf
  10216. = $(iq).find('>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  10217. updateDtmf(jid, supportsDtmf);
  10218. }
  10219. /**
  10220. * Updates the 'supportsDtmf' field for a member.
  10221. * @param jid the jid of the member.
  10222. * @param newValue the new value for the 'supportsDtmf' field.
  10223. */
  10224. function updateDtmf(jid, newValue) {
  10225. var oldValue = members[jid].supportsDtmf;
  10226. members[jid].supportsDtmf = newValue;
  10227. if (newValue != oldValue) {
  10228. updateAtLeastOneDtmf();
  10229. }
  10230. }
  10231. /**
  10232. * Checks each member's 'supportsDtmf' field and updates
  10233. * 'atLastOneSupportsDtmf'.
  10234. */
  10235. function updateAtLeastOneDtmf(){
  10236. var newAtLeastOneDtmf = false;
  10237. for (var key in members) {
  10238. if (typeof members[key].supportsDtmf !== 'undefined'
  10239. && members[key].supportsDtmf) {
  10240. newAtLeastOneDtmf= true;
  10241. break;
  10242. }
  10243. }
  10244. if (atLeastOneDtmf != newAtLeastOneDtmf) {
  10245. atLeastOneDtmf = newAtLeastOneDtmf;
  10246. eventEmitter.emit(Events.DTMF_SUPPORT_CHANGED, atLeastOneDtmf);
  10247. }
  10248. }
  10249. /**
  10250. * Exported interface.
  10251. */
  10252. var Members = {
  10253. start: function(){
  10254. registerListeners();
  10255. },
  10256. addListener: function(type, listener)
  10257. {
  10258. eventEmitter.on(type, listener);
  10259. },
  10260. removeListener: function (type, listener) {
  10261. eventEmitter.removeListener(type, listener);
  10262. },
  10263. size: function () {
  10264. return Object.keys(members).length;
  10265. },
  10266. getMembers: function () {
  10267. return members;
  10268. }
  10269. };
  10270. module.exports = Members;
  10271. },{"../../service/members/Events":106,"../../service/xmpp/XMPPEvents":108,"events":109}],47:[function(require,module,exports){
  10272. var email = '';
  10273. var displayName = '';
  10274. var userId;
  10275. var language = null;
  10276. function supportsLocalStorage() {
  10277. try {
  10278. return 'localStorage' in window && window.localStorage !== null;
  10279. } catch (e) {
  10280. console.log("localstorage is not supported");
  10281. return false;
  10282. }
  10283. }
  10284. function generateUniqueId() {
  10285. function _p8() {
  10286. return (Math.random().toString(16) + "000000000").substr(2, 8);
  10287. }
  10288. return _p8() + _p8() + _p8() + _p8();
  10289. }
  10290. if (supportsLocalStorage()) {
  10291. if (!window.localStorage.jitsiMeetId) {
  10292. window.localStorage.jitsiMeetId = generateUniqueId();
  10293. console.log("generated id", window.localStorage.jitsiMeetId);
  10294. }
  10295. userId = window.localStorage.jitsiMeetId || '';
  10296. email = window.localStorage.email || '';
  10297. displayName = window.localStorage.displayname || '';
  10298. language = window.localStorage.language;
  10299. } else {
  10300. console.log("local storage is not supported");
  10301. userId = generateUniqueId();
  10302. }
  10303. var Settings =
  10304. {
  10305. setDisplayName: function (newDisplayName) {
  10306. displayName = newDisplayName;
  10307. window.localStorage.displayname = displayName;
  10308. return displayName;
  10309. },
  10310. setEmail: function (newEmail)
  10311. {
  10312. email = newEmail;
  10313. window.localStorage.email = newEmail;
  10314. return email;
  10315. },
  10316. getSettings: function () {
  10317. return {
  10318. email: email,
  10319. displayName: displayName,
  10320. uid: userId,
  10321. language: language
  10322. };
  10323. },
  10324. setLanguage: function (lang) {
  10325. language = lang;
  10326. window.localStorage.language = lang;
  10327. }
  10328. };
  10329. module.exports = Settings;
  10330. },{}],48:[function(require,module,exports){
  10331. var callStats = null;
  10332. function initCallback (err, msg) {
  10333. console.log("Initializing Status: err="+err+" msg="+msg);
  10334. }
  10335. var CallStats = {
  10336. init: function (jingleSession) {
  10337. if(!config.callStatsID || !config.callStatsSecret || callStats !== null)
  10338. return;
  10339. callStats = new callstats($,io,jsSHA);
  10340. this.session = jingleSession;
  10341. this.peerconnection = jingleSession.peerconnection.peerconnection;
  10342. this.userID = APP.xmpp.myResource();
  10343. var location = window.location;
  10344. this.confID = location.protocol + "//" +
  10345. location.hostname + location.pathname;
  10346. //userID is generated or given by the origin server
  10347. callStats.initialize(config.callStatsID,
  10348. config.callStatsSecret,
  10349. this.userID,
  10350. initCallback);
  10351. var usage = callStats.fabricUsage.unbundled;
  10352. if(config.useBundle)
  10353. usage = callStats.fabricUsage.multiplex;
  10354. callStats.addNewFabric(this.peerconnection,
  10355. Strophe.getResourceFromJid(jingleSession.peerjid),
  10356. usage,
  10357. this.confID,
  10358. this.pcCallback.bind(this));
  10359. },
  10360. pcCallback: function (err, msg) {
  10361. if(!callStats)
  10362. return;
  10363. console.log("Monitoring status: "+ err + " msg: " + msg);
  10364. callStats.sendFabricEvent(this.peerconnection,
  10365. callStats.fabricEvent.fabricSetup, this.confID);
  10366. },
  10367. sendMuteEvent: function (mute, type) {
  10368. if(!callStats)
  10369. return;
  10370. var event = null;
  10371. if(type === "video")
  10372. {
  10373. event = (mute? callStats.fabricEvent.videoPause :
  10374. callStats.fabricEvent.videoResume);
  10375. }
  10376. else
  10377. {
  10378. event = (mute? callStats.fabricEvent.audioMute :
  10379. callStats.fabricEvent.audioUnmute);
  10380. }
  10381. callStats.sendFabricEvent(this.peerconnection, event, this.confID);
  10382. },
  10383. sendTerminateEvent: function () {
  10384. if(!callStats)
  10385. return;
  10386. callStats.sendFabricEvent(this.peerconnection,
  10387. callStats.fabricEvent.fabricTerminated, this.confID);
  10388. },
  10389. sendSetupFailedEvent: function () {
  10390. if(!callStats)
  10391. return;
  10392. callStats.sendFabricEvent(this.peerconnection,
  10393. callStats.fabricEvent.fabricSetupFailed, this.confID);
  10394. }
  10395. };
  10396. module.exports = CallStats;
  10397. },{}],49:[function(require,module,exports){
  10398. /**
  10399. * Provides statistics for the local stream.
  10400. */
  10401. var RTCBrowserType = require('../RTC/RTCBrowserType');
  10402. /**
  10403. * Size of the webaudio analizer buffer.
  10404. * @type {number}
  10405. */
  10406. var WEBAUDIO_ANALIZER_FFT_SIZE = 2048;
  10407. /**
  10408. * Value of the webaudio analizer smoothing time parameter.
  10409. * @type {number}
  10410. */
  10411. var WEBAUDIO_ANALIZER_SMOOTING_TIME = 0.8;
  10412. /**
  10413. * Converts time domain data array to audio level.
  10414. * @param array the time domain data array.
  10415. * @returns {number} the audio level
  10416. */
  10417. function timeDomainDataToAudioLevel(samples) {
  10418. var maxVolume = 0;
  10419. var length = samples.length;
  10420. for (var i = 0; i < length; i++) {
  10421. if (maxVolume < samples[i])
  10422. maxVolume = samples[i];
  10423. }
  10424. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  10425. };
  10426. /**
  10427. * Animates audio level change
  10428. * @param newLevel the new audio level
  10429. * @param lastLevel the last audio level
  10430. * @returns {Number} the audio level to be set
  10431. */
  10432. function animateLevel(newLevel, lastLevel)
  10433. {
  10434. var value = 0;
  10435. var diff = lastLevel - newLevel;
  10436. if(diff > 0.2)
  10437. {
  10438. value = lastLevel - 0.2;
  10439. }
  10440. else if(diff < -0.4)
  10441. {
  10442. value = lastLevel + 0.4;
  10443. }
  10444. else
  10445. {
  10446. value = newLevel;
  10447. }
  10448. return parseFloat(value.toFixed(3));
  10449. }
  10450. /**
  10451. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  10452. *
  10453. * @param stream the local stream
  10454. * @param interval stats refresh interval given in ms.
  10455. * @param {function(LocalStatsCollector)} updateCallback the callback called on stats
  10456. * update.
  10457. * @constructor
  10458. */
  10459. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  10460. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  10461. this.stream = stream;
  10462. this.intervalId = null;
  10463. this.intervalMilis = interval;
  10464. this.eventEmitter = eventEmitter;
  10465. this.audioLevel = 0;
  10466. this.statisticsService = statisticsService;
  10467. }
  10468. /**
  10469. * Starts the collecting the statistics.
  10470. */
  10471. LocalStatsCollector.prototype.start = function () {
  10472. if (config.disableAudioLevels || !window.AudioContext
  10473. || RTCBrowserType.isTemasysPluginUsed())
  10474. return;
  10475. var context = new AudioContext();
  10476. var analyser = context.createAnalyser();
  10477. analyser.smoothingTimeConstant = WEBAUDIO_ANALIZER_SMOOTING_TIME;
  10478. analyser.fftSize = WEBAUDIO_ANALIZER_FFT_SIZE;
  10479. var source = context.createMediaStreamSource(this.stream);
  10480. source.connect(analyser);
  10481. var self = this;
  10482. this.intervalId = setInterval(
  10483. function () {
  10484. var array = new Uint8Array(analyser.frequencyBinCount);
  10485. analyser.getByteTimeDomainData(array);
  10486. var audioLevel = timeDomainDataToAudioLevel(array);
  10487. if(audioLevel != self.audioLevel) {
  10488. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  10489. self.eventEmitter.emit(
  10490. "statistics.audioLevel",
  10491. self.statisticsService.LOCAL_JID,
  10492. self.audioLevel);
  10493. }
  10494. },
  10495. this.intervalMilis
  10496. );
  10497. };
  10498. /**
  10499. * Stops collecting the statistics.
  10500. */
  10501. LocalStatsCollector.prototype.stop = function () {
  10502. if (this.intervalId) {
  10503. clearInterval(this.intervalId);
  10504. this.intervalId = null;
  10505. }
  10506. };
  10507. module.exports = LocalStatsCollector;
  10508. },{"../RTC/RTCBrowserType":8}],50:[function(require,module,exports){
  10509. /* global ssrc2jid */
  10510. /* jshint -W117 */
  10511. var RTCBrowserType = require("../RTC/RTCBrowserType");
  10512. /**
  10513. * Calculates packet lost percent using the number of lost packets and the
  10514. * number of all packet.
  10515. * @param lostPackets the number of lost packets
  10516. * @param totalPackets the number of all packets.
  10517. * @returns {number} packet loss percent
  10518. */
  10519. function calculatePacketLoss(lostPackets, totalPackets) {
  10520. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  10521. return 0;
  10522. return Math.round((lostPackets/totalPackets)*100);
  10523. }
  10524. function getStatValue(item, name) {
  10525. var browserType = RTCBrowserType.getBrowserType();
  10526. if (!keyMap[browserType][name])
  10527. throw "The property isn't supported!";
  10528. var key = keyMap[browserType][name];
  10529. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  10530. item.stat(key) : item[key];
  10531. }
  10532. /**
  10533. * Peer statistics data holder.
  10534. * @constructor
  10535. */
  10536. function PeerStats()
  10537. {
  10538. this.ssrc2Loss = {};
  10539. this.ssrc2AudioLevel = {};
  10540. this.ssrc2bitrate = {};
  10541. this.ssrc2resolution = {};
  10542. }
  10543. /**
  10544. * The bandwidth
  10545. * @type {{}}
  10546. */
  10547. PeerStats.bandwidth = {};
  10548. /**
  10549. * The bit rate
  10550. * @type {{}}
  10551. */
  10552. PeerStats.bitrate = {};
  10553. /**
  10554. * The packet loss rate
  10555. * @type {{}}
  10556. */
  10557. PeerStats.packetLoss = null;
  10558. /**
  10559. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  10560. * represented by this instance.
  10561. * @param ssrc audio or video RTP stream SSRC.
  10562. * @param lossRate new packet loss rate value to be set.
  10563. */
  10564. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  10565. {
  10566. this.ssrc2Loss[ssrc] = lossRate;
  10567. };
  10568. /**
  10569. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  10570. * represented by this instance.
  10571. * @param ssrc audio or video RTP stream SSRC.
  10572. * @param resolution new resolution value to be set.
  10573. */
  10574. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  10575. {
  10576. if(resolution === null && this.ssrc2resolution[ssrc])
  10577. {
  10578. delete this.ssrc2resolution[ssrc];
  10579. }
  10580. else if(resolution !== null)
  10581. this.ssrc2resolution[ssrc] = resolution;
  10582. };
  10583. /**
  10584. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  10585. * represented by this instance.
  10586. * @param ssrc audio or video RTP stream SSRC.
  10587. * @param bitrate new bitrate value to be set.
  10588. */
  10589. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  10590. {
  10591. if(this.ssrc2bitrate[ssrc])
  10592. {
  10593. this.ssrc2bitrate[ssrc].download += bitrate.download;
  10594. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  10595. }
  10596. else {
  10597. this.ssrc2bitrate[ssrc] = bitrate;
  10598. }
  10599. };
  10600. /**
  10601. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  10602. * the stream which belongs to the peer represented by this instance.
  10603. * @param ssrc RTP stream SSRC for which current audio level value will be
  10604. * updated.
  10605. * @param audioLevel the new audio level value to be set. Value is truncated to
  10606. * fit the range from 0 to 1.
  10607. */
  10608. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  10609. {
  10610. // Range limit 0 - 1
  10611. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  10612. };
  10613. function formatAudioLevel(audioLevel) {
  10614. return Math.min(Math.max(audioLevel, 0), 1);
  10615. }
  10616. /**
  10617. * Array with the transport information.
  10618. * @type {Array}
  10619. */
  10620. PeerStats.transport = [];
  10621. /**
  10622. * <tt>StatsCollector</tt> registers for stats updates of given
  10623. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  10624. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  10625. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  10626. * instance as an event source.
  10627. *
  10628. * @param peerconnection webRTC peer connection object.
  10629. * @param interval stats refresh interval given in ms.
  10630. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  10631. * called on stats update.
  10632. * @constructor
  10633. */
  10634. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  10635. {
  10636. this.peerconnection = peerconnection;
  10637. this.baselineAudioLevelsReport = null;
  10638. this.currentAudioLevelsReport = null;
  10639. this.currentStatsReport = null;
  10640. this.baselineStatsReport = null;
  10641. this.audioLevelsIntervalId = null;
  10642. this.eventEmitter = eventEmitter;
  10643. /**
  10644. * Gather PeerConnection stats once every this many milliseconds.
  10645. */
  10646. this.GATHER_INTERVAL = 15000;
  10647. /**
  10648. * Log stats via the focus once every this many milliseconds.
  10649. */
  10650. this.LOG_INTERVAL = 60000;
  10651. /**
  10652. * Gather stats and store them in this.statsToBeLogged.
  10653. */
  10654. this.gatherStatsIntervalId = null;
  10655. /**
  10656. * Send the stats already saved in this.statsToBeLogged to be logged via
  10657. * the focus.
  10658. */
  10659. this.logStatsIntervalId = null;
  10660. /**
  10661. * Stores the statistics which will be send to the focus to be logged.
  10662. */
  10663. this.statsToBeLogged =
  10664. {
  10665. timestamps: [],
  10666. stats: {}
  10667. };
  10668. // Updates stats interval
  10669. this.audioLevelsIntervalMilis = audioLevelsInterval;
  10670. this.statsIntervalId = null;
  10671. this.statsIntervalMilis = statsInterval;
  10672. // Map of jids to PeerStats
  10673. this.jid2stats = {};
  10674. }
  10675. module.exports = StatsCollector;
  10676. /**
  10677. * Stops stats updates.
  10678. */
  10679. StatsCollector.prototype.stop = function () {
  10680. if (this.audioLevelsIntervalId) {
  10681. clearInterval(this.audioLevelsIntervalId);
  10682. this.audioLevelsIntervalId = null;
  10683. }
  10684. if (this.statsIntervalId)
  10685. {
  10686. clearInterval(this.statsIntervalId);
  10687. this.statsIntervalId = null;
  10688. }
  10689. if(this.logStatsIntervalId)
  10690. {
  10691. clearInterval(this.logStatsIntervalId);
  10692. this.logStatsIntervalId = null;
  10693. }
  10694. if(this.gatherStatsIntervalId)
  10695. {
  10696. clearInterval(this.gatherStatsIntervalId);
  10697. this.gatherStatsIntervalId = null;
  10698. }
  10699. };
  10700. /**
  10701. * Callback passed to <tt>getStats</tt> method.
  10702. * @param error an error that occurred on <tt>getStats</tt> call.
  10703. */
  10704. StatsCollector.prototype.errorCallback = function (error)
  10705. {
  10706. console.error("Get stats error", error);
  10707. this.stop();
  10708. };
  10709. /**
  10710. * Starts stats updates.
  10711. */
  10712. StatsCollector.prototype.start = function ()
  10713. {
  10714. var self = this;
  10715. if(!config.disableAudioLevels) {
  10716. this.audioLevelsIntervalId = setInterval(
  10717. function () {
  10718. // Interval updates
  10719. self.peerconnection.getStats(
  10720. function (report) {
  10721. var results = null;
  10722. if (!report || !report.result ||
  10723. typeof report.result != 'function') {
  10724. results = report;
  10725. }
  10726. else {
  10727. results = report.result();
  10728. }
  10729. //console.error("Got interval report", results);
  10730. self.currentAudioLevelsReport = results;
  10731. self.processAudioLevelReport();
  10732. self.baselineAudioLevelsReport =
  10733. self.currentAudioLevelsReport;
  10734. },
  10735. self.errorCallback
  10736. );
  10737. },
  10738. self.audioLevelsIntervalMilis
  10739. );
  10740. }
  10741. if(!config.disableStats && !navigator.mozGetUserMedia) {
  10742. this.statsIntervalId = setInterval(
  10743. function () {
  10744. // Interval updates
  10745. self.peerconnection.getStats(
  10746. function (report) {
  10747. var results = null;
  10748. if (!report || !report.result ||
  10749. typeof report.result != 'function') {
  10750. //firefox
  10751. results = report;
  10752. }
  10753. else {
  10754. //chrome
  10755. results = report.result();
  10756. }
  10757. //console.error("Got interval report", results);
  10758. self.currentStatsReport = results;
  10759. try {
  10760. self.processStatsReport();
  10761. }
  10762. catch (e) {
  10763. console.error("Unsupported key:" + e, e);
  10764. }
  10765. self.baselineStatsReport = self.currentStatsReport;
  10766. },
  10767. self.errorCallback
  10768. );
  10769. },
  10770. self.statsIntervalMilis
  10771. );
  10772. }
  10773. if (config.logStats && !navigator.mozGetUserMedia) {
  10774. this.gatherStatsIntervalId = setInterval(
  10775. function () {
  10776. self.peerconnection.getStats(
  10777. function (report) {
  10778. self.addStatsToBeLogged(report.result());
  10779. },
  10780. function () {
  10781. }
  10782. );
  10783. },
  10784. this.GATHER_INTERVAL
  10785. );
  10786. this.logStatsIntervalId = setInterval(
  10787. function() { self.logStats(); },
  10788. this.LOG_INTERVAL);
  10789. }
  10790. };
  10791. /**
  10792. * Checks whether a certain record should be included in the logged statistics.
  10793. */
  10794. function acceptStat(reportId, reportType, statName) {
  10795. if (reportType == "googCandidatePair" && statName == "googChannelId")
  10796. return false;
  10797. if (reportType == "ssrc") {
  10798. if (statName == "googTrackId" ||
  10799. statName == "transportId" ||
  10800. statName == "ssrc")
  10801. return false;
  10802. }
  10803. return true;
  10804. }
  10805. /**
  10806. * Checks whether a certain record should be included in the logged statistics.
  10807. */
  10808. function acceptReport(id, type) {
  10809. if (id.substring(0, 15) == "googCertificate" ||
  10810. id.substring(0, 9) == "googTrack" ||
  10811. id.substring(0, 20) == "googLibjingleSession")
  10812. return false;
  10813. if (type == "googComponent")
  10814. return false;
  10815. return true;
  10816. }
  10817. /**
  10818. * Converts the stats to the format used for logging, and saves the data in
  10819. * this.statsToBeLogged.
  10820. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  10821. */
  10822. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  10823. var self = this;
  10824. var num_records = this.statsToBeLogged.timestamps.length;
  10825. this.statsToBeLogged.timestamps.push(new Date().getTime());
  10826. reports.map(function (report) {
  10827. if (!acceptReport(report.id, report.type))
  10828. return;
  10829. var stat = self.statsToBeLogged.stats[report.id];
  10830. if (!stat) {
  10831. stat = self.statsToBeLogged.stats[report.id] = {};
  10832. }
  10833. stat.type = report.type;
  10834. report.names().map(function (name) {
  10835. if (!acceptStat(report.id, report.type, name))
  10836. return;
  10837. var values = stat[name];
  10838. if (!values) {
  10839. values = stat[name] = [];
  10840. }
  10841. while (values.length < num_records) {
  10842. values.push(null);
  10843. }
  10844. values.push(report.stat(name));
  10845. });
  10846. });
  10847. };
  10848. StatsCollector.prototype.logStats = function () {
  10849. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  10850. return;
  10851. // Reset the stats
  10852. this.statsToBeLogged.stats = {};
  10853. this.statsToBeLogged.timestamps = [];
  10854. };
  10855. var keyMap = {};
  10856. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  10857. "ssrc": "ssrc",
  10858. "packetsReceived": "packetsReceived",
  10859. "packetsLost": "packetsLost",
  10860. "packetsSent": "packetsSent",
  10861. "bytesReceived": "bytesReceived",
  10862. "bytesSent": "bytesSent"
  10863. };
  10864. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  10865. "receiveBandwidth": "googAvailableReceiveBandwidth",
  10866. "sendBandwidth": "googAvailableSendBandwidth",
  10867. "remoteAddress": "googRemoteAddress",
  10868. "transportType": "googTransportType",
  10869. "localAddress": "googLocalAddress",
  10870. "activeConnection": "googActiveConnection",
  10871. "ssrc": "ssrc",
  10872. "packetsReceived": "packetsReceived",
  10873. "packetsSent": "packetsSent",
  10874. "packetsLost": "packetsLost",
  10875. "bytesReceived": "bytesReceived",
  10876. "bytesSent": "bytesSent",
  10877. "googFrameHeightReceived": "googFrameHeightReceived",
  10878. "googFrameWidthReceived": "googFrameWidthReceived",
  10879. "googFrameHeightSent": "googFrameHeightSent",
  10880. "googFrameWidthSent": "googFrameWidthSent",
  10881. "audioInputLevel": "audioInputLevel",
  10882. "audioOutputLevel": "audioOutputLevel"
  10883. };
  10884. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  10885. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  10886. /**
  10887. * Stats processing logic.
  10888. */
  10889. StatsCollector.prototype.processStatsReport = function () {
  10890. if (!this.baselineStatsReport) {
  10891. return;
  10892. }
  10893. for (var idx in this.currentStatsReport) {
  10894. var now = this.currentStatsReport[idx];
  10895. try {
  10896. if (getStatValue(now, 'receiveBandwidth') ||
  10897. getStatValue(now, 'sendBandwidth')) {
  10898. PeerStats.bandwidth = {
  10899. "download": Math.round(
  10900. (getStatValue(now, 'receiveBandwidth')) / 1000),
  10901. "upload": Math.round(
  10902. (getStatValue(now, 'sendBandwidth')) / 1000)
  10903. };
  10904. }
  10905. }
  10906. catch(e){/*not supported*/}
  10907. if(now.type == 'googCandidatePair')
  10908. {
  10909. var ip, type, localIP, active;
  10910. try {
  10911. ip = getStatValue(now, 'remoteAddress');
  10912. type = getStatValue(now, "transportType");
  10913. localIP = getStatValue(now, "localAddress");
  10914. active = getStatValue(now, "activeConnection");
  10915. }
  10916. catch(e){/*not supported*/}
  10917. if(!ip || !type || !localIP || active != "true")
  10918. continue;
  10919. var addressSaved = false;
  10920. for(var i = 0; i < PeerStats.transport.length; i++)
  10921. {
  10922. if(PeerStats.transport[i].ip == ip &&
  10923. PeerStats.transport[i].type == type &&
  10924. PeerStats.transport[i].localip == localIP)
  10925. {
  10926. addressSaved = true;
  10927. }
  10928. }
  10929. if(addressSaved)
  10930. continue;
  10931. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  10932. continue;
  10933. }
  10934. if(now.type == "candidatepair")
  10935. {
  10936. if(now.state == "succeeded")
  10937. continue;
  10938. var local = this.currentStatsReport[now.localCandidateId];
  10939. var remote = this.currentStatsReport[now.remoteCandidateId];
  10940. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  10941. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  10942. }
  10943. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  10944. now.type != "inboundrtp") {
  10945. continue;
  10946. }
  10947. var before = this.baselineStatsReport[idx];
  10948. if (!before) {
  10949. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  10950. continue;
  10951. }
  10952. var ssrc = getStatValue(now, 'ssrc');
  10953. if(!ssrc)
  10954. continue;
  10955. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  10956. if (!jid && (Date.now() - now.timestamp) < 3000) {
  10957. console.warn("No jid for ssrc: " + ssrc);
  10958. continue;
  10959. }
  10960. var jidStats = this.jid2stats[jid];
  10961. if (!jidStats) {
  10962. jidStats = new PeerStats();
  10963. this.jid2stats[jid] = jidStats;
  10964. }
  10965. var isDownloadStream = true;
  10966. var key = 'packetsReceived';
  10967. if (!getStatValue(now, key))
  10968. {
  10969. isDownloadStream = false;
  10970. key = 'packetsSent';
  10971. if (!getStatValue(now, key))
  10972. {
  10973. console.warn("No packetsReceived nor packetSent stat found");
  10974. continue;
  10975. }
  10976. }
  10977. var packetsNow = getStatValue(now, key);
  10978. if(!packetsNow || packetsNow < 0)
  10979. packetsNow = 0;
  10980. var packetsBefore = getStatValue(before, key);
  10981. if(!packetsBefore || packetsBefore < 0)
  10982. packetsBefore = 0;
  10983. var packetRate = packetsNow - packetsBefore;
  10984. if(!packetRate || packetRate < 0)
  10985. packetRate = 0;
  10986. var currentLoss = getStatValue(now, 'packetsLost');
  10987. if(!currentLoss || currentLoss < 0)
  10988. currentLoss = 0;
  10989. var previousLoss = getStatValue(before, 'packetsLost');
  10990. if(!previousLoss || previousLoss < 0)
  10991. previousLoss = 0;
  10992. var lossRate = currentLoss - previousLoss;
  10993. if(!lossRate || lossRate < 0)
  10994. lossRate = 0;
  10995. var packetsTotal = (packetRate + lossRate);
  10996. jidStats.setSsrcLoss(ssrc,
  10997. {"packetsTotal": packetsTotal,
  10998. "packetsLost": lossRate,
  10999. "isDownloadStream": isDownloadStream});
  11000. var bytesReceived = 0, bytesSent = 0;
  11001. if(getStatValue(now, "bytesReceived"))
  11002. {
  11003. bytesReceived = getStatValue(now, "bytesReceived") -
  11004. getStatValue(before, "bytesReceived");
  11005. }
  11006. if(getStatValue(now, "bytesSent"))
  11007. {
  11008. bytesSent = getStatValue(now, "bytesSent") -
  11009. getStatValue(before, "bytesSent");
  11010. }
  11011. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  11012. if(bytesReceived <= 0 || time <= 0)
  11013. {
  11014. bytesReceived = 0;
  11015. }
  11016. else
  11017. {
  11018. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  11019. }
  11020. if(bytesSent <= 0 || time <= 0)
  11021. {
  11022. bytesSent = 0;
  11023. }
  11024. else
  11025. {
  11026. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  11027. }
  11028. jidStats.setSsrcBitrate(ssrc, {
  11029. "download": bytesReceived,
  11030. "upload": bytesSent});
  11031. var resolution = {height: null, width: null};
  11032. try {
  11033. if (getStatValue(now, "googFrameHeightReceived") &&
  11034. getStatValue(now, "googFrameWidthReceived")) {
  11035. resolution.height = getStatValue(now, "googFrameHeightReceived");
  11036. resolution.width = getStatValue(now, "googFrameWidthReceived");
  11037. }
  11038. else if (getStatValue(now, "googFrameHeightSent") &&
  11039. getStatValue(now, "googFrameWidthSent")) {
  11040. resolution.height = getStatValue(now, "googFrameHeightSent");
  11041. resolution.width = getStatValue(now, "googFrameWidthSent");
  11042. }
  11043. }
  11044. catch(e){/*not supported*/}
  11045. if(resolution.height && resolution.width)
  11046. {
  11047. jidStats.setSsrcResolution(ssrc, resolution);
  11048. }
  11049. else
  11050. {
  11051. jidStats.setSsrcResolution(ssrc, null);
  11052. }
  11053. }
  11054. var self = this;
  11055. // Jid stats
  11056. var totalPackets = {download: 0, upload: 0};
  11057. var lostPackets = {download: 0, upload: 0};
  11058. var bitrateDownload = 0;
  11059. var bitrateUpload = 0;
  11060. var resolutions = {};
  11061. Object.keys(this.jid2stats).forEach(
  11062. function (jid)
  11063. {
  11064. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  11065. function (ssrc)
  11066. {
  11067. var type = "upload";
  11068. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  11069. type = "download";
  11070. totalPackets[type] +=
  11071. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  11072. lostPackets[type] +=
  11073. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  11074. }
  11075. );
  11076. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  11077. function (ssrc) {
  11078. bitrateDownload +=
  11079. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  11080. bitrateUpload +=
  11081. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  11082. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  11083. }
  11084. );
  11085. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  11086. }
  11087. );
  11088. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  11089. PeerStats.packetLoss = {
  11090. total:
  11091. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  11092. totalPackets.download + totalPackets.upload),
  11093. download:
  11094. calculatePacketLoss(lostPackets.download, totalPackets.download),
  11095. upload:
  11096. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  11097. };
  11098. this.eventEmitter.emit("statistics.connectionstats",
  11099. {
  11100. "bitrate": PeerStats.bitrate,
  11101. "packetLoss": PeerStats.packetLoss,
  11102. "bandwidth": PeerStats.bandwidth,
  11103. "resolution": resolutions,
  11104. "transport": PeerStats.transport
  11105. });
  11106. PeerStats.transport = [];
  11107. };
  11108. /**
  11109. * Stats processing logic.
  11110. */
  11111. StatsCollector.prototype.processAudioLevelReport = function ()
  11112. {
  11113. if (!this.baselineAudioLevelsReport)
  11114. {
  11115. return;
  11116. }
  11117. for (var idx in this.currentAudioLevelsReport)
  11118. {
  11119. var now = this.currentAudioLevelsReport[idx];
  11120. if (now.type != 'ssrc')
  11121. {
  11122. continue;
  11123. }
  11124. var before = this.baselineAudioLevelsReport[idx];
  11125. if (!before)
  11126. {
  11127. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  11128. continue;
  11129. }
  11130. var ssrc = getStatValue(now, 'ssrc');
  11131. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  11132. if (!jid)
  11133. {
  11134. if((Date.now() - now.timestamp) < 3000)
  11135. console.warn("No jid for ssrc: " + ssrc);
  11136. continue;
  11137. }
  11138. var jidStats = this.jid2stats[jid];
  11139. if (!jidStats)
  11140. {
  11141. jidStats = new PeerStats();
  11142. this.jid2stats[jid] = jidStats;
  11143. }
  11144. // Audio level
  11145. var audioLevel = null;
  11146. try {
  11147. audioLevel = getStatValue(now, 'audioInputLevel');
  11148. if (!audioLevel)
  11149. audioLevel = getStatValue(now, 'audioOutputLevel');
  11150. }
  11151. catch(e) {/*not supported*/
  11152. console.warn("Audio Levels are not available in the statistics.");
  11153. clearInterval(this.audioLevelsIntervalId);
  11154. return;
  11155. }
  11156. if (audioLevel)
  11157. {
  11158. // TODO: can't find specs about what this value really is,
  11159. // but it seems to vary between 0 and around 32k.
  11160. audioLevel = audioLevel / 32767;
  11161. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  11162. if(jid != APP.xmpp.myJid())
  11163. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  11164. }
  11165. }
  11166. };
  11167. },{"../RTC/RTCBrowserType":8}],51:[function(require,module,exports){
  11168. /**
  11169. * Created by hristo on 8/4/14.
  11170. */
  11171. var LocalStats = require("./LocalStatsCollector.js");
  11172. var RTPStats = require("./RTPStatsCollector.js");
  11173. var EventEmitter = require("events");
  11174. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  11175. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11176. var CallStats = require("./CallStats");
  11177. var RTCEvents = require("../../service/RTC/RTCEvents");
  11178. var eventEmitter = new EventEmitter();
  11179. var localStats = null;
  11180. var rtpStats = null;
  11181. function stopLocal()
  11182. {
  11183. if(localStats)
  11184. {
  11185. localStats.stop();
  11186. localStats = null;
  11187. }
  11188. }
  11189. function stopRemote()
  11190. {
  11191. if(rtpStats)
  11192. {
  11193. rtpStats.stop();
  11194. eventEmitter.emit("statistics.stop");
  11195. rtpStats = null;
  11196. }
  11197. }
  11198. function startRemoteStats (peerconnection) {
  11199. if(rtpStats)
  11200. {
  11201. rtpStats.stop();
  11202. rtpStats = null;
  11203. }
  11204. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  11205. rtpStats.start();
  11206. }
  11207. function onStreamCreated(stream)
  11208. {
  11209. if(stream.getOriginalStream().getAudioTracks().length === 0)
  11210. return;
  11211. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  11212. eventEmitter);
  11213. localStats.start();
  11214. }
  11215. function onDisposeConference(onUnload) {
  11216. CallStats.sendTerminateEvent();
  11217. stopRemote();
  11218. if(onUnload) {
  11219. stopLocal();
  11220. eventEmitter.removeAllListeners();
  11221. }
  11222. }
  11223. var statistics =
  11224. {
  11225. /**
  11226. * Indicates that this audio level is for local jid.
  11227. * @type {string}
  11228. */
  11229. LOCAL_JID: 'local',
  11230. addAudioLevelListener: function(listener)
  11231. {
  11232. eventEmitter.on("statistics.audioLevel", listener);
  11233. },
  11234. removeAudioLevelListener: function(listener)
  11235. {
  11236. eventEmitter.removeListener("statistics.audioLevel", listener);
  11237. },
  11238. addConnectionStatsListener: function(listener)
  11239. {
  11240. eventEmitter.on("statistics.connectionstats", listener);
  11241. },
  11242. removeConnectionStatsListener: function(listener)
  11243. {
  11244. eventEmitter.removeListener("statistics.connectionstats", listener);
  11245. },
  11246. addRemoteStatsStopListener: function(listener)
  11247. {
  11248. eventEmitter.on("statistics.stop", listener);
  11249. },
  11250. removeRemoteStatsStopListener: function(listener)
  11251. {
  11252. eventEmitter.removeListener("statistics.stop", listener);
  11253. },
  11254. stop: function () {
  11255. stopLocal();
  11256. stopRemote();
  11257. if(eventEmitter)
  11258. {
  11259. eventEmitter.removeAllListeners();
  11260. }
  11261. },
  11262. stopRemoteStatistics: function()
  11263. {
  11264. stopRemote();
  11265. },
  11266. start: function () {
  11267. APP.RTC.addStreamListener(onStreamCreated,
  11268. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  11269. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  11270. //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  11271. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  11272. startRemoteStats(event.peerconnection);
  11273. // CallStats.init(event);
  11274. });
  11275. APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  11276. CallStats.init(session);
  11277. })
  11278. APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  11279. CallStats.sendMuteEvent(mute, "audio");
  11280. });
  11281. APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  11282. CallStats.sendSetupFailedEvent();
  11283. })
  11284. APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  11285. CallStats.sendMuteEvent(mute, "video");
  11286. });
  11287. }
  11288. };
  11289. module.exports = statistics;
  11290. },{"../../service/RTC/RTCEvents":99,"../../service/RTC/StreamEventTypes.js":101,"../../service/xmpp/XMPPEvents":108,"./CallStats":48,"./LocalStatsCollector.js":49,"./RTPStatsCollector.js":50,"events":109}],52:[function(require,module,exports){
  11291. var i18n = require("i18next-client");
  11292. var languages = require("../../service/translation/languages");
  11293. var Settings = require("../settings/Settings");
  11294. var DEFAULT_LANG = languages.EN;
  11295. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  11296. return value.replace("__app__", interfaceConfig.APP_NAME);
  11297. });
  11298. var defaultOptions = {
  11299. detectLngQS: "lang",
  11300. useCookie: false,
  11301. fallbackLng: DEFAULT_LANG,
  11302. load: "unspecific",
  11303. resGetPath: 'lang/__ns__-__lng__.json',
  11304. ns: {
  11305. namespaces: ['main', 'languages'],
  11306. defaultNs: 'main'
  11307. },
  11308. lngWhitelist : languages.getLanguages(),
  11309. fallbackOnNull: true,
  11310. fallbackOnEmpty: true,
  11311. useDataAttrOptions: true,
  11312. defaultValueFromContent: false,
  11313. app: interfaceConfig.APP_NAME,
  11314. getAsync: false,
  11315. defaultValueFromContent: false,
  11316. customLoad: function(lng, ns, options, done) {
  11317. var resPath = "lang/__ns__-__lng__.json";
  11318. if(lng === languages.EN)
  11319. resPath = "lang/__ns__.json";
  11320. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  11321. i18n.functions.ajax({
  11322. url: url,
  11323. success: function(data, status, xhr) {
  11324. i18n.functions.log('loaded: ' + url);
  11325. done(null, data);
  11326. },
  11327. error : function(xhr, status, error) {
  11328. if ((status && status == 200) ||
  11329. (xhr && xhr.status && xhr.status == 200)) {
  11330. // file loaded but invalid json, stop waste time !
  11331. i18n.functions.error('There is a typo in: ' + url);
  11332. } else if ((status && status == 404) ||
  11333. (xhr && xhr.status && xhr.status == 404)) {
  11334. i18n.functions.log('Does not exist: ' + url);
  11335. } else {
  11336. var theStatus = status ? status :
  11337. ((xhr && xhr.status) ? xhr.status : null);
  11338. i18n.functions.log(theStatus + ' when loading ' + url);
  11339. }
  11340. done(error, {});
  11341. },
  11342. dataType: "json",
  11343. async : options.getAsync
  11344. });
  11345. }
  11346. // options for caching
  11347. // useLocalStorage: true,
  11348. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  11349. };
  11350. function initCompleted(t)
  11351. {
  11352. $("[data-i18n]").i18n();
  11353. }
  11354. function checkForParameter() {
  11355. var query = window.location.search.substring(1);
  11356. var vars = query.split("&");
  11357. for (var i=0;i<vars.length;i++) {
  11358. var pair = vars[i].split("=");
  11359. if(pair[0] == "lang")
  11360. {
  11361. return pair[1];
  11362. }
  11363. }
  11364. return null;
  11365. }
  11366. module.exports = {
  11367. init: function (lang) {
  11368. var options = defaultOptions;
  11369. if(!lang)
  11370. {
  11371. lang = checkForParameter();
  11372. if(!lang)
  11373. {
  11374. var settings = Settings.getSettings();
  11375. if(settings)
  11376. lang = settings.language;
  11377. if(!lang && config.defaultLanguage)
  11378. {
  11379. lang = config.defaultLanguage;
  11380. }
  11381. }
  11382. }
  11383. if(lang) {
  11384. options.lng = lang;
  11385. }
  11386. i18n.init(options, initCompleted);
  11387. },
  11388. translateString: function (key, options) {
  11389. return i18n.t(key, options);
  11390. },
  11391. setLanguage: function (lang) {
  11392. if(!lang)
  11393. lang = DEFAULT_LANG;
  11394. i18n.setLng(lang, defaultOptions, initCompleted);
  11395. },
  11396. getCurrentLanguage: function () {
  11397. return i18n.lng();
  11398. },
  11399. translateElement: function (selector) {
  11400. selector.i18n();
  11401. },
  11402. generateTranslationHTML: function (key, options) {
  11403. var str = "<span data-i18n=\"" + key + "\"";
  11404. if(options)
  11405. {
  11406. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  11407. }
  11408. str += ">";
  11409. str += this.translateString(key, options);
  11410. str += "</span>";
  11411. return str;
  11412. }
  11413. };
  11414. },{"../../service/translation/languages":107,"../settings/Settings":47,"i18next-client":68}],53:[function(require,module,exports){
  11415. /* jshint -W117 */
  11416. var TraceablePeerConnection = require("./TraceablePeerConnection");
  11417. var SDPDiffer = require("./SDPDiffer");
  11418. var SDPUtil = require("./SDPUtil");
  11419. var SDP = require("./SDP");
  11420. var async = require("async");
  11421. var transform = require("sdp-transform");
  11422. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11423. var RTCBrowserType = require("../RTC/RTCBrowserType");
  11424. // Jingle stuff
  11425. function JingleSession(me, sid, connection, service, eventEmitter) {
  11426. this.me = me;
  11427. this.sid = sid;
  11428. this.connection = connection;
  11429. this.initiator = null;
  11430. this.responder = null;
  11431. this.isInitiator = null;
  11432. this.peerjid = null;
  11433. this.state = null;
  11434. this.localSDP = null;
  11435. this.remoteSDP = null;
  11436. this.relayedStreams = [];
  11437. this.startTime = null;
  11438. this.stopTime = null;
  11439. this.media_constraints = null;
  11440. this.pc_constraints = null;
  11441. this.ice_config = {};
  11442. this.drip_container = [];
  11443. this.service = service;
  11444. this.eventEmitter = eventEmitter;
  11445. this.usetrickle = true;
  11446. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  11447. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  11448. this.hadstuncandidate = false;
  11449. this.hadturncandidate = false;
  11450. this.lasticecandidate = false;
  11451. this.statsinterval = null;
  11452. this.reason = null;
  11453. this.addssrc = [];
  11454. this.removessrc = [];
  11455. this.pendingop = null;
  11456. this.switchstreams = false;
  11457. this.wait = true;
  11458. this.localStreamsSSRC = null;
  11459. this.ssrcOwners = {};
  11460. this.ssrcVideoTypes = {};
  11461. this.eventEmitter = eventEmitter;
  11462. /**
  11463. * The indicator which determines whether the (local) video has been muted
  11464. * in response to a user command in contrast to an automatic decision made
  11465. * by the application logic.
  11466. */
  11467. this.videoMuteByUser = false;
  11468. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  11469. // We start with the queue paused. We resume it when the signaling state is
  11470. // stable and the ice connection state is connected.
  11471. this.modifySourcesQueue.pause();
  11472. }
  11473. JingleSession.prototype.updateModifySourcesQueue = function() {
  11474. var signalingState = this.peerconnection.signalingState;
  11475. var iceConnectionState = this.peerconnection.iceConnectionState;
  11476. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  11477. this.modifySourcesQueue.resume();
  11478. } else {
  11479. this.modifySourcesQueue.pause();
  11480. }
  11481. };
  11482. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  11483. var self = this;
  11484. if (this.state !== null) {
  11485. console.error('attempt to initiate on session ' + this.sid +
  11486. 'in state ' + this.state);
  11487. return;
  11488. }
  11489. this.isInitiator = isInitiator;
  11490. this.state = 'pending';
  11491. this.initiator = isInitiator ? this.me : peerjid;
  11492. this.responder = !isInitiator ? this.me : peerjid;
  11493. this.peerjid = peerjid;
  11494. this.hadstuncandidate = false;
  11495. this.hadturncandidate = false;
  11496. this.lasticecandidate = false;
  11497. this.peerconnection
  11498. = new TraceablePeerConnection(
  11499. this.connection.jingle.ice_config,
  11500. this.connection.jingle.pc_constraints,
  11501. this);
  11502. this.peerconnection.onicecandidate = function (event) {
  11503. self.sendIceCandidate(event.candidate);
  11504. };
  11505. this.peerconnection.onaddstream = function (event) {
  11506. if (event.stream.id !== 'default') {
  11507. console.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  11508. self.remoteStreamAdded(event);
  11509. } else {
  11510. // This is a recvonly stream. Clients that implement Unified Plan,
  11511. // such as Firefox use recvonly "streams/channels/tracks" for
  11512. // receiving remote stream/tracks, as opposed to Plan B where there
  11513. // are only 3 channels: audio, video and data.
  11514. console.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  11515. }
  11516. };
  11517. this.peerconnection.onremovestream = function (event) {
  11518. // Remove the stream from remoteStreams
  11519. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  11520. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  11521. };
  11522. this.peerconnection.onsignalingstatechange = function (event) {
  11523. if (!(self && self.peerconnection)) return;
  11524. self.updateModifySourcesQueue();
  11525. };
  11526. this.peerconnection.oniceconnectionstatechange = function (event) {
  11527. if (!(self && self.peerconnection)) return;
  11528. self.updateModifySourcesQueue();
  11529. switch (self.peerconnection.iceConnectionState) {
  11530. case 'connected':
  11531. this.startTime = new Date();
  11532. break;
  11533. case 'disconnected':
  11534. this.stopTime = new Date();
  11535. break;
  11536. case 'failed':
  11537. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11538. break;
  11539. }
  11540. onIceConnectionStateChange(self.sid, self);
  11541. };
  11542. this.peerconnection.onnegotiationneeded = function (event) {
  11543. self.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  11544. };
  11545. // add any local and relayed stream
  11546. APP.RTC.localStreams.forEach(function(stream) {
  11547. self.peerconnection.addStream(stream.getOriginalStream());
  11548. });
  11549. this.relayedStreams.forEach(function(stream) {
  11550. self.peerconnection.addStream(stream);
  11551. });
  11552. };
  11553. function onIceConnectionStateChange(sid, session) {
  11554. switch (session.peerconnection.iceConnectionState) {
  11555. case 'checking':
  11556. session.timeChecking = (new Date()).getTime();
  11557. session.firstconnect = true;
  11558. break;
  11559. case 'completed': // on caller side
  11560. case 'connected':
  11561. if (session.firstconnect) {
  11562. session.firstconnect = false;
  11563. var metadata = {};
  11564. metadata.setupTime
  11565. = (new Date()).getTime() - session.timeChecking;
  11566. session.peerconnection.getStats(function (res) {
  11567. if(res && res.result) {
  11568. res.result().forEach(function (report) {
  11569. if (report.type == 'googCandidatePair' &&
  11570. report.stat('googActiveConnection') == 'true') {
  11571. metadata.localCandidateType
  11572. = report.stat('googLocalCandidateType');
  11573. metadata.remoteCandidateType
  11574. = report.stat('googRemoteCandidateType');
  11575. // log pair as well so we can get nice pie
  11576. // charts
  11577. metadata.candidatePair
  11578. = report.stat('googLocalCandidateType') +
  11579. ';' +
  11580. report.stat('googRemoteCandidateType');
  11581. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  11582. {
  11583. metadata.ipv6 = true;
  11584. }
  11585. }
  11586. });
  11587. }
  11588. });
  11589. }
  11590. break;
  11591. }
  11592. }
  11593. JingleSession.prototype.getVideoType = function () {
  11594. return APP.desktopsharing.isUsingScreenStream() ? 'screen' : 'camera';
  11595. };
  11596. JingleSession.prototype.accept = function () {
  11597. this.state = 'active';
  11598. var pranswer = this.peerconnection.localDescription;
  11599. if (!pranswer || pranswer.type != 'pranswer') {
  11600. return;
  11601. }
  11602. console.log('going from pranswer to answer');
  11603. if (this.usetrickle) {
  11604. // remove candidates already sent from session-accept
  11605. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  11606. for (var i = 0; i < lines.length; i++) {
  11607. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  11608. }
  11609. }
  11610. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  11611. // FIXME: change any inactive to sendrecv or whatever they were originally
  11612. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  11613. }
  11614. var prsdp = new SDP(pranswer.sdp);
  11615. var accept = $iq({to: this.peerjid,
  11616. type: 'set'})
  11617. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11618. action: 'session-accept',
  11619. initiator: this.initiator,
  11620. responder: this.responder,
  11621. sid: this.sid });
  11622. // FIXME why do we generate session-accept in 3 different places ?
  11623. prsdp.toJingle(
  11624. accept,
  11625. this.initiator == this.me ? 'initiator' : 'responder',
  11626. this.localStreamsSSRC,
  11627. self.getVideoType());
  11628. var sdp = this.peerconnection.localDescription.sdp;
  11629. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  11630. // FIXME: change any inactive to sendrecv or whatever they were originally
  11631. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  11632. }
  11633. var self = this;
  11634. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  11635. function () {
  11636. //console.log('setLocalDescription success');
  11637. self.setLocalDescription();
  11638. self.connection.sendIQ(accept,
  11639. function () {
  11640. var ack = {};
  11641. ack.source = 'answer';
  11642. $(document).trigger('ack.jingle', [self.sid, ack]);
  11643. },
  11644. function (stanza) {
  11645. var error = ($(stanza).find('error').length) ? {
  11646. code: $(stanza).find('error').attr('code'),
  11647. reason: $(stanza).find('error :first')[0].tagName
  11648. }:{};
  11649. error.source = 'answer';
  11650. JingleSession.onJingleError(self.sid, error);
  11651. },
  11652. 10000);
  11653. },
  11654. function (e) {
  11655. console.error('setLocalDescription failed', e);
  11656. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11657. }
  11658. );
  11659. };
  11660. JingleSession.prototype.terminate = function (reason) {
  11661. this.state = 'ended';
  11662. this.reason = reason;
  11663. this.peerconnection.close();
  11664. if (this.statsinterval !== null) {
  11665. window.clearInterval(this.statsinterval);
  11666. this.statsinterval = null;
  11667. }
  11668. };
  11669. JingleSession.prototype.active = function () {
  11670. return this.state == 'active';
  11671. };
  11672. JingleSession.prototype.sendIceCandidate = function (candidate) {
  11673. var self = this;
  11674. if (candidate && !this.lasticecandidate) {
  11675. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  11676. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  11677. if (!(ice && jcand)) {
  11678. console.error('failed to get ice && jcand');
  11679. return;
  11680. }
  11681. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11682. if (jcand.type === 'srflx') {
  11683. this.hadstuncandidate = true;
  11684. } else if (jcand.type === 'relay') {
  11685. this.hadturncandidate = true;
  11686. }
  11687. if (this.usetrickle) {
  11688. if (this.usedrip) {
  11689. if (this.drip_container.length === 0) {
  11690. // start 20ms callout
  11691. window.setTimeout(function () {
  11692. if (self.drip_container.length === 0) return;
  11693. self.sendIceCandidates(self.drip_container);
  11694. self.drip_container = [];
  11695. }, 20);
  11696. }
  11697. this.drip_container.push(candidate);
  11698. return;
  11699. } else {
  11700. self.sendIceCandidate([candidate]);
  11701. }
  11702. }
  11703. } else {
  11704. //console.log('sendIceCandidate: last candidate.');
  11705. if (!this.usetrickle) {
  11706. //console.log('should send full offer now...');
  11707. //FIXME why do we generate session-accept in 3 different places ?
  11708. var init = $iq({to: this.peerjid,
  11709. type: 'set'})
  11710. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11711. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  11712. initiator: this.initiator,
  11713. sid: this.sid});
  11714. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  11715. var self = this;
  11716. var sendJingle = function (ssrc) {
  11717. if(!ssrc)
  11718. ssrc = {};
  11719. self.localSDP.toJingle(
  11720. init,
  11721. self.initiator == self.me ? 'initiator' : 'responder',
  11722. ssrc,
  11723. self.getVideoType());
  11724. self.connection.sendIQ(init,
  11725. function () {
  11726. //console.log('session initiate ack');
  11727. var ack = {};
  11728. ack.source = 'offer';
  11729. $(document).trigger('ack.jingle', [self.sid, ack]);
  11730. },
  11731. function (stanza) {
  11732. self.state = 'error';
  11733. self.peerconnection.close();
  11734. var error = ($(stanza).find('error').length) ? {
  11735. code: $(stanza).find('error').attr('code'),
  11736. reason: $(stanza).find('error :first')[0].tagName,
  11737. }:{};
  11738. error.source = 'offer';
  11739. JingleSession.onJingleError(self.sid, error);
  11740. },
  11741. 10000);
  11742. }
  11743. sendJingle();
  11744. }
  11745. this.lasticecandidate = true;
  11746. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  11747. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  11748. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  11749. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  11750. }
  11751. }
  11752. };
  11753. JingleSession.prototype.sendIceCandidates = function (candidates) {
  11754. console.log('sendIceCandidates', candidates);
  11755. var cand = $iq({to: this.peerjid, type: 'set'})
  11756. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11757. action: 'transport-info',
  11758. initiator: this.initiator,
  11759. sid: this.sid});
  11760. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  11761. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  11762. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  11763. if (cands.length > 0) {
  11764. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  11765. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11766. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  11767. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  11768. }).c('transport', ice);
  11769. for (var i = 0; i < cands.length; i++) {
  11770. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  11771. }
  11772. // add fingerprint
  11773. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  11774. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  11775. tmp.required = true;
  11776. cand.c(
  11777. 'fingerprint',
  11778. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  11779. .t(tmp.fingerprint);
  11780. delete tmp.fingerprint;
  11781. cand.attrs(tmp);
  11782. cand.up();
  11783. }
  11784. cand.up(); // transport
  11785. cand.up(); // content
  11786. }
  11787. }
  11788. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  11789. //console.log('was this the last candidate', this.lasticecandidate);
  11790. this.connection.sendIQ(cand,
  11791. function () {
  11792. var ack = {};
  11793. ack.source = 'transportinfo';
  11794. $(document).trigger('ack.jingle', [this.sid, ack]);
  11795. },
  11796. function (stanza) {
  11797. var error = ($(stanza).find('error').length) ? {
  11798. code: $(stanza).find('error').attr('code'),
  11799. reason: $(stanza).find('error :first')[0].tagName,
  11800. }:{};
  11801. error.source = 'transportinfo';
  11802. JingleSession.onJingleError(this.sid, error);
  11803. },
  11804. 10000);
  11805. };
  11806. JingleSession.prototype.sendOffer = function () {
  11807. //console.log('sendOffer...');
  11808. var self = this;
  11809. this.peerconnection.createOffer(function (sdp) {
  11810. self.createdOffer(sdp);
  11811. },
  11812. function (e) {
  11813. console.error('createOffer failed', e);
  11814. },
  11815. this.media_constraints
  11816. );
  11817. };
  11818. // FIXME createdOffer is never used in jitsi-meet
  11819. JingleSession.prototype.createdOffer = function (sdp) {
  11820. //console.log('createdOffer', sdp);
  11821. var self = this;
  11822. this.localSDP = new SDP(sdp.sdp);
  11823. //this.localSDP.mangle();
  11824. var sendJingle = function () {
  11825. var init = $iq({to: this.peerjid,
  11826. type: 'set'})
  11827. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11828. action: 'session-initiate',
  11829. initiator: this.initiator,
  11830. sid: this.sid});
  11831. self.localSDP.toJingle(
  11832. init,
  11833. this.initiator == this.me ? 'initiator' : 'responder',
  11834. this.localStreamsSSRC,
  11835. self.getVideoType());
  11836. self.connection.sendIQ(init,
  11837. function () {
  11838. var ack = {};
  11839. ack.source = 'offer';
  11840. $(document).trigger('ack.jingle', [self.sid, ack]);
  11841. },
  11842. function (stanza) {
  11843. self.state = 'error';
  11844. self.peerconnection.close();
  11845. var error = ($(stanza).find('error').length) ? {
  11846. code: $(stanza).find('error').attr('code'),
  11847. reason: $(stanza).find('error :first')[0].tagName,
  11848. }:{};
  11849. error.source = 'offer';
  11850. JingleSession.onJingleError(self.sid, error);
  11851. },
  11852. 10000);
  11853. }
  11854. sdp.sdp = this.localSDP.raw;
  11855. this.peerconnection.setLocalDescription(sdp,
  11856. function () {
  11857. if(self.usetrickle)
  11858. {
  11859. sendJingle();
  11860. }
  11861. self.setLocalDescription();
  11862. //console.log('setLocalDescription success');
  11863. },
  11864. function (e) {
  11865. console.error('setLocalDescription failed', e);
  11866. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11867. }
  11868. );
  11869. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  11870. for (var i = 0; i < cands.length; i++) {
  11871. var cand = SDPUtil.parse_icecandidate(cands[i]);
  11872. if (cand.type == 'srflx') {
  11873. this.hadstuncandidate = true;
  11874. } else if (cand.type == 'relay') {
  11875. this.hadturncandidate = true;
  11876. }
  11877. }
  11878. };
  11879. JingleSession.prototype.readSsrcInfo = function (contents) {
  11880. var self = this;
  11881. $(contents).each(function (idx, content) {
  11882. var name = $(content).attr('name');
  11883. var mediaType = this.getAttribute('name');
  11884. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  11885. ssrcs.each(function () {
  11886. var ssrc = this.getAttribute('ssrc');
  11887. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  11888. function () {
  11889. var owner = this.getAttribute('owner');
  11890. var videoType = this.getAttribute('video-type');
  11891. self.ssrcOwners[ssrc] = owner;
  11892. self.ssrcVideoTypes[ssrc] = videoType;
  11893. }
  11894. );
  11895. });
  11896. });
  11897. };
  11898. JingleSession.prototype.getSsrcOwner = function (ssrc) {
  11899. return this.ssrcOwners[ssrc];
  11900. };
  11901. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  11902. //console.log('setting remote description... ', desctype);
  11903. this.remoteSDP = new SDP('');
  11904. this.remoteSDP.fromJingle(elem);
  11905. this.readSsrcInfo($(elem).find(">content"));
  11906. if (this.peerconnection.remoteDescription !== null) {
  11907. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  11908. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  11909. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  11910. for (var i = 0; i < pranswer.media.length; i++) {
  11911. // make sure we have ice ufrag and pwd
  11912. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  11913. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  11914. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  11915. } else {
  11916. console.warn('no ice ufrag?');
  11917. }
  11918. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  11919. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  11920. } else {
  11921. console.warn('no ice pwd?');
  11922. }
  11923. }
  11924. // copy over candidates
  11925. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  11926. for (var j = 0; j < lines.length; j++) {
  11927. this.remoteSDP.media[i] += lines[j] + '\r\n';
  11928. }
  11929. }
  11930. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  11931. }
  11932. }
  11933. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  11934. this.peerconnection.setRemoteDescription(remotedesc,
  11935. function () {
  11936. //console.log('setRemoteDescription success');
  11937. },
  11938. function (e) {
  11939. console.error('setRemoteDescription error', e);
  11940. JingleSession.onJingleFatalError(self, e);
  11941. }
  11942. );
  11943. };
  11944. JingleSession.prototype.addIceCandidate = function (elem) {
  11945. var self = this;
  11946. if (this.peerconnection.signalingState == 'closed') {
  11947. return;
  11948. }
  11949. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  11950. console.log('trickle ice candidate arriving before session accept...');
  11951. // create a PRANSWER for setRemoteDescription
  11952. if (!this.remoteSDP) {
  11953. var cobbled = 'v=0\r\n' +
  11954. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  11955. 's=-\r\n' +
  11956. 't=0 0\r\n';
  11957. // first, take some things from the local description
  11958. for (var i = 0; i < this.localSDP.media.length; i++) {
  11959. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  11960. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  11961. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  11962. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  11963. }
  11964. cobbled += 'a=inactive\r\n';
  11965. }
  11966. this.remoteSDP = new SDP(cobbled);
  11967. }
  11968. // then add things like ice and dtls from remote candidate
  11969. elem.each(function () {
  11970. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  11971. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11972. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11973. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  11974. var tmp = $(this).find('transport');
  11975. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  11976. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  11977. tmp = $(this).find('transport>fingerprint');
  11978. if (tmp.length) {
  11979. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  11980. } else {
  11981. console.log('no dtls fingerprint (webrtc issue #1718?)');
  11982. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  11983. }
  11984. break;
  11985. }
  11986. }
  11987. }
  11988. });
  11989. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  11990. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  11991. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  11992. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  11993. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  11994. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  11995. }).length == this.remoteSDP.media.length;
  11996. if (iscomplete) {
  11997. console.log('setting pranswer');
  11998. try {
  11999. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  12000. function() {
  12001. },
  12002. function(e) {
  12003. console.log('setRemoteDescription pranswer failed', e.toString());
  12004. });
  12005. } catch (e) {
  12006. console.error('setting pranswer failed', e);
  12007. }
  12008. } else {
  12009. //console.log('not yet setting pranswer');
  12010. }
  12011. }
  12012. // operate on each content element
  12013. elem.each(function () {
  12014. // would love to deactivate this, but firefox still requires it
  12015. var idx = -1;
  12016. var i;
  12017. for (i = 0; i < self.remoteSDP.media.length; i++) {
  12018. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12019. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12020. idx = i;
  12021. break;
  12022. }
  12023. }
  12024. if (idx == -1) { // fall back to localdescription
  12025. for (i = 0; i < self.localSDP.media.length; i++) {
  12026. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12027. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12028. idx = i;
  12029. break;
  12030. }
  12031. }
  12032. }
  12033. var name = $(this).attr('name');
  12034. // TODO: check ice-pwd and ice-ufrag?
  12035. $(this).find('transport>candidate').each(function () {
  12036. var line, candidate;
  12037. line = SDPUtil.candidateFromJingle(this);
  12038. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  12039. sdpMid: name,
  12040. candidate: line});
  12041. try {
  12042. self.peerconnection.addIceCandidate(candidate);
  12043. } catch (e) {
  12044. console.error('addIceCandidate failed', e.toString(), line);
  12045. }
  12046. });
  12047. });
  12048. };
  12049. JingleSession.prototype.sendAnswer = function (provisional) {
  12050. //console.log('createAnswer', provisional);
  12051. var self = this;
  12052. this.peerconnection.createAnswer(
  12053. function (sdp) {
  12054. self.createdAnswer(sdp, provisional);
  12055. },
  12056. function (e) {
  12057. console.error('createAnswer failed', e);
  12058. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12059. },
  12060. this.media_constraints
  12061. );
  12062. };
  12063. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  12064. //console.log('createAnswer callback');
  12065. var self = this;
  12066. this.localSDP = new SDP(sdp.sdp);
  12067. //this.localSDP.mangle();
  12068. this.usepranswer = provisional === true;
  12069. if (this.usetrickle) {
  12070. if (this.usepranswer) {
  12071. sdp.type = 'pranswer';
  12072. for (var i = 0; i < this.localSDP.media.length; i++) {
  12073. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  12074. }
  12075. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  12076. }
  12077. }
  12078. var self = this;
  12079. var sendJingle = function (ssrcs) {
  12080. // FIXME why do we generate session-accept in 3 different places ?
  12081. var accept = $iq({to: self.peerjid,
  12082. type: 'set'})
  12083. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12084. action: 'session-accept',
  12085. initiator: self.initiator,
  12086. responder: self.responder,
  12087. sid: self.sid });
  12088. self.localSDP.toJingle(
  12089. accept,
  12090. self.initiator == self.me ? 'initiator' : 'responder',
  12091. ssrcs,
  12092. self.getVideoType());
  12093. self.connection.sendIQ(accept,
  12094. function () {
  12095. var ack = {};
  12096. ack.source = 'answer';
  12097. $(document).trigger('ack.jingle', [self.sid, ack]);
  12098. },
  12099. function (stanza) {
  12100. var error = ($(stanza).find('error').length) ? {
  12101. code: $(stanza).find('error').attr('code'),
  12102. reason: $(stanza).find('error :first')[0].tagName,
  12103. }:{};
  12104. error.source = 'answer';
  12105. JingleSession.onJingleError(self.sid, error);
  12106. },
  12107. 10000);
  12108. }
  12109. sdp.sdp = this.localSDP.raw;
  12110. this.peerconnection.setLocalDescription(sdp,
  12111. function () {
  12112. //console.log('setLocalDescription success');
  12113. if (self.usetrickle && !self.usepranswer) {
  12114. sendJingle();
  12115. }
  12116. self.setLocalDescription();
  12117. },
  12118. function (e) {
  12119. console.error('setLocalDescription failed', e);
  12120. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12121. }
  12122. );
  12123. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  12124. for (var j = 0; j < cands.length; j++) {
  12125. var cand = SDPUtil.parse_icecandidate(cands[j]);
  12126. if (cand.type == 'srflx') {
  12127. this.hadstuncandidate = true;
  12128. } else if (cand.type == 'relay') {
  12129. this.hadturncandidate = true;
  12130. }
  12131. }
  12132. };
  12133. JingleSession.prototype.sendTerminate = function (reason, text) {
  12134. var self = this,
  12135. term = $iq({to: this.peerjid,
  12136. type: 'set'})
  12137. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12138. action: 'session-terminate',
  12139. initiator: this.initiator,
  12140. sid: this.sid})
  12141. .c('reason')
  12142. .c(reason || 'success');
  12143. if (text) {
  12144. term.up().c('text').t(text);
  12145. }
  12146. this.connection.sendIQ(term,
  12147. function () {
  12148. self.peerconnection.close();
  12149. self.peerconnection = null;
  12150. self.terminate();
  12151. var ack = {};
  12152. ack.source = 'terminate';
  12153. $(document).trigger('ack.jingle', [self.sid, ack]);
  12154. },
  12155. function (stanza) {
  12156. var error = ($(stanza).find('error').length) ? {
  12157. code: $(stanza).find('error').attr('code'),
  12158. reason: $(stanza).find('error :first')[0].tagName,
  12159. }:{};
  12160. $(document).trigger('ack.jingle', [self.sid, error]);
  12161. },
  12162. 10000);
  12163. if (this.statsinterval !== null) {
  12164. window.clearInterval(this.statsinterval);
  12165. this.statsinterval = null;
  12166. }
  12167. };
  12168. JingleSession.prototype.addSource = function (elem, fromJid) {
  12169. var self = this;
  12170. // FIXME: dirty waiting
  12171. if (!this.peerconnection.localDescription)
  12172. {
  12173. console.warn("addSource - localDescription not ready yet")
  12174. setTimeout(function()
  12175. {
  12176. self.addSource(elem, fromJid);
  12177. },
  12178. 200
  12179. );
  12180. return;
  12181. }
  12182. console.log('addssrc', new Date().getTime());
  12183. console.log('ice', this.peerconnection.iceConnectionState);
  12184. this.readSsrcInfo(elem);
  12185. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12186. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12187. $(elem).each(function (idx, content) {
  12188. var name = $(content).attr('name');
  12189. var lines = '';
  12190. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12191. var semantics = this.getAttribute('semantics');
  12192. var ssrcs = $(this).find('>source').map(function () {
  12193. return this.getAttribute('ssrc');
  12194. }).get();
  12195. if (ssrcs.length != 0) {
  12196. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12197. }
  12198. });
  12199. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12200. tmp.each(function () {
  12201. var ssrc = $(this).attr('ssrc');
  12202. if(mySdp.containsSSRC(ssrc)){
  12203. /**
  12204. * This happens when multiple participants change their streams at the same time and
  12205. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  12206. * addssrc are scheduled for update IQ. See
  12207. */
  12208. console.warn("Got add stream request for my own ssrc: "+ssrc);
  12209. return;
  12210. }
  12211. $(this).find('>parameter').each(function () {
  12212. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12213. if ($(this).attr('value') && $(this).attr('value').length)
  12214. lines += ':' + $(this).attr('value');
  12215. lines += '\r\n';
  12216. });
  12217. });
  12218. sdp.media.forEach(function(media, idx) {
  12219. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12220. return;
  12221. sdp.media[idx] += lines;
  12222. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  12223. self.addssrc[idx] += lines;
  12224. });
  12225. sdp.raw = sdp.session + sdp.media.join('');
  12226. });
  12227. this.modifySourcesQueue.push(function() {
  12228. // When a source is added and if this is FF, a new channel is allocated
  12229. // for receiving the added source. We need to diffuse the SSRC of this
  12230. // new recvonly channel to the rest of the peers.
  12231. console.log('modify sources done');
  12232. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12233. console.log("SDPs", mySdp, newSdp);
  12234. self.notifyMySSRCUpdate(mySdp, newSdp);
  12235. });
  12236. };
  12237. JingleSession.prototype.removeSource = function (elem, fromJid) {
  12238. var self = this;
  12239. // FIXME: dirty waiting
  12240. if (!this.peerconnection.localDescription)
  12241. {
  12242. console.warn("removeSource - localDescription not ready yet")
  12243. setTimeout(function()
  12244. {
  12245. self.removeSource(elem, fromJid);
  12246. },
  12247. 200
  12248. );
  12249. return;
  12250. }
  12251. console.log('removessrc', new Date().getTime());
  12252. console.log('ice', this.peerconnection.iceConnectionState);
  12253. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12254. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12255. $(elem).each(function (idx, content) {
  12256. var name = $(content).attr('name');
  12257. var lines = '';
  12258. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12259. var semantics = this.getAttribute('semantics');
  12260. var ssrcs = $(this).find('>source').map(function () {
  12261. return this.getAttribute('ssrc');
  12262. }).get();
  12263. if (ssrcs.length != 0) {
  12264. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12265. }
  12266. });
  12267. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12268. tmp.each(function () {
  12269. var ssrc = $(this).attr('ssrc');
  12270. // This should never happen, but can be useful for bug detection
  12271. if(mySdp.containsSSRC(ssrc)){
  12272. console.error("Got remove stream request for my own ssrc: "+ssrc);
  12273. return;
  12274. }
  12275. $(this).find('>parameter').each(function () {
  12276. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12277. if ($(this).attr('value') && $(this).attr('value').length)
  12278. lines += ':' + $(this).attr('value');
  12279. lines += '\r\n';
  12280. });
  12281. });
  12282. sdp.media.forEach(function(media, idx) {
  12283. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12284. return;
  12285. sdp.media[idx] += lines;
  12286. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  12287. self.removessrc[idx] += lines;
  12288. });
  12289. sdp.raw = sdp.session + sdp.media.join('');
  12290. });
  12291. this.modifySourcesQueue.push(function() {
  12292. // When a source is removed and if this is FF, the recvonly channel that
  12293. // receives the remote stream is deactivated . We need to diffuse the
  12294. // recvonly SSRC removal to the rest of the peers.
  12295. console.log('modify sources done');
  12296. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12297. console.log("SDPs", mySdp, newSdp);
  12298. self.notifyMySSRCUpdate(mySdp, newSdp);
  12299. });
  12300. };
  12301. JingleSession.prototype._modifySources = function (successCallback, queueCallback) {
  12302. var self = this;
  12303. if (this.peerconnection.signalingState == 'closed') return;
  12304. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  12305. // There is nothing to do since scheduled job might have been executed by another succeeding call
  12306. this.setLocalDescription();
  12307. if(successCallback){
  12308. successCallback();
  12309. }
  12310. queueCallback();
  12311. return;
  12312. }
  12313. // Reset switch streams flag
  12314. this.switchstreams = false;
  12315. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12316. // add sources
  12317. this.addssrc.forEach(function(lines, idx) {
  12318. sdp.media[idx] += lines;
  12319. });
  12320. this.addssrc = [];
  12321. // remove sources
  12322. this.removessrc.forEach(function(lines, idx) {
  12323. lines = lines.split('\r\n');
  12324. lines.pop(); // remove empty last element;
  12325. lines.forEach(function(line) {
  12326. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  12327. });
  12328. });
  12329. this.removessrc = [];
  12330. sdp.raw = sdp.session + sdp.media.join('');
  12331. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  12332. function() {
  12333. if(self.signalingState == 'closed') {
  12334. console.error("createAnswer attempt on closed state");
  12335. queueCallback("createAnswer attempt on closed state");
  12336. return;
  12337. }
  12338. self.peerconnection.createAnswer(
  12339. function(modifiedAnswer) {
  12340. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  12341. if (self.pendingop !== null) {
  12342. var sdp = new SDP(modifiedAnswer.sdp);
  12343. if (sdp.media.length > 1) {
  12344. switch(self.pendingop) {
  12345. case 'mute':
  12346. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  12347. break;
  12348. case 'unmute':
  12349. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  12350. break;
  12351. }
  12352. sdp.raw = sdp.session + sdp.media.join('');
  12353. modifiedAnswer.sdp = sdp.raw;
  12354. }
  12355. self.pendingop = null;
  12356. }
  12357. // FIXME: pushing down an answer while ice connection state
  12358. // is still checking is bad...
  12359. //console.log(self.peerconnection.iceConnectionState);
  12360. // trying to work around another chrome bug
  12361. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  12362. self.peerconnection.setLocalDescription(modifiedAnswer,
  12363. function() {
  12364. //console.log('modified setLocalDescription ok');
  12365. self.setLocalDescription();
  12366. if(successCallback){
  12367. successCallback();
  12368. }
  12369. queueCallback();
  12370. },
  12371. function(error) {
  12372. console.error('modified setLocalDescription failed', error);
  12373. queueCallback(error);
  12374. }
  12375. );
  12376. },
  12377. function(error) {
  12378. console.error('modified answer failed', error);
  12379. queueCallback(error);
  12380. }
  12381. );
  12382. },
  12383. function(error) {
  12384. console.error('modify failed', error);
  12385. queueCallback(error);
  12386. }
  12387. );
  12388. };
  12389. /**
  12390. * Switches video streams.
  12391. * @param new_stream new stream that will be used as video of this session.
  12392. * @param oldStream old video stream of this session.
  12393. * @param success_callback callback executed after successful stream switch.
  12394. */
  12395. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback, isAudio) {
  12396. var self = this;
  12397. // Remember SDP to figure out added/removed SSRCs
  12398. var oldSdp = null;
  12399. if(self.peerconnection) {
  12400. if(self.peerconnection.localDescription) {
  12401. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  12402. }
  12403. self.peerconnection.removeStream(oldStream, true);
  12404. if(new_stream)
  12405. self.peerconnection.addStream(new_stream);
  12406. }
  12407. // Conference is not active
  12408. if(!oldSdp || !self.peerconnection) {
  12409. success_callback();
  12410. return;
  12411. }
  12412. self.switchstreams = true;
  12413. self.modifySourcesQueue.push(function() {
  12414. console.log('modify sources done');
  12415. success_callback();
  12416. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12417. console.log("SDPs", oldSdp, newSdp);
  12418. self.notifyMySSRCUpdate(oldSdp, newSdp);
  12419. });
  12420. };
  12421. /**
  12422. * Figures out added/removed ssrcs and send update IQs.
  12423. * @param old_sdp SDP object for old description.
  12424. * @param new_sdp SDP object for new description.
  12425. */
  12426. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  12427. if (!(this.peerconnection.signalingState == 'stable' &&
  12428. this.peerconnection.iceConnectionState == 'connected')){
  12429. console.log("Too early to send updates");
  12430. return;
  12431. }
  12432. // send source-remove IQ.
  12433. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  12434. var remove = $iq({to: this.peerjid, type: 'set'})
  12435. .c('jingle', {
  12436. xmlns: 'urn:xmpp:jingle:1',
  12437. action: 'source-remove',
  12438. initiator: this.initiator,
  12439. sid: this.sid
  12440. }
  12441. );
  12442. var removed = sdpDiffer.toJingle(remove);
  12443. if (removed) {
  12444. this.connection.sendIQ(remove,
  12445. function (res) {
  12446. console.info('got remove result', res);
  12447. },
  12448. function (err) {
  12449. console.error('got remove error', err);
  12450. }
  12451. );
  12452. } else {
  12453. console.log('removal not necessary');
  12454. }
  12455. // send source-add IQ.
  12456. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  12457. var add = $iq({to: this.peerjid, type: 'set'})
  12458. .c('jingle', {
  12459. xmlns: 'urn:xmpp:jingle:1',
  12460. action: 'source-add',
  12461. initiator: this.initiator,
  12462. sid: this.sid
  12463. }
  12464. );
  12465. var added = sdpDiffer.toJingle(add, this.getVideoType());
  12466. if (added) {
  12467. this.connection.sendIQ(add,
  12468. function (res) {
  12469. console.info('got add result', res);
  12470. },
  12471. function (err) {
  12472. console.error('got add error', err);
  12473. }
  12474. );
  12475. } else {
  12476. console.log('addition not necessary');
  12477. }
  12478. };
  12479. /**
  12480. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  12481. *
  12482. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  12483. * tracks; otherwise, <tt>false</tt>
  12484. * @param callback a function to be invoked with <tt>mute</tt> after all video
  12485. * tracks have been enabled/disabled. The function may, optionally, return
  12486. * another function which is to be invoked after the whole mute/unmute operation
  12487. * has completed successfully.
  12488. * @param options an object which specifies optional arguments such as the
  12489. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  12490. * specifies whether the method was initiated in response to a user command (in
  12491. * contrast to an automatic decision made by the application logic)
  12492. */
  12493. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  12494. var byUser;
  12495. if (options) {
  12496. byUser = options.byUser;
  12497. if (typeof byUser === 'undefined') {
  12498. byUser = true;
  12499. }
  12500. } else {
  12501. byUser = true;
  12502. }
  12503. // The user's command to mute the (local) video takes precedence over any
  12504. // automatic decision made by the application logic.
  12505. if (byUser) {
  12506. this.videoMuteByUser = mute;
  12507. } else if (this.videoMuteByUser) {
  12508. return;
  12509. }
  12510. this.hardMuteVideo(mute);
  12511. var self = this;
  12512. var oldSdp = null;
  12513. if(self.peerconnection) {
  12514. if(self.peerconnection.localDescription) {
  12515. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  12516. }
  12517. }
  12518. this.modifySourcesQueue.push(function() {
  12519. console.log('modify sources done');
  12520. callback(mute);
  12521. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12522. console.log("SDPs", oldSdp, newSdp);
  12523. self.notifyMySSRCUpdate(oldSdp, newSdp);
  12524. });
  12525. };
  12526. JingleSession.prototype.hardMuteVideo = function (muted) {
  12527. this.pendingop = muted ? 'mute' : 'unmute';
  12528. };
  12529. JingleSession.prototype.sendMute = function (muted, content) {
  12530. var info = $iq({to: this.peerjid,
  12531. type: 'set'})
  12532. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12533. action: 'session-info',
  12534. initiator: this.initiator,
  12535. sid: this.sid });
  12536. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  12537. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  12538. if (content) {
  12539. info.attrs({'name': content});
  12540. }
  12541. this.connection.send(info);
  12542. };
  12543. JingleSession.prototype.sendRinging = function () {
  12544. var info = $iq({to: this.peerjid,
  12545. type: 'set'})
  12546. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12547. action: 'session-info',
  12548. initiator: this.initiator,
  12549. sid: this.sid });
  12550. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  12551. this.connection.send(info);
  12552. };
  12553. JingleSession.prototype.getStats = function (interval) {
  12554. var self = this;
  12555. var recv = {audio: 0, video: 0};
  12556. var lost = {audio: 0, video: 0};
  12557. var lastrecv = {audio: 0, video: 0};
  12558. var lastlost = {audio: 0, video: 0};
  12559. var loss = {audio: 0, video: 0};
  12560. var delta = {audio: 0, video: 0};
  12561. this.statsinterval = window.setInterval(function () {
  12562. if (self && self.peerconnection && self.peerconnection.getStats) {
  12563. self.peerconnection.getStats(function (stats) {
  12564. var results = stats.result();
  12565. // TODO: there are so much statistics you can get from this..
  12566. for (var i = 0; i < results.length; ++i) {
  12567. if (results[i].type == 'ssrc') {
  12568. var packetsrecv = results[i].stat('packetsReceived');
  12569. var packetslost = results[i].stat('packetsLost');
  12570. if (packetsrecv && packetslost) {
  12571. packetsrecv = parseInt(packetsrecv, 10);
  12572. packetslost = parseInt(packetslost, 10);
  12573. if (results[i].stat('googFrameRateReceived')) {
  12574. lastlost.video = lost.video;
  12575. lastrecv.video = recv.video;
  12576. recv.video = packetsrecv;
  12577. lost.video = packetslost;
  12578. } else {
  12579. lastlost.audio = lost.audio;
  12580. lastrecv.audio = recv.audio;
  12581. recv.audio = packetsrecv;
  12582. lost.audio = packetslost;
  12583. }
  12584. }
  12585. }
  12586. }
  12587. delta.audio = recv.audio - lastrecv.audio;
  12588. delta.video = recv.video - lastrecv.video;
  12589. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  12590. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  12591. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  12592. });
  12593. }
  12594. }, interval || 3000);
  12595. return this.statsinterval;
  12596. };
  12597. JingleSession.onJingleError = function (session, error)
  12598. {
  12599. console.error("Jingle error", error);
  12600. }
  12601. JingleSession.onJingleFatalError = function (session, error)
  12602. {
  12603. this.service.sessionTerminated = true;
  12604. this.connection.emuc.doLeave();
  12605. this.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12606. this.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  12607. }
  12608. JingleSession.prototype.setLocalDescription = function () {
  12609. var self = this;
  12610. var newssrcs = [];
  12611. var session = transform.parse(this.peerconnection.localDescription.sdp);
  12612. session.media.forEach(function (media) {
  12613. if (media.ssrcs != null && media.ssrcs.length > 0) {
  12614. // TODO(gp) maybe exclude FID streams?
  12615. media.ssrcs.forEach(function (ssrc) {
  12616. if (ssrc.attribute !== 'cname') {
  12617. return;
  12618. }
  12619. newssrcs.push({
  12620. 'ssrc': ssrc.id,
  12621. 'type': media.type
  12622. });
  12623. });
  12624. }
  12625. else if(self.localStreamsSSRC && self.localStreamsSSRC[media.type])
  12626. {
  12627. newssrcs.push({
  12628. 'ssrc': self.localStreamsSSRC[media.type],
  12629. 'type': media.type
  12630. });
  12631. }
  12632. });
  12633. console.log('new ssrcs', newssrcs);
  12634. // Bind us as local SSRCs owner
  12635. if (newssrcs.length > 0) {
  12636. for (var i = 1; i <= newssrcs.length; i ++) {
  12637. var ssrc = newssrcs[i-1].ssrc;
  12638. var myJid = self.connection.emuc.myroomjid;
  12639. self.ssrcOwners[ssrc] = myJid;
  12640. if (newssrcs[i-1].type === 'video'){
  12641. self.ssrcVideoTypes[ssrc] = self.getVideoType();
  12642. }
  12643. }
  12644. }
  12645. }
  12646. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  12647. function sendKeyframe(pc) {
  12648. console.log('sendkeyframe', pc.iceConnectionState);
  12649. if (pc.iceConnectionState !== 'connected') return; // safe...
  12650. var self = this;
  12651. pc.setRemoteDescription(
  12652. pc.remoteDescription,
  12653. function () {
  12654. pc.createAnswer(
  12655. function (modifiedAnswer) {
  12656. pc.setLocalDescription(
  12657. modifiedAnswer,
  12658. function () {
  12659. // noop
  12660. },
  12661. function (error) {
  12662. console.log('triggerKeyframe setLocalDescription failed', error);
  12663. eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  12664. }
  12665. );
  12666. },
  12667. function (error) {
  12668. console.log('triggerKeyframe createAnswer failed', error);
  12669. eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  12670. }
  12671. );
  12672. },
  12673. function (error) {
  12674. console.log('triggerKeyframe setRemoteDescription failed', error);
  12675. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  12676. }
  12677. );
  12678. }
  12679. JingleSession.prototype.remoteStreamAdded = function (data, times) {
  12680. var self = this;
  12681. var thessrc;
  12682. var streamId = APP.RTC.getStreamID(data.stream);
  12683. // look up an associated JID for a stream id
  12684. if (!streamId) {
  12685. console.error("No stream ID for", data.stream);
  12686. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  12687. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  12688. var ssrclines
  12689. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  12690. ssrclines = ssrclines.filter(function (line) {
  12691. // NOTE(gp) previously we filtered on the mslabel, but that property
  12692. // is not always present.
  12693. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  12694. if (RTCBrowserType.isTemasysPluginUsed()) {
  12695. return ((line.indexOf('mslabel:' + streamId) !== -1));
  12696. } else {
  12697. return ((line.indexOf('msid:' + streamId) !== -1));
  12698. }
  12699. });
  12700. if (ssrclines.length) {
  12701. thessrc = ssrclines[0].substring(7).split(' ')[0];
  12702. if (!self.ssrcOwners[thessrc]) {
  12703. console.error("No SSRC owner known for: " + thessrc);
  12704. return;
  12705. }
  12706. data.peerjid = self.ssrcOwners[thessrc];
  12707. data.videoType = self.ssrcVideoTypes[thessrc]
  12708. console.log('associated jid', self.ssrcOwners[thessrc],
  12709. thessrc, data.videoType);
  12710. } else {
  12711. console.error("No SSRC lines for ", streamId);
  12712. }
  12713. }
  12714. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  12715. var isVideo = data.stream.getVideoTracks().length > 0;
  12716. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  12717. if (isVideo &&
  12718. data.peerjid && this.peerjid === data.peerjid &&
  12719. data.stream.getVideoTracks().length === 0 &&
  12720. APP.RTC.localVideo.getTracks().length > 0) {
  12721. window.setTimeout(function () {
  12722. sendKeyframe(self.peerconnection);
  12723. }, 3000);
  12724. }
  12725. }
  12726. module.exports = JingleSession;
  12727. },{"../../service/xmpp/XMPPEvents":108,"../RTC/RTCBrowserType":8,"./SDP":54,"./SDPDiffer":55,"./SDPUtil":56,"./TraceablePeerConnection":57,"async":67,"sdp-transform":95}],54:[function(require,module,exports){
  12728. /* jshint -W117 */
  12729. var SDPUtil = require("./SDPUtil");
  12730. // SDP STUFF
  12731. function SDP(sdp) {
  12732. this.media = sdp.split('\r\nm=');
  12733. for (var i = 1; i < this.media.length; i++) {
  12734. this.media[i] = 'm=' + this.media[i];
  12735. if (i != this.media.length - 1) {
  12736. this.media[i] += '\r\n';
  12737. }
  12738. }
  12739. this.session = this.media.shift() + '\r\n';
  12740. this.raw = this.session + this.media.join('');
  12741. }
  12742. /**
  12743. * Returns map of MediaChannel mapped per channel idx.
  12744. */
  12745. SDP.prototype.getMediaSsrcMap = function() {
  12746. var self = this;
  12747. var media_ssrcs = {};
  12748. var tmp;
  12749. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  12750. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  12751. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  12752. var media = {
  12753. mediaindex: mediaindex,
  12754. mid: mid,
  12755. ssrcs: {},
  12756. ssrcGroups: []
  12757. };
  12758. media_ssrcs[mediaindex] = media;
  12759. tmp.forEach(function (line) {
  12760. var linessrc = line.substring(7).split(' ')[0];
  12761. // allocate new ChannelSsrc
  12762. if(!media.ssrcs[linessrc]) {
  12763. media.ssrcs[linessrc] = {
  12764. ssrc: linessrc,
  12765. lines: []
  12766. };
  12767. }
  12768. media.ssrcs[linessrc].lines.push(line);
  12769. });
  12770. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  12771. tmp.forEach(function(line){
  12772. var semantics = line.substr(0, idx).substr(13);
  12773. var ssrcs = line.substr(14 + semantics.length).split(' ');
  12774. if (ssrcs.length != 0) {
  12775. media.ssrcGroups.push({
  12776. semantics: semantics,
  12777. ssrcs: ssrcs
  12778. });
  12779. }
  12780. });
  12781. }
  12782. return media_ssrcs;
  12783. };
  12784. /**
  12785. * Returns <tt>true</tt> if this SDP contains given SSRC.
  12786. * @param ssrc the ssrc to check.
  12787. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  12788. */
  12789. SDP.prototype.containsSSRC = function(ssrc) {
  12790. var medias = this.getMediaSsrcMap();
  12791. var contains = false;
  12792. Object.keys(medias).forEach(function(mediaindex){
  12793. var media = medias[mediaindex];
  12794. //console.log("Check", channel, ssrc);
  12795. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  12796. contains = true;
  12797. }
  12798. });
  12799. return contains;
  12800. };
  12801. // remove iSAC and CN from SDP
  12802. SDP.prototype.mangle = function () {
  12803. var i, j, mline, lines, rtpmap, newdesc;
  12804. for (i = 0; i < this.media.length; i++) {
  12805. lines = this.media[i].split('\r\n');
  12806. lines.pop(); // remove empty last element
  12807. mline = SDPUtil.parse_mline(lines.shift());
  12808. if (mline.media != 'audio')
  12809. continue;
  12810. newdesc = '';
  12811. mline.fmt.length = 0;
  12812. for (j = 0; j < lines.length; j++) {
  12813. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  12814. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  12815. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  12816. continue;
  12817. mline.fmt.push(rtpmap.id);
  12818. newdesc += lines[j] + '\r\n';
  12819. } else {
  12820. newdesc += lines[j] + '\r\n';
  12821. }
  12822. }
  12823. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  12824. this.media[i] += newdesc;
  12825. }
  12826. this.raw = this.session + this.media.join('');
  12827. };
  12828. // remove lines matching prefix from session section
  12829. SDP.prototype.removeSessionLines = function(prefix) {
  12830. var self = this;
  12831. var lines = SDPUtil.find_lines(this.session, prefix);
  12832. lines.forEach(function(line) {
  12833. self.session = self.session.replace(line + '\r\n', '');
  12834. });
  12835. this.raw = this.session + this.media.join('');
  12836. return lines;
  12837. }
  12838. // remove lines matching prefix from a media section specified by mediaindex
  12839. // TODO: non-numeric mediaindex could match mid
  12840. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  12841. var self = this;
  12842. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  12843. lines.forEach(function(line) {
  12844. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  12845. });
  12846. this.raw = this.session + this.media.join('');
  12847. return lines;
  12848. }
  12849. // add content's to a jingle element
  12850. SDP.prototype.toJingle = function (elem, thecreator, ssrcs, videoType) {
  12851. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  12852. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  12853. var self = this;
  12854. // new bundle plan
  12855. if (SDPUtil.find_line(this.session, 'a=group:')) {
  12856. lines = SDPUtil.find_lines(this.session, 'a=group:');
  12857. for (i = 0; i < lines.length; i++) {
  12858. tmp = lines[i].split(' ');
  12859. var semantics = tmp.shift().substr(8);
  12860. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  12861. for (j = 0; j < tmp.length; j++) {
  12862. elem.c('content', {name: tmp[j]}).up();
  12863. }
  12864. elem.up();
  12865. }
  12866. }
  12867. for (i = 0; i < this.media.length; i++) {
  12868. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  12869. if (!(mline.media === 'audio' ||
  12870. mline.media === 'video' ||
  12871. mline.media === 'application'))
  12872. {
  12873. continue;
  12874. }
  12875. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  12876. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  12877. } else {
  12878. if(ssrcs && ssrcs[mline.media])
  12879. {
  12880. ssrc = ssrcs[mline.media];
  12881. }
  12882. else
  12883. ssrc = false;
  12884. }
  12885. elem.c('content', {creator: thecreator, name: mline.media});
  12886. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  12887. // prefer identifier from a=mid if present
  12888. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  12889. elem.attrs({ name: mid });
  12890. }
  12891. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  12892. {
  12893. elem.c('description',
  12894. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  12895. media: mline.media });
  12896. if (ssrc) {
  12897. elem.attrs({ssrc: ssrc});
  12898. }
  12899. for (j = 0; j < mline.fmt.length; j++) {
  12900. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  12901. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  12902. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  12903. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  12904. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  12905. for (k = 0; k < tmp.length; k++) {
  12906. elem.c('parameter', tmp[k]).up();
  12907. }
  12908. }
  12909. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  12910. elem.up();
  12911. }
  12912. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  12913. elem.c('encryption', {required: 1});
  12914. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  12915. crypto.forEach(function(line) {
  12916. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  12917. });
  12918. elem.up(); // end of encryption
  12919. }
  12920. if (ssrc) {
  12921. // new style mapping
  12922. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12923. // FIXME: group by ssrc and support multiple different ssrcs
  12924. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  12925. if(ssrclines.length > 0) {
  12926. ssrclines.forEach(function (line) {
  12927. idx = line.indexOf(' ');
  12928. var linessrc = line.substr(0, idx).substr(7);
  12929. if (linessrc != ssrc) {
  12930. elem.up();
  12931. ssrc = linessrc;
  12932. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12933. }
  12934. var kv = line.substr(idx + 1);
  12935. elem.c('parameter');
  12936. if (kv.indexOf(':') == -1) {
  12937. elem.attrs({ name: kv });
  12938. } else {
  12939. var k = kv.split(':', 2)[0];
  12940. elem.attrs({ name: k });
  12941. var v = kv.split(':', 2)[1];
  12942. v = SDPUtil.filter_special_chars(v);
  12943. elem.attrs({ value: v });
  12944. }
  12945. elem.up();
  12946. });
  12947. }
  12948. else
  12949. {
  12950. elem.up();
  12951. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12952. elem.c('parameter');
  12953. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  12954. elem.up();
  12955. var msid = null;
  12956. if(mline.media == "audio")
  12957. {
  12958. msid = APP.RTC.localAudio.getId();
  12959. }
  12960. else
  12961. {
  12962. msid = APP.RTC.localVideo.getId();
  12963. }
  12964. if(msid != null)
  12965. {
  12966. msid = SDPUtil.filter_special_chars(msid);
  12967. elem.c('parameter');
  12968. elem.attrs({name: "msid", value:msid});
  12969. elem.up();
  12970. elem.c('parameter');
  12971. elem.attrs({name: "mslabel", value:msid});
  12972. elem.up();
  12973. elem.c('parameter');
  12974. elem.attrs({name: "label", value:msid});
  12975. elem.up();
  12976. }
  12977. }
  12978. // Video type
  12979. if (videoType && mline.media == "video") {
  12980. elem.c('ssrc-info',
  12981. {
  12982. xmlns: 'http://jitsi.org/jitmeet',
  12983. 'video-type': videoType
  12984. }).up();
  12985. }
  12986. elem.up();
  12987. // XEP-0339 handle ssrc-group attributes
  12988. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  12989. ssrc_group_lines.forEach(function(line) {
  12990. idx = line.indexOf(' ');
  12991. var semantics = line.substr(0, idx).substr(13);
  12992. var ssrcs = line.substr(14 + semantics.length).split(' ');
  12993. if (ssrcs.length != 0) {
  12994. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12995. ssrcs.forEach(function(ssrc) {
  12996. elem.c('source', { ssrc: ssrc })
  12997. .up();
  12998. });
  12999. elem.up();
  13000. }
  13001. });
  13002. }
  13003. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  13004. elem.c('rtcp-mux').up();
  13005. }
  13006. // XEP-0293 -- map a=rtcp-fb:*
  13007. this.RtcpFbToJingle(i, elem, '*');
  13008. // XEP-0294
  13009. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  13010. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  13011. for (j = 0; j < lines.length; j++) {
  13012. tmp = SDPUtil.parse_extmap(lines[j]);
  13013. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  13014. uri: tmp.uri,
  13015. id: tmp.value });
  13016. if (tmp.hasOwnProperty('direction')) {
  13017. switch (tmp.direction) {
  13018. case 'sendonly':
  13019. elem.attrs({senders: 'responder'});
  13020. break;
  13021. case 'recvonly':
  13022. elem.attrs({senders: 'initiator'});
  13023. break;
  13024. case 'sendrecv':
  13025. elem.attrs({senders: 'both'});
  13026. break;
  13027. case 'inactive':
  13028. elem.attrs({senders: 'none'});
  13029. break;
  13030. }
  13031. }
  13032. // TODO: handle params
  13033. elem.up();
  13034. }
  13035. }
  13036. elem.up(); // end of description
  13037. }
  13038. // map ice-ufrag/pwd, dtls fingerprint, candidates
  13039. this.TransportToJingle(i, elem);
  13040. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  13041. elem.attrs({senders: 'both'});
  13042. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  13043. elem.attrs({senders: 'initiator'});
  13044. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  13045. elem.attrs({senders: 'responder'});
  13046. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  13047. elem.attrs({senders: 'none'});
  13048. }
  13049. if (mline.port == '0') {
  13050. // estos hack to reject an m-line
  13051. elem.attrs({senders: 'rejected'});
  13052. }
  13053. elem.up(); // end of content
  13054. }
  13055. elem.up();
  13056. return elem;
  13057. };
  13058. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  13059. var i = mediaindex;
  13060. var tmp;
  13061. var self = this;
  13062. elem.c('transport');
  13063. // XEP-0343 DTLS/SCTP
  13064. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  13065. {
  13066. var sctpmap = SDPUtil.find_line(
  13067. this.media[i], 'a=sctpmap:', self.session);
  13068. if (sctpmap)
  13069. {
  13070. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  13071. elem.c('sctpmap',
  13072. {
  13073. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  13074. number: sctpAttrs[0], /* SCTP port */
  13075. protocol: sctpAttrs[1], /* protocol */
  13076. });
  13077. // Optional stream count attribute
  13078. if (sctpAttrs.length > 2)
  13079. elem.attrs({ streams: sctpAttrs[2]});
  13080. elem.up();
  13081. }
  13082. }
  13083. // XEP-0320
  13084. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  13085. fingerprints.forEach(function(line) {
  13086. tmp = SDPUtil.parse_fingerprint(line);
  13087. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  13088. elem.c('fingerprint').t(tmp.fingerprint);
  13089. delete tmp.fingerprint;
  13090. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  13091. if (line) {
  13092. tmp.setup = line.substr(8);
  13093. }
  13094. elem.attrs(tmp);
  13095. elem.up(); // end of fingerprint
  13096. });
  13097. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  13098. if (tmp) {
  13099. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  13100. elem.attrs(tmp);
  13101. // XEP-0176
  13102. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  13103. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  13104. lines.forEach(function (line) {
  13105. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  13106. });
  13107. }
  13108. }
  13109. elem.up(); // end of transport
  13110. }
  13111. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  13112. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  13113. lines.forEach(function (line) {
  13114. var tmp = SDPUtil.parse_rtcpfb(line);
  13115. if (tmp.type == 'trr-int') {
  13116. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  13117. elem.up();
  13118. } else {
  13119. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  13120. if (tmp.params.length > 0) {
  13121. elem.attrs({'subtype': tmp.params[0]});
  13122. }
  13123. elem.up();
  13124. }
  13125. });
  13126. };
  13127. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  13128. var media = '';
  13129. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  13130. if (tmp.length) {
  13131. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  13132. if (tmp.attr('value')) {
  13133. media += tmp.attr('value');
  13134. } else {
  13135. media += '0';
  13136. }
  13137. media += '\r\n';
  13138. }
  13139. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  13140. tmp.each(function () {
  13141. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  13142. if ($(this).attr('subtype')) {
  13143. media += ' ' + $(this).attr('subtype');
  13144. }
  13145. media += '\r\n';
  13146. });
  13147. return media;
  13148. };
  13149. // construct an SDP from a jingle stanza
  13150. SDP.prototype.fromJingle = function (jingle) {
  13151. var self = this;
  13152. this.raw = 'v=0\r\n' +
  13153. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  13154. 's=-\r\n' +
  13155. 't=0 0\r\n';
  13156. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  13157. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  13158. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  13159. var contents = $(group).find('>content').map(function (idx, content) {
  13160. return content.getAttribute('name');
  13161. }).get();
  13162. if (contents.length > 0) {
  13163. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  13164. }
  13165. });
  13166. }
  13167. this.session = this.raw;
  13168. jingle.find('>content').each(function () {
  13169. var m = self.jingle2media($(this));
  13170. self.media.push(m);
  13171. });
  13172. // reconstruct msid-semantic -- apparently not necessary
  13173. /*
  13174. var msid = SDPUtil.parse_ssrc(this.raw);
  13175. if (msid.hasOwnProperty('mslabel')) {
  13176. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  13177. }
  13178. */
  13179. this.raw = this.session + this.media.join('');
  13180. };
  13181. // translate a jingle content element into an an SDP media part
  13182. SDP.prototype.jingle2media = function (content) {
  13183. var media = '',
  13184. desc = content.find('description'),
  13185. ssrc = desc.attr('ssrc'),
  13186. self = this,
  13187. tmp;
  13188. var sctp = content.find(
  13189. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  13190. tmp = { media: desc.attr('media') };
  13191. tmp.port = '1';
  13192. if (content.attr('senders') == 'rejected') {
  13193. // estos hack to reject an m-line.
  13194. tmp.port = '0';
  13195. }
  13196. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  13197. if (sctp.length)
  13198. tmp.proto = 'DTLS/SCTP';
  13199. else
  13200. tmp.proto = 'RTP/SAVPF';
  13201. } else {
  13202. tmp.proto = 'RTP/AVPF';
  13203. }
  13204. if (!sctp.length)
  13205. {
  13206. tmp.fmt = desc.find('payload-type').map(
  13207. function () { return this.getAttribute('id'); }).get();
  13208. media += SDPUtil.build_mline(tmp) + '\r\n';
  13209. }
  13210. else
  13211. {
  13212. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  13213. media += 'a=sctpmap:' + sctp.attr('number') +
  13214. ' ' + sctp.attr('protocol');
  13215. var streamCount = sctp.attr('streams');
  13216. if (streamCount)
  13217. media += ' ' + streamCount + '\r\n';
  13218. else
  13219. media += '\r\n';
  13220. }
  13221. media += 'c=IN IP4 0.0.0.0\r\n';
  13222. if (!sctp.length)
  13223. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  13224. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  13225. if (tmp.length) {
  13226. if (tmp.attr('ufrag')) {
  13227. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  13228. }
  13229. if (tmp.attr('pwd')) {
  13230. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  13231. }
  13232. tmp.find('>fingerprint').each(function () {
  13233. // FIXME: check namespace at some point
  13234. media += 'a=fingerprint:' + this.getAttribute('hash');
  13235. media += ' ' + $(this).text();
  13236. media += '\r\n';
  13237. if (this.getAttribute('setup')) {
  13238. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  13239. }
  13240. });
  13241. }
  13242. switch (content.attr('senders')) {
  13243. case 'initiator':
  13244. media += 'a=sendonly\r\n';
  13245. break;
  13246. case 'responder':
  13247. media += 'a=recvonly\r\n';
  13248. break;
  13249. case 'none':
  13250. media += 'a=inactive\r\n';
  13251. break;
  13252. case 'both':
  13253. media += 'a=sendrecv\r\n';
  13254. break;
  13255. }
  13256. media += 'a=mid:' + content.attr('name') + '\r\n';
  13257. // <description><rtcp-mux/></description>
  13258. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  13259. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  13260. if (desc.find('rtcp-mux').length) {
  13261. media += 'a=rtcp-mux\r\n';
  13262. }
  13263. if (desc.find('encryption').length) {
  13264. desc.find('encryption>crypto').each(function () {
  13265. media += 'a=crypto:' + this.getAttribute('tag');
  13266. media += ' ' + this.getAttribute('crypto-suite');
  13267. media += ' ' + this.getAttribute('key-params');
  13268. if (this.getAttribute('session-params')) {
  13269. media += ' ' + this.getAttribute('session-params');
  13270. }
  13271. media += '\r\n';
  13272. });
  13273. }
  13274. desc.find('payload-type').each(function () {
  13275. media += SDPUtil.build_rtpmap(this) + '\r\n';
  13276. if ($(this).find('>parameter').length) {
  13277. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  13278. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  13279. media += '\r\n';
  13280. }
  13281. // xep-0293
  13282. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  13283. });
  13284. // xep-0293
  13285. media += self.RtcpFbFromJingle(desc, '*');
  13286. // xep-0294
  13287. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  13288. tmp.each(function () {
  13289. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  13290. });
  13291. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  13292. media += SDPUtil.candidateFromJingle(this);
  13293. });
  13294. // XEP-0339 handle ssrc-group attributes
  13295. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  13296. var semantics = this.getAttribute('semantics');
  13297. var ssrcs = $(this).find('>source').map(function() {
  13298. return this.getAttribute('ssrc');
  13299. }).get();
  13300. if (ssrcs.length != 0) {
  13301. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  13302. }
  13303. });
  13304. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  13305. tmp.each(function () {
  13306. var ssrc = this.getAttribute('ssrc');
  13307. $(this).find('>parameter').each(function () {
  13308. var name = this.getAttribute('name');
  13309. var value = this.getAttribute('value');
  13310. value = SDPUtil.filter_special_chars(value);
  13311. media += 'a=ssrc:' + ssrc + ' ' + name;
  13312. if (value && value.length)
  13313. media += ':' + value;
  13314. media += '\r\n';
  13315. });
  13316. });
  13317. return media;
  13318. };
  13319. module.exports = SDP;
  13320. },{"./SDPUtil":56}],55:[function(require,module,exports){
  13321. var SDPUtil = require("./SDPUtil");
  13322. function SDPDiffer(mySDP, otherSDP) {
  13323. this.mySDP = mySDP;
  13324. this.otherSDP = otherSDP;
  13325. }
  13326. /**
  13327. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  13328. * @param otherSdp the other SDP to check ssrc with.
  13329. */
  13330. SDPDiffer.prototype.getNewMedia = function() {
  13331. // this could be useful in Array.prototype.
  13332. function arrayEquals(array) {
  13333. // if the other array is a falsy value, return
  13334. if (!array)
  13335. return false;
  13336. // compare lengths - can save a lot of time
  13337. if (this.length != array.length)
  13338. return false;
  13339. for (var i = 0, l=this.length; i < l; i++) {
  13340. // Check if we have nested arrays
  13341. if (this[i] instanceof Array && array[i] instanceof Array) {
  13342. // recurse into the nested arrays
  13343. if (!this[i].equals(array[i]))
  13344. return false;
  13345. }
  13346. else if (this[i] != array[i]) {
  13347. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  13348. return false;
  13349. }
  13350. }
  13351. return true;
  13352. }
  13353. var myMedias = this.mySDP.getMediaSsrcMap();
  13354. var othersMedias = this.otherSDP.getMediaSsrcMap();
  13355. var newMedia = {};
  13356. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  13357. var myMedia = myMedias[othersMediaIdx];
  13358. var othersMedia = othersMedias[othersMediaIdx];
  13359. if(!myMedia && othersMedia) {
  13360. // Add whole channel
  13361. newMedia[othersMediaIdx] = othersMedia;
  13362. return;
  13363. }
  13364. // Look for new ssrcs accross the channel
  13365. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  13366. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  13367. // Allocate channel if we've found ssrc that doesn't exist in our channel
  13368. if(!newMedia[othersMediaIdx]){
  13369. newMedia[othersMediaIdx] = {
  13370. mediaindex: othersMedia.mediaindex,
  13371. mid: othersMedia.mid,
  13372. ssrcs: {},
  13373. ssrcGroups: []
  13374. };
  13375. }
  13376. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  13377. }
  13378. });
  13379. // Look for new ssrc groups across the channels
  13380. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  13381. // try to match the other ssrc-group with an ssrc-group of ours
  13382. var matched = false;
  13383. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  13384. var mySsrcGroup = myMedia.ssrcGroups[i];
  13385. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  13386. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  13387. matched = true;
  13388. break;
  13389. }
  13390. }
  13391. if (!matched) {
  13392. // Allocate channel if we've found an ssrc-group that doesn't
  13393. // exist in our channel
  13394. if(!newMedia[othersMediaIdx]){
  13395. newMedia[othersMediaIdx] = {
  13396. mediaindex: othersMedia.mediaindex,
  13397. mid: othersMedia.mid,
  13398. ssrcs: {},
  13399. ssrcGroups: []
  13400. };
  13401. }
  13402. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  13403. }
  13404. });
  13405. });
  13406. return newMedia;
  13407. };
  13408. /**
  13409. * Sends SSRC update IQ.
  13410. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  13411. * @param sid session identifier that will be put into the IQ.
  13412. * @param initiator initiator identifier.
  13413. * @param toJid destination Jid
  13414. * @param isAdd indicates if this is remove or add operation.
  13415. */
  13416. SDPDiffer.prototype.toJingle = function(modify, videoType) {
  13417. var sdpMediaSsrcs = this.getNewMedia();
  13418. var self = this;
  13419. // FIXME: only announce video ssrcs since we mix audio and dont need
  13420. // the audio ssrcs therefore
  13421. var modified = false;
  13422. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  13423. modified = true;
  13424. var media = sdpMediaSsrcs[mediaindex];
  13425. modify.c('content', {name: media.mid});
  13426. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  13427. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  13428. // generate sources from lines
  13429. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  13430. var mediaSsrc = media.ssrcs[ssrcNum];
  13431. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13432. modify.attrs({ssrc: mediaSsrc.ssrc});
  13433. // iterate over ssrc lines
  13434. mediaSsrc.lines.forEach(function (line) {
  13435. var idx = line.indexOf(' ');
  13436. var kv = line.substr(idx + 1);
  13437. modify.c('parameter');
  13438. if (kv.indexOf(':') == -1) {
  13439. modify.attrs({ name: kv });
  13440. } else {
  13441. var nv = kv.split(':', 2);
  13442. var name = nv[0];
  13443. var value = SDPUtil.filter_special_chars(nv[1]);
  13444. modify.attrs({ name: name });
  13445. modify.attrs({ value: value });
  13446. }
  13447. modify.up(); // end of parameter
  13448. });
  13449. // indicate video type
  13450. if (videoType && media.mid == 'video') {
  13451. modify.c('ssrc-info',
  13452. {
  13453. xmlns: 'http://jitsi.org/jitmeet',
  13454. 'video-type': videoType
  13455. })
  13456. .up();
  13457. }
  13458. modify.up(); // end of source
  13459. });
  13460. // generate source groups from lines
  13461. media.ssrcGroups.forEach(function(ssrcGroup) {
  13462. if (ssrcGroup.ssrcs.length != 0) {
  13463. modify.c('ssrc-group', {
  13464. semantics: ssrcGroup.semantics,
  13465. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  13466. });
  13467. ssrcGroup.ssrcs.forEach(function (ssrc) {
  13468. modify.c('source', { ssrc: ssrc })
  13469. .up(); // end of source
  13470. });
  13471. modify.up(); // end of ssrc-group
  13472. }
  13473. });
  13474. modify.up(); // end of description
  13475. modify.up(); // end of content
  13476. });
  13477. return modified;
  13478. };
  13479. module.exports = SDPDiffer;
  13480. },{"./SDPUtil":56}],56:[function(require,module,exports){
  13481. SDPUtil = {
  13482. filter_special_chars: function (text) {
  13483. return text.replace(/[\\\/\{,\}\+]/g, "");
  13484. },
  13485. iceparams: function (mediadesc, sessiondesc) {
  13486. var data = null;
  13487. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  13488. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  13489. data = {
  13490. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  13491. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  13492. };
  13493. }
  13494. return data;
  13495. },
  13496. parse_iceufrag: function (line) {
  13497. return line.substring(12);
  13498. },
  13499. build_iceufrag: function (frag) {
  13500. return 'a=ice-ufrag:' + frag;
  13501. },
  13502. parse_icepwd: function (line) {
  13503. return line.substring(10);
  13504. },
  13505. build_icepwd: function (pwd) {
  13506. return 'a=ice-pwd:' + pwd;
  13507. },
  13508. parse_mid: function (line) {
  13509. return line.substring(6);
  13510. },
  13511. parse_mline: function (line) {
  13512. var parts = line.substring(2).split(' '),
  13513. data = {};
  13514. data.media = parts.shift();
  13515. data.port = parts.shift();
  13516. data.proto = parts.shift();
  13517. if (parts[parts.length - 1] === '') { // trailing whitespace
  13518. parts.pop();
  13519. }
  13520. data.fmt = parts;
  13521. return data;
  13522. },
  13523. build_mline: function (mline) {
  13524. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  13525. },
  13526. parse_rtpmap: function (line) {
  13527. var parts = line.substring(9).split(' '),
  13528. data = {};
  13529. data.id = parts.shift();
  13530. parts = parts[0].split('/');
  13531. data.name = parts.shift();
  13532. data.clockrate = parts.shift();
  13533. data.channels = parts.length ? parts.shift() : '1';
  13534. return data;
  13535. },
  13536. /**
  13537. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  13538. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  13539. * @returns [SCTP port number, protocol, streams]
  13540. */
  13541. parse_sctpmap: function (line)
  13542. {
  13543. var parts = line.substring(10).split(' ');
  13544. var sctpPort = parts[0];
  13545. var protocol = parts[1];
  13546. // Stream count is optional
  13547. var streamCount = parts.length > 2 ? parts[2] : null;
  13548. return [sctpPort, protocol, streamCount];// SCTP port
  13549. },
  13550. build_rtpmap: function (el) {
  13551. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  13552. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  13553. line += '/' + el.getAttribute('channels');
  13554. }
  13555. return line;
  13556. },
  13557. parse_crypto: function (line) {
  13558. var parts = line.substring(9).split(' '),
  13559. data = {};
  13560. data.tag = parts.shift();
  13561. data['crypto-suite'] = parts.shift();
  13562. data['key-params'] = parts.shift();
  13563. if (parts.length) {
  13564. data['session-params'] = parts.join(' ');
  13565. }
  13566. return data;
  13567. },
  13568. parse_fingerprint: function (line) { // RFC 4572
  13569. var parts = line.substring(14).split(' '),
  13570. data = {};
  13571. data.hash = parts.shift();
  13572. data.fingerprint = parts.shift();
  13573. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  13574. return data;
  13575. },
  13576. parse_fmtp: function (line) {
  13577. var parts = line.split(' '),
  13578. i, key, value,
  13579. data = [];
  13580. parts.shift();
  13581. parts = parts.join(' ').split(';');
  13582. for (i = 0; i < parts.length; i++) {
  13583. key = parts[i].split('=')[0];
  13584. while (key.length && key[0] == ' ') {
  13585. key = key.substring(1);
  13586. }
  13587. value = parts[i].split('=')[1];
  13588. if (key && value) {
  13589. data.push({name: key, value: value});
  13590. } else if (key) {
  13591. // rfc 4733 (DTMF) style stuff
  13592. data.push({name: '', value: key});
  13593. }
  13594. }
  13595. return data;
  13596. },
  13597. parse_icecandidate: function (line) {
  13598. var candidate = {},
  13599. elems = line.split(' ');
  13600. candidate.foundation = elems[0].substring(12);
  13601. candidate.component = elems[1];
  13602. candidate.protocol = elems[2].toLowerCase();
  13603. candidate.priority = elems[3];
  13604. candidate.ip = elems[4];
  13605. candidate.port = elems[5];
  13606. // elems[6] => "typ"
  13607. candidate.type = elems[7];
  13608. candidate.generation = 0; // default value, may be overwritten below
  13609. for (var i = 8; i < elems.length; i += 2) {
  13610. switch (elems[i]) {
  13611. case 'raddr':
  13612. candidate['rel-addr'] = elems[i + 1];
  13613. break;
  13614. case 'rport':
  13615. candidate['rel-port'] = elems[i + 1];
  13616. break;
  13617. case 'generation':
  13618. candidate.generation = elems[i + 1];
  13619. break;
  13620. case 'tcptype':
  13621. candidate.tcptype = elems[i + 1];
  13622. break;
  13623. default: // TODO
  13624. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  13625. }
  13626. }
  13627. candidate.network = '1';
  13628. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  13629. return candidate;
  13630. },
  13631. build_icecandidate: function (cand) {
  13632. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  13633. line += ' ';
  13634. switch (cand.type) {
  13635. case 'srflx':
  13636. case 'prflx':
  13637. case 'relay':
  13638. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  13639. line += 'raddr';
  13640. line += ' ';
  13641. line += cand['rel-addr'];
  13642. line += ' ';
  13643. line += 'rport';
  13644. line += ' ';
  13645. line += cand['rel-port'];
  13646. line += ' ';
  13647. }
  13648. break;
  13649. }
  13650. if (cand.hasOwnAttribute('tcptype')) {
  13651. line += 'tcptype';
  13652. line += ' ';
  13653. line += cand.tcptype;
  13654. line += ' ';
  13655. }
  13656. line += 'generation';
  13657. line += ' ';
  13658. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  13659. return line;
  13660. },
  13661. parse_ssrc: function (desc) {
  13662. // proprietary mapping of a=ssrc lines
  13663. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  13664. // and parse according to that
  13665. var lines = desc.split('\r\n'),
  13666. data = {};
  13667. for (var i = 0; i < lines.length; i++) {
  13668. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  13669. var idx = lines[i].indexOf(' ');
  13670. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  13671. }
  13672. }
  13673. return data;
  13674. },
  13675. parse_rtcpfb: function (line) {
  13676. var parts = line.substr(10).split(' ');
  13677. var data = {};
  13678. data.pt = parts.shift();
  13679. data.type = parts.shift();
  13680. data.params = parts;
  13681. return data;
  13682. },
  13683. parse_extmap: function (line) {
  13684. var parts = line.substr(9).split(' ');
  13685. var data = {};
  13686. data.value = parts.shift();
  13687. if (data.value.indexOf('/') != -1) {
  13688. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  13689. data.value = data.value.substr(0, data.value.indexOf('/'));
  13690. } else {
  13691. data.direction = 'both';
  13692. }
  13693. data.uri = parts.shift();
  13694. data.params = parts;
  13695. return data;
  13696. },
  13697. find_line: function (haystack, needle, sessionpart) {
  13698. var lines = haystack.split('\r\n');
  13699. for (var i = 0; i < lines.length; i++) {
  13700. if (lines[i].substring(0, needle.length) == needle) {
  13701. return lines[i];
  13702. }
  13703. }
  13704. if (!sessionpart) {
  13705. return false;
  13706. }
  13707. // search session part
  13708. lines = sessionpart.split('\r\n');
  13709. for (var j = 0; j < lines.length; j++) {
  13710. if (lines[j].substring(0, needle.length) == needle) {
  13711. return lines[j];
  13712. }
  13713. }
  13714. return false;
  13715. },
  13716. find_lines: function (haystack, needle, sessionpart) {
  13717. var lines = haystack.split('\r\n'),
  13718. needles = [];
  13719. for (var i = 0; i < lines.length; i++) {
  13720. if (lines[i].substring(0, needle.length) == needle)
  13721. needles.push(lines[i]);
  13722. }
  13723. if (needles.length || !sessionpart) {
  13724. return needles;
  13725. }
  13726. // search session part
  13727. lines = sessionpart.split('\r\n');
  13728. for (var j = 0; j < lines.length; j++) {
  13729. if (lines[j].substring(0, needle.length) == needle) {
  13730. needles.push(lines[j]);
  13731. }
  13732. }
  13733. return needles;
  13734. },
  13735. candidateToJingle: function (line) {
  13736. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  13737. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  13738. if (line.indexOf('candidate:') === 0) {
  13739. line = 'a=' + line;
  13740. } else if (line.substring(0, 12) != 'a=candidate:') {
  13741. console.log('parseCandidate called with a line that is not a candidate line');
  13742. console.log(line);
  13743. return null;
  13744. }
  13745. if (line.substring(line.length - 2) == '\r\n') // chomp it
  13746. line = line.substring(0, line.length - 2);
  13747. var candidate = {},
  13748. elems = line.split(' '),
  13749. i;
  13750. if (elems[6] != 'typ') {
  13751. console.log('did not find typ in the right place');
  13752. console.log(line);
  13753. return null;
  13754. }
  13755. candidate.foundation = elems[0].substring(12);
  13756. candidate.component = elems[1];
  13757. candidate.protocol = elems[2].toLowerCase();
  13758. candidate.priority = elems[3];
  13759. candidate.ip = elems[4];
  13760. candidate.port = elems[5];
  13761. // elems[6] => "typ"
  13762. candidate.type = elems[7];
  13763. candidate.generation = '0'; // default, may be overwritten below
  13764. for (i = 8; i < elems.length; i += 2) {
  13765. switch (elems[i]) {
  13766. case 'raddr':
  13767. candidate['rel-addr'] = elems[i + 1];
  13768. break;
  13769. case 'rport':
  13770. candidate['rel-port'] = elems[i + 1];
  13771. break;
  13772. case 'generation':
  13773. candidate.generation = elems[i + 1];
  13774. break;
  13775. case 'tcptype':
  13776. candidate.tcptype = elems[i + 1];
  13777. break;
  13778. default: // TODO
  13779. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  13780. }
  13781. }
  13782. candidate.network = '1';
  13783. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  13784. return candidate;
  13785. },
  13786. candidateFromJingle: function (cand) {
  13787. var line = 'a=candidate:';
  13788. line += cand.getAttribute('foundation');
  13789. line += ' ';
  13790. line += cand.getAttribute('component');
  13791. line += ' ';
  13792. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  13793. line += ' ';
  13794. line += cand.getAttribute('priority');
  13795. line += ' ';
  13796. line += cand.getAttribute('ip');
  13797. line += ' ';
  13798. line += cand.getAttribute('port');
  13799. line += ' ';
  13800. line += 'typ';
  13801. line += ' ' + cand.getAttribute('type');
  13802. line += ' ';
  13803. switch (cand.getAttribute('type')) {
  13804. case 'srflx':
  13805. case 'prflx':
  13806. case 'relay':
  13807. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  13808. line += 'raddr';
  13809. line += ' ';
  13810. line += cand.getAttribute('rel-addr');
  13811. line += ' ';
  13812. line += 'rport';
  13813. line += ' ';
  13814. line += cand.getAttribute('rel-port');
  13815. line += ' ';
  13816. }
  13817. break;
  13818. }
  13819. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  13820. line += 'tcptype';
  13821. line += ' ';
  13822. line += cand.getAttribute('tcptype');
  13823. line += ' ';
  13824. }
  13825. line += 'generation';
  13826. line += ' ';
  13827. line += cand.getAttribute('generation') || '0';
  13828. return line + '\r\n';
  13829. }
  13830. };
  13831. module.exports = SDPUtil;
  13832. },{}],57:[function(require,module,exports){
  13833. var RTC = require('../RTC/RTC');
  13834. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  13835. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13836. function TraceablePeerConnection(ice_config, constraints, session) {
  13837. var self = this;
  13838. var RTCPeerconnectionType = null;
  13839. if (RTCBrowserType.isFirefox()) {
  13840. RTCPeerconnectionType = mozRTCPeerConnection;
  13841. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  13842. RTCPeerconnectionType = RTCPeerConnection;
  13843. } else {
  13844. RTCPeerconnectionType = webkitRTCPeerConnection;
  13845. }
  13846. this.peerconnection = new RTCPeerconnectionType(ice_config, constraints);
  13847. this.updateLog = [];
  13848. this.stats = {};
  13849. this.statsinterval = null;
  13850. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  13851. var Interop = require('sdp-interop').Interop;
  13852. this.interop = new Interop();
  13853. var Simulcast = require('sdp-simulcast');
  13854. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  13855. // override as desired
  13856. this.trace = function (what, info) {
  13857. /*console.warn('WTRACE', what, info);
  13858. if (info && RTCBrowserType.isIExplorer()) {
  13859. if (info.length > 1024) {
  13860. console.warn('WTRACE', what, info.substr(1024));
  13861. }
  13862. if (info.length > 2048) {
  13863. console.warn('WTRACE', what, info.substr(2048));
  13864. }
  13865. }*/
  13866. self.updateLog.push({
  13867. time: new Date(),
  13868. type: what,
  13869. value: info || ""
  13870. });
  13871. };
  13872. this.onicecandidate = null;
  13873. this.peerconnection.onicecandidate = function (event) {
  13874. // FIXME: this causes stack overflow with Temasys Plugin
  13875. if (!RTCBrowserType.isTemasysPluginUsed())
  13876. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  13877. if (self.onicecandidate !== null) {
  13878. self.onicecandidate(event);
  13879. }
  13880. };
  13881. this.onaddstream = null;
  13882. this.peerconnection.onaddstream = function (event) {
  13883. self.trace('onaddstream', event.stream.id);
  13884. if (self.onaddstream !== null) {
  13885. self.onaddstream(event);
  13886. }
  13887. };
  13888. this.onremovestream = null;
  13889. this.peerconnection.onremovestream = function (event) {
  13890. self.trace('onremovestream', event.stream.id);
  13891. if (self.onremovestream !== null) {
  13892. self.onremovestream(event);
  13893. }
  13894. };
  13895. this.onsignalingstatechange = null;
  13896. this.peerconnection.onsignalingstatechange = function (event) {
  13897. self.trace('onsignalingstatechange', self.signalingState);
  13898. if (self.onsignalingstatechange !== null) {
  13899. self.onsignalingstatechange(event);
  13900. }
  13901. };
  13902. this.oniceconnectionstatechange = null;
  13903. this.peerconnection.oniceconnectionstatechange = function (event) {
  13904. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  13905. if (self.oniceconnectionstatechange !== null) {
  13906. self.oniceconnectionstatechange(event);
  13907. }
  13908. };
  13909. this.onnegotiationneeded = null;
  13910. this.peerconnection.onnegotiationneeded = function (event) {
  13911. self.trace('onnegotiationneeded');
  13912. if (self.onnegotiationneeded !== null) {
  13913. self.onnegotiationneeded(event);
  13914. }
  13915. };
  13916. self.ondatachannel = null;
  13917. this.peerconnection.ondatachannel = function (event) {
  13918. self.trace('ondatachannel', event);
  13919. if (self.ondatachannel !== null) {
  13920. self.ondatachannel(event);
  13921. }
  13922. };
  13923. // XXX: do all non-firefox browsers which we support also support this?
  13924. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  13925. this.statsinterval = window.setInterval(function() {
  13926. self.peerconnection.getStats(function(stats) {
  13927. var results = stats.result();
  13928. for (var i = 0; i < results.length; ++i) {
  13929. //console.log(results[i].type, results[i].id, results[i].names())
  13930. var now = new Date();
  13931. results[i].names().forEach(function (name) {
  13932. var id = results[i].id + '-' + name;
  13933. if (!self.stats[id]) {
  13934. self.stats[id] = {
  13935. startTime: now,
  13936. endTime: now,
  13937. values: [],
  13938. times: []
  13939. };
  13940. }
  13941. self.stats[id].values.push(results[i].stat(name));
  13942. self.stats[id].times.push(now.getTime());
  13943. if (self.stats[id].values.length > self.maxstats) {
  13944. self.stats[id].values.shift();
  13945. self.stats[id].times.shift();
  13946. }
  13947. self.stats[id].endTime = now;
  13948. });
  13949. }
  13950. });
  13951. }, 1000);
  13952. }
  13953. };
  13954. dumpSDP = function(description) {
  13955. if (typeof description === 'undefined' || description == null) {
  13956. return '';
  13957. }
  13958. return 'type: ' + description.type + '\r\n' + description.sdp;
  13959. };
  13960. /**
  13961. * Takes a SessionDescription object and returns a "normalized" version.
  13962. * Currently it only takes care of ordering the a=ssrc lines.
  13963. */
  13964. normalizePlanB = function(desc) {
  13965. if (typeof desc !== 'object' || desc === null ||
  13966. typeof desc.sdp !== 'string') {
  13967. console.warn('An empty description was passed as an argument.');
  13968. return desc;
  13969. }
  13970. var transform = require('sdp-transform');
  13971. var session = transform.parse(desc.sdp);
  13972. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  13973. Array.isArray(session.media)) {
  13974. session.media.forEach(function (mLine) {
  13975. // Chrome appears to be picky about the order in which a=ssrc lines
  13976. // are listed in an m-line when rtx is enabled (and thus there are
  13977. // a=ssrc-group lines with FID semantics). Specifically if we have
  13978. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  13979. // the "a=ssrc:S1" lines, SRD fails.
  13980. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  13981. // first.
  13982. var firstSsrcs = [];
  13983. var newSsrcLines = [];
  13984. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  13985. mLine.ssrcGroups.forEach(function (group) {
  13986. if (typeof group.semantics !== 'undefined' &&
  13987. group.semantics === 'FID') {
  13988. if (typeof group.ssrcs !== 'undefined') {
  13989. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  13990. }
  13991. }
  13992. });
  13993. }
  13994. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  13995. for (var i = 0; i<mLine.ssrcs.length; i++){
  13996. if (typeof mLine.ssrcs[i] === 'object'
  13997. && typeof mLine.ssrcs[i].id !== 'undefined'
  13998. && $.inArray(mLine.ssrcs[i].id, firstSsrcs) == 0) {
  13999. newSsrcLines.push(mLine.ssrcs[i]);
  14000. delete mLine.ssrcs[i];
  14001. }
  14002. }
  14003. for (var i = 0; i<mLine.ssrcs.length; i++){
  14004. if (typeof mLine.ssrcs[i] !== 'undefined') {
  14005. newSsrcLines.push(mLine.ssrcs[i]);
  14006. }
  14007. }
  14008. mLine.ssrcs = newSsrcLines;
  14009. }
  14010. });
  14011. }
  14012. var resStr = transform.write(session);
  14013. return new RTCSessionDescription({
  14014. type: desc.type,
  14015. sdp: resStr
  14016. });
  14017. };
  14018. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  14019. TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
  14020. TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
  14021. TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() {
  14022. var desc = this.peerconnection.localDescription;
  14023. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  14024. // if we're running on FF, transform to Plan B first.
  14025. if (RTCBrowserType.usesUnifiedPlan()) {
  14026. desc = this.interop.toPlanB(desc);
  14027. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  14028. }
  14029. return desc;
  14030. });
  14031. TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() {
  14032. var desc = this.peerconnection.remoteDescription;
  14033. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  14034. // if we're running on FF, transform to Plan B first.
  14035. if (RTCBrowserType.usesUnifiedPlan()) {
  14036. desc = this.interop.toPlanB(desc);
  14037. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  14038. }
  14039. return desc;
  14040. });
  14041. }
  14042. TraceablePeerConnection.prototype.addStream = function (stream) {
  14043. this.trace('addStream', stream.id);
  14044. try
  14045. {
  14046. this.peerconnection.addStream(stream);
  14047. }
  14048. catch (e)
  14049. {
  14050. console.error(e);
  14051. return;
  14052. }
  14053. };
  14054. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  14055. this.trace('removeStream', stream.id);
  14056. if(stopStreams) {
  14057. stream.getAudioTracks().forEach(function (track) {
  14058. // stop() not supported with IE
  14059. if (track.stop) {
  14060. track.stop();
  14061. }
  14062. });
  14063. stream.getVideoTracks().forEach(function (track) {
  14064. // stop() not supported with IE
  14065. if (track.stop) {
  14066. track.stop();
  14067. }
  14068. });
  14069. if (stream.stop) {
  14070. stream.stop();
  14071. }
  14072. }
  14073. try {
  14074. // FF doesn't support this yet.
  14075. if (this.peerconnection.removeStream)
  14076. this.peerconnection.removeStream(stream);
  14077. } catch (e) {
  14078. console.error(e);
  14079. }
  14080. };
  14081. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  14082. this.trace('createDataChannel', label, opts);
  14083. return this.peerconnection.createDataChannel(label, opts);
  14084. };
  14085. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  14086. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  14087. // if we're running on FF, transform to Plan A first.
  14088. if (RTCBrowserType.usesUnifiedPlan()) {
  14089. description = this.interop.toUnifiedPlan(description);
  14090. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  14091. }
  14092. var self = this;
  14093. this.peerconnection.setLocalDescription(description,
  14094. function () {
  14095. self.trace('setLocalDescriptionOnSuccess');
  14096. successCallback();
  14097. },
  14098. function (err) {
  14099. self.trace('setLocalDescriptionOnFailure', err);
  14100. failureCallback(err);
  14101. }
  14102. );
  14103. /*
  14104. if (this.statsinterval === null && this.maxstats > 0) {
  14105. // start gathering stats
  14106. }
  14107. */
  14108. };
  14109. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  14110. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  14111. // TODO the focus should squeze or explode the remote simulcast
  14112. description = this.simulcast.mungeRemoteDescription(description);
  14113. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  14114. // if we're running on FF, transform to Plan A first.
  14115. if (RTCBrowserType.usesUnifiedPlan()) {
  14116. description = this.interop.toUnifiedPlan(description);
  14117. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  14118. }
  14119. if (RTCBrowserType.usesPlanB()) {
  14120. description = normalizePlanB(description);
  14121. }
  14122. var self = this;
  14123. this.peerconnection.setRemoteDescription(description,
  14124. function () {
  14125. self.trace('setRemoteDescriptionOnSuccess');
  14126. successCallback();
  14127. },
  14128. function (err) {
  14129. self.trace('setRemoteDescriptionOnFailure', err);
  14130. failureCallback(err);
  14131. }
  14132. );
  14133. /*
  14134. if (this.statsinterval === null && this.maxstats > 0) {
  14135. // start gathering stats
  14136. }
  14137. */
  14138. };
  14139. TraceablePeerConnection.prototype.close = function () {
  14140. this.trace('stop');
  14141. if (this.statsinterval !== null) {
  14142. window.clearInterval(this.statsinterval);
  14143. this.statsinterval = null;
  14144. }
  14145. this.peerconnection.close();
  14146. };
  14147. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  14148. var self = this;
  14149. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  14150. this.peerconnection.createOffer(
  14151. function (offer) {
  14152. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  14153. // if we're running on FF, transform to Plan B first.
  14154. // NOTE this is not tested because in meet the focus generates the
  14155. // offer.
  14156. if (RTCBrowserType.usesUnifiedPlan()) {
  14157. offer = self.interop.toPlanB(offer);
  14158. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  14159. }
  14160. if (config.enableSimulcast && self.simulcast.isSupported()) {
  14161. offer = self.simulcast.mungeLocalDescription(offer);
  14162. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  14163. }
  14164. successCallback(offer);
  14165. },
  14166. function(err) {
  14167. self.trace('createOfferOnFailure', err);
  14168. failureCallback(err);
  14169. },
  14170. constraints
  14171. );
  14172. };
  14173. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  14174. var self = this;
  14175. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  14176. this.peerconnection.createAnswer(
  14177. function (answer) {
  14178. self.trace('createAnswerOnSuccess::preTransfom', dumpSDP(answer));
  14179. // if we're running on FF, transform to Plan A first.
  14180. if (RTCBrowserType.usesUnifiedPlan()) {
  14181. answer = self.interop.toPlanB(answer);
  14182. self.trace('createAnswerOnSuccess::postTransfom (Plan B)', dumpSDP(answer));
  14183. }
  14184. if (config.enableSimulcast && self.simulcast.isSupported()) {
  14185. answer = self.simulcast.mungeLocalDescription(answer);
  14186. self.trace('createAnswerOnSuccess::postTransfom (simulcast)', dumpSDP(answer));
  14187. }
  14188. successCallback(answer);
  14189. },
  14190. function(err) {
  14191. self.trace('createAnswerOnFailure', err);
  14192. failureCallback(err);
  14193. },
  14194. constraints
  14195. );
  14196. };
  14197. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  14198. var self = this;
  14199. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  14200. this.peerconnection.addIceCandidate(candidate);
  14201. /* maybe later
  14202. this.peerconnection.addIceCandidate(candidate,
  14203. function () {
  14204. self.trace('addIceCandidateOnSuccess');
  14205. successCallback();
  14206. },
  14207. function (err) {
  14208. self.trace('addIceCandidateOnFailure', err);
  14209. failureCallback(err);
  14210. }
  14211. );
  14212. */
  14213. };
  14214. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  14215. // TODO: Is this the correct way to handle Opera, Temasys?
  14216. if (RTCBrowserType.isFirefox()) {
  14217. // ignore for now...
  14218. if(!errback)
  14219. errback = function () {};
  14220. this.peerconnection.getStats(null,callback,errback);
  14221. } else {
  14222. this.peerconnection.getStats(callback);
  14223. }
  14224. };
  14225. module.exports = TraceablePeerConnection;
  14226. },{"../../service/xmpp/XMPPEvents":108,"../RTC/RTC":7,"../RTC/RTCBrowserType.js":8,"sdp-interop":89,"sdp-simulcast":92,"sdp-transform":95}],58:[function(require,module,exports){
  14227. /* global $, $iq, APP, config, connection, messageHandler,
  14228. roomName, sessionTerminated, Strophe, Util */
  14229. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14230. var Settings = require("../settings/Settings");
  14231. var AuthenticationEvents
  14232. = require("../../service/authentication/AuthenticationEvents");
  14233. /**
  14234. * Contains logic responsible for enabling/disabling functionality available
  14235. * only to moderator users.
  14236. */
  14237. var connection = null;
  14238. var focusUserJid;
  14239. function createExpBackoffTimer(step) {
  14240. var count = 1;
  14241. return function (reset) {
  14242. // Reset call
  14243. if (reset) {
  14244. count = 1;
  14245. return;
  14246. }
  14247. // Calculate next timeout
  14248. var timeout = Math.pow(2, count - 1);
  14249. count += 1;
  14250. return timeout * step;
  14251. };
  14252. }
  14253. var getNextTimeout = createExpBackoffTimer(1000);
  14254. var getNextErrorTimeout = createExpBackoffTimer(1000);
  14255. // External authentication stuff
  14256. var externalAuthEnabled = false;
  14257. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  14258. // it will be enabled automatically if focus detects the component through
  14259. // service discovery.
  14260. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  14261. var eventEmitter = null;
  14262. var Moderator = {
  14263. isModerator: function () {
  14264. return connection && connection.emuc.isModerator();
  14265. },
  14266. isPeerModerator: function (peerJid) {
  14267. return connection &&
  14268. connection.emuc.getMemberRole(peerJid) === 'moderator';
  14269. },
  14270. isExternalAuthEnabled: function () {
  14271. return externalAuthEnabled;
  14272. },
  14273. isSipGatewayEnabled: function () {
  14274. return sipGatewayEnabled;
  14275. },
  14276. setConnection: function (con) {
  14277. connection = con;
  14278. },
  14279. init: function (xmpp, emitter) {
  14280. this.xmppService = xmpp;
  14281. eventEmitter = emitter;
  14282. // Message listener that talks to POPUP window
  14283. function listener(event) {
  14284. if (event.data && event.data.sessionId) {
  14285. if (event.origin !== window.location.origin) {
  14286. console.warn(
  14287. "Ignoring sessionId from different origin: " + event.origin);
  14288. return;
  14289. }
  14290. localStorage.setItem('sessionId', event.data.sessionId);
  14291. // After popup is closed we will authenticate
  14292. }
  14293. }
  14294. // Register
  14295. if (window.addEventListener) {
  14296. window.addEventListener("message", listener, false);
  14297. } else {
  14298. window.attachEvent("onmessage", listener);
  14299. }
  14300. },
  14301. onMucMemberLeft: function (jid) {
  14302. console.info("Someone left is it focus ? " + jid);
  14303. var resource = Strophe.getResourceFromJid(jid);
  14304. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  14305. console.info(
  14306. "Focus has left the room - leaving conference");
  14307. //hangUp();
  14308. // We'd rather reload to have everything re-initialized
  14309. // FIXME: show some message before reload
  14310. location.reload();
  14311. }
  14312. },
  14313. setFocusUserJid: function (focusJid) {
  14314. if (!focusUserJid) {
  14315. focusUserJid = focusJid;
  14316. console.info("Focus jid set to: " + focusUserJid);
  14317. }
  14318. },
  14319. getFocusUserJid: function () {
  14320. return focusUserJid;
  14321. },
  14322. getFocusComponent: function () {
  14323. // Get focus component address
  14324. var focusComponent = config.hosts.focus;
  14325. // If not specified use default: 'focus.domain'
  14326. if (!focusComponent) {
  14327. focusComponent = 'focus.' + config.hosts.domain;
  14328. }
  14329. return focusComponent;
  14330. },
  14331. createConferenceIq: function (roomName) {
  14332. // Generate create conference IQ
  14333. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  14334. // Session Id used for authentication
  14335. var sessionId = localStorage.getItem('sessionId');
  14336. var machineUID = Settings.getSettings().uid;
  14337. console.info(
  14338. "Session ID: " + sessionId + " machine UID: " + machineUID);
  14339. elem.c('conference', {
  14340. xmlns: 'http://jitsi.org/protocol/focus',
  14341. room: roomName,
  14342. 'machine-uid': machineUID
  14343. });
  14344. if (sessionId) {
  14345. elem.attrs({ 'session-id': sessionId});
  14346. }
  14347. if (config.hosts.bridge !== undefined) {
  14348. elem.c(
  14349. 'property',
  14350. { name: 'bridge', value: config.hosts.bridge})
  14351. .up();
  14352. }
  14353. // Tell the focus we have Jigasi configured
  14354. if (config.hosts.call_control !== undefined) {
  14355. elem.c(
  14356. 'property',
  14357. { name: 'call_control', value: config.hosts.call_control})
  14358. .up();
  14359. }
  14360. if (config.channelLastN !== undefined) {
  14361. elem.c(
  14362. 'property',
  14363. { name: 'channelLastN', value: config.channelLastN})
  14364. .up();
  14365. }
  14366. if (config.adaptiveLastN !== undefined) {
  14367. elem.c(
  14368. 'property',
  14369. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  14370. .up();
  14371. }
  14372. if (config.adaptiveSimulcast !== undefined) {
  14373. elem.c(
  14374. 'property',
  14375. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  14376. .up();
  14377. }
  14378. if (config.openSctp !== undefined) {
  14379. elem.c(
  14380. 'property',
  14381. { name: 'openSctp', value: config.openSctp})
  14382. .up();
  14383. }
  14384. if(config.startAudioMuted !== undefined)
  14385. {
  14386. elem.c(
  14387. 'property',
  14388. { name: 'startAudioMuted', value: config.startAudioMuted})
  14389. .up();
  14390. }
  14391. if(config.startVideoMuted !== undefined)
  14392. {
  14393. elem.c(
  14394. 'property',
  14395. { name: 'startVideoMuted', value: config.startVideoMuted})
  14396. .up();
  14397. }
  14398. elem.c(
  14399. 'property',
  14400. { name: 'simulcastMode', value: 'rewriting'})
  14401. .up();
  14402. elem.up();
  14403. return elem;
  14404. },
  14405. parseSessionId: function (resultIq) {
  14406. var sessionId = $(resultIq).find('conference').attr('session-id');
  14407. if (sessionId) {
  14408. console.info('Received sessionId: ' + sessionId);
  14409. localStorage.setItem('sessionId', sessionId);
  14410. }
  14411. },
  14412. parseConfigOptions: function (resultIq) {
  14413. Moderator.setFocusUserJid(
  14414. $(resultIq).find('conference').attr('focusjid'));
  14415. var authenticationEnabled
  14416. = $(resultIq).find(
  14417. '>conference>property' +
  14418. '[name=\'authentication\'][value=\'true\']').length > 0;
  14419. console.info("Authentication enabled: " + authenticationEnabled);
  14420. externalAuthEnabled
  14421. = $(resultIq).find(
  14422. '>conference>property' +
  14423. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  14424. console.info('External authentication enabled: ' + externalAuthEnabled);
  14425. if (!externalAuthEnabled) {
  14426. // We expect to receive sessionId in 'internal' authentication mode
  14427. Moderator.parseSessionId(resultIq);
  14428. }
  14429. var authIdentity = $(resultIq).find('>conference').attr('identity');
  14430. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  14431. authenticationEnabled, authIdentity);
  14432. // Check if focus has auto-detected Jigasi component(this will be also
  14433. // included if we have passed our host from the config)
  14434. if ($(resultIq).find(
  14435. '>conference>property' +
  14436. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  14437. sipGatewayEnabled = true;
  14438. }
  14439. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  14440. },
  14441. // FIXME: we need to show the fact that we're waiting for the focus
  14442. // to the user(or that focus is not available)
  14443. allocateConferenceFocus: function (roomName, callback) {
  14444. // Try to use focus user JID from the config
  14445. Moderator.setFocusUserJid(config.focusUserJid);
  14446. // Send create conference IQ
  14447. var iq = Moderator.createConferenceIq(roomName);
  14448. var self = this;
  14449. connection.sendIQ(
  14450. iq,
  14451. function (result) {
  14452. // Setup config options
  14453. Moderator.parseConfigOptions(result);
  14454. if ('true' === $(result).find('conference').attr('ready')) {
  14455. // Reset both timers
  14456. getNextTimeout(true);
  14457. getNextErrorTimeout(true);
  14458. // Exec callback
  14459. callback();
  14460. } else {
  14461. var waitMs = getNextTimeout();
  14462. console.info("Waiting for the focus... " + waitMs);
  14463. // Reset error timeout
  14464. getNextErrorTimeout(true);
  14465. window.setTimeout(
  14466. function () {
  14467. Moderator.allocateConferenceFocus(
  14468. roomName, callback);
  14469. }, waitMs);
  14470. }
  14471. },
  14472. function (error) {
  14473. // Invalid session ? remove and try again
  14474. // without session ID to get a new one
  14475. var invalidSession
  14476. = $(error).find('>error>session-invalid').length;
  14477. if (invalidSession) {
  14478. console.info("Session expired! - removing");
  14479. localStorage.removeItem("sessionId");
  14480. }
  14481. if ($(error).find('>error>graceful-shutdown').length) {
  14482. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  14483. return;
  14484. }
  14485. // Check for error returned by the reservation system
  14486. var reservationErr = $(error).find('>error>reservation-error');
  14487. if (reservationErr.length) {
  14488. // Trigger error event
  14489. var errorCode = reservationErr.attr('error-code');
  14490. var errorMsg;
  14491. if ($(error).find('>error>text')) {
  14492. errorMsg = $(error).find('>error>text').text();
  14493. }
  14494. eventEmitter.emit(
  14495. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  14496. return;
  14497. }
  14498. // Not authorized to create new room
  14499. if ($(error).find('>error>not-authorized').length) {
  14500. console.warn("Unauthorized to start the conference", error);
  14501. var toDomain
  14502. = Strophe.getDomainFromJid(error.getAttribute('to'));
  14503. if (toDomain !== config.hosts.anonymousdomain) {
  14504. // FIXME: "is external" should come either from
  14505. // the focus or config.js
  14506. externalAuthEnabled = true;
  14507. }
  14508. eventEmitter.emit(
  14509. XMPPEvents.AUTHENTICATION_REQUIRED,
  14510. function () {
  14511. Moderator.allocateConferenceFocus(
  14512. roomName, callback);
  14513. });
  14514. return;
  14515. }
  14516. var waitMs = getNextErrorTimeout();
  14517. console.error("Focus error, retry after " + waitMs, error);
  14518. // Show message
  14519. var focusComponent = Moderator.getFocusComponent();
  14520. var retrySec = waitMs / 1000;
  14521. // FIXME: message is duplicated ?
  14522. // Do not show in case of session invalid
  14523. // which means just a retry
  14524. if (!invalidSession) {
  14525. eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED, focusComponent, retrySec);
  14526. }
  14527. // Reset response timeout
  14528. getNextTimeout(true);
  14529. window.setTimeout(
  14530. function () {
  14531. Moderator.allocateConferenceFocus(roomName, callback);
  14532. }, waitMs);
  14533. }
  14534. );
  14535. },
  14536. getLoginUrl: function (roomName, urlCallback) {
  14537. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  14538. iq.c('login-url', {
  14539. xmlns: 'http://jitsi.org/protocol/focus',
  14540. room: roomName,
  14541. 'machine-uid': Settings.getSettings().uid
  14542. });
  14543. connection.sendIQ(
  14544. iq,
  14545. function (result) {
  14546. var url = $(result).find('login-url').attr('url');
  14547. url = url = decodeURIComponent(url);
  14548. if (url) {
  14549. console.info("Got auth url: " + url);
  14550. urlCallback(url);
  14551. } else {
  14552. console.error(
  14553. "Failed to get auth url from the focus", result);
  14554. }
  14555. },
  14556. function (error) {
  14557. console.error("Get auth url error", error);
  14558. }
  14559. );
  14560. },
  14561. getPopupLoginUrl: function (roomName, urlCallback) {
  14562. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  14563. iq.c('login-url', {
  14564. xmlns: 'http://jitsi.org/protocol/focus',
  14565. room: roomName,
  14566. 'machine-uid': Settings.getSettings().uid,
  14567. popup: true
  14568. });
  14569. connection.sendIQ(
  14570. iq,
  14571. function (result) {
  14572. var url = $(result).find('login-url').attr('url');
  14573. url = url = decodeURIComponent(url);
  14574. if (url) {
  14575. console.info("Got POPUP auth url: " + url);
  14576. urlCallback(url);
  14577. } else {
  14578. console.error(
  14579. "Failed to get POPUP auth url from the focus", result);
  14580. }
  14581. },
  14582. function (error) {
  14583. console.error('Get POPUP auth url error', error);
  14584. }
  14585. );
  14586. },
  14587. logout: function (callback) {
  14588. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  14589. var sessionId = localStorage.getItem('sessionId');
  14590. if (!sessionId) {
  14591. callback();
  14592. return;
  14593. }
  14594. iq.c('logout', {
  14595. xmlns: 'http://jitsi.org/protocol/focus',
  14596. 'session-id': sessionId
  14597. });
  14598. connection.sendIQ(
  14599. iq,
  14600. function (result) {
  14601. var logoutUrl = $(result).find('logout').attr('logout-url');
  14602. if (logoutUrl) {
  14603. logoutUrl = decodeURIComponent(logoutUrl);
  14604. }
  14605. console.info("Log out OK, url: " + logoutUrl, result);
  14606. localStorage.removeItem('sessionId');
  14607. callback(logoutUrl);
  14608. },
  14609. function (error) {
  14610. console.error("Logout error", error);
  14611. }
  14612. );
  14613. }
  14614. };
  14615. module.exports = Moderator;
  14616. },{"../../service/authentication/AuthenticationEvents":103,"../../service/xmpp/XMPPEvents":108,"../settings/Settings":47}],59:[function(require,module,exports){
  14617. /* global $, $iq, config, connection, focusMucJid, messageHandler, Moderator,
  14618. Toolbar, Util */
  14619. var Moderator = require("./moderator");
  14620. var recordingToken = null;
  14621. var recordingEnabled;
  14622. /**
  14623. * Whether to use a jirecon component for recording, or use the videobridge
  14624. * through COLIBRI.
  14625. */
  14626. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  14627. /**
  14628. * The ID of the jirecon recording session. Jirecon generates it when we
  14629. * initially start recording, and it needs to be used in subsequent requests
  14630. * to jirecon.
  14631. */
  14632. var jireconRid = null;
  14633. function setRecordingToken(token) {
  14634. recordingToken = token;
  14635. }
  14636. function setRecording(state, token, callback, connection) {
  14637. if (useJirecon){
  14638. setRecordingJirecon(state, token, callback, connection);
  14639. } else {
  14640. setRecordingColibri(state, token, callback, connection);
  14641. }
  14642. }
  14643. function setRecordingJirecon(state, token, callback, connection) {
  14644. if (state == recordingEnabled){
  14645. return;
  14646. }
  14647. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  14648. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  14649. action: state ? 'start' : 'stop',
  14650. mucjid: connection.emuc.roomjid});
  14651. if (!state){
  14652. iq.attrs({rid: jireconRid});
  14653. }
  14654. console.log('Start recording');
  14655. connection.sendIQ(
  14656. iq,
  14657. function (result) {
  14658. // TODO wait for an IQ with the real status, since this is
  14659. // provisional?
  14660. jireconRid = $(result).find('recording').attr('rid');
  14661. console.log('Recording ' + (state ? 'started' : 'stopped') +
  14662. '(jirecon)' + result);
  14663. recordingEnabled = state;
  14664. if (!state){
  14665. jireconRid = null;
  14666. }
  14667. callback(state);
  14668. },
  14669. function (error) {
  14670. console.log('Failed to start recording, error: ', error);
  14671. callback(recordingEnabled);
  14672. });
  14673. }
  14674. // Sends a COLIBRI message which enables or disables (according to 'state')
  14675. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  14676. // with the new recording state, according to the IQ.
  14677. function setRecordingColibri(state, token, callback, connection) {
  14678. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  14679. elem.c('conference', {
  14680. xmlns: 'http://jitsi.org/protocol/colibri'
  14681. });
  14682. elem.c('recording', {state: state, token: token});
  14683. connection.sendIQ(elem,
  14684. function (result) {
  14685. console.log('Set recording "', state, '". Result:', result);
  14686. var recordingElem = $(result).find('>conference>recording');
  14687. var newState = ('true' === recordingElem.attr('state'));
  14688. recordingEnabled = newState;
  14689. callback(newState);
  14690. },
  14691. function (error) {
  14692. console.warn(error);
  14693. callback(recordingEnabled);
  14694. }
  14695. );
  14696. }
  14697. var Recording = {
  14698. toggleRecording: function (tokenEmptyCallback,
  14699. startingCallback, startedCallback, connection) {
  14700. if (!Moderator.isModerator()) {
  14701. console.log(
  14702. 'non-focus, or conference not yet organized:' +
  14703. ' not enabling recording');
  14704. return;
  14705. }
  14706. var self = this;
  14707. // Jirecon does not (currently) support a token.
  14708. if (!recordingToken && !useJirecon) {
  14709. tokenEmptyCallback(function (value) {
  14710. setRecordingToken(value);
  14711. self.toggleRecording(tokenEmptyCallback,
  14712. startingCallback, startedCallback, connection);
  14713. });
  14714. return;
  14715. }
  14716. var oldState = recordingEnabled;
  14717. startingCallback(!oldState);
  14718. setRecording(!oldState,
  14719. recordingToken,
  14720. function (state) {
  14721. console.log("New recording state: ", state);
  14722. if (state === oldState) {
  14723. // FIXME: new focus:
  14724. // this will not work when moderator changes
  14725. // during active session. Then it will assume that
  14726. // recording status has changed to true, but it might have
  14727. // been already true(and we only received actual status from
  14728. // the focus).
  14729. //
  14730. // SO we start with status null, so that it is initialized
  14731. // here and will fail only after second click, so if invalid
  14732. // token was used we have to press the button twice before
  14733. // current status will be fetched and token will be reset.
  14734. //
  14735. // Reliable way would be to return authentication error.
  14736. // Or status update when moderator connects.
  14737. // Or we have to stop recording session when current
  14738. // moderator leaves the room.
  14739. // Failed to change, reset the token because it might
  14740. // have been wrong
  14741. setRecordingToken(null);
  14742. }
  14743. startedCallback(state);
  14744. },
  14745. connection
  14746. );
  14747. }
  14748. }
  14749. module.exports = Recording;
  14750. },{"./moderator":58}],60:[function(require,module,exports){
  14751. /* jshint -W117 */
  14752. /* a simple MUC connection plugin
  14753. * can only handle a single MUC room
  14754. */
  14755. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14756. var Moderator = require("./moderator");
  14757. var JingleSession = require("./JingleSession");
  14758. var bridgeIsDown = false;
  14759. module.exports = function(XMPP, eventEmitter) {
  14760. Strophe.addConnectionPlugin('emuc', {
  14761. connection: null,
  14762. roomjid: null,
  14763. myroomjid: null,
  14764. members: {},
  14765. list_members: [], // so we can elect a new focus
  14766. presMap: {},
  14767. preziMap: {},
  14768. joined: false,
  14769. isOwner: false,
  14770. role: null,
  14771. focusMucJid: null,
  14772. init: function (conn) {
  14773. this.connection = conn;
  14774. },
  14775. initPresenceMap: function (myroomjid) {
  14776. this.presMap['to'] = myroomjid;
  14777. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  14778. if (APP.RTC.localAudio && APP.RTC.localAudio.isMuted())
  14779. {
  14780. this.addAudioInfoToPresence(true);
  14781. }
  14782. if (APP.RTC.localVideo && APP.RTC.localVideo.isMuted())
  14783. {
  14784. this.addVideoInfoToPresence(true);
  14785. }
  14786. },
  14787. doJoin: function (jid, password) {
  14788. this.myroomjid = jid;
  14789. console.info("Joined MUC as " + this.myroomjid);
  14790. this.initPresenceMap(this.myroomjid);
  14791. if (!this.roomjid) {
  14792. this.roomjid = Strophe.getBareJidFromJid(jid);
  14793. // add handlers (just once)
  14794. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  14795. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  14796. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  14797. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  14798. }
  14799. if (password !== undefined) {
  14800. this.presMap['password'] = password;
  14801. }
  14802. this.sendPresence();
  14803. },
  14804. doLeave: function () {
  14805. console.log("do leave", this.myroomjid);
  14806. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  14807. this.presMap.length = 0;
  14808. this.connection.send(pres);
  14809. },
  14810. createNonAnonymousRoom: function () {
  14811. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  14812. var getForm = $iq({type: 'get', to: this.roomjid})
  14813. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  14814. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  14815. var self = this;
  14816. this.connection.sendIQ(getForm, function (form) {
  14817. if (!$(form).find(
  14818. '>query>x[xmlns="jabber:x:data"]' +
  14819. '>field[var="muc#roomconfig_whois"]').length) {
  14820. console.error('non-anonymous rooms not supported');
  14821. return;
  14822. }
  14823. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  14824. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  14825. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  14826. formSubmit.c('field', {'var': 'FORM_TYPE'})
  14827. .c('value')
  14828. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  14829. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  14830. .c('value').t('anyone').up().up();
  14831. self.connection.sendIQ(formSubmit);
  14832. }, function (error) {
  14833. console.error("Error getting room configuration form");
  14834. });
  14835. },
  14836. onPresence: function (pres) {
  14837. var from = pres.getAttribute('from');
  14838. // What is this for? A workaround for something?
  14839. if (pres.getAttribute('type')) {
  14840. return true;
  14841. }
  14842. // Parse etherpad tag.
  14843. var etherpad = $(pres).find('>etherpad');
  14844. if (etherpad.length) {
  14845. if (config.etherpad_base) {
  14846. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  14847. }
  14848. }
  14849. // Parse prezi tag.
  14850. var presentation = $(pres).find('>prezi');
  14851. if (presentation.length) {
  14852. var url = presentation.attr('url');
  14853. var current = presentation.find('>current').text();
  14854. console.log('presentation info received from', from, url);
  14855. if (this.preziMap[from] == null) {
  14856. this.preziMap[from] = url;
  14857. $(document).trigger('presentationadded.muc', [from, url, current]);
  14858. }
  14859. else {
  14860. $(document).trigger('gotoslide.muc', [from, url, current]);
  14861. }
  14862. }
  14863. else if (this.preziMap[from] != null) {
  14864. var url = this.preziMap[from];
  14865. delete this.preziMap[from];
  14866. $(document).trigger('presentationremoved.muc', [from, url]);
  14867. }
  14868. // Parse audio info tag.
  14869. var audioMuted = $(pres).find('>audiomuted');
  14870. if (audioMuted.length) {
  14871. eventEmitter.emit(XMPPEvents.AUDIO_MUTED,
  14872. from, (audioMuted.text() === "true"));
  14873. }
  14874. // Parse video info tag.
  14875. var videoMuted = $(pres).find('>videomuted');
  14876. if (videoMuted.length) {
  14877. eventEmitter.emit(XMPPEvents.VIDEO_MUTED,
  14878. from, (videoMuted.text() === "true"));
  14879. }
  14880. var startMuted = $(pres).find('>startmuted');
  14881. if (startMuted.length)
  14882. {
  14883. eventEmitter.emit(XMPPEvents.START_MUTED_SETTING_CHANGED,
  14884. startMuted.attr("audio") === "true", startMuted.attr("video") === "true");
  14885. }
  14886. var devices = $(pres).find('>devices');
  14887. if(devices.length)
  14888. {
  14889. var audio = devices.find('>audio');
  14890. var video = devices.find('>video');
  14891. var devicesValues = {audio: false, video: false};
  14892. if(audio.length && audio.text() === "true")
  14893. {
  14894. devicesValues.audio = true;
  14895. }
  14896. if(video.length && video.text() === "true")
  14897. {
  14898. devicesValues.video = true;
  14899. }
  14900. eventEmitter.emit(XMPPEvents.DEVICE_AVAILABLE,
  14901. Strophe.getResourceFromJid(from), devicesValues);
  14902. }
  14903. var stats = $(pres).find('>stats');
  14904. if (stats.length) {
  14905. var statsObj = {};
  14906. Strophe.forEachChild(stats[0], "stat", function (el) {
  14907. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  14908. });
  14909. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  14910. }
  14911. // Parse status.
  14912. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  14913. this.isOwner = true;
  14914. this.createNonAnonymousRoom();
  14915. }
  14916. // Parse roles.
  14917. var member = {};
  14918. member.show = $(pres).find('>show').text();
  14919. member.status = $(pres).find('>status').text();
  14920. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  14921. member.affiliation = tmp.attr('affiliation');
  14922. member.role = tmp.attr('role');
  14923. // Focus recognition
  14924. member.jid = tmp.attr('jid');
  14925. member.isFocus = false;
  14926. if (member.jid
  14927. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  14928. member.isFocus = true;
  14929. }
  14930. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  14931. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  14932. if (from == this.myroomjid) {
  14933. if (member.affiliation == 'owner') this.isOwner = true;
  14934. if (this.role !== member.role) {
  14935. this.role = member.role;
  14936. eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  14937. from, member, pres, Moderator.isModerator());
  14938. }
  14939. if (!this.joined) {
  14940. this.joined = true;
  14941. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  14942. this.list_members.push(from);
  14943. }
  14944. } else if (this.members[from] === undefined) {
  14945. // new participant
  14946. this.members[from] = member;
  14947. this.list_members.push(from);
  14948. console.log('entered', from, member);
  14949. if (member.isFocus) {
  14950. this.focusMucJid = from;
  14951. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  14952. }
  14953. else {
  14954. var id = $(pres).find('>userId').text();
  14955. var email = $(pres).find('>email');
  14956. if (email.length > 0) {
  14957. id = email.text();
  14958. }
  14959. eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, id, member.displayName);
  14960. }
  14961. } else {
  14962. // Presence update for existing participant
  14963. // Watch role change:
  14964. if (this.members[from].role != member.role) {
  14965. this.members[from].role = member.role;
  14966. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  14967. member.role, member.displayName);
  14968. }
  14969. }
  14970. // Always trigger presence to update bindings
  14971. this.parsePresence(from, member, pres);
  14972. // Trigger status message update
  14973. if (member.status) {
  14974. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  14975. }
  14976. return true;
  14977. },
  14978. onPresenceUnavailable: function (pres) {
  14979. var from = pres.getAttribute('from');
  14980. // room destroyed ?
  14981. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  14982. '>destroy').length) {
  14983. var reason;
  14984. var reasonSelect = $(pres).find(
  14985. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  14986. '>destroy>reason');
  14987. if (reasonSelect.length) {
  14988. reason = reasonSelect.text();
  14989. }
  14990. XMPP.disposeConference(false);
  14991. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  14992. return true;
  14993. }
  14994. // Status code 110 indicates that this notification is "self-presence".
  14995. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  14996. delete this.members[from];
  14997. this.list_members.splice(this.list_members.indexOf(from), 1);
  14998. this.onParticipantLeft(from);
  14999. }
  15000. // If the status code is 110 this means we're leaving and we would like
  15001. // to remove everyone else from our view, so we trigger the event.
  15002. else if (this.list_members.length > 1) {
  15003. for (var i = 0; i < this.list_members.length; i++) {
  15004. var member = this.list_members[i];
  15005. delete this.members[i];
  15006. this.list_members.splice(i, 1);
  15007. this.onParticipantLeft(member);
  15008. }
  15009. }
  15010. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  15011. $(document).trigger('kicked.muc', [from]);
  15012. if (this.myroomjid === from) {
  15013. XMPP.disposeConference(false);
  15014. eventEmitter.emit(XMPPEvents.KICKED);
  15015. }
  15016. }
  15017. return true;
  15018. },
  15019. onPresenceError: function (pres) {
  15020. var from = pres.getAttribute('from');
  15021. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  15022. console.log('on password required', from);
  15023. var self = this;
  15024. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  15025. self.doJoin(from, value);
  15026. });
  15027. } else if ($(pres).find(
  15028. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  15029. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  15030. if (toDomain === config.hosts.anonymousdomain) {
  15031. // enter the room by replying with 'not-authorized'. This would
  15032. // result in reconnection from authorized domain.
  15033. // We're either missing Jicofo/Prosody config for anonymous
  15034. // domains or something is wrong.
  15035. // XMPP.promptLogin();
  15036. eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  15037. } else {
  15038. console.warn('onPresError ', pres);
  15039. eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  15040. }
  15041. } else {
  15042. console.warn('onPresError ', pres);
  15043. eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  15044. }
  15045. return true;
  15046. },
  15047. sendMessage: function (body, nickname) {
  15048. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  15049. msg.c('body', body).up();
  15050. if (nickname) {
  15051. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  15052. }
  15053. this.connection.send(msg);
  15054. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  15055. },
  15056. setSubject: function (subject) {
  15057. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  15058. msg.c('subject', subject);
  15059. this.connection.send(msg);
  15060. console.log("topic changed to " + subject);
  15061. },
  15062. onMessage: function (msg) {
  15063. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  15064. var from = msg.getAttribute('from');
  15065. var nick =
  15066. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  15067. .text() ||
  15068. Strophe.getResourceFromJid(from);
  15069. var txt = $(msg).find('>body').text();
  15070. var type = msg.getAttribute("type");
  15071. if (type == "error") {
  15072. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  15073. $(msg).find('>text').text(), txt);
  15074. return true;
  15075. }
  15076. var subject = $(msg).find('>subject');
  15077. if (subject.length) {
  15078. var subjectText = subject.text();
  15079. if (subjectText || subjectText == "") {
  15080. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  15081. console.log("Subject is changed to " + subjectText);
  15082. }
  15083. }
  15084. // xep-0203 delay
  15085. var stamp = $(msg).find('>delay').attr('stamp');
  15086. if (!stamp) {
  15087. // or xep-0091 delay, UTC timestamp
  15088. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  15089. if (stamp) {
  15090. // the format is CCYYMMDDThh:mm:ss
  15091. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  15092. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  15093. }
  15094. }
  15095. if (txt) {
  15096. console.log('chat', nick, txt);
  15097. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  15098. from, nick, txt, this.myroomjid, stamp);
  15099. }
  15100. return true;
  15101. },
  15102. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  15103. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  15104. var ob = this;
  15105. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  15106. function (res) {
  15107. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  15108. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  15109. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15110. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  15111. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  15112. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  15113. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  15114. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  15115. ob.connection.sendIQ(formsubmit,
  15116. onSuccess,
  15117. onError);
  15118. } else {
  15119. onNotSupported();
  15120. }
  15121. }, onError);
  15122. },
  15123. kick: function (jid) {
  15124. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  15125. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  15126. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  15127. .c('reason').t('You have been kicked.').up().up().up();
  15128. this.connection.sendIQ(
  15129. kickIQ,
  15130. function (result) {
  15131. console.log('Kick participant with jid: ', jid, result);
  15132. },
  15133. function (error) {
  15134. console.log('Kick participant error: ', error);
  15135. });
  15136. },
  15137. sendPresence: function () {
  15138. if (!this.presMap['to']) {
  15139. // Too early to send presence - not initialized
  15140. return;
  15141. }
  15142. var pres = $pres({to: this.presMap['to'] });
  15143. pres.c('x', {xmlns: this.presMap['xns']});
  15144. if (this.presMap['password']) {
  15145. pres.c('password').t(this.presMap['password']).up();
  15146. }
  15147. pres.up();
  15148. // Send XEP-0115 'c' stanza that contains our capabilities info
  15149. if (this.connection.caps) {
  15150. this.connection.caps.node = config.clientNode;
  15151. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  15152. }
  15153. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  15154. .t(navigator.userAgent).up();
  15155. if (this.presMap['bridgeIsDown']) {
  15156. pres.c('bridgeIsDown').up();
  15157. }
  15158. if (this.presMap['email']) {
  15159. pres.c('email').t(this.presMap['email']).up();
  15160. }
  15161. if (this.presMap['userId']) {
  15162. pres.c('userId').t(this.presMap['userId']).up();
  15163. }
  15164. if (this.presMap['displayName']) {
  15165. // XEP-0172
  15166. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  15167. .t(this.presMap['displayName']).up();
  15168. }
  15169. if(this.presMap["devices"])
  15170. {
  15171. pres.c('devices').c('audio').t(this.presMap['devices'].audio).up()
  15172. .c('video').t(this.presMap['devices'].video).up().up();
  15173. }
  15174. if (this.presMap['audions']) {
  15175. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  15176. .t(this.presMap['audiomuted']).up();
  15177. }
  15178. if (this.presMap['videons']) {
  15179. pres.c('videomuted', {xmlns: this.presMap['videons']})
  15180. .t(this.presMap['videomuted']).up();
  15181. }
  15182. if (this.presMap['statsns']) {
  15183. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  15184. for (var stat in this.presMap["stats"])
  15185. if (this.presMap["stats"][stat] != null)
  15186. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  15187. pres.up();
  15188. }
  15189. if (this.presMap['prezins']) {
  15190. pres.c('prezi',
  15191. {xmlns: this.presMap['prezins'],
  15192. 'url': this.presMap['preziurl']})
  15193. .c('current').t(this.presMap['prezicurrent']).up().up();
  15194. }
  15195. if(this.presMap["startMuted"] !== undefined)
  15196. {
  15197. pres.c("startmuted", {audio: this.presMap["startMuted"].audio,
  15198. video: this.presMap["startMuted"].video,
  15199. xmlns: "http://jitsi.org/jitmeet/start-muted"});
  15200. delete this.presMap["startMuted"];
  15201. }
  15202. pres.up();
  15203. this.connection.send(pres);
  15204. },
  15205. addDisplayNameToPresence: function (displayName) {
  15206. this.presMap['displayName'] = displayName;
  15207. },
  15208. addDevicesToPresence: function (devices) {
  15209. this.presMap['devices'] = devices;
  15210. },
  15211. addPreziToPresence: function (url, currentSlide) {
  15212. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  15213. this.presMap['preziurl'] = url;
  15214. this.presMap['prezicurrent'] = currentSlide;
  15215. },
  15216. removePreziFromPresence: function () {
  15217. delete this.presMap['prezins'];
  15218. delete this.presMap['preziurl'];
  15219. delete this.presMap['prezicurrent'];
  15220. },
  15221. addCurrentSlideToPresence: function (currentSlide) {
  15222. this.presMap['prezicurrent'] = currentSlide;
  15223. },
  15224. getPrezi: function (roomjid) {
  15225. return this.preziMap[roomjid];
  15226. },
  15227. addAudioInfoToPresence: function (isMuted) {
  15228. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  15229. this.presMap['audiomuted'] = isMuted.toString();
  15230. },
  15231. addVideoInfoToPresence: function (isMuted) {
  15232. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  15233. this.presMap['videomuted'] = isMuted.toString();
  15234. },
  15235. addConnectionInfoToPresence: function (stats) {
  15236. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  15237. this.presMap['stats'] = stats;
  15238. },
  15239. findJidFromResource: function (resourceJid) {
  15240. if (resourceJid &&
  15241. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  15242. return this.myroomjid;
  15243. }
  15244. var peerJid = null;
  15245. Object.keys(this.members).some(function (jid) {
  15246. peerJid = jid;
  15247. return Strophe.getResourceFromJid(jid) === resourceJid;
  15248. });
  15249. return peerJid;
  15250. },
  15251. addBridgeIsDownToPresence: function () {
  15252. this.presMap['bridgeIsDown'] = true;
  15253. },
  15254. addEmailToPresence: function (email) {
  15255. this.presMap['email'] = email;
  15256. },
  15257. addUserIdToPresence: function (userId) {
  15258. this.presMap['userId'] = userId;
  15259. },
  15260. addStartMutedToPresence: function (audio, video) {
  15261. this.presMap["startMuted"] = {audio: audio, video: video};
  15262. },
  15263. isModerator: function () {
  15264. return this.role === 'moderator';
  15265. },
  15266. getMemberRole: function (peerJid) {
  15267. if (this.members[peerJid]) {
  15268. return this.members[peerJid].role;
  15269. }
  15270. return null;
  15271. },
  15272. onParticipantLeft: function (jid) {
  15273. eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  15274. this.connection.jingle.terminateByJid(jid);
  15275. if (this.getPrezi(jid)) {
  15276. $(document).trigger('presentationremoved.muc',
  15277. [jid, this.getPrezi(jid)]);
  15278. }
  15279. Moderator.onMucMemberLeft(jid);
  15280. },
  15281. parsePresence: function (from, memeber, pres) {
  15282. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  15283. bridgeIsDown = true;
  15284. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  15285. }
  15286. if(memeber.isFocus)
  15287. return;
  15288. var displayName = !config.displayJids
  15289. ? memeber.displayName : Strophe.getResourceFromJid(from);
  15290. if (displayName && displayName.length > 0)
  15291. {
  15292. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  15293. }
  15294. var id = $(pres).find('>userID').text();
  15295. var email = $(pres).find('>email');
  15296. if(email.length > 0) {
  15297. id = email.text();
  15298. }
  15299. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  15300. }
  15301. });
  15302. };
  15303. },{"../../service/xmpp/XMPPEvents":108,"./JingleSession":53,"./moderator":58}],61:[function(require,module,exports){
  15304. /* jshint -W117 */
  15305. var JingleSession = require("./JingleSession");
  15306. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15307. var RTCBrowserType = require("../RTC/RTCBrowserType");
  15308. module.exports = function(XMPP, eventEmitter)
  15309. {
  15310. function CallIncomingJingle(sid, connection) {
  15311. var sess = connection.jingle.sessions[sid];
  15312. // TODO: do we check activecall == null?
  15313. connection.jingle.activecall = sess;
  15314. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  15315. // TODO: check affiliation and/or role
  15316. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  15317. sess.usedrip = true; // not-so-naive trickle ice
  15318. sess.sendAnswer();
  15319. sess.accept();
  15320. };
  15321. Strophe.addConnectionPlugin('jingle', {
  15322. connection: null,
  15323. sessions: {},
  15324. jid2session: {},
  15325. ice_config: {iceServers: []},
  15326. pc_constraints: {},
  15327. activecall: null,
  15328. media_constraints: {
  15329. mandatory: {
  15330. 'OfferToReceiveAudio': true,
  15331. 'OfferToReceiveVideo': true
  15332. }
  15333. // MozDontOfferDataChannel: true when this is firefox
  15334. },
  15335. init: function (conn) {
  15336. this.connection = conn;
  15337. if (this.connection.disco) {
  15338. // http://xmpp.org/extensions/xep-0167.html#support
  15339. // http://xmpp.org/extensions/xep-0176.html#support
  15340. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  15341. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  15342. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  15343. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  15344. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  15345. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  15346. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  15347. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  15348. || RTCBrowserType.isTemasysPluginUsed()) {
  15349. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  15350. }
  15351. // this is dealt with by SDP O/A so we don't need to annouce this
  15352. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  15353. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  15354. if (config.useRtcpMux) {
  15355. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  15356. }
  15357. if (config.useBundle) {
  15358. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  15359. }
  15360. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  15361. }
  15362. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  15363. },
  15364. onJingle: function (iq) {
  15365. var sid = $(iq).find('jingle').attr('sid');
  15366. var action = $(iq).find('jingle').attr('action');
  15367. var fromJid = iq.getAttribute('from');
  15368. // send ack first
  15369. var ack = $iq({type: 'result',
  15370. to: fromJid,
  15371. id: iq.getAttribute('id')
  15372. });
  15373. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  15374. var sess = this.sessions[sid];
  15375. if ('session-initiate' != action) {
  15376. if (sess === null) {
  15377. ack.type = 'error';
  15378. ack.c('error', {type: 'cancel'})
  15379. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  15380. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  15381. this.connection.send(ack);
  15382. return true;
  15383. }
  15384. // compare from to sess.peerjid (bare jid comparison for later compat with message-mode)
  15385. // local jid is not checked
  15386. if (Strophe.getBareJidFromJid(fromJid) != Strophe.getBareJidFromJid(sess.peerjid)) {
  15387. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  15388. ack.type = 'error';
  15389. ack.c('error', {type: 'cancel'})
  15390. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  15391. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  15392. this.connection.send(ack);
  15393. return true;
  15394. }
  15395. } else if (sess !== undefined) {
  15396. // existing session with same session id
  15397. // this might be out-of-order if the sess.peerjid is the same as from
  15398. ack.type = 'error';
  15399. ack.c('error', {type: 'cancel'})
  15400. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  15401. console.warn('duplicate session id', sid);
  15402. this.connection.send(ack);
  15403. return true;
  15404. }
  15405. // FIXME: check for a defined action
  15406. this.connection.send(ack);
  15407. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  15408. switch (action) {
  15409. case 'session-initiate':
  15410. var startMuted = $(iq).find('jingle>startmuted');
  15411. if(startMuted && startMuted.length > 0)
  15412. {
  15413. var audioMuted = startMuted.attr("audio");
  15414. var videoMuted = startMuted.attr("video");
  15415. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  15416. autioMuted === "true", videoMuted === "true");
  15417. }
  15418. sess = new JingleSession(
  15419. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  15420. this.connection, XMPP, eventEmitter);
  15421. // configure session
  15422. sess.media_constraints = this.media_constraints;
  15423. sess.pc_constraints = this.pc_constraints;
  15424. sess.ice_config = this.ice_config;
  15425. sess.initiate(fromJid, false);
  15426. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  15427. sess.setRemoteDescription($(iq).find('>jingle'), 'offer');
  15428. this.sessions[sess.sid] = sess;
  15429. this.jid2session[sess.peerjid] = sess;
  15430. // the callback should either
  15431. // .sendAnswer and .accept
  15432. // or .sendTerminate -- not necessarily synchronus
  15433. CallIncomingJingle(sess.sid, this.connection);
  15434. break;
  15435. case 'session-accept':
  15436. sess.setRemoteDescription($(iq).find('>jingle'), 'answer');
  15437. sess.accept();
  15438. $(document).trigger('callaccepted.jingle', [sess.sid]);
  15439. break;
  15440. case 'session-terminate':
  15441. // If this is not the focus sending the terminate, we have
  15442. // nothing more to do here.
  15443. if (Object.keys(this.sessions).length < 1
  15444. || !(this.sessions[Object.keys(this.sessions)[0]]
  15445. instanceof JingleSession))
  15446. {
  15447. break;
  15448. }
  15449. console.log('terminating...', sess.sid);
  15450. sess.terminate();
  15451. this.terminate(sess.sid);
  15452. if ($(iq).find('>jingle>reason').length) {
  15453. $(document).trigger('callterminated.jingle', [
  15454. sess.sid,
  15455. sess.peerjid,
  15456. $(iq).find('>jingle>reason>:first')[0].tagName,
  15457. $(iq).find('>jingle>reason>text').text()
  15458. ]);
  15459. } else {
  15460. $(document).trigger('callterminated.jingle',
  15461. [sess.sid, sess.peerjid]);
  15462. }
  15463. break;
  15464. case 'transport-info':
  15465. sess.addIceCandidate($(iq).find('>jingle>content'));
  15466. break;
  15467. case 'session-info':
  15468. var affected;
  15469. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15470. $(document).trigger('ringing.jingle', [sess.sid]);
  15471. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15472. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  15473. $(document).trigger('mute.jingle', [sess.sid, affected]);
  15474. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15475. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  15476. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  15477. }
  15478. break;
  15479. case 'addsource': // FIXME: proprietary, un-jingleish
  15480. case 'source-add': // FIXME: proprietary
  15481. sess.addSource($(iq).find('>jingle>content'), fromJid);
  15482. break;
  15483. case 'removesource': // FIXME: proprietary, un-jingleish
  15484. case 'source-remove': // FIXME: proprietary
  15485. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  15486. break;
  15487. default:
  15488. console.warn('jingle action not implemented', action);
  15489. break;
  15490. }
  15491. return true;
  15492. },
  15493. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  15494. var sess = new JingleSession(myjid || this.connection.jid,
  15495. Math.random().toString(36).substr(2, 12), // random string
  15496. this.connection, XMPP, eventEmitter);
  15497. // configure session
  15498. sess.media_constraints = this.media_constraints;
  15499. sess.pc_constraints = this.pc_constraints;
  15500. sess.ice_config = this.ice_config;
  15501. sess.initiate(peerjid, true);
  15502. this.sessions[sess.sid] = sess;
  15503. this.jid2session[sess.peerjid] = sess;
  15504. sess.sendOffer();
  15505. return sess;
  15506. },
  15507. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  15508. if (sid === null || sid === undefined) {
  15509. for (sid in this.sessions) {
  15510. if (this.sessions[sid].state != 'ended') {
  15511. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  15512. this.sessions[sid].terminate();
  15513. }
  15514. delete this.jid2session[this.sessions[sid].peerjid];
  15515. delete this.sessions[sid];
  15516. }
  15517. } else if (this.sessions.hasOwnProperty(sid)) {
  15518. if (this.sessions[sid].state != 'ended') {
  15519. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  15520. this.sessions[sid].terminate();
  15521. }
  15522. delete this.jid2session[this.sessions[sid].peerjid];
  15523. delete this.sessions[sid];
  15524. }
  15525. },
  15526. // Used to terminate a session when an unavailable presence is received.
  15527. terminateByJid: function (jid) {
  15528. if (this.jid2session.hasOwnProperty(jid)) {
  15529. var sess = this.jid2session[jid];
  15530. if (sess) {
  15531. sess.terminate();
  15532. console.log('peer went away silently', jid);
  15533. delete this.sessions[sess.sid];
  15534. delete this.jid2session[jid];
  15535. $(document).trigger('callterminated.jingle',
  15536. [sess.sid, jid], 'gone');
  15537. }
  15538. }
  15539. },
  15540. terminateRemoteByJid: function (jid, reason) {
  15541. if (this.jid2session.hasOwnProperty(jid)) {
  15542. var sess = this.jid2session[jid];
  15543. if (sess) {
  15544. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  15545. sess.terminate();
  15546. console.log('terminate peer with jid', sess.sid, jid);
  15547. delete this.sessions[sess.sid];
  15548. delete this.jid2session[jid];
  15549. $(document).trigger('callterminated.jingle',
  15550. [sess.sid, jid, 'kicked']);
  15551. }
  15552. }
  15553. },
  15554. getStunAndTurnCredentials: function () {
  15555. // get stun and turn configuration from server via xep-0215
  15556. // uses time-limited credentials as described in
  15557. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  15558. //
  15559. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  15560. // for a prosody module which implements this
  15561. //
  15562. // currently, this doesn't work with updateIce and therefore credentials with a long
  15563. // validity have to be fetched before creating the peerconnection
  15564. // TODO: implement refresh via updateIce as described in
  15565. // https://code.google.com/p/webrtc/issues/detail?id=1650
  15566. var self = this;
  15567. this.connection.sendIQ(
  15568. $iq({type: 'get', to: this.connection.domain})
  15569. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  15570. function (res) {
  15571. var iceservers = [];
  15572. $(res).find('>services>service').each(function (idx, el) {
  15573. el = $(el);
  15574. var dict = {};
  15575. var type = el.attr('type');
  15576. switch (type) {
  15577. case 'stun':
  15578. dict.url = 'stun:' + el.attr('host');
  15579. if (el.attr('port')) {
  15580. dict.url += ':' + el.attr('port');
  15581. }
  15582. iceservers.push(dict);
  15583. break;
  15584. case 'turn':
  15585. case 'turns':
  15586. dict.url = type + ':';
  15587. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  15588. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  15589. dict.url += el.attr('username') + '@';
  15590. } else {
  15591. dict.username = el.attr('username'); // only works in M28
  15592. }
  15593. }
  15594. dict.url += el.attr('host');
  15595. if (el.attr('port') && el.attr('port') != '3478') {
  15596. dict.url += ':' + el.attr('port');
  15597. }
  15598. if (el.attr('transport') && el.attr('transport') != 'udp') {
  15599. dict.url += '?transport=' + el.attr('transport');
  15600. }
  15601. if (el.attr('password')) {
  15602. dict.credential = el.attr('password');
  15603. }
  15604. iceservers.push(dict);
  15605. break;
  15606. }
  15607. });
  15608. self.ice_config.iceServers = iceservers;
  15609. },
  15610. function (err) {
  15611. console.warn('getting turn credentials failed', err);
  15612. console.warn('is mod_turncredentials or similar installed?');
  15613. }
  15614. );
  15615. // implement push?
  15616. },
  15617. /**
  15618. * Populates the log data
  15619. */
  15620. populateData: function () {
  15621. var data = {};
  15622. var self = this;
  15623. Object.keys(this.sessions).forEach(function (sid) {
  15624. var session = self.sessions[sid];
  15625. if (session.peerconnection && session.peerconnection.updateLog) {
  15626. // FIXME: should probably be a .dump call
  15627. data["jingle_" + session.sid] = {
  15628. updateLog: session.peerconnection.updateLog,
  15629. stats: session.peerconnection.stats,
  15630. url: window.location.href
  15631. };
  15632. }
  15633. });
  15634. return data;
  15635. }
  15636. });
  15637. };
  15638. },{"../../service/xmpp/XMPPEvents":108,"../RTC/RTCBrowserType":8,"./JingleSession":53}],62:[function(require,module,exports){
  15639. /* global Strophe */
  15640. module.exports = function () {
  15641. Strophe.addConnectionPlugin('logger', {
  15642. // logs raw stanzas and makes them available for download as JSON
  15643. connection: null,
  15644. log: [],
  15645. init: function (conn) {
  15646. this.connection = conn;
  15647. this.connection.rawInput = this.log_incoming.bind(this);
  15648. this.connection.rawOutput = this.log_outgoing.bind(this);
  15649. },
  15650. log_incoming: function (stanza) {
  15651. this.log.push([new Date().getTime(), 'incoming', stanza]);
  15652. },
  15653. log_outgoing: function (stanza) {
  15654. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  15655. }
  15656. });
  15657. };
  15658. },{}],63:[function(require,module,exports){
  15659. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  15660. setAudioMuted, Strophe */
  15661. /**
  15662. * Moderate connection plugin.
  15663. */
  15664. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15665. module.exports = function (XMPP, eventEmitter) {
  15666. Strophe.addConnectionPlugin('moderate', {
  15667. connection: null,
  15668. init: function (conn) {
  15669. this.connection = conn;
  15670. this.connection.addHandler(this.onMute.bind(this),
  15671. 'http://jitsi.org/jitmeet/audio',
  15672. 'iq',
  15673. 'set',
  15674. null,
  15675. null);
  15676. },
  15677. setMute: function (jid, mute) {
  15678. console.info("set mute", mute);
  15679. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  15680. .c('mute', {
  15681. xmlns: 'http://jitsi.org/jitmeet/audio',
  15682. jid: jid
  15683. })
  15684. .t(mute.toString())
  15685. .up();
  15686. this.connection.sendIQ(
  15687. iqToFocus,
  15688. function (result) {
  15689. console.log('set mute', result);
  15690. },
  15691. function (error) {
  15692. console.log('set mute error', error);
  15693. });
  15694. },
  15695. onMute: function (iq) {
  15696. var from = iq.getAttribute('from');
  15697. if (from !== this.connection.emuc.focusMucJid) {
  15698. console.warn("Ignored mute from non focus peer");
  15699. return false;
  15700. }
  15701. var mute = $(iq).find('mute');
  15702. if (mute.length) {
  15703. var doMuteAudio = mute.text() === "true";
  15704. eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
  15705. XMPP.forceMuted = doMuteAudio;
  15706. }
  15707. return true;
  15708. },
  15709. eject: function (jid) {
  15710. // We're not the focus, so can't terminate
  15711. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  15712. this.connection.emuc.kick(jid);
  15713. }
  15714. });
  15715. }
  15716. },{"../../service/xmpp/XMPPEvents":108}],64:[function(require,module,exports){
  15717. /* jshint -W117 */
  15718. module.exports = function() {
  15719. Strophe.addConnectionPlugin('rayo',
  15720. {
  15721. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  15722. connection: null,
  15723. init: function (conn) {
  15724. this.connection = conn;
  15725. if (this.connection.disco) {
  15726. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  15727. }
  15728. this.connection.addHandler(
  15729. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  15730. },
  15731. onRayo: function (iq) {
  15732. console.info("Rayo IQ", iq);
  15733. },
  15734. dial: function (to, from, roomName, roomPass) {
  15735. var self = this;
  15736. var req = $iq(
  15737. {
  15738. type: 'set',
  15739. to: this.connection.emuc.focusMucJid
  15740. }
  15741. );
  15742. req.c('dial',
  15743. {
  15744. xmlns: this.RAYO_XMLNS,
  15745. to: to,
  15746. from: from
  15747. });
  15748. req.c('header',
  15749. {
  15750. name: 'JvbRoomName',
  15751. value: roomName
  15752. }).up();
  15753. if (roomPass !== null && roomPass.length) {
  15754. req.c('header',
  15755. {
  15756. name: 'JvbRoomPassword',
  15757. value: roomPass
  15758. }).up();
  15759. }
  15760. this.connection.sendIQ(
  15761. req,
  15762. function (result) {
  15763. console.info('Dial result ', result);
  15764. var resource = $(result).find('ref').attr('uri');
  15765. this.call_resource = resource.substr('xmpp:'.length);
  15766. console.info(
  15767. "Received call resource: " + this.call_resource);
  15768. },
  15769. function (error) {
  15770. console.info('Dial error ', error);
  15771. }
  15772. );
  15773. },
  15774. hang_up: function () {
  15775. if (!this.call_resource) {
  15776. console.warn("No call in progress");
  15777. return;
  15778. }
  15779. var self = this;
  15780. var req = $iq(
  15781. {
  15782. type: 'set',
  15783. to: this.call_resource
  15784. }
  15785. );
  15786. req.c('hangup',
  15787. {
  15788. xmlns: this.RAYO_XMLNS
  15789. });
  15790. this.connection.sendIQ(
  15791. req,
  15792. function (result) {
  15793. console.info('Hangup result ', result);
  15794. self.call_resource = null;
  15795. },
  15796. function (error) {
  15797. console.info('Hangup error ', error);
  15798. self.call_resource = null;
  15799. }
  15800. );
  15801. }
  15802. }
  15803. );
  15804. };
  15805. },{}],65:[function(require,module,exports){
  15806. /**
  15807. * Strophe logger implementation. Logs from level WARN and above.
  15808. */
  15809. module.exports = function () {
  15810. Strophe.log = function (level, msg) {
  15811. switch (level) {
  15812. case Strophe.LogLevel.WARN:
  15813. console.warn("Strophe: " + msg);
  15814. break;
  15815. case Strophe.LogLevel.ERROR:
  15816. case Strophe.LogLevel.FATAL:
  15817. console.error("Strophe: " + msg);
  15818. break;
  15819. }
  15820. };
  15821. Strophe.getStatusString = function (status) {
  15822. switch (status) {
  15823. case Strophe.Status.ERROR:
  15824. return "ERROR";
  15825. case Strophe.Status.CONNECTING:
  15826. return "CONNECTING";
  15827. case Strophe.Status.CONNFAIL:
  15828. return "CONNFAIL";
  15829. case Strophe.Status.AUTHENTICATING:
  15830. return "AUTHENTICATING";
  15831. case Strophe.Status.AUTHFAIL:
  15832. return "AUTHFAIL";
  15833. case Strophe.Status.CONNECTED:
  15834. return "CONNECTED";
  15835. case Strophe.Status.DISCONNECTED:
  15836. return "DISCONNECTED";
  15837. case Strophe.Status.DISCONNECTING:
  15838. return "DISCONNECTING";
  15839. case Strophe.Status.ATTACHED:
  15840. return "ATTACHED";
  15841. default:
  15842. return "unknown";
  15843. }
  15844. };
  15845. };
  15846. },{}],66:[function(require,module,exports){
  15847. /* global $, APP, config, Strophe*/
  15848. var Moderator = require("./moderator");
  15849. var EventEmitter = require("events");
  15850. var Recording = require("./recording");
  15851. var SDP = require("./SDP");
  15852. var Settings = require("../settings/Settings");
  15853. var Pako = require("pako");
  15854. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  15855. var RTCEvents = require("../../service/RTC/RTCEvents");
  15856. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15857. var retry = require('retry');
  15858. var eventEmitter = new EventEmitter();
  15859. var connection = null;
  15860. var authenticatedUser = false;
  15861. function connect(jid, password) {
  15862. var faultTolerantConnect = retry.operation({
  15863. retries: 3
  15864. });
  15865. // fault tolerant connect
  15866. faultTolerantConnect.attempt(function () {
  15867. connection = XMPP.createConnection();
  15868. Moderator.setConnection(connection);
  15869. if (connection.disco) {
  15870. // for chrome, add multistream cap
  15871. }
  15872. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  15873. if (config.useIPv6) {
  15874. // https://code.google.com/p/webrtc/issues/detail?id=2828
  15875. if (!connection.jingle.pc_constraints.optional)
  15876. connection.jingle.pc_constraints.optional = [];
  15877. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  15878. }
  15879. // Include user info in MUC presence
  15880. var settings = Settings.getSettings();
  15881. if (settings.email) {
  15882. connection.emuc.addEmailToPresence(settings.email);
  15883. }
  15884. if (settings.uid) {
  15885. connection.emuc.addUserIdToPresence(settings.uid);
  15886. }
  15887. if (settings.displayName) {
  15888. connection.emuc.addDisplayNameToPresence(settings.displayName);
  15889. }
  15890. // connection.connect() starts the connection process.
  15891. //
  15892. // As the connection process proceeds, the user supplied callback will
  15893. // be triggered multiple times with status updates. The callback should
  15894. // take two arguments - the status code and the error condition.
  15895. //
  15896. // The status code will be one of the values in the Strophe.Status
  15897. // constants. The error condition will be one of the conditions defined
  15898. // in RFC 3920 or the condition ‘strophe-parsererror’.
  15899. //
  15900. // The Parameters wait, hold and route are optional and only relevant
  15901. // for BOSH connections. Please see XEP 124 for a more detailed
  15902. // explanation of the optional parameters.
  15903. //
  15904. // Connection status constants for use by the connection handler
  15905. // callback.
  15906. //
  15907. // Status.ERROR - An error has occurred (websockets specific)
  15908. // Status.CONNECTING - The connection is currently being made
  15909. // Status.CONNFAIL - The connection attempt failed
  15910. // Status.AUTHENTICATING - The connection is authenticating
  15911. // Status.AUTHFAIL - The authentication attempt failed
  15912. // Status.CONNECTED - The connection has succeeded
  15913. // Status.DISCONNECTED - The connection has been terminated
  15914. // Status.DISCONNECTING - The connection is currently being terminated
  15915. // Status.ATTACHED - The connection has been attached
  15916. var anonymousConnectionFailed = false;
  15917. var connectionFailed = false;
  15918. var lastErrorMsg;
  15919. connection.connect(jid, password, function (status, msg) {
  15920. console.log('Strophe status changed to',
  15921. Strophe.getStatusString(status), msg);
  15922. if (status === Strophe.Status.CONNECTED) {
  15923. if (config.useStunTurn) {
  15924. connection.jingle.getStunAndTurnCredentials();
  15925. }
  15926. console.info("My Jabber ID: " + connection.jid);
  15927. if (password)
  15928. authenticatedUser = true;
  15929. maybeDoJoin();
  15930. } else if (status === Strophe.Status.CONNFAIL) {
  15931. if (msg === 'x-strophe-bad-non-anon-jid') {
  15932. anonymousConnectionFailed = true;
  15933. } else {
  15934. connectionFailed = true;
  15935. }
  15936. lastErrorMsg = msg;
  15937. } else if (status === Strophe.Status.DISCONNECTED) {
  15938. if (anonymousConnectionFailed) {
  15939. // prompt user for username and password
  15940. XMPP.promptLogin();
  15941. } else {
  15942. // Strophe already has built-in HTTP/BOSH error handling and
  15943. // request retry logic. Requests are resent automatically
  15944. // until their error count reaches 5. Strophe.js disconnects
  15945. // if the error count is > 5. We are not replicating this
  15946. // here.
  15947. //
  15948. // The "problem" is that failed HTTP/BOSH requests don't
  15949. // trigger a callback with a status update, so when a
  15950. // callback with status Strophe.Status.DISCONNECTED arrives,
  15951. // we can't be sure if it's a graceful disconnect or if it's
  15952. // triggered by some HTTP/BOSH error.
  15953. //
  15954. // But that's a minor issue in Jitsi Meet as we never
  15955. // disconnect anyway, not even when the user closes the
  15956. // browser window (which is kind of wrong, but the point is
  15957. // that we should never ever get disconnected).
  15958. //
  15959. // On the other hand, failed connections due to XMPP layer
  15960. // errors, trigger a callback with status Strophe.Status.CONNFAIL.
  15961. //
  15962. // Here we implement retry logic for failed connections due
  15963. // to XMPP layer errors and we display an error to the user
  15964. // if we get disconnected from the XMPP server permanently.
  15965. // If the connection failed, retry.
  15966. if (connectionFailed
  15967. && faultTolerantConnect.retry("connection-failed")) {
  15968. return;
  15969. }
  15970. // If we failed to connect to the XMPP server, fire an event
  15971. // to let all the interested module now about it.
  15972. eventEmitter.emit(XMPPEvents.CONNECTION_FAILED,
  15973. msg ? msg : lastErrorMsg);
  15974. }
  15975. } else if (status === Strophe.Status.AUTHFAIL) {
  15976. // wrong password or username, prompt user
  15977. XMPP.promptLogin();
  15978. }
  15979. });
  15980. });
  15981. }
  15982. function maybeDoJoin() {
  15983. if (connection && connection.connected &&
  15984. Strophe.getResourceFromJid(connection.jid)
  15985. && (APP.RTC.localAudio || APP.RTC.localVideo)) {
  15986. // .connected is true while connecting?
  15987. doJoin();
  15988. }
  15989. }
  15990. function doJoin() {
  15991. eventEmitter.emit(XMPPEvents.READY_TO_JOIN);
  15992. }
  15993. function initStrophePlugins()
  15994. {
  15995. require("./strophe.emuc")(XMPP, eventEmitter);
  15996. require("./strophe.jingle")(XMPP, eventEmitter);
  15997. require("./strophe.moderate")(XMPP, eventEmitter);
  15998. require("./strophe.util")();
  15999. require("./strophe.rayo")();
  16000. require("./strophe.logger")();
  16001. }
  16002. function registerListeners() {
  16003. APP.RTC.addStreamListener(maybeDoJoin,
  16004. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  16005. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  16006. XMPP.addToPresence("devices", devices);
  16007. });
  16008. }
  16009. var unload = (function () {
  16010. var unloaded = false;
  16011. return function () {
  16012. if (unloaded) { return; }
  16013. unloaded = true;
  16014. if (connection && connection.connected) {
  16015. // ensure signout
  16016. $.ajax({
  16017. type: 'POST',
  16018. url: config.bosh,
  16019. async: false,
  16020. cache: false,
  16021. contentType: 'application/xml',
  16022. data: "<body rid='" + (connection.rid || connection._proto.rid) +
  16023. "' xmlns='http://jabber.org/protocol/httpbind' sid='" +
  16024. (connection.sid || connection._proto.sid) +
  16025. "' type='terminate'>" +
  16026. "<presence xmlns='jabber:client' type='unavailable'/>" +
  16027. "</body>",
  16028. success: function (data) {
  16029. console.log('signed out');
  16030. console.log(data);
  16031. },
  16032. error: function (XMLHttpRequest, textStatus, errorThrown) {
  16033. console.log('signout error',
  16034. textStatus + ' (' + errorThrown + ')');
  16035. }
  16036. });
  16037. }
  16038. XMPP.disposeConference(true);
  16039. };
  16040. })();
  16041. function setupEvents() {
  16042. // In recent versions of FF the 'beforeunload' event is not fired when the
  16043. // window or the tab is closed. It is only fired when we leave the page
  16044. // (change URL). If this participant doesn't unload properly, then it
  16045. // becomes a ghost for the rest of the participants that stay in the
  16046. // conference. Thankfully handling the 'unload' event in addition to the
  16047. // 'beforeunload' event seems to garante the execution of the 'unload'
  16048. // method at least once.
  16049. //
  16050. // The 'unload' method can safely be run multiple times, it will actually do
  16051. // something only the first time that it's run, so we're don't have to worry
  16052. // about browsers that fire both events.
  16053. $(window).bind('beforeunload', unload);
  16054. $(window).bind('unload', unload);
  16055. }
  16056. var XMPP = {
  16057. getConnection: function(){ return connection; },
  16058. sessionTerminated: false,
  16059. /**
  16060. * XMPP connection status
  16061. */
  16062. Status: Strophe.Status,
  16063. /**
  16064. * Remembers if we were muted by the focus.
  16065. * @type {boolean}
  16066. */
  16067. forceMuted: false,
  16068. start: function () {
  16069. setupEvents();
  16070. initStrophePlugins();
  16071. registerListeners();
  16072. Moderator.init(this, eventEmitter);
  16073. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  16074. // Force authenticated domain if room is appended with '?login=true'
  16075. if (config.hosts.anonymousdomain &&
  16076. window.location.search.indexOf("login=true") !== -1) {
  16077. configDomain = config.hosts.domain;
  16078. }
  16079. var jid = configDomain || window.location.hostname;
  16080. connect(jid, null);
  16081. },
  16082. createConnection: function () {
  16083. var bosh = config.bosh || '/http-bind';
  16084. return new Strophe.Connection(bosh);
  16085. },
  16086. getStatusString: function (status) {
  16087. return Strophe.getStatusString(status);
  16088. },
  16089. promptLogin: function () {
  16090. eventEmitter.emit(XMPPEvents.PROMPT_FOR_LOGIN);
  16091. },
  16092. joinRoom: function(roomName, useNicks, nick)
  16093. {
  16094. var roomjid;
  16095. roomjid = roomName;
  16096. if (useNicks) {
  16097. if (nick) {
  16098. roomjid += '/' + nick;
  16099. } else {
  16100. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  16101. }
  16102. } else {
  16103. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  16104. if(!authenticatedUser)
  16105. tmpJid = tmpJid.substr(0, 8);
  16106. roomjid += '/' + tmpJid;
  16107. }
  16108. connection.emuc.doJoin(roomjid);
  16109. },
  16110. myJid: function () {
  16111. if(!connection)
  16112. return null;
  16113. return connection.emuc.myroomjid;
  16114. },
  16115. myResource: function () {
  16116. if(!connection || ! connection.emuc.myroomjid)
  16117. return null;
  16118. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  16119. },
  16120. disposeConference: function (onUnload) {
  16121. var handler = connection.jingle.activecall;
  16122. if (handler && handler.peerconnection) {
  16123. // FIXME: probably removing streams is not required and close() should
  16124. // be enough
  16125. if (APP.RTC.localAudio) {
  16126. handler.peerconnection.removeStream(
  16127. APP.RTC.localAudio.getOriginalStream(), onUnload);
  16128. }
  16129. if (APP.RTC.localVideo) {
  16130. handler.peerconnection.removeStream(
  16131. APP.RTC.localVideo.getOriginalStream(), onUnload);
  16132. }
  16133. handler.peerconnection.close();
  16134. }
  16135. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  16136. connection.jingle.activecall = null;
  16137. if(!onUnload)
  16138. {
  16139. this.sessionTerminated = true;
  16140. connection.emuc.doLeave();
  16141. }
  16142. },
  16143. addListener: function(type, listener)
  16144. {
  16145. eventEmitter.on(type, listener);
  16146. },
  16147. removeListener: function (type, listener) {
  16148. eventEmitter.removeListener(type, listener);
  16149. },
  16150. allocateConferenceFocus: function(roomName, callback) {
  16151. Moderator.allocateConferenceFocus(roomName, callback);
  16152. },
  16153. getLoginUrl: function (roomName, callback) {
  16154. Moderator.getLoginUrl(roomName, callback);
  16155. },
  16156. getPopupLoginUrl: function (roomName, callback) {
  16157. Moderator.getPopupLoginUrl(roomName, callback);
  16158. },
  16159. isModerator: function () {
  16160. return Moderator.isModerator();
  16161. },
  16162. isSipGatewayEnabled: function () {
  16163. return Moderator.isSipGatewayEnabled();
  16164. },
  16165. isExternalAuthEnabled: function () {
  16166. return Moderator.isExternalAuthEnabled();
  16167. },
  16168. isConferenceInProgress: function () {
  16169. return connection && connection.jingle.activecall &&
  16170. connection.jingle.activecall.peerconnection;
  16171. },
  16172. switchStreams: function (stream, oldStream, callback, isAudio) {
  16173. if (this.isConferenceInProgress()) {
  16174. // FIXME: will block switchInProgress on true value in case of exception
  16175. connection.jingle.activecall.switchStreams(stream, oldStream, callback, isAudio);
  16176. } else {
  16177. // We are done immediately
  16178. console.warn("No conference handler or conference not started yet");
  16179. callback();
  16180. }
  16181. },
  16182. sendVideoInfoPresence: function (mute) {
  16183. if(!connection)
  16184. return;
  16185. connection.emuc.addVideoInfoToPresence(mute);
  16186. connection.emuc.sendPresence();
  16187. },
  16188. setVideoMute: function (mute, callback, options) {
  16189. if(!connection)
  16190. return;
  16191. var self = this;
  16192. var localCallback = function (mute) {
  16193. self.sendVideoInfoPresence(mute);
  16194. return callback(mute);
  16195. };
  16196. if(connection.jingle.activecall)
  16197. {
  16198. connection.jingle.activecall.setVideoMute(
  16199. mute, localCallback, options);
  16200. }
  16201. else {
  16202. localCallback(mute);
  16203. }
  16204. },
  16205. setAudioMute: function (mute, callback) {
  16206. if (!(connection && APP.RTC.localAudio)) {
  16207. return false;
  16208. }
  16209. if (this.forceMuted && !mute) {
  16210. console.info("Asking focus for unmute");
  16211. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  16212. // FIXME: wait for result before resetting muted status
  16213. this.forceMuted = false;
  16214. }
  16215. if (mute == APP.RTC.localAudio.isMuted()) {
  16216. // Nothing to do
  16217. return true;
  16218. }
  16219. // It is not clear what is the right way to handle multiple tracks.
  16220. // So at least make sure that they are all muted or all unmuted and
  16221. // that we send presence just once.
  16222. APP.RTC.localAudio.setMute(!mute);
  16223. // isMuted is the opposite of audioEnabled
  16224. this.sendAudioInfoPresence(mute, callback);
  16225. return true;
  16226. },
  16227. sendAudioInfoPresence: function(mute, callback)
  16228. {
  16229. if(connection) {
  16230. connection.emuc.addAudioInfoToPresence(mute);
  16231. connection.emuc.sendPresence();
  16232. }
  16233. callback();
  16234. return true;
  16235. },
  16236. // Really mute video, i.e. dont even send black frames
  16237. muteVideo: function (pc, unmute) {
  16238. // FIXME: this probably needs another of those lovely state safeguards...
  16239. // which checks for iceconn == connected and sigstate == stable
  16240. pc.setRemoteDescription(pc.remoteDescription,
  16241. function () {
  16242. pc.createAnswer(
  16243. function (answer) {
  16244. var sdp = new SDP(answer.sdp);
  16245. if (sdp.media.length > 1) {
  16246. if (unmute)
  16247. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  16248. else
  16249. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  16250. sdp.raw = sdp.session + sdp.media.join('');
  16251. answer.sdp = sdp.raw;
  16252. }
  16253. pc.setLocalDescription(answer,
  16254. function () {
  16255. console.log('mute SLD ok');
  16256. },
  16257. function (error) {
  16258. console.log('mute SLD error');
  16259. eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  16260. }
  16261. );
  16262. },
  16263. function (error) {
  16264. console.log(error);
  16265. eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  16266. }
  16267. );
  16268. },
  16269. function (error) {
  16270. console.log('muteVideo SRD error');
  16271. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  16272. }
  16273. );
  16274. },
  16275. toggleRecording: function (tokenEmptyCallback,
  16276. startingCallback, startedCallback) {
  16277. Recording.toggleRecording(tokenEmptyCallback,
  16278. startingCallback, startedCallback, connection);
  16279. },
  16280. addToPresence: function (name, value, dontSend) {
  16281. switch (name)
  16282. {
  16283. case "displayName":
  16284. connection.emuc.addDisplayNameToPresence(value);
  16285. break;
  16286. case "prezi":
  16287. connection.emuc.addPreziToPresence(value, 0);
  16288. break;
  16289. case "preziSlide":
  16290. connection.emuc.addCurrentSlideToPresence(value);
  16291. break;
  16292. case "connectionQuality":
  16293. connection.emuc.addConnectionInfoToPresence(value);
  16294. break;
  16295. case "email":
  16296. connection.emuc.addEmailToPresence(value);
  16297. break;
  16298. case "devices":
  16299. connection.emuc.addDevicesToPresence(value);
  16300. break;
  16301. case "startMuted":
  16302. if(!Moderator.isModerator())
  16303. return;
  16304. connection.emuc.addStartMutedToPresence(value[0],
  16305. value[1]);
  16306. break;
  16307. default :
  16308. console.log("Unknown tag for presence: " + name);
  16309. return;
  16310. }
  16311. if (!dontSend)
  16312. connection.emuc.sendPresence();
  16313. },
  16314. /**
  16315. * Sends 'data' as a log message to the focus. Returns true iff a message
  16316. * was sent.
  16317. * @param data
  16318. * @returns {boolean} true iff a message was sent.
  16319. */
  16320. sendLogs: function (data) {
  16321. if(!connection.emuc.focusMucJid)
  16322. return false;
  16323. var deflate = true;
  16324. var content = JSON.stringify(data);
  16325. if (deflate) {
  16326. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  16327. }
  16328. content = Base64.encode(content);
  16329. // XEP-0337-ish
  16330. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  16331. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  16332. id: 'PeerConnectionStats'});
  16333. message.c('message').t(content).up();
  16334. if (deflate) {
  16335. message.c('tag', {name: "deflated", value: "true"}).up();
  16336. }
  16337. message.up();
  16338. connection.send(message);
  16339. return true;
  16340. },
  16341. populateData: function () {
  16342. var data = {};
  16343. if (connection.jingle) {
  16344. data = connection.jingle.populateData();
  16345. }
  16346. return data;
  16347. },
  16348. getLogger: function () {
  16349. if(connection.logger)
  16350. return connection.logger.log;
  16351. return null;
  16352. },
  16353. getPrezi: function () {
  16354. return connection.emuc.getPrezi(this.myJid());
  16355. },
  16356. removePreziFromPresence: function () {
  16357. connection.emuc.removePreziFromPresence();
  16358. connection.emuc.sendPresence();
  16359. },
  16360. sendChatMessage: function (message, nickname) {
  16361. connection.emuc.sendMessage(message, nickname);
  16362. },
  16363. setSubject: function (topic) {
  16364. connection.emuc.setSubject(topic);
  16365. },
  16366. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  16367. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  16368. },
  16369. dial: function (to, from, roomName,roomPass) {
  16370. connection.rayo.dial(to, from, roomName,roomPass);
  16371. },
  16372. setMute: function (jid, mute) {
  16373. connection.moderate.setMute(jid, mute);
  16374. },
  16375. eject: function (jid) {
  16376. connection.moderate.eject(jid);
  16377. },
  16378. logout: function (callback) {
  16379. Moderator.logout(callback);
  16380. },
  16381. findJidFromResource: function (resource) {
  16382. return connection.emuc.findJidFromResource(resource);
  16383. },
  16384. getMembers: function () {
  16385. return connection.emuc.members;
  16386. },
  16387. getJidFromSSRC: function (ssrc) {
  16388. if (!this.isConferenceInProgress())
  16389. return null;
  16390. return connection.jingle.activecall.getSsrcOwner(ssrc);
  16391. },
  16392. getMUCJoined: function () {
  16393. return connection.emuc.joined;
  16394. },
  16395. getSessions: function () {
  16396. return connection.jingle.sessions;
  16397. },
  16398. removeStream: function (stream) {
  16399. if (!this.isConferenceInProgress())
  16400. return;
  16401. connection.jingle.activecall.peerconnection.removeStream(stream);
  16402. }
  16403. };
  16404. module.exports = XMPP;
  16405. },{"../../service/RTC/RTCEvents":99,"../../service/RTC/StreamEventTypes":101,"../../service/xmpp/XMPPEvents":108,"../settings/Settings":47,"./SDP":54,"./moderator":58,"./recording":59,"./strophe.emuc":60,"./strophe.jingle":61,"./strophe.logger":62,"./strophe.moderate":63,"./strophe.rayo":64,"./strophe.util":65,"events":109,"pako":69,"retry":85}],67:[function(require,module,exports){
  16406. (function (process){
  16407. /*!
  16408. * async
  16409. * https://github.com/caolan/async
  16410. *
  16411. * Copyright 2010-2014 Caolan McMahon
  16412. * Released under the MIT license
  16413. */
  16414. /*jshint onevar: false, indent:4 */
  16415. /*global setImmediate: false, setTimeout: false, console: false */
  16416. (function () {
  16417. var async = {};
  16418. // global on the server, window in the browser
  16419. var root, previous_async;
  16420. root = this;
  16421. if (root != null) {
  16422. previous_async = root.async;
  16423. }
  16424. async.noConflict = function () {
  16425. root.async = previous_async;
  16426. return async;
  16427. };
  16428. function only_once(fn) {
  16429. var called = false;
  16430. return function() {
  16431. if (called) throw new Error("Callback was already called.");
  16432. called = true;
  16433. fn.apply(root, arguments);
  16434. }
  16435. }
  16436. //// cross-browser compatiblity functions ////
  16437. var _toString = Object.prototype.toString;
  16438. var _isArray = Array.isArray || function (obj) {
  16439. return _toString.call(obj) === '[object Array]';
  16440. };
  16441. var _each = function (arr, iterator) {
  16442. if (arr.forEach) {
  16443. return arr.forEach(iterator);
  16444. }
  16445. for (var i = 0; i < arr.length; i += 1) {
  16446. iterator(arr[i], i, arr);
  16447. }
  16448. };
  16449. var _map = function (arr, iterator) {
  16450. if (arr.map) {
  16451. return arr.map(iterator);
  16452. }
  16453. var results = [];
  16454. _each(arr, function (x, i, a) {
  16455. results.push(iterator(x, i, a));
  16456. });
  16457. return results;
  16458. };
  16459. var _reduce = function (arr, iterator, memo) {
  16460. if (arr.reduce) {
  16461. return arr.reduce(iterator, memo);
  16462. }
  16463. _each(arr, function (x, i, a) {
  16464. memo = iterator(memo, x, i, a);
  16465. });
  16466. return memo;
  16467. };
  16468. var _keys = function (obj) {
  16469. if (Object.keys) {
  16470. return Object.keys(obj);
  16471. }
  16472. var keys = [];
  16473. for (var k in obj) {
  16474. if (obj.hasOwnProperty(k)) {
  16475. keys.push(k);
  16476. }
  16477. }
  16478. return keys;
  16479. };
  16480. //// exported async module functions ////
  16481. //// nextTick implementation with browser-compatible fallback ////
  16482. if (typeof process === 'undefined' || !(process.nextTick)) {
  16483. if (typeof setImmediate === 'function') {
  16484. async.nextTick = function (fn) {
  16485. // not a direct alias for IE10 compatibility
  16486. setImmediate(fn);
  16487. };
  16488. async.setImmediate = async.nextTick;
  16489. }
  16490. else {
  16491. async.nextTick = function (fn) {
  16492. setTimeout(fn, 0);
  16493. };
  16494. async.setImmediate = async.nextTick;
  16495. }
  16496. }
  16497. else {
  16498. async.nextTick = process.nextTick;
  16499. if (typeof setImmediate !== 'undefined') {
  16500. async.setImmediate = function (fn) {
  16501. // not a direct alias for IE10 compatibility
  16502. setImmediate(fn);
  16503. };
  16504. }
  16505. else {
  16506. async.setImmediate = async.nextTick;
  16507. }
  16508. }
  16509. async.each = function (arr, iterator, callback) {
  16510. callback = callback || function () {};
  16511. if (!arr.length) {
  16512. return callback();
  16513. }
  16514. var completed = 0;
  16515. _each(arr, function (x) {
  16516. iterator(x, only_once(done) );
  16517. });
  16518. function done(err) {
  16519. if (err) {
  16520. callback(err);
  16521. callback = function () {};
  16522. }
  16523. else {
  16524. completed += 1;
  16525. if (completed >= arr.length) {
  16526. callback();
  16527. }
  16528. }
  16529. }
  16530. };
  16531. async.forEach = async.each;
  16532. async.eachSeries = function (arr, iterator, callback) {
  16533. callback = callback || function () {};
  16534. if (!arr.length) {
  16535. return callback();
  16536. }
  16537. var completed = 0;
  16538. var iterate = function () {
  16539. iterator(arr[completed], function (err) {
  16540. if (err) {
  16541. callback(err);
  16542. callback = function () {};
  16543. }
  16544. else {
  16545. completed += 1;
  16546. if (completed >= arr.length) {
  16547. callback();
  16548. }
  16549. else {
  16550. iterate();
  16551. }
  16552. }
  16553. });
  16554. };
  16555. iterate();
  16556. };
  16557. async.forEachSeries = async.eachSeries;
  16558. async.eachLimit = function (arr, limit, iterator, callback) {
  16559. var fn = _eachLimit(limit);
  16560. fn.apply(null, [arr, iterator, callback]);
  16561. };
  16562. async.forEachLimit = async.eachLimit;
  16563. var _eachLimit = function (limit) {
  16564. return function (arr, iterator, callback) {
  16565. callback = callback || function () {};
  16566. if (!arr.length || limit <= 0) {
  16567. return callback();
  16568. }
  16569. var completed = 0;
  16570. var started = 0;
  16571. var running = 0;
  16572. (function replenish () {
  16573. if (completed >= arr.length) {
  16574. return callback();
  16575. }
  16576. while (running < limit && started < arr.length) {
  16577. started += 1;
  16578. running += 1;
  16579. iterator(arr[started - 1], function (err) {
  16580. if (err) {
  16581. callback(err);
  16582. callback = function () {};
  16583. }
  16584. else {
  16585. completed += 1;
  16586. running -= 1;
  16587. if (completed >= arr.length) {
  16588. callback();
  16589. }
  16590. else {
  16591. replenish();
  16592. }
  16593. }
  16594. });
  16595. }
  16596. })();
  16597. };
  16598. };
  16599. var doParallel = function (fn) {
  16600. return function () {
  16601. var args = Array.prototype.slice.call(arguments);
  16602. return fn.apply(null, [async.each].concat(args));
  16603. };
  16604. };
  16605. var doParallelLimit = function(limit, fn) {
  16606. return function () {
  16607. var args = Array.prototype.slice.call(arguments);
  16608. return fn.apply(null, [_eachLimit(limit)].concat(args));
  16609. };
  16610. };
  16611. var doSeries = function (fn) {
  16612. return function () {
  16613. var args = Array.prototype.slice.call(arguments);
  16614. return fn.apply(null, [async.eachSeries].concat(args));
  16615. };
  16616. };
  16617. var _asyncMap = function (eachfn, arr, iterator, callback) {
  16618. arr = _map(arr, function (x, i) {
  16619. return {index: i, value: x};
  16620. });
  16621. if (!callback) {
  16622. eachfn(arr, function (x, callback) {
  16623. iterator(x.value, function (err) {
  16624. callback(err);
  16625. });
  16626. });
  16627. } else {
  16628. var results = [];
  16629. eachfn(arr, function (x, callback) {
  16630. iterator(x.value, function (err, v) {
  16631. results[x.index] = v;
  16632. callback(err);
  16633. });
  16634. }, function (err) {
  16635. callback(err, results);
  16636. });
  16637. }
  16638. };
  16639. async.map = doParallel(_asyncMap);
  16640. async.mapSeries = doSeries(_asyncMap);
  16641. async.mapLimit = function (arr, limit, iterator, callback) {
  16642. return _mapLimit(limit)(arr, iterator, callback);
  16643. };
  16644. var _mapLimit = function(limit) {
  16645. return doParallelLimit(limit, _asyncMap);
  16646. };
  16647. // reduce only has a series version, as doing reduce in parallel won't
  16648. // work in many situations.
  16649. async.reduce = function (arr, memo, iterator, callback) {
  16650. async.eachSeries(arr, function (x, callback) {
  16651. iterator(memo, x, function (err, v) {
  16652. memo = v;
  16653. callback(err);
  16654. });
  16655. }, function (err) {
  16656. callback(err, memo);
  16657. });
  16658. };
  16659. // inject alias
  16660. async.inject = async.reduce;
  16661. // foldl alias
  16662. async.foldl = async.reduce;
  16663. async.reduceRight = function (arr, memo, iterator, callback) {
  16664. var reversed = _map(arr, function (x) {
  16665. return x;
  16666. }).reverse();
  16667. async.reduce(reversed, memo, iterator, callback);
  16668. };
  16669. // foldr alias
  16670. async.foldr = async.reduceRight;
  16671. var _filter = function (eachfn, arr, iterator, callback) {
  16672. var results = [];
  16673. arr = _map(arr, function (x, i) {
  16674. return {index: i, value: x};
  16675. });
  16676. eachfn(arr, function (x, callback) {
  16677. iterator(x.value, function (v) {
  16678. if (v) {
  16679. results.push(x);
  16680. }
  16681. callback();
  16682. });
  16683. }, function (err) {
  16684. callback(_map(results.sort(function (a, b) {
  16685. return a.index - b.index;
  16686. }), function (x) {
  16687. return x.value;
  16688. }));
  16689. });
  16690. };
  16691. async.filter = doParallel(_filter);
  16692. async.filterSeries = doSeries(_filter);
  16693. // select alias
  16694. async.select = async.filter;
  16695. async.selectSeries = async.filterSeries;
  16696. var _reject = function (eachfn, arr, iterator, callback) {
  16697. var results = [];
  16698. arr = _map(arr, function (x, i) {
  16699. return {index: i, value: x};
  16700. });
  16701. eachfn(arr, function (x, callback) {
  16702. iterator(x.value, function (v) {
  16703. if (!v) {
  16704. results.push(x);
  16705. }
  16706. callback();
  16707. });
  16708. }, function (err) {
  16709. callback(_map(results.sort(function (a, b) {
  16710. return a.index - b.index;
  16711. }), function (x) {
  16712. return x.value;
  16713. }));
  16714. });
  16715. };
  16716. async.reject = doParallel(_reject);
  16717. async.rejectSeries = doSeries(_reject);
  16718. var _detect = function (eachfn, arr, iterator, main_callback) {
  16719. eachfn(arr, function (x, callback) {
  16720. iterator(x, function (result) {
  16721. if (result) {
  16722. main_callback(x);
  16723. main_callback = function () {};
  16724. }
  16725. else {
  16726. callback();
  16727. }
  16728. });
  16729. }, function (err) {
  16730. main_callback();
  16731. });
  16732. };
  16733. async.detect = doParallel(_detect);
  16734. async.detectSeries = doSeries(_detect);
  16735. async.some = function (arr, iterator, main_callback) {
  16736. async.each(arr, function (x, callback) {
  16737. iterator(x, function (v) {
  16738. if (v) {
  16739. main_callback(true);
  16740. main_callback = function () {};
  16741. }
  16742. callback();
  16743. });
  16744. }, function (err) {
  16745. main_callback(false);
  16746. });
  16747. };
  16748. // any alias
  16749. async.any = async.some;
  16750. async.every = function (arr, iterator, main_callback) {
  16751. async.each(arr, function (x, callback) {
  16752. iterator(x, function (v) {
  16753. if (!v) {
  16754. main_callback(false);
  16755. main_callback = function () {};
  16756. }
  16757. callback();
  16758. });
  16759. }, function (err) {
  16760. main_callback(true);
  16761. });
  16762. };
  16763. // all alias
  16764. async.all = async.every;
  16765. async.sortBy = function (arr, iterator, callback) {
  16766. async.map(arr, function (x, callback) {
  16767. iterator(x, function (err, criteria) {
  16768. if (err) {
  16769. callback(err);
  16770. }
  16771. else {
  16772. callback(null, {value: x, criteria: criteria});
  16773. }
  16774. });
  16775. }, function (err, results) {
  16776. if (err) {
  16777. return callback(err);
  16778. }
  16779. else {
  16780. var fn = function (left, right) {
  16781. var a = left.criteria, b = right.criteria;
  16782. return a < b ? -1 : a > b ? 1 : 0;
  16783. };
  16784. callback(null, _map(results.sort(fn), function (x) {
  16785. return x.value;
  16786. }));
  16787. }
  16788. });
  16789. };
  16790. async.auto = function (tasks, callback) {
  16791. callback = callback || function () {};
  16792. var keys = _keys(tasks);
  16793. var remainingTasks = keys.length
  16794. if (!remainingTasks) {
  16795. return callback();
  16796. }
  16797. var results = {};
  16798. var listeners = [];
  16799. var addListener = function (fn) {
  16800. listeners.unshift(fn);
  16801. };
  16802. var removeListener = function (fn) {
  16803. for (var i = 0; i < listeners.length; i += 1) {
  16804. if (listeners[i] === fn) {
  16805. listeners.splice(i, 1);
  16806. return;
  16807. }
  16808. }
  16809. };
  16810. var taskComplete = function () {
  16811. remainingTasks--
  16812. _each(listeners.slice(0), function (fn) {
  16813. fn();
  16814. });
  16815. };
  16816. addListener(function () {
  16817. if (!remainingTasks) {
  16818. var theCallback = callback;
  16819. // prevent final callback from calling itself if it errors
  16820. callback = function () {};
  16821. theCallback(null, results);
  16822. }
  16823. });
  16824. _each(keys, function (k) {
  16825. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  16826. var taskCallback = function (err) {
  16827. var args = Array.prototype.slice.call(arguments, 1);
  16828. if (args.length <= 1) {
  16829. args = args[0];
  16830. }
  16831. if (err) {
  16832. var safeResults = {};
  16833. _each(_keys(results), function(rkey) {
  16834. safeResults[rkey] = results[rkey];
  16835. });
  16836. safeResults[k] = args;
  16837. callback(err, safeResults);
  16838. // stop subsequent errors hitting callback multiple times
  16839. callback = function () {};
  16840. }
  16841. else {
  16842. results[k] = args;
  16843. async.setImmediate(taskComplete);
  16844. }
  16845. };
  16846. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  16847. var ready = function () {
  16848. return _reduce(requires, function (a, x) {
  16849. return (a && results.hasOwnProperty(x));
  16850. }, true) && !results.hasOwnProperty(k);
  16851. };
  16852. if (ready()) {
  16853. task[task.length - 1](taskCallback, results);
  16854. }
  16855. else {
  16856. var listener = function () {
  16857. if (ready()) {
  16858. removeListener(listener);
  16859. task[task.length - 1](taskCallback, results);
  16860. }
  16861. };
  16862. addListener(listener);
  16863. }
  16864. });
  16865. };
  16866. async.retry = function(times, task, callback) {
  16867. var DEFAULT_TIMES = 5;
  16868. var attempts = [];
  16869. // Use defaults if times not passed
  16870. if (typeof times === 'function') {
  16871. callback = task;
  16872. task = times;
  16873. times = DEFAULT_TIMES;
  16874. }
  16875. // Make sure times is a number
  16876. times = parseInt(times, 10) || DEFAULT_TIMES;
  16877. var wrappedTask = function(wrappedCallback, wrappedResults) {
  16878. var retryAttempt = function(task, finalAttempt) {
  16879. return function(seriesCallback) {
  16880. task(function(err, result){
  16881. seriesCallback(!err || finalAttempt, {err: err, result: result});
  16882. }, wrappedResults);
  16883. };
  16884. };
  16885. while (times) {
  16886. attempts.push(retryAttempt(task, !(times-=1)));
  16887. }
  16888. async.series(attempts, function(done, data){
  16889. data = data[data.length - 1];
  16890. (wrappedCallback || callback)(data.err, data.result);
  16891. });
  16892. }
  16893. // If a callback is passed, run this as a controll flow
  16894. return callback ? wrappedTask() : wrappedTask
  16895. };
  16896. async.waterfall = function (tasks, callback) {
  16897. callback = callback || function () {};
  16898. if (!_isArray(tasks)) {
  16899. var err = new Error('First argument to waterfall must be an array of functions');
  16900. return callback(err);
  16901. }
  16902. if (!tasks.length) {
  16903. return callback();
  16904. }
  16905. var wrapIterator = function (iterator) {
  16906. return function (err) {
  16907. if (err) {
  16908. callback.apply(null, arguments);
  16909. callback = function () {};
  16910. }
  16911. else {
  16912. var args = Array.prototype.slice.call(arguments, 1);
  16913. var next = iterator.next();
  16914. if (next) {
  16915. args.push(wrapIterator(next));
  16916. }
  16917. else {
  16918. args.push(callback);
  16919. }
  16920. async.setImmediate(function () {
  16921. iterator.apply(null, args);
  16922. });
  16923. }
  16924. };
  16925. };
  16926. wrapIterator(async.iterator(tasks))();
  16927. };
  16928. var _parallel = function(eachfn, tasks, callback) {
  16929. callback = callback || function () {};
  16930. if (_isArray(tasks)) {
  16931. eachfn.map(tasks, function (fn, callback) {
  16932. if (fn) {
  16933. fn(function (err) {
  16934. var args = Array.prototype.slice.call(arguments, 1);
  16935. if (args.length <= 1) {
  16936. args = args[0];
  16937. }
  16938. callback.call(null, err, args);
  16939. });
  16940. }
  16941. }, callback);
  16942. }
  16943. else {
  16944. var results = {};
  16945. eachfn.each(_keys(tasks), function (k, callback) {
  16946. tasks[k](function (err) {
  16947. var args = Array.prototype.slice.call(arguments, 1);
  16948. if (args.length <= 1) {
  16949. args = args[0];
  16950. }
  16951. results[k] = args;
  16952. callback(err);
  16953. });
  16954. }, function (err) {
  16955. callback(err, results);
  16956. });
  16957. }
  16958. };
  16959. async.parallel = function (tasks, callback) {
  16960. _parallel({ map: async.map, each: async.each }, tasks, callback);
  16961. };
  16962. async.parallelLimit = function(tasks, limit, callback) {
  16963. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  16964. };
  16965. async.series = function (tasks, callback) {
  16966. callback = callback || function () {};
  16967. if (_isArray(tasks)) {
  16968. async.mapSeries(tasks, function (fn, callback) {
  16969. if (fn) {
  16970. fn(function (err) {
  16971. var args = Array.prototype.slice.call(arguments, 1);
  16972. if (args.length <= 1) {
  16973. args = args[0];
  16974. }
  16975. callback.call(null, err, args);
  16976. });
  16977. }
  16978. }, callback);
  16979. }
  16980. else {
  16981. var results = {};
  16982. async.eachSeries(_keys(tasks), function (k, callback) {
  16983. tasks[k](function (err) {
  16984. var args = Array.prototype.slice.call(arguments, 1);
  16985. if (args.length <= 1) {
  16986. args = args[0];
  16987. }
  16988. results[k] = args;
  16989. callback(err);
  16990. });
  16991. }, function (err) {
  16992. callback(err, results);
  16993. });
  16994. }
  16995. };
  16996. async.iterator = function (tasks) {
  16997. var makeCallback = function (index) {
  16998. var fn = function () {
  16999. if (tasks.length) {
  17000. tasks[index].apply(null, arguments);
  17001. }
  17002. return fn.next();
  17003. };
  17004. fn.next = function () {
  17005. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  17006. };
  17007. return fn;
  17008. };
  17009. return makeCallback(0);
  17010. };
  17011. async.apply = function (fn) {
  17012. var args = Array.prototype.slice.call(arguments, 1);
  17013. return function () {
  17014. return fn.apply(
  17015. null, args.concat(Array.prototype.slice.call(arguments))
  17016. );
  17017. };
  17018. };
  17019. var _concat = function (eachfn, arr, fn, callback) {
  17020. var r = [];
  17021. eachfn(arr, function (x, cb) {
  17022. fn(x, function (err, y) {
  17023. r = r.concat(y || []);
  17024. cb(err);
  17025. });
  17026. }, function (err) {
  17027. callback(err, r);
  17028. });
  17029. };
  17030. async.concat = doParallel(_concat);
  17031. async.concatSeries = doSeries(_concat);
  17032. async.whilst = function (test, iterator, callback) {
  17033. if (test()) {
  17034. iterator(function (err) {
  17035. if (err) {
  17036. return callback(err);
  17037. }
  17038. async.whilst(test, iterator, callback);
  17039. });
  17040. }
  17041. else {
  17042. callback();
  17043. }
  17044. };
  17045. async.doWhilst = function (iterator, test, callback) {
  17046. iterator(function (err) {
  17047. if (err) {
  17048. return callback(err);
  17049. }
  17050. var args = Array.prototype.slice.call(arguments, 1);
  17051. if (test.apply(null, args)) {
  17052. async.doWhilst(iterator, test, callback);
  17053. }
  17054. else {
  17055. callback();
  17056. }
  17057. });
  17058. };
  17059. async.until = function (test, iterator, callback) {
  17060. if (!test()) {
  17061. iterator(function (err) {
  17062. if (err) {
  17063. return callback(err);
  17064. }
  17065. async.until(test, iterator, callback);
  17066. });
  17067. }
  17068. else {
  17069. callback();
  17070. }
  17071. };
  17072. async.doUntil = function (iterator, test, callback) {
  17073. iterator(function (err) {
  17074. if (err) {
  17075. return callback(err);
  17076. }
  17077. var args = Array.prototype.slice.call(arguments, 1);
  17078. if (!test.apply(null, args)) {
  17079. async.doUntil(iterator, test, callback);
  17080. }
  17081. else {
  17082. callback();
  17083. }
  17084. });
  17085. };
  17086. async.queue = function (worker, concurrency) {
  17087. if (concurrency === undefined) {
  17088. concurrency = 1;
  17089. }
  17090. function _insert(q, data, pos, callback) {
  17091. if (!q.started){
  17092. q.started = true;
  17093. }
  17094. if (!_isArray(data)) {
  17095. data = [data];
  17096. }
  17097. if(data.length == 0) {
  17098. // call drain immediately if there are no tasks
  17099. return async.setImmediate(function() {
  17100. if (q.drain) {
  17101. q.drain();
  17102. }
  17103. });
  17104. }
  17105. _each(data, function(task) {
  17106. var item = {
  17107. data: task,
  17108. callback: typeof callback === 'function' ? callback : null
  17109. };
  17110. if (pos) {
  17111. q.tasks.unshift(item);
  17112. } else {
  17113. q.tasks.push(item);
  17114. }
  17115. if (q.saturated && q.tasks.length === q.concurrency) {
  17116. q.saturated();
  17117. }
  17118. async.setImmediate(q.process);
  17119. });
  17120. }
  17121. var workers = 0;
  17122. var q = {
  17123. tasks: [],
  17124. concurrency: concurrency,
  17125. saturated: null,
  17126. empty: null,
  17127. drain: null,
  17128. started: false,
  17129. paused: false,
  17130. push: function (data, callback) {
  17131. _insert(q, data, false, callback);
  17132. },
  17133. kill: function () {
  17134. q.drain = null;
  17135. q.tasks = [];
  17136. },
  17137. unshift: function (data, callback) {
  17138. _insert(q, data, true, callback);
  17139. },
  17140. process: function () {
  17141. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  17142. var task = q.tasks.shift();
  17143. if (q.empty && q.tasks.length === 0) {
  17144. q.empty();
  17145. }
  17146. workers += 1;
  17147. var next = function () {
  17148. workers -= 1;
  17149. if (task.callback) {
  17150. task.callback.apply(task, arguments);
  17151. }
  17152. if (q.drain && q.tasks.length + workers === 0) {
  17153. q.drain();
  17154. }
  17155. q.process();
  17156. };
  17157. var cb = only_once(next);
  17158. worker(task.data, cb);
  17159. }
  17160. },
  17161. length: function () {
  17162. return q.tasks.length;
  17163. },
  17164. running: function () {
  17165. return workers;
  17166. },
  17167. idle: function() {
  17168. return q.tasks.length + workers === 0;
  17169. },
  17170. pause: function () {
  17171. if (q.paused === true) { return; }
  17172. q.paused = true;
  17173. q.process();
  17174. },
  17175. resume: function () {
  17176. if (q.paused === false) { return; }
  17177. q.paused = false;
  17178. q.process();
  17179. }
  17180. };
  17181. return q;
  17182. };
  17183. async.priorityQueue = function (worker, concurrency) {
  17184. function _compareTasks(a, b){
  17185. return a.priority - b.priority;
  17186. };
  17187. function _binarySearch(sequence, item, compare) {
  17188. var beg = -1,
  17189. end = sequence.length - 1;
  17190. while (beg < end) {
  17191. var mid = beg + ((end - beg + 1) >>> 1);
  17192. if (compare(item, sequence[mid]) >= 0) {
  17193. beg = mid;
  17194. } else {
  17195. end = mid - 1;
  17196. }
  17197. }
  17198. return beg;
  17199. }
  17200. function _insert(q, data, priority, callback) {
  17201. if (!q.started){
  17202. q.started = true;
  17203. }
  17204. if (!_isArray(data)) {
  17205. data = [data];
  17206. }
  17207. if(data.length == 0) {
  17208. // call drain immediately if there are no tasks
  17209. return async.setImmediate(function() {
  17210. if (q.drain) {
  17211. q.drain();
  17212. }
  17213. });
  17214. }
  17215. _each(data, function(task) {
  17216. var item = {
  17217. data: task,
  17218. priority: priority,
  17219. callback: typeof callback === 'function' ? callback : null
  17220. };
  17221. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  17222. if (q.saturated && q.tasks.length === q.concurrency) {
  17223. q.saturated();
  17224. }
  17225. async.setImmediate(q.process);
  17226. });
  17227. }
  17228. // Start with a normal queue
  17229. var q = async.queue(worker, concurrency);
  17230. // Override push to accept second parameter representing priority
  17231. q.push = function (data, priority, callback) {
  17232. _insert(q, data, priority, callback);
  17233. };
  17234. // Remove unshift function
  17235. delete q.unshift;
  17236. return q;
  17237. };
  17238. async.cargo = function (worker, payload) {
  17239. var working = false,
  17240. tasks = [];
  17241. var cargo = {
  17242. tasks: tasks,
  17243. payload: payload,
  17244. saturated: null,
  17245. empty: null,
  17246. drain: null,
  17247. drained: true,
  17248. push: function (data, callback) {
  17249. if (!_isArray(data)) {
  17250. data = [data];
  17251. }
  17252. _each(data, function(task) {
  17253. tasks.push({
  17254. data: task,
  17255. callback: typeof callback === 'function' ? callback : null
  17256. });
  17257. cargo.drained = false;
  17258. if (cargo.saturated && tasks.length === payload) {
  17259. cargo.saturated();
  17260. }
  17261. });
  17262. async.setImmediate(cargo.process);
  17263. },
  17264. process: function process() {
  17265. if (working) return;
  17266. if (tasks.length === 0) {
  17267. if(cargo.drain && !cargo.drained) cargo.drain();
  17268. cargo.drained = true;
  17269. return;
  17270. }
  17271. var ts = typeof payload === 'number'
  17272. ? tasks.splice(0, payload)
  17273. : tasks.splice(0, tasks.length);
  17274. var ds = _map(ts, function (task) {
  17275. return task.data;
  17276. });
  17277. if(cargo.empty) cargo.empty();
  17278. working = true;
  17279. worker(ds, function () {
  17280. working = false;
  17281. var args = arguments;
  17282. _each(ts, function (data) {
  17283. if (data.callback) {
  17284. data.callback.apply(null, args);
  17285. }
  17286. });
  17287. process();
  17288. });
  17289. },
  17290. length: function () {
  17291. return tasks.length;
  17292. },
  17293. running: function () {
  17294. return working;
  17295. }
  17296. };
  17297. return cargo;
  17298. };
  17299. var _console_fn = function (name) {
  17300. return function (fn) {
  17301. var args = Array.prototype.slice.call(arguments, 1);
  17302. fn.apply(null, args.concat([function (err) {
  17303. var args = Array.prototype.slice.call(arguments, 1);
  17304. if (typeof console !== 'undefined') {
  17305. if (err) {
  17306. if (console.error) {
  17307. console.error(err);
  17308. }
  17309. }
  17310. else if (console[name]) {
  17311. _each(args, function (x) {
  17312. console[name](x);
  17313. });
  17314. }
  17315. }
  17316. }]));
  17317. };
  17318. };
  17319. async.log = _console_fn('log');
  17320. async.dir = _console_fn('dir');
  17321. /*async.info = _console_fn('info');
  17322. async.warn = _console_fn('warn');
  17323. async.error = _console_fn('error');*/
  17324. async.memoize = function (fn, hasher) {
  17325. var memo = {};
  17326. var queues = {};
  17327. hasher = hasher || function (x) {
  17328. return x;
  17329. };
  17330. var memoized = function () {
  17331. var args = Array.prototype.slice.call(arguments);
  17332. var callback = args.pop();
  17333. var key = hasher.apply(null, args);
  17334. if (key in memo) {
  17335. async.nextTick(function () {
  17336. callback.apply(null, memo[key]);
  17337. });
  17338. }
  17339. else if (key in queues) {
  17340. queues[key].push(callback);
  17341. }
  17342. else {
  17343. queues[key] = [callback];
  17344. fn.apply(null, args.concat([function () {
  17345. memo[key] = arguments;
  17346. var q = queues[key];
  17347. delete queues[key];
  17348. for (var i = 0, l = q.length; i < l; i++) {
  17349. q[i].apply(null, arguments);
  17350. }
  17351. }]));
  17352. }
  17353. };
  17354. memoized.memo = memo;
  17355. memoized.unmemoized = fn;
  17356. return memoized;
  17357. };
  17358. async.unmemoize = function (fn) {
  17359. return function () {
  17360. return (fn.unmemoized || fn).apply(null, arguments);
  17361. };
  17362. };
  17363. async.times = function (count, iterator, callback) {
  17364. var counter = [];
  17365. for (var i = 0; i < count; i++) {
  17366. counter.push(i);
  17367. }
  17368. return async.map(counter, iterator, callback);
  17369. };
  17370. async.timesSeries = function (count, iterator, callback) {
  17371. var counter = [];
  17372. for (var i = 0; i < count; i++) {
  17373. counter.push(i);
  17374. }
  17375. return async.mapSeries(counter, iterator, callback);
  17376. };
  17377. async.seq = function (/* functions... */) {
  17378. var fns = arguments;
  17379. return function () {
  17380. var that = this;
  17381. var args = Array.prototype.slice.call(arguments);
  17382. var callback = args.pop();
  17383. async.reduce(fns, args, function (newargs, fn, cb) {
  17384. fn.apply(that, newargs.concat([function () {
  17385. var err = arguments[0];
  17386. var nextargs = Array.prototype.slice.call(arguments, 1);
  17387. cb(err, nextargs);
  17388. }]))
  17389. },
  17390. function (err, results) {
  17391. callback.apply(that, [err].concat(results));
  17392. });
  17393. };
  17394. };
  17395. async.compose = function (/* functions... */) {
  17396. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  17397. };
  17398. var _applyEach = function (eachfn, fns /*args...*/) {
  17399. var go = function () {
  17400. var that = this;
  17401. var args = Array.prototype.slice.call(arguments);
  17402. var callback = args.pop();
  17403. return eachfn(fns, function (fn, cb) {
  17404. fn.apply(that, args.concat([cb]));
  17405. },
  17406. callback);
  17407. };
  17408. if (arguments.length > 2) {
  17409. var args = Array.prototype.slice.call(arguments, 2);
  17410. return go.apply(this, args);
  17411. }
  17412. else {
  17413. return go;
  17414. }
  17415. };
  17416. async.applyEach = doParallel(_applyEach);
  17417. async.applyEachSeries = doSeries(_applyEach);
  17418. async.forever = function (fn, callback) {
  17419. function next(err) {
  17420. if (err) {
  17421. if (callback) {
  17422. return callback(err);
  17423. }
  17424. throw err;
  17425. }
  17426. fn(next);
  17427. }
  17428. next();
  17429. };
  17430. // Node.js
  17431. if (typeof module !== 'undefined' && module.exports) {
  17432. module.exports = async;
  17433. }
  17434. // AMD / RequireJS
  17435. else if (typeof define !== 'undefined' && define.amd) {
  17436. define([], function () {
  17437. return async;
  17438. });
  17439. }
  17440. // included directly via <script> tag
  17441. else {
  17442. root.async = async;
  17443. }
  17444. }());
  17445. }).call(this,require('_process'))
  17446. },{"_process":110}],68:[function(require,module,exports){
  17447. // i18next, v1.7.7
  17448. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  17449. // Distributed under MIT license
  17450. // http://i18next.com
  17451. (function() {
  17452. // add indexOf to non ECMA-262 standard compliant browsers
  17453. if (!Array.prototype.indexOf) {
  17454. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  17455. "use strict";
  17456. if (this == null) {
  17457. throw new TypeError();
  17458. }
  17459. var t = Object(this);
  17460. var len = t.length >>> 0;
  17461. if (len === 0) {
  17462. return -1;
  17463. }
  17464. var n = 0;
  17465. if (arguments.length > 0) {
  17466. n = Number(arguments[1]);
  17467. if (n != n) { // shortcut for verifying if it's NaN
  17468. n = 0;
  17469. } else if (n != 0 && n != Infinity && n != -Infinity) {
  17470. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  17471. }
  17472. }
  17473. if (n >= len) {
  17474. return -1;
  17475. }
  17476. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  17477. for (; k < len; k++) {
  17478. if (k in t && t[k] === searchElement) {
  17479. return k;
  17480. }
  17481. }
  17482. return -1;
  17483. }
  17484. }
  17485. // add lastIndexOf to non ECMA-262 standard compliant browsers
  17486. if (!Array.prototype.lastIndexOf) {
  17487. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  17488. "use strict";
  17489. if (this == null) {
  17490. throw new TypeError();
  17491. }
  17492. var t = Object(this);
  17493. var len = t.length >>> 0;
  17494. if (len === 0) {
  17495. return -1;
  17496. }
  17497. var n = len;
  17498. if (arguments.length > 1) {
  17499. n = Number(arguments[1]);
  17500. if (n != n) {
  17501. n = 0;
  17502. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  17503. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  17504. }
  17505. }
  17506. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  17507. for (; k >= 0; k--) {
  17508. if (k in t && t[k] === searchElement) {
  17509. return k;
  17510. }
  17511. }
  17512. return -1;
  17513. };
  17514. }
  17515. // Add string trim for IE8.
  17516. if (typeof String.prototype.trim !== 'function') {
  17517. String.prototype.trim = function() {
  17518. return this.replace(/^\s+|\s+$/g, '');
  17519. }
  17520. }
  17521. var root = this
  17522. , $ = root.jQuery || root.Zepto
  17523. , i18n = {}
  17524. , resStore = {}
  17525. , currentLng
  17526. , replacementCounter = 0
  17527. , languages = []
  17528. , initialized = false
  17529. , sync = {};
  17530. // Export the i18next object for **CommonJS**.
  17531. // If we're not in CommonJS, add `i18n` to the
  17532. // global object or to jquery.
  17533. if (typeof module !== 'undefined' && module.exports) {
  17534. if (!$) {
  17535. try {
  17536. $ = require('jquery');
  17537. } catch(e) {
  17538. // just ignore
  17539. }
  17540. }
  17541. if ($) {
  17542. $.i18n = $.i18n || i18n;
  17543. }
  17544. module.exports = i18n;
  17545. } else {
  17546. if ($) {
  17547. $.i18n = $.i18n || i18n;
  17548. }
  17549. root.i18n = root.i18n || i18n;
  17550. }
  17551. sync = {
  17552. load: function(lngs, options, cb) {
  17553. if (options.useLocalStorage) {
  17554. sync._loadLocal(lngs, options, function(err, store) {
  17555. var missingLngs = [];
  17556. for (var i = 0, len = lngs.length; i < len; i++) {
  17557. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  17558. }
  17559. if (missingLngs.length > 0) {
  17560. sync._fetch(missingLngs, options, function(err, fetched) {
  17561. f.extend(store, fetched);
  17562. sync._storeLocal(fetched);
  17563. cb(null, store);
  17564. });
  17565. } else {
  17566. cb(null, store);
  17567. }
  17568. });
  17569. } else {
  17570. sync._fetch(lngs, options, function(err, store){
  17571. cb(null, store);
  17572. });
  17573. }
  17574. },
  17575. _loadLocal: function(lngs, options, cb) {
  17576. var store = {}
  17577. , nowMS = new Date().getTime();
  17578. if(window.localStorage) {
  17579. var todo = lngs.length;
  17580. f.each(lngs, function(key, lng) {
  17581. var local = window.localStorage.getItem('res_' + lng);
  17582. if (local) {
  17583. local = JSON.parse(local);
  17584. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  17585. store[lng] = local;
  17586. }
  17587. }
  17588. todo--; // wait for all done befor callback
  17589. if (todo === 0) cb(null, store);
  17590. });
  17591. }
  17592. },
  17593. _storeLocal: function(store) {
  17594. if(window.localStorage) {
  17595. for (var m in store) {
  17596. store[m].i18nStamp = new Date().getTime();
  17597. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  17598. }
  17599. }
  17600. return;
  17601. },
  17602. _fetch: function(lngs, options, cb) {
  17603. var ns = options.ns
  17604. , store = {};
  17605. if (!options.dynamicLoad) {
  17606. var todo = ns.namespaces.length * lngs.length
  17607. , errors;
  17608. // load each file individual
  17609. f.each(ns.namespaces, function(nsIndex, nsValue) {
  17610. f.each(lngs, function(lngIndex, lngValue) {
  17611. // Call this once our translation has returned.
  17612. var loadComplete = function(err, data) {
  17613. if (err) {
  17614. errors = errors || [];
  17615. errors.push(err);
  17616. }
  17617. store[lngValue] = store[lngValue] || {};
  17618. store[lngValue][nsValue] = data;
  17619. todo--; // wait for all done befor callback
  17620. if (todo === 0) cb(errors, store);
  17621. };
  17622. if(typeof options.customLoad == 'function'){
  17623. // Use the specified custom callback.
  17624. options.customLoad(lngValue, nsValue, options, loadComplete);
  17625. } else {
  17626. //~ // Use our inbuilt sync.
  17627. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  17628. }
  17629. });
  17630. });
  17631. } else {
  17632. // Call this once our translation has returned.
  17633. var loadComplete = function(err, data) {
  17634. cb(null, data);
  17635. };
  17636. if(typeof options.customLoad == 'function'){
  17637. // Use the specified custom callback.
  17638. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  17639. } else {
  17640. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  17641. // load all needed stuff once
  17642. f.ajax({
  17643. url: url,
  17644. success: function(data, status, xhr) {
  17645. f.log('loaded: ' + url);
  17646. loadComplete(null, data);
  17647. },
  17648. error : function(xhr, status, error) {
  17649. f.log('failed loading: ' + url);
  17650. loadComplete('failed loading resource.json error: ' + error);
  17651. },
  17652. dataType: "json",
  17653. async : options.getAsync
  17654. });
  17655. }
  17656. }
  17657. },
  17658. _fetchOne: function(lng, ns, options, done) {
  17659. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  17660. f.ajax({
  17661. url: url,
  17662. success: function(data, status, xhr) {
  17663. f.log('loaded: ' + url);
  17664. done(null, data);
  17665. },
  17666. error : function(xhr, status, error) {
  17667. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  17668. // file loaded but invalid json, stop waste time !
  17669. f.error('There is a typo in: ' + url);
  17670. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  17671. f.log('Does not exist: ' + url);
  17672. } else {
  17673. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  17674. f.log(theStatus + ' when loading ' + url);
  17675. }
  17676. done(error, {});
  17677. },
  17678. dataType: "json",
  17679. async : options.getAsync
  17680. });
  17681. },
  17682. postMissing: function(lng, ns, key, defaultValue, lngs) {
  17683. var payload = {};
  17684. payload[key] = defaultValue;
  17685. var urls = [];
  17686. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  17687. for (var i = 0; i < o.fallbackLng.length; i++) {
  17688. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  17689. }
  17690. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  17691. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  17692. } else if (o.sendMissingTo === 'all') {
  17693. for (var i = 0, l = lngs.length; i < l; i++) {
  17694. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  17695. }
  17696. }
  17697. for (var y = 0, len = urls.length; y < len; y++) {
  17698. var item = urls[y];
  17699. f.ajax({
  17700. url: item.url,
  17701. type: o.sendType,
  17702. data: payload,
  17703. success: function(data, status, xhr) {
  17704. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  17705. // add key to resStore
  17706. var keys = key.split('.');
  17707. var x = 0;
  17708. var value = resStore[item.lng][ns];
  17709. while (keys[x]) {
  17710. if (x === keys.length - 1) {
  17711. value = value[keys[x]] = defaultValue;
  17712. } else {
  17713. value = value[keys[x]] = value[keys[x]] || {};
  17714. }
  17715. x++;
  17716. }
  17717. },
  17718. error : function(xhr, status, error) {
  17719. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  17720. },
  17721. dataType: "json",
  17722. async : o.postAsync
  17723. });
  17724. }
  17725. },
  17726. reload: reload
  17727. };
  17728. // defaults
  17729. var o = {
  17730. lng: undefined,
  17731. load: 'all',
  17732. preload: [],
  17733. lowerCaseLng: false,
  17734. returnObjectTrees: false,
  17735. fallbackLng: ['dev'],
  17736. fallbackNS: [],
  17737. detectLngQS: 'setLng',
  17738. detectLngFromLocalStorage: false,
  17739. ns: 'translation',
  17740. fallbackOnNull: true,
  17741. fallbackOnEmpty: false,
  17742. fallbackToDefaultNS: false,
  17743. nsseparator: ':',
  17744. keyseparator: '.',
  17745. selectorAttr: 'data-i18n',
  17746. debug: false,
  17747. resGetPath: 'locales/__lng__/__ns__.json',
  17748. resPostPath: 'locales/add/__lng__/__ns__',
  17749. getAsync: true,
  17750. postAsync: true,
  17751. resStore: undefined,
  17752. useLocalStorage: false,
  17753. localStorageExpirationTime: 7*24*60*60*1000,
  17754. dynamicLoad: false,
  17755. sendMissing: false,
  17756. sendMissingTo: 'fallback', // current | all
  17757. sendType: 'POST',
  17758. interpolationPrefix: '__',
  17759. interpolationSuffix: '__',
  17760. defaultVariables: false,
  17761. reusePrefix: '$t(',
  17762. reuseSuffix: ')',
  17763. pluralSuffix: '_plural',
  17764. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  17765. contextNotFound: ['context_not_found', Math.random()].join(''),
  17766. escapeInterpolation: false,
  17767. indefiniteSuffix: '_indefinite',
  17768. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  17769. setJqueryExt: true,
  17770. defaultValueFromContent: true,
  17771. useDataAttrOptions: false,
  17772. cookieExpirationTime: undefined,
  17773. useCookie: true,
  17774. cookieName: 'i18next',
  17775. cookieDomain: undefined,
  17776. objectTreeKeyHandler: undefined,
  17777. postProcess: undefined,
  17778. parseMissingKey: undefined,
  17779. missingKeyHandler: sync.postMissing,
  17780. shortcutFunction: 'sprintf' // or: defaultValue
  17781. };
  17782. function _extend(target, source) {
  17783. if (!source || typeof source === 'function') {
  17784. return target;
  17785. }
  17786. for (var attr in source) { target[attr] = source[attr]; }
  17787. return target;
  17788. }
  17789. function _deepExtend(target, source) {
  17790. for (var prop in source)
  17791. if (prop in target)
  17792. _deepExtend(target[prop], source[prop]);
  17793. else
  17794. target[prop] = source[prop];
  17795. return target;
  17796. }
  17797. function _each(object, callback, args) {
  17798. var name, i = 0,
  17799. length = object.length,
  17800. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  17801. if (args) {
  17802. if (isObj) {
  17803. for (name in object) {
  17804. if (callback.apply(object[name], args) === false) {
  17805. break;
  17806. }
  17807. }
  17808. } else {
  17809. for ( ; i < length; ) {
  17810. if (callback.apply(object[i++], args) === false) {
  17811. break;
  17812. }
  17813. }
  17814. }
  17815. // A special, fast, case for the most common use of each
  17816. } else {
  17817. if (isObj) {
  17818. for (name in object) {
  17819. if (callback.call(object[name], name, object[name]) === false) {
  17820. break;
  17821. }
  17822. }
  17823. } else {
  17824. for ( ; i < length; ) {
  17825. if (callback.call(object[i], i, object[i++]) === false) {
  17826. break;
  17827. }
  17828. }
  17829. }
  17830. }
  17831. return object;
  17832. }
  17833. var _entityMap = {
  17834. "&": "&amp;",
  17835. "<": "&lt;",
  17836. ">": "&gt;",
  17837. '"': '&quot;',
  17838. "'": '&#39;',
  17839. "/": '&#x2F;'
  17840. };
  17841. function _escape(data) {
  17842. if (typeof data === 'string') {
  17843. return data.replace(/[&<>"'\/]/g, function (s) {
  17844. return _entityMap[s];
  17845. });
  17846. }else{
  17847. return data;
  17848. }
  17849. }
  17850. function _ajax(options) {
  17851. // v0.5.0 of https://github.com/goloroden/http.js
  17852. var getXhr = function (callback) {
  17853. // Use the native XHR object if the browser supports it.
  17854. if (window.XMLHttpRequest) {
  17855. return callback(null, new XMLHttpRequest());
  17856. } else if (window.ActiveXObject) {
  17857. // In Internet Explorer check for ActiveX versions of the XHR object.
  17858. try {
  17859. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  17860. } catch (e) {
  17861. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  17862. }
  17863. }
  17864. // If no XHR support was found, throw an error.
  17865. return callback(new Error());
  17866. };
  17867. var encodeUsingUrlEncoding = function (data) {
  17868. if(typeof data === 'string') {
  17869. return data;
  17870. }
  17871. var result = [];
  17872. for(var dataItem in data) {
  17873. if(data.hasOwnProperty(dataItem)) {
  17874. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  17875. }
  17876. }
  17877. return result.join('&');
  17878. };
  17879. var utf8 = function (text) {
  17880. text = text.replace(/\r\n/g, '\n');
  17881. var result = '';
  17882. for(var i = 0; i < text.length; i++) {
  17883. var c = text.charCodeAt(i);
  17884. if(c < 128) {
  17885. result += String.fromCharCode(c);
  17886. } else if((c > 127) && (c < 2048)) {
  17887. result += String.fromCharCode((c >> 6) | 192);
  17888. result += String.fromCharCode((c & 63) | 128);
  17889. } else {
  17890. result += String.fromCharCode((c >> 12) | 224);
  17891. result += String.fromCharCode(((c >> 6) & 63) | 128);
  17892. result += String.fromCharCode((c & 63) | 128);
  17893. }
  17894. }
  17895. return result;
  17896. };
  17897. var base64 = function (text) {
  17898. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  17899. text = utf8(text);
  17900. var result = '',
  17901. chr1, chr2, chr3,
  17902. enc1, enc2, enc3, enc4,
  17903. i = 0;
  17904. do {
  17905. chr1 = text.charCodeAt(i++);
  17906. chr2 = text.charCodeAt(i++);
  17907. chr3 = text.charCodeAt(i++);
  17908. enc1 = chr1 >> 2;
  17909. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  17910. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  17911. enc4 = chr3 & 63;
  17912. if(isNaN(chr2)) {
  17913. enc3 = enc4 = 64;
  17914. } else if(isNaN(chr3)) {
  17915. enc4 = 64;
  17916. }
  17917. result +=
  17918. keyStr.charAt(enc1) +
  17919. keyStr.charAt(enc2) +
  17920. keyStr.charAt(enc3) +
  17921. keyStr.charAt(enc4);
  17922. chr1 = chr2 = chr3 = '';
  17923. enc1 = enc2 = enc3 = enc4 = '';
  17924. } while(i < text.length);
  17925. return result;
  17926. };
  17927. var mergeHeaders = function () {
  17928. // Use the first header object as base.
  17929. var result = arguments[0];
  17930. // Iterate through the remaining header objects and add them.
  17931. for(var i = 1; i < arguments.length; i++) {
  17932. var currentHeaders = arguments[i];
  17933. for(var header in currentHeaders) {
  17934. if(currentHeaders.hasOwnProperty(header)) {
  17935. result[header] = currentHeaders[header];
  17936. }
  17937. }
  17938. }
  17939. // Return the merged headers.
  17940. return result;
  17941. };
  17942. var ajax = function (method, url, options, callback) {
  17943. // Adjust parameters.
  17944. if(typeof options === 'function') {
  17945. callback = options;
  17946. options = {};
  17947. }
  17948. // Set default parameter values.
  17949. options.cache = options.cache || false;
  17950. options.data = options.data || {};
  17951. options.headers = options.headers || {};
  17952. options.jsonp = options.jsonp || false;
  17953. options.async = options.async === undefined ? true : options.async;
  17954. // Merge the various header objects.
  17955. var headers = mergeHeaders({
  17956. 'accept': '*/*',
  17957. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  17958. }, ajax.headers, options.headers);
  17959. // Encode the data according to the content-type.
  17960. var payload;
  17961. if (headers['content-type'] === 'application/json') {
  17962. payload = JSON.stringify(options.data);
  17963. } else {
  17964. payload = encodeUsingUrlEncoding(options.data);
  17965. }
  17966. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  17967. // if neccessary.
  17968. if(method === 'GET') {
  17969. // Setup the query string.
  17970. var queryString = [];
  17971. if(payload) {
  17972. queryString.push(payload);
  17973. payload = null;
  17974. }
  17975. // Handle caching.
  17976. if(!options.cache) {
  17977. queryString.push('_=' + (new Date()).getTime());
  17978. }
  17979. // If neccessary prepare the query string for a JSONP call.
  17980. if(options.jsonp) {
  17981. queryString.push('callback=' + options.jsonp);
  17982. queryString.push('jsonp=' + options.jsonp);
  17983. }
  17984. // Merge the query string and attach it to the url.
  17985. queryString = queryString.join('&');
  17986. if (queryString.length > 1) {
  17987. if (url.indexOf('?') > -1) {
  17988. url += '&' + queryString;
  17989. } else {
  17990. url += '?' + queryString;
  17991. }
  17992. }
  17993. // Make a JSONP call if neccessary.
  17994. if(options.jsonp) {
  17995. var head = document.getElementsByTagName('head')[0];
  17996. var script = document.createElement('script');
  17997. script.type = 'text/javascript';
  17998. script.src = url;
  17999. head.appendChild(script);
  18000. return;
  18001. }
  18002. }
  18003. // Since we got here, it is no JSONP request, so make a normal XHR request.
  18004. getXhr(function (err, xhr) {
  18005. if(err) return callback(err);
  18006. // Open the request.
  18007. xhr.open(method, url, options.async);
  18008. // Set the request headers.
  18009. for(var header in headers) {
  18010. if(headers.hasOwnProperty(header)) {
  18011. xhr.setRequestHeader(header, headers[header]);
  18012. }
  18013. }
  18014. // Handle the request events.
  18015. xhr.onreadystatechange = function () {
  18016. if(xhr.readyState === 4) {
  18017. var data = xhr.responseText || '';
  18018. // If no callback is given, return.
  18019. if(!callback) {
  18020. return;
  18021. }
  18022. // Return an object that provides access to the data as text and JSON.
  18023. callback(xhr.status, {
  18024. text: function () {
  18025. return data;
  18026. },
  18027. json: function () {
  18028. try {
  18029. return JSON.parse(data)
  18030. } catch (e) {
  18031. f.error('Can not parse JSON. URL: ' + url);
  18032. return {};
  18033. }
  18034. }
  18035. });
  18036. }
  18037. };
  18038. // Actually send the XHR request.
  18039. xhr.send(payload);
  18040. });
  18041. };
  18042. // Define the external interface.
  18043. var http = {
  18044. authBasic: function (username, password) {
  18045. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  18046. },
  18047. connect: function (url, options, callback) {
  18048. return ajax('CONNECT', url, options, callback);
  18049. },
  18050. del: function (url, options, callback) {
  18051. return ajax('DELETE', url, options, callback);
  18052. },
  18053. get: function (url, options, callback) {
  18054. return ajax('GET', url, options, callback);
  18055. },
  18056. head: function (url, options, callback) {
  18057. return ajax('HEAD', url, options, callback);
  18058. },
  18059. headers: function (headers) {
  18060. ajax.headers = headers || {};
  18061. },
  18062. isAllowed: function (url, verb, callback) {
  18063. this.options(url, function (status, data) {
  18064. callback(data.text().indexOf(verb) !== -1);
  18065. });
  18066. },
  18067. options: function (url, options, callback) {
  18068. return ajax('OPTIONS', url, options, callback);
  18069. },
  18070. patch: function (url, options, callback) {
  18071. return ajax('PATCH', url, options, callback);
  18072. },
  18073. post: function (url, options, callback) {
  18074. return ajax('POST', url, options, callback);
  18075. },
  18076. put: function (url, options, callback) {
  18077. return ajax('PUT', url, options, callback);
  18078. },
  18079. trace: function (url, options, callback) {
  18080. return ajax('TRACE', url, options, callback);
  18081. }
  18082. };
  18083. var methode = options.type ? options.type.toLowerCase() : 'get';
  18084. http[methode](options.url, options, function (status, data) {
  18085. // file: protocol always gives status code 0, so check for data
  18086. if (status === 200 || (status === 0 && data.text())) {
  18087. options.success(data.json(), status, null);
  18088. } else {
  18089. options.error(data.text(), status, null);
  18090. }
  18091. });
  18092. }
  18093. var _cookie = {
  18094. create: function(name,value,minutes,domain) {
  18095. var expires;
  18096. if (minutes) {
  18097. var date = new Date();
  18098. date.setTime(date.getTime()+(minutes*60*1000));
  18099. expires = "; expires="+date.toGMTString();
  18100. }
  18101. else expires = "";
  18102. domain = (domain)? "domain="+domain+";" : "";
  18103. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  18104. },
  18105. read: function(name) {
  18106. var nameEQ = name + "=";
  18107. var ca = document.cookie.split(';');
  18108. for(var i=0;i < ca.length;i++) {
  18109. var c = ca[i];
  18110. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  18111. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  18112. }
  18113. return null;
  18114. },
  18115. remove: function(name) {
  18116. this.create(name,"",-1);
  18117. }
  18118. };
  18119. var cookie_noop = {
  18120. create: function(name,value,minutes,domain) {},
  18121. read: function(name) { return null; },
  18122. remove: function(name) {}
  18123. };
  18124. // move dependent functions to a container so that
  18125. // they can be overriden easier in no jquery environment (node.js)
  18126. var f = {
  18127. extend: $ ? $.extend : _extend,
  18128. deepExtend: _deepExtend,
  18129. each: $ ? $.each : _each,
  18130. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  18131. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  18132. detectLanguage: detectLanguage,
  18133. escape: _escape,
  18134. log: function(str) {
  18135. if (o.debug && typeof console !== "undefined") console.log(str);
  18136. },
  18137. error: function(str) {
  18138. if (typeof console !== "undefined") console.error(str);
  18139. },
  18140. getCountyIndexOfLng: function(lng) {
  18141. var lng_index = 0;
  18142. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  18143. return lng_index;
  18144. },
  18145. toLanguages: function(lng) {
  18146. var log = this.log;
  18147. function applyCase(l) {
  18148. var ret = l;
  18149. if (typeof l === 'string' && l.indexOf('-') > -1) {
  18150. var parts = l.split('-');
  18151. ret = o.lowerCaseLng ?
  18152. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  18153. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  18154. } else {
  18155. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  18156. }
  18157. return ret;
  18158. }
  18159. var languages = [];
  18160. var whitelist = o.lngWhitelist || false;
  18161. var addLanguage = function(language){
  18162. //reject langs not whitelisted
  18163. if(!whitelist || whitelist.indexOf(language) > -1){
  18164. languages.push(language);
  18165. }else{
  18166. log('rejecting non-whitelisted language: ' + language);
  18167. }
  18168. };
  18169. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  18170. var parts = lng.split('-');
  18171. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  18172. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  18173. } else {
  18174. addLanguage(applyCase(lng));
  18175. }
  18176. for (var i = 0; i < o.fallbackLng.length; i++) {
  18177. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  18178. }
  18179. return languages;
  18180. },
  18181. regexEscape: function(str) {
  18182. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  18183. },
  18184. regexReplacementEscape: function(strOrFn) {
  18185. if (typeof strOrFn === 'string') {
  18186. return strOrFn.replace(/\$/g, "$$$$");
  18187. } else {
  18188. return strOrFn;
  18189. }
  18190. },
  18191. localStorage: {
  18192. setItem: function(key, value) {
  18193. if (window.localStorage) {
  18194. try {
  18195. window.localStorage.setItem(key, value);
  18196. } catch (e) {
  18197. f.log('failed to set value for key "' + key + '" to localStorage.');
  18198. }
  18199. }
  18200. }
  18201. }
  18202. };
  18203. function init(options, cb) {
  18204. if (typeof options === 'function') {
  18205. cb = options;
  18206. options = {};
  18207. }
  18208. options = options || {};
  18209. // override defaults with passed in options
  18210. f.extend(o, options);
  18211. delete o.fixLng; /* passed in each time */
  18212. // override functions: .log(), .detectLanguage(), etc
  18213. if (o.functions) {
  18214. delete o.functions;
  18215. f.extend(f, options.functions);
  18216. }
  18217. // create namespace object if namespace is passed in as string
  18218. if (typeof o.ns == 'string') {
  18219. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  18220. }
  18221. // fallback namespaces
  18222. if (typeof o.fallbackNS == 'string') {
  18223. o.fallbackNS = [o.fallbackNS];
  18224. }
  18225. // fallback languages
  18226. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  18227. o.fallbackLng = [o.fallbackLng];
  18228. }
  18229. // escape prefix/suffix
  18230. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  18231. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  18232. if (!o.lng) o.lng = f.detectLanguage();
  18233. languages = f.toLanguages(o.lng);
  18234. currentLng = languages[0];
  18235. f.log('currentLng set to: ' + currentLng);
  18236. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  18237. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  18238. }
  18239. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  18240. f.localStorage.setItem('i18next_lng', currentLng);
  18241. }
  18242. var lngTranslate = translate;
  18243. if (options.fixLng) {
  18244. lngTranslate = function(key, options) {
  18245. options = options || {};
  18246. options.lng = options.lng || lngTranslate.lng;
  18247. return translate(key, options);
  18248. };
  18249. lngTranslate.lng = currentLng;
  18250. }
  18251. pluralExtensions.setCurrentLng(currentLng);
  18252. // add JQuery extensions
  18253. if ($ && o.setJqueryExt) addJqueryFunct();
  18254. // jQuery deferred
  18255. var deferred;
  18256. if ($ && $.Deferred) {
  18257. deferred = $.Deferred();
  18258. }
  18259. // return immidiatly if res are passed in
  18260. if (o.resStore) {
  18261. resStore = o.resStore;
  18262. initialized = true;
  18263. if (cb) cb(lngTranslate);
  18264. if (deferred) deferred.resolve(lngTranslate);
  18265. if (deferred) return deferred.promise();
  18266. return;
  18267. }
  18268. // languages to load
  18269. var lngsToLoad = f.toLanguages(o.lng);
  18270. if (typeof o.preload === 'string') o.preload = [o.preload];
  18271. for (var i = 0, l = o.preload.length; i < l; i++) {
  18272. var pres = f.toLanguages(o.preload[i]);
  18273. for (var y = 0, len = pres.length; y < len; y++) {
  18274. if (lngsToLoad.indexOf(pres[y]) < 0) {
  18275. lngsToLoad.push(pres[y]);
  18276. }
  18277. }
  18278. }
  18279. // else load them
  18280. i18n.sync.load(lngsToLoad, o, function(err, store) {
  18281. resStore = store;
  18282. initialized = true;
  18283. if (cb) cb(lngTranslate);
  18284. if (deferred) deferred.resolve(lngTranslate);
  18285. });
  18286. if (deferred) return deferred.promise();
  18287. }
  18288. function preload(lngs, cb) {
  18289. if (typeof lngs === 'string') lngs = [lngs];
  18290. for (var i = 0, l = lngs.length; i < l; i++) {
  18291. if (o.preload.indexOf(lngs[i]) < 0) {
  18292. o.preload.push(lngs[i]);
  18293. }
  18294. }
  18295. return init(cb);
  18296. }
  18297. function addResourceBundle(lng, ns, resources, deep) {
  18298. if (typeof ns !== 'string') {
  18299. resources = ns;
  18300. ns = o.ns.defaultNs;
  18301. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18302. o.ns.namespaces.push(ns);
  18303. }
  18304. resStore[lng] = resStore[lng] || {};
  18305. resStore[lng][ns] = resStore[lng][ns] || {};
  18306. if (deep) {
  18307. f.deepExtend(resStore[lng][ns], resources);
  18308. } else {
  18309. f.extend(resStore[lng][ns], resources);
  18310. }
  18311. }
  18312. function hasResourceBundle(lng, ns) {
  18313. if (typeof ns !== 'string') {
  18314. ns = o.ns.defaultNs;
  18315. }
  18316. resStore[lng] = resStore[lng] || {};
  18317. var res = resStore[lng][ns] || {};
  18318. var hasValues = false;
  18319. for(var prop in res) {
  18320. if (res.hasOwnProperty(prop)) {
  18321. hasValues = true;
  18322. }
  18323. }
  18324. return hasValues;
  18325. }
  18326. function removeResourceBundle(lng, ns) {
  18327. if (typeof ns !== 'string') {
  18328. ns = o.ns.defaultNs;
  18329. }
  18330. resStore[lng] = resStore[lng] || {};
  18331. resStore[lng][ns] = {};
  18332. }
  18333. function addResource(lng, ns, key, value) {
  18334. if (typeof ns !== 'string') {
  18335. resource = ns;
  18336. ns = o.ns.defaultNs;
  18337. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18338. o.ns.namespaces.push(ns);
  18339. }
  18340. resStore[lng] = resStore[lng] || {};
  18341. resStore[lng][ns] = resStore[lng][ns] || {};
  18342. var keys = key.split(o.keyseparator);
  18343. var x = 0;
  18344. var node = resStore[lng][ns];
  18345. var origRef = node;
  18346. while (keys[x]) {
  18347. if (x == keys.length - 1)
  18348. node[keys[x]] = value;
  18349. else {
  18350. if (node[keys[x]] == null)
  18351. node[keys[x]] = {};
  18352. node = node[keys[x]];
  18353. }
  18354. x++;
  18355. }
  18356. }
  18357. function addResources(lng, ns, resources) {
  18358. if (typeof ns !== 'string') {
  18359. resource = ns;
  18360. ns = o.ns.defaultNs;
  18361. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18362. o.ns.namespaces.push(ns);
  18363. }
  18364. for (var m in resources) {
  18365. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  18366. }
  18367. }
  18368. function setDefaultNamespace(ns) {
  18369. o.ns.defaultNs = ns;
  18370. }
  18371. function loadNamespace(namespace, cb) {
  18372. loadNamespaces([namespace], cb);
  18373. }
  18374. function loadNamespaces(namespaces, cb) {
  18375. var opts = {
  18376. dynamicLoad: o.dynamicLoad,
  18377. resGetPath: o.resGetPath,
  18378. getAsync: o.getAsync,
  18379. customLoad: o.customLoad,
  18380. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  18381. };
  18382. // languages to load
  18383. var lngsToLoad = f.toLanguages(o.lng);
  18384. if (typeof o.preload === 'string') o.preload = [o.preload];
  18385. for (var i = 0, l = o.preload.length; i < l; i++) {
  18386. var pres = f.toLanguages(o.preload[i]);
  18387. for (var y = 0, len = pres.length; y < len; y++) {
  18388. if (lngsToLoad.indexOf(pres[y]) < 0) {
  18389. lngsToLoad.push(pres[y]);
  18390. }
  18391. }
  18392. }
  18393. // check if we have to load
  18394. var lngNeedLoad = [];
  18395. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  18396. var needLoad = false;
  18397. var resSet = resStore[lngsToLoad[a]];
  18398. if (resSet) {
  18399. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  18400. if (!resSet[namespaces[b]]) needLoad = true;
  18401. }
  18402. } else {
  18403. needLoad = true;
  18404. }
  18405. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  18406. }
  18407. if (lngNeedLoad.length) {
  18408. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  18409. var todo = namespaces.length * lngNeedLoad.length;
  18410. // load each file individual
  18411. f.each(namespaces, function(nsIndex, nsValue) {
  18412. // append namespace to namespace array
  18413. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  18414. o.ns.namespaces.push(nsValue);
  18415. }
  18416. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  18417. resStore[lngValue] = resStore[lngValue] || {};
  18418. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  18419. todo--; // wait for all done befor callback
  18420. if (todo === 0 && cb) {
  18421. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  18422. cb();
  18423. }
  18424. });
  18425. });
  18426. });
  18427. } else {
  18428. if (cb) cb();
  18429. }
  18430. }
  18431. function setLng(lng, options, cb) {
  18432. if (typeof options === 'function') {
  18433. cb = options;
  18434. options = {};
  18435. } else if (!options) {
  18436. options = {};
  18437. }
  18438. options.lng = lng;
  18439. return init(options, cb);
  18440. }
  18441. function lng() {
  18442. return currentLng;
  18443. }
  18444. function reload(cb) {
  18445. resStore = {};
  18446. setLng(currentLng, cb);
  18447. }
  18448. function addJqueryFunct() {
  18449. // $.t shortcut
  18450. $.t = $.t || translate;
  18451. function parse(ele, key, options) {
  18452. if (key.length === 0) return;
  18453. var attr = 'text';
  18454. if (key.indexOf('[') === 0) {
  18455. var parts = key.split(']');
  18456. key = parts[1];
  18457. attr = parts[0].substr(1, parts[0].length-1);
  18458. }
  18459. if (key.indexOf(';') === key.length-1) {
  18460. key = key.substr(0, key.length-2);
  18461. }
  18462. var optionsToUse;
  18463. if (attr === 'html') {
  18464. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18465. ele.html($.t(key, optionsToUse));
  18466. } else if (attr === 'text') {
  18467. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  18468. ele.text($.t(key, optionsToUse));
  18469. } else if (attr === 'prepend') {
  18470. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18471. ele.prepend($.t(key, optionsToUse));
  18472. } else if (attr === 'append') {
  18473. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18474. ele.append($.t(key, optionsToUse));
  18475. } else if (attr.indexOf("data-") === 0) {
  18476. var dataAttr = attr.substr(("data-").length);
  18477. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  18478. var translated = $.t(key, optionsToUse);
  18479. //we change into the data cache
  18480. ele.data(dataAttr, translated);
  18481. //we change into the dom
  18482. ele.attr(attr, translated);
  18483. } else {
  18484. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  18485. ele.attr(attr, $.t(key, optionsToUse));
  18486. }
  18487. }
  18488. function localize(ele, options) {
  18489. var key = ele.attr(o.selectorAttr);
  18490. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  18491. if (!key) return;
  18492. var target = ele
  18493. , targetSelector = ele.data("i18n-target");
  18494. if (targetSelector) {
  18495. target = ele.find(targetSelector) || ele;
  18496. }
  18497. if (!options && o.useDataAttrOptions === true) {
  18498. options = ele.data("i18n-options");
  18499. }
  18500. options = options || {};
  18501. if (key.indexOf(';') >= 0) {
  18502. var keys = key.split(';');
  18503. $.each(keys, function(m, k) {
  18504. if (k !== '') parse(target, k, options);
  18505. });
  18506. } else {
  18507. parse(target, key, options);
  18508. }
  18509. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  18510. }
  18511. // fn
  18512. $.fn.i18n = function (options) {
  18513. return this.each(function() {
  18514. // localize element itself
  18515. localize($(this), options);
  18516. // localize childs
  18517. var elements = $(this).find('[' + o.selectorAttr + ']');
  18518. elements.each(function() {
  18519. localize($(this), options);
  18520. });
  18521. });
  18522. };
  18523. }
  18524. function applyReplacement(str, replacementHash, nestedKey, options) {
  18525. if (!str) return str;
  18526. options = options || replacementHash; // first call uses replacement hash combined with options
  18527. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  18528. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  18529. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  18530. , unEscapingSuffix = 'HTML'+suffix;
  18531. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  18532. f.each(hash, function(key, value) {
  18533. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  18534. if (typeof value === 'object' && value !== null) {
  18535. str = applyReplacement(str, value, nextKey, options);
  18536. } else {
  18537. if (options.escapeInterpolation || o.escapeInterpolation) {
  18538. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  18539. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  18540. } else {
  18541. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  18542. }
  18543. // str = options.escapeInterpolation;
  18544. }
  18545. });
  18546. return str;
  18547. }
  18548. // append it to functions
  18549. f.applyReplacement = applyReplacement;
  18550. function applyReuse(translated, options) {
  18551. var comma = ',';
  18552. var options_open = '{';
  18553. var options_close = '}';
  18554. var opts = f.extend({}, options);
  18555. delete opts.postProcess;
  18556. while (translated.indexOf(o.reusePrefix) != -1) {
  18557. replacementCounter++;
  18558. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  18559. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  18560. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  18561. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  18562. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  18563. if (index_of_end_of_closing <= index_of_opening) {
  18564. f.error('there is an missing closing in following translation value', translated);
  18565. return '';
  18566. }
  18567. if (token_without_symbols.indexOf(comma) != -1) {
  18568. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  18569. 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) {
  18570. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  18571. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  18572. try {
  18573. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  18574. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  18575. } catch (e) {
  18576. }
  18577. }
  18578. }
  18579. var translated_token = _translate(token_without_symbols, opts);
  18580. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  18581. }
  18582. return translated;
  18583. }
  18584. function hasContext(options) {
  18585. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  18586. }
  18587. function needsPlural(options, lng) {
  18588. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  18589. }
  18590. function needsIndefiniteArticle(options) {
  18591. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  18592. }
  18593. function exists(key, options) {
  18594. options = options || {};
  18595. var notFound = _getDefaultValue(key, options)
  18596. , found = _find(key, options);
  18597. return found !== undefined || found === notFound;
  18598. }
  18599. function translate(key, options) {
  18600. options = options || {};
  18601. if (!initialized) {
  18602. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  18603. return options.defaultValue || '';
  18604. };
  18605. replacementCounter = 0;
  18606. return _translate.apply(null, arguments);
  18607. }
  18608. function _getDefaultValue(key, options) {
  18609. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  18610. }
  18611. function _injectSprintfProcessor() {
  18612. var values = [];
  18613. // mh: build array from second argument onwards
  18614. for (var i = 1; i < arguments.length; i++) {
  18615. values.push(arguments[i]);
  18616. }
  18617. return {
  18618. postProcess: 'sprintf',
  18619. sprintf: values
  18620. };
  18621. }
  18622. function _translate(potentialKeys, options) {
  18623. if (options && typeof options !== 'object') {
  18624. if (o.shortcutFunction === 'sprintf') {
  18625. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  18626. options = _injectSprintfProcessor.apply(null, arguments);
  18627. } else if (o.shortcutFunction === 'defaultValue') {
  18628. options = {
  18629. defaultValue: options
  18630. }
  18631. }
  18632. } else {
  18633. options = options || {};
  18634. }
  18635. if (typeof o.defaultVariables === 'object') {
  18636. options = f.extend({}, o.defaultVariables, options);
  18637. }
  18638. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  18639. if (typeof potentialKeys === 'string') {
  18640. potentialKeys = [potentialKeys];
  18641. }
  18642. var key = potentialKeys[0];
  18643. if (potentialKeys.length > 1) {
  18644. for (var i = 0; i < potentialKeys.length; i++) {
  18645. key = potentialKeys[i];
  18646. if (exists(key, options)) {
  18647. break;
  18648. }
  18649. }
  18650. }
  18651. var notFound = _getDefaultValue(key, options)
  18652. , found = _find(key, options)
  18653. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  18654. , ns = options.ns || o.ns.defaultNs
  18655. , parts;
  18656. // split ns and key
  18657. if (key.indexOf(o.nsseparator) > -1) {
  18658. parts = key.split(o.nsseparator);
  18659. ns = parts[0];
  18660. key = parts[1];
  18661. }
  18662. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  18663. if (options.lng) {
  18664. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  18665. } else {
  18666. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  18667. }
  18668. }
  18669. var postProcessor = options.postProcess || o.postProcess;
  18670. if (found !== undefined && postProcessor) {
  18671. if (postProcessors[postProcessor]) {
  18672. found = postProcessors[postProcessor](found, key, options);
  18673. }
  18674. }
  18675. // process notFound if function exists
  18676. var splitNotFound = notFound;
  18677. if (notFound.indexOf(o.nsseparator) > -1) {
  18678. parts = notFound.split(o.nsseparator);
  18679. splitNotFound = parts[1];
  18680. }
  18681. if (splitNotFound === key && o.parseMissingKey) {
  18682. notFound = o.parseMissingKey(notFound);
  18683. }
  18684. if (found === undefined) {
  18685. notFound = applyReplacement(notFound, options);
  18686. notFound = applyReuse(notFound, options);
  18687. if (postProcessor && postProcessors[postProcessor]) {
  18688. var val = _getDefaultValue(key, options);
  18689. found = postProcessors[postProcessor](val, key, options);
  18690. }
  18691. }
  18692. return (found !== undefined) ? found : notFound;
  18693. }
  18694. function _find(key, options) {
  18695. options = options || {};
  18696. var optionWithoutCount, translated
  18697. , notFound = _getDefaultValue(key, options)
  18698. , lngs = languages;
  18699. if (!resStore) { return notFound; } // no resStore to translate from
  18700. // CI mode
  18701. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  18702. // passed in lng
  18703. if (options.lngs) lngs = options.lngs;
  18704. if (options.lng) {
  18705. lngs = f.toLanguages(options.lng, options.fallbackLng);
  18706. if (!resStore[lngs[0]]) {
  18707. var oldAsync = o.getAsync;
  18708. o.getAsync = false;
  18709. i18n.sync.load(lngs, o, function(err, store) {
  18710. f.extend(resStore, store);
  18711. o.getAsync = oldAsync;
  18712. });
  18713. }
  18714. }
  18715. var ns = options.ns || o.ns.defaultNs;
  18716. if (key.indexOf(o.nsseparator) > -1) {
  18717. var parts = key.split(o.nsseparator);
  18718. ns = parts[0];
  18719. key = parts[1];
  18720. }
  18721. if (hasContext(options)) {
  18722. optionWithoutCount = f.extend({}, options);
  18723. delete optionWithoutCount.context;
  18724. optionWithoutCount.defaultValue = o.contextNotFound;
  18725. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  18726. translated = translate(contextKey, optionWithoutCount);
  18727. if (translated != o.contextNotFound) {
  18728. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  18729. } // else continue translation with original/nonContext key
  18730. }
  18731. if (needsPlural(options, lngs[0])) {
  18732. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  18733. delete optionWithoutCount.count;
  18734. delete optionWithoutCount.lng;
  18735. optionWithoutCount.defaultValue = o.pluralNotFound;
  18736. var pluralKey;
  18737. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  18738. pluralKey = ns + o.nsseparator + key;
  18739. } else {
  18740. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  18741. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  18742. if (pluralExtension >= 0) {
  18743. pluralKey = pluralKey + '_' + pluralExtension;
  18744. } else if (pluralExtension === 1) {
  18745. pluralKey = ns + o.nsseparator + key; // singular
  18746. }
  18747. }
  18748. translated = translate(pluralKey, optionWithoutCount);
  18749. if (translated != o.pluralNotFound) {
  18750. return applyReplacement(translated, {
  18751. count: options.count,
  18752. interpolationPrefix: options.interpolationPrefix,
  18753. interpolationSuffix: options.interpolationSuffix
  18754. }); // apply replacement for count only
  18755. } else if (lngs.length > 1) {
  18756. // remove failed lng
  18757. var clone = lngs.slice();
  18758. clone.shift();
  18759. options = f.extend(options, { lngs: clone });
  18760. delete options.lng;
  18761. // retry with fallbacks
  18762. translated = translate(ns + o.nsseparator + key, options);
  18763. if (translated != o.pluralNotFound) return translated;
  18764. } else {
  18765. return translated;
  18766. }
  18767. }
  18768. if (needsIndefiniteArticle(options)) {
  18769. var optionsWithoutIndef = f.extend({}, options);
  18770. delete optionsWithoutIndef.indefinite_article;
  18771. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  18772. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  18773. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  18774. translated = translate(indefiniteKey, optionsWithoutIndef);
  18775. if (translated != o.indefiniteNotFound) {
  18776. return translated;
  18777. }
  18778. }
  18779. var found;
  18780. var keys = key.split(o.keyseparator);
  18781. for (var i = 0, len = lngs.length; i < len; i++ ) {
  18782. if (found !== undefined) break;
  18783. var l = lngs[i];
  18784. var x = 0;
  18785. var value = resStore[l] && resStore[l][ns];
  18786. while (keys[x]) {
  18787. value = value && value[keys[x]];
  18788. x++;
  18789. }
  18790. if (value !== undefined) {
  18791. var valueType = Object.prototype.toString.apply(value);
  18792. if (typeof value === 'string') {
  18793. value = applyReplacement(value, options);
  18794. value = applyReuse(value, options);
  18795. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  18796. value = value.join('\n');
  18797. value = applyReplacement(value, options);
  18798. value = applyReuse(value, options);
  18799. } else if (value === null && o.fallbackOnNull === true) {
  18800. value = undefined;
  18801. } else if (value !== null) {
  18802. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  18803. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  18804. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  18805. } else {
  18806. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  18807. 'returned an object instead of string.';
  18808. f.log(value);
  18809. }
  18810. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  18811. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  18812. f.each(value, function(m) {
  18813. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  18814. });
  18815. value = copy;
  18816. }
  18817. }
  18818. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  18819. value = undefined;
  18820. found = value;
  18821. }
  18822. }
  18823. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  18824. // set flag for fallback lookup - avoid recursion
  18825. options.isFallbackLookup = true;
  18826. if (o.fallbackNS.length) {
  18827. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  18828. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  18829. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  18830. /* compare value without namespace */
  18831. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  18832. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  18833. if (foundValue !== notFoundValue) break;
  18834. }
  18835. }
  18836. } else {
  18837. found = _find(key, options); // fallback to default NS
  18838. }
  18839. options.isFallbackLookup = false;
  18840. }
  18841. return found;
  18842. }
  18843. function detectLanguage() {
  18844. var detectedLng;
  18845. var whitelist = o.lngWhitelist || [];
  18846. var userLngChoices = [];
  18847. // get from qs
  18848. var qsParm = [];
  18849. if (typeof window !== 'undefined') {
  18850. (function() {
  18851. var query = window.location.search.substring(1);
  18852. var params = query.split('&');
  18853. for (var i=0; i<params.length; i++) {
  18854. var pos = params[i].indexOf('=');
  18855. if (pos > 0) {
  18856. var key = params[i].substring(0,pos);
  18857. if (key == o.detectLngQS) {
  18858. userLngChoices.push(params[i].substring(pos+1));
  18859. }
  18860. }
  18861. }
  18862. })();
  18863. }
  18864. // get from cookie
  18865. if (o.useCookie && typeof document !== 'undefined') {
  18866. var c = f.cookie.read(o.cookieName);
  18867. if (c) userLngChoices.push(c);
  18868. }
  18869. // get from localStorage
  18870. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  18871. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  18872. }
  18873. // get from navigator
  18874. if (typeof navigator !== 'undefined') {
  18875. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  18876. for (var i=0;i<navigator.languages.length;i++) {
  18877. userLngChoices.push(navigator.languages[i]);
  18878. }
  18879. }
  18880. if (navigator.userLanguage) {
  18881. userLngChoices.push(navigator.userLanguage);
  18882. }
  18883. if (navigator.language) {
  18884. userLngChoices.push(navigator.language);
  18885. }
  18886. }
  18887. (function() {
  18888. for (var i=0;i<userLngChoices.length;i++) {
  18889. var lng = userLngChoices[i];
  18890. if (lng.indexOf('-') > -1) {
  18891. var parts = lng.split('-');
  18892. lng = o.lowerCaseLng ?
  18893. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  18894. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  18895. }
  18896. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  18897. detectedLng = lng;
  18898. break;
  18899. }
  18900. }
  18901. })();
  18902. //fallback
  18903. if (!detectedLng){
  18904. detectedLng = o.fallbackLng[0];
  18905. }
  18906. return detectedLng;
  18907. }
  18908. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  18909. /* [code, name, numbers, pluralsType] */
  18910. var _rules = [
  18911. ["ach", "Acholi", [1,2], 1],
  18912. ["af", "Afrikaans",[1,2], 2],
  18913. ["ak", "Akan", [1,2], 1],
  18914. ["am", "Amharic", [1,2], 1],
  18915. ["an", "Aragonese",[1,2], 2],
  18916. ["ar", "Arabic", [0,1,2,3,11,100],5],
  18917. ["arn", "Mapudungun",[1,2], 1],
  18918. ["ast", "Asturian", [1,2], 2],
  18919. ["ay", "Aymará", [1], 3],
  18920. ["az", "Azerbaijani",[1,2],2],
  18921. ["be", "Belarusian",[1,2,5],4],
  18922. ["bg", "Bulgarian",[1,2], 2],
  18923. ["bn", "Bengali", [1,2], 2],
  18924. ["bo", "Tibetan", [1], 3],
  18925. ["br", "Breton", [1,2], 1],
  18926. ["bs", "Bosnian", [1,2,5],4],
  18927. ["ca", "Catalan", [1,2], 2],
  18928. ["cgg", "Chiga", [1], 3],
  18929. ["cs", "Czech", [1,2,5],6],
  18930. ["csb", "Kashubian",[1,2,5],7],
  18931. ["cy", "Welsh", [1,2,3,8],8],
  18932. ["da", "Danish", [1,2], 2],
  18933. ["de", "German", [1,2], 2],
  18934. ["dev", "Development Fallback", [1,2], 2],
  18935. ["dz", "Dzongkha", [1], 3],
  18936. ["el", "Greek", [1,2], 2],
  18937. ["en", "English", [1,2], 2],
  18938. ["eo", "Esperanto",[1,2], 2],
  18939. ["es", "Spanish", [1,2], 2],
  18940. ["es_ar","Argentinean Spanish", [1,2], 2],
  18941. ["et", "Estonian", [1,2], 2],
  18942. ["eu", "Basque", [1,2], 2],
  18943. ["fa", "Persian", [1], 3],
  18944. ["fi", "Finnish", [1,2], 2],
  18945. ["fil", "Filipino", [1,2], 1],
  18946. ["fo", "Faroese", [1,2], 2],
  18947. ["fr", "French", [1,2], 9],
  18948. ["fur", "Friulian", [1,2], 2],
  18949. ["fy", "Frisian", [1,2], 2],
  18950. ["ga", "Irish", [1,2,3,7,11],10],
  18951. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  18952. ["gl", "Galician", [1,2], 2],
  18953. ["gu", "Gujarati", [1,2], 2],
  18954. ["gun", "Gun", [1,2], 1],
  18955. ["ha", "Hausa", [1,2], 2],
  18956. ["he", "Hebrew", [1,2], 2],
  18957. ["hi", "Hindi", [1,2], 2],
  18958. ["hr", "Croatian", [1,2,5],4],
  18959. ["hu", "Hungarian",[1,2], 2],
  18960. ["hy", "Armenian", [1,2], 2],
  18961. ["ia", "Interlingua",[1,2],2],
  18962. ["id", "Indonesian",[1], 3],
  18963. ["is", "Icelandic",[1,2], 12],
  18964. ["it", "Italian", [1,2], 2],
  18965. ["ja", "Japanese", [1], 3],
  18966. ["jbo", "Lojban", [1], 3],
  18967. ["jv", "Javanese", [0,1], 13],
  18968. ["ka", "Georgian", [1], 3],
  18969. ["kk", "Kazakh", [1], 3],
  18970. ["km", "Khmer", [1], 3],
  18971. ["kn", "Kannada", [1,2], 2],
  18972. ["ko", "Korean", [1], 3],
  18973. ["ku", "Kurdish", [1,2], 2],
  18974. ["kw", "Cornish", [1,2,3,4],14],
  18975. ["ky", "Kyrgyz", [1], 3],
  18976. ["lb", "Letzeburgesch",[1,2],2],
  18977. ["ln", "Lingala", [1,2], 1],
  18978. ["lo", "Lao", [1], 3],
  18979. ["lt", "Lithuanian",[1,2,10],15],
  18980. ["lv", "Latvian", [1,2,0],16],
  18981. ["mai", "Maithili", [1,2], 2],
  18982. ["mfe", "Mauritian Creole",[1,2],1],
  18983. ["mg", "Malagasy", [1,2], 1],
  18984. ["mi", "Maori", [1,2], 1],
  18985. ["mk", "Macedonian",[1,2],17],
  18986. ["ml", "Malayalam",[1,2], 2],
  18987. ["mn", "Mongolian",[1,2], 2],
  18988. ["mnk", "Mandinka", [0,1,2],18],
  18989. ["mr", "Marathi", [1,2], 2],
  18990. ["ms", "Malay", [1], 3],
  18991. ["mt", "Maltese", [1,2,11,20],19],
  18992. ["nah", "Nahuatl", [1,2], 2],
  18993. ["nap", "Neapolitan",[1,2], 2],
  18994. ["nb", "Norwegian Bokmal",[1,2],2],
  18995. ["ne", "Nepali", [1,2], 2],
  18996. ["nl", "Dutch", [1,2], 2],
  18997. ["nn", "Norwegian Nynorsk",[1,2],2],
  18998. ["no", "Norwegian",[1,2], 2],
  18999. ["nso", "Northern Sotho",[1,2],2],
  19000. ["oc", "Occitan", [1,2], 1],
  19001. ["or", "Oriya", [2,1], 2],
  19002. ["pa", "Punjabi", [1,2], 2],
  19003. ["pap", "Papiamento",[1,2], 2],
  19004. ["pl", "Polish", [1,2,5],7],
  19005. ["pms", "Piemontese",[1,2], 2],
  19006. ["ps", "Pashto", [1,2], 2],
  19007. ["pt", "Portuguese",[1,2], 2],
  19008. ["pt_br","Brazilian Portuguese",[1,2], 2],
  19009. ["rm", "Romansh", [1,2], 2],
  19010. ["ro", "Romanian", [1,2,20],20],
  19011. ["ru", "Russian", [1,2,5],4],
  19012. ["sah", "Yakut", [1], 3],
  19013. ["sco", "Scots", [1,2], 2],
  19014. ["se", "Northern Sami",[1,2], 2],
  19015. ["si", "Sinhala", [1,2], 2],
  19016. ["sk", "Slovak", [1,2,5],6],
  19017. ["sl", "Slovenian",[5,1,2,3],21],
  19018. ["so", "Somali", [1,2], 2],
  19019. ["son", "Songhay", [1,2], 2],
  19020. ["sq", "Albanian", [1,2], 2],
  19021. ["sr", "Serbian", [1,2,5],4],
  19022. ["su", "Sundanese",[1], 3],
  19023. ["sv", "Swedish", [1,2], 2],
  19024. ["sw", "Swahili", [1,2], 2],
  19025. ["ta", "Tamil", [1,2], 2],
  19026. ["te", "Telugu", [1,2], 2],
  19027. ["tg", "Tajik", [1,2], 1],
  19028. ["th", "Thai", [1], 3],
  19029. ["ti", "Tigrinya", [1,2], 1],
  19030. ["tk", "Turkmen", [1,2], 2],
  19031. ["tr", "Turkish", [1,2], 1],
  19032. ["tt", "Tatar", [1], 3],
  19033. ["ug", "Uyghur", [1], 3],
  19034. ["uk", "Ukrainian",[1,2,5],4],
  19035. ["ur", "Urdu", [1,2], 2],
  19036. ["uz", "Uzbek", [1,2], 1],
  19037. ["vi", "Vietnamese",[1], 3],
  19038. ["wa", "Walloon", [1,2], 1],
  19039. ["wo", "Wolof", [1], 3],
  19040. ["yo", "Yoruba", [1,2], 2],
  19041. ["zh", "Chinese", [1], 3]
  19042. ];
  19043. var _rulesPluralsTypes = {
  19044. 1: function(n) {return Number(n > 1);},
  19045. 2: function(n) {return Number(n != 1);},
  19046. 3: function(n) {return 0;},
  19047. 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);},
  19048. 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);},
  19049. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  19050. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  19051. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  19052. 9: function(n) {return Number(n >= 2);},
  19053. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  19054. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  19055. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  19056. 13: function(n) {return Number(n !== 0);},
  19057. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  19058. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  19059. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  19060. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  19061. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  19062. 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);},
  19063. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  19064. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  19065. };
  19066. var pluralExtensions = {
  19067. rules: (function () {
  19068. var l, rules = {};
  19069. for (l=_rules.length; l-- ;) {
  19070. rules[_rules[l][0]] = {
  19071. name: _rules[l][1],
  19072. numbers: _rules[l][2],
  19073. plurals: _rulesPluralsTypes[_rules[l][3]]
  19074. }
  19075. }
  19076. return rules;
  19077. }()),
  19078. // you can add your own pluralExtensions
  19079. addRule: function(lng, obj) {
  19080. pluralExtensions.rules[lng] = obj;
  19081. },
  19082. setCurrentLng: function(lng) {
  19083. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  19084. var parts = lng.split('-');
  19085. pluralExtensions.currentRule = {
  19086. lng: lng,
  19087. rule: pluralExtensions.rules[parts[0]]
  19088. };
  19089. }
  19090. },
  19091. needsPlural: function(lng, count) {
  19092. var parts = lng.split('-');
  19093. var ext;
  19094. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  19095. ext = pluralExtensions.currentRule.rule;
  19096. } else {
  19097. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  19098. }
  19099. if (ext && ext.numbers.length <= 1) {
  19100. return false;
  19101. } else {
  19102. return this.get(lng, count) !== 1;
  19103. }
  19104. },
  19105. get: function(lng, count) {
  19106. var parts = lng.split('-');
  19107. function getResult(l, c) {
  19108. var ext;
  19109. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  19110. ext = pluralExtensions.currentRule.rule;
  19111. } else {
  19112. ext = pluralExtensions.rules[l];
  19113. }
  19114. if (ext) {
  19115. var i;
  19116. if (ext.noAbs) {
  19117. i = ext.plurals(c);
  19118. } else {
  19119. i = ext.plurals(Math.abs(c));
  19120. }
  19121. var number = ext.numbers[i];
  19122. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  19123. if (number === 2) {
  19124. number = -1; // regular plural
  19125. } else if (number === 1) {
  19126. number = 1; // singular
  19127. }
  19128. }//console.log(count + '-' + number);
  19129. return number;
  19130. } else {
  19131. return c === 1 ? '1' : '-1';
  19132. }
  19133. }
  19134. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  19135. }
  19136. };
  19137. var postProcessors = {};
  19138. var addPostProcessor = function(name, fc) {
  19139. postProcessors[name] = fc;
  19140. };
  19141. // sprintf support
  19142. var sprintf = (function() {
  19143. function get_type(variable) {
  19144. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  19145. }
  19146. function str_repeat(input, multiplier) {
  19147. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  19148. return output.join('');
  19149. }
  19150. var str_format = function() {
  19151. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  19152. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  19153. }
  19154. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  19155. };
  19156. str_format.format = function(parse_tree, argv) {
  19157. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  19158. for (i = 0; i < tree_length; i++) {
  19159. node_type = get_type(parse_tree[i]);
  19160. if (node_type === 'string') {
  19161. output.push(parse_tree[i]);
  19162. }
  19163. else if (node_type === 'array') {
  19164. match = parse_tree[i]; // convenience purposes only
  19165. if (match[2]) { // keyword argument
  19166. arg = argv[cursor];
  19167. for (k = 0; k < match[2].length; k++) {
  19168. if (!arg.hasOwnProperty(match[2][k])) {
  19169. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  19170. }
  19171. arg = arg[match[2][k]];
  19172. }
  19173. }
  19174. else if (match[1]) { // positional argument (explicit)
  19175. arg = argv[match[1]];
  19176. }
  19177. else { // positional argument (implicit)
  19178. arg = argv[cursor++];
  19179. }
  19180. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  19181. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  19182. }
  19183. switch (match[8]) {
  19184. case 'b': arg = arg.toString(2); break;
  19185. case 'c': arg = String.fromCharCode(arg); break;
  19186. case 'd': arg = parseInt(arg, 10); break;
  19187. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  19188. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  19189. case 'o': arg = arg.toString(8); break;
  19190. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  19191. case 'u': arg = Math.abs(arg); break;
  19192. case 'x': arg = arg.toString(16); break;
  19193. case 'X': arg = arg.toString(16).toUpperCase(); break;
  19194. }
  19195. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  19196. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  19197. pad_length = match[6] - String(arg).length;
  19198. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  19199. output.push(match[5] ? arg + pad : pad + arg);
  19200. }
  19201. }
  19202. return output.join('');
  19203. };
  19204. str_format.cache = {};
  19205. str_format.parse = function(fmt) {
  19206. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  19207. while (_fmt) {
  19208. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  19209. parse_tree.push(match[0]);
  19210. }
  19211. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  19212. parse_tree.push('%');
  19213. }
  19214. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  19215. if (match[2]) {
  19216. arg_names |= 1;
  19217. var field_list = [], replacement_field = match[2], field_match = [];
  19218. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  19219. field_list.push(field_match[1]);
  19220. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  19221. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  19222. field_list.push(field_match[1]);
  19223. }
  19224. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  19225. field_list.push(field_match[1]);
  19226. }
  19227. else {
  19228. throw('[sprintf] huh?');
  19229. }
  19230. }
  19231. }
  19232. else {
  19233. throw('[sprintf] huh?');
  19234. }
  19235. match[2] = field_list;
  19236. }
  19237. else {
  19238. arg_names |= 2;
  19239. }
  19240. if (arg_names === 3) {
  19241. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  19242. }
  19243. parse_tree.push(match);
  19244. }
  19245. else {
  19246. throw('[sprintf] huh?');
  19247. }
  19248. _fmt = _fmt.substring(match[0].length);
  19249. }
  19250. return parse_tree;
  19251. };
  19252. return str_format;
  19253. })();
  19254. var vsprintf = function(fmt, argv) {
  19255. argv.unshift(fmt);
  19256. return sprintf.apply(null, argv);
  19257. };
  19258. addPostProcessor("sprintf", function(val, key, opts) {
  19259. if (!opts.sprintf) return val;
  19260. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  19261. return vsprintf(val, opts.sprintf);
  19262. } else if (typeof opts.sprintf === 'object') {
  19263. return sprintf(val, opts.sprintf);
  19264. }
  19265. return val;
  19266. });
  19267. // public api interface
  19268. i18n.init = init;
  19269. i18n.setLng = setLng;
  19270. i18n.preload = preload;
  19271. i18n.addResourceBundle = addResourceBundle;
  19272. i18n.hasResourceBundle = hasResourceBundle;
  19273. i18n.addResource = addResource;
  19274. i18n.addResources = addResources;
  19275. i18n.removeResourceBundle = removeResourceBundle;
  19276. i18n.loadNamespace = loadNamespace;
  19277. i18n.loadNamespaces = loadNamespaces;
  19278. i18n.setDefaultNamespace = setDefaultNamespace;
  19279. i18n.t = translate;
  19280. i18n.translate = translate;
  19281. i18n.exists = exists;
  19282. i18n.detectLanguage = f.detectLanguage;
  19283. i18n.pluralExtensions = pluralExtensions;
  19284. i18n.sync = sync;
  19285. i18n.functions = f;
  19286. i18n.lng = lng;
  19287. i18n.addPostProcessor = addPostProcessor;
  19288. i18n.options = o;
  19289. })();
  19290. },{"jquery":"jquery"}],69:[function(require,module,exports){
  19291. // Top level file is just a mixin of submodules & constants
  19292. 'use strict';
  19293. var assign = require('./lib/utils/common').assign;
  19294. var deflate = require('./lib/deflate');
  19295. var inflate = require('./lib/inflate');
  19296. var constants = require('./lib/zlib/constants');
  19297. var pako = {};
  19298. assign(pako, deflate, inflate, constants);
  19299. module.exports = pako;
  19300. },{"./lib/deflate":70,"./lib/inflate":71,"./lib/utils/common":72,"./lib/zlib/constants":75}],70:[function(require,module,exports){
  19301. 'use strict';
  19302. var zlib_deflate = require('./zlib/deflate.js');
  19303. var utils = require('./utils/common');
  19304. var strings = require('./utils/strings');
  19305. var msg = require('./zlib/messages');
  19306. var zstream = require('./zlib/zstream');
  19307. var toString = Object.prototype.toString;
  19308. /* Public constants ==========================================================*/
  19309. /* ===========================================================================*/
  19310. var Z_NO_FLUSH = 0;
  19311. var Z_FINISH = 4;
  19312. var Z_OK = 0;
  19313. var Z_STREAM_END = 1;
  19314. var Z_SYNC_FLUSH = 2;
  19315. var Z_DEFAULT_COMPRESSION = -1;
  19316. var Z_DEFAULT_STRATEGY = 0;
  19317. var Z_DEFLATED = 8;
  19318. /* ===========================================================================*/
  19319. /**
  19320. * class Deflate
  19321. *
  19322. * Generic JS-style wrapper for zlib calls. If you don't need
  19323. * streaming behaviour - use more simple functions: [[deflate]],
  19324. * [[deflateRaw]] and [[gzip]].
  19325. **/
  19326. /* internal
  19327. * Deflate.chunks -> Array
  19328. *
  19329. * Chunks of output data, if [[Deflate#onData]] not overriden.
  19330. **/
  19331. /**
  19332. * Deflate.result -> Uint8Array|Array
  19333. *
  19334. * Compressed result, generated by default [[Deflate#onData]]
  19335. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  19336. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  19337. * push a chunk with explicit flush (call [[Deflate#push]] with
  19338. * `Z_SYNC_FLUSH` param).
  19339. **/
  19340. /**
  19341. * Deflate.err -> Number
  19342. *
  19343. * Error code after deflate finished. 0 (Z_OK) on success.
  19344. * You will not need it in real life, because deflate errors
  19345. * are possible only on wrong options or bad `onData` / `onEnd`
  19346. * custom handlers.
  19347. **/
  19348. /**
  19349. * Deflate.msg -> String
  19350. *
  19351. * Error message, if [[Deflate.err]] != 0
  19352. **/
  19353. /**
  19354. * new Deflate(options)
  19355. * - options (Object): zlib deflate options.
  19356. *
  19357. * Creates new deflator instance with specified params. Throws exception
  19358. * on bad params. Supported options:
  19359. *
  19360. * - `level`
  19361. * - `windowBits`
  19362. * - `memLevel`
  19363. * - `strategy`
  19364. *
  19365. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19366. * for more information on these.
  19367. *
  19368. * Additional options, for internal needs:
  19369. *
  19370. * - `chunkSize` - size of generated data chunks (16K by default)
  19371. * - `raw` (Boolean) - do raw deflate
  19372. * - `gzip` (Boolean) - create gzip wrapper
  19373. * - `to` (String) - if equal to 'string', then result will be "binary string"
  19374. * (each char code [0..255])
  19375. * - `header` (Object) - custom header for gzip
  19376. * - `text` (Boolean) - true if compressed data believed to be text
  19377. * - `time` (Number) - modification time, unix timestamp
  19378. * - `os` (Number) - operation system code
  19379. * - `extra` (Array) - array of bytes with extra data (max 65536)
  19380. * - `name` (String) - file name (binary string)
  19381. * - `comment` (String) - comment (binary string)
  19382. * - `hcrc` (Boolean) - true if header crc should be added
  19383. *
  19384. * ##### Example:
  19385. *
  19386. * ```javascript
  19387. * var pako = require('pako')
  19388. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  19389. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  19390. *
  19391. * var deflate = new pako.Deflate({ level: 3});
  19392. *
  19393. * deflate.push(chunk1, false);
  19394. * deflate.push(chunk2, true); // true -> last chunk
  19395. *
  19396. * if (deflate.err) { throw new Error(deflate.err); }
  19397. *
  19398. * console.log(deflate.result);
  19399. * ```
  19400. **/
  19401. var Deflate = function(options) {
  19402. this.options = utils.assign({
  19403. level: Z_DEFAULT_COMPRESSION,
  19404. method: Z_DEFLATED,
  19405. chunkSize: 16384,
  19406. windowBits: 15,
  19407. memLevel: 8,
  19408. strategy: Z_DEFAULT_STRATEGY,
  19409. to: ''
  19410. }, options || {});
  19411. var opt = this.options;
  19412. if (opt.raw && (opt.windowBits > 0)) {
  19413. opt.windowBits = -opt.windowBits;
  19414. }
  19415. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  19416. opt.windowBits += 16;
  19417. }
  19418. this.err = 0; // error code, if happens (0 = Z_OK)
  19419. this.msg = ''; // error message
  19420. this.ended = false; // used to avoid multiple onEnd() calls
  19421. this.chunks = []; // chunks of compressed data
  19422. this.strm = new zstream();
  19423. this.strm.avail_out = 0;
  19424. var status = zlib_deflate.deflateInit2(
  19425. this.strm,
  19426. opt.level,
  19427. opt.method,
  19428. opt.windowBits,
  19429. opt.memLevel,
  19430. opt.strategy
  19431. );
  19432. if (status !== Z_OK) {
  19433. throw new Error(msg[status]);
  19434. }
  19435. if (opt.header) {
  19436. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  19437. }
  19438. };
  19439. /**
  19440. * Deflate#push(data[, mode]) -> Boolean
  19441. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  19442. * converted to utf8 byte sequence.
  19443. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  19444. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  19445. *
  19446. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  19447. * new compressed chunks. Returns `true` on success. The last data block must have
  19448. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  19449. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  19450. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  19451. *
  19452. * On fail call [[Deflate#onEnd]] with error code and return false.
  19453. *
  19454. * We strongly recommend to use `Uint8Array` on input for best speed (output
  19455. * array format is detected automatically). Also, don't skip last param and always
  19456. * use the same type in your code (boolean or number). That will improve JS speed.
  19457. *
  19458. * For regular `Array`-s make sure all elements are [0..255].
  19459. *
  19460. * ##### Example
  19461. *
  19462. * ```javascript
  19463. * push(chunk, false); // push one of data chunks
  19464. * ...
  19465. * push(chunk, true); // push last chunk
  19466. * ```
  19467. **/
  19468. Deflate.prototype.push = function(data, mode) {
  19469. var strm = this.strm;
  19470. var chunkSize = this.options.chunkSize;
  19471. var status, _mode;
  19472. if (this.ended) { return false; }
  19473. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  19474. // Convert data if needed
  19475. if (typeof data === 'string') {
  19476. // If we need to compress text, change encoding to utf8.
  19477. strm.input = strings.string2buf(data);
  19478. } else if (toString.call(data) === '[object ArrayBuffer]') {
  19479. strm.input = new Uint8Array(data);
  19480. } else {
  19481. strm.input = data;
  19482. }
  19483. strm.next_in = 0;
  19484. strm.avail_in = strm.input.length;
  19485. do {
  19486. if (strm.avail_out === 0) {
  19487. strm.output = new utils.Buf8(chunkSize);
  19488. strm.next_out = 0;
  19489. strm.avail_out = chunkSize;
  19490. }
  19491. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  19492. if (status !== Z_STREAM_END && status !== Z_OK) {
  19493. this.onEnd(status);
  19494. this.ended = true;
  19495. return false;
  19496. }
  19497. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  19498. if (this.options.to === 'string') {
  19499. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  19500. } else {
  19501. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  19502. }
  19503. }
  19504. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  19505. // Finalize on the last chunk.
  19506. if (_mode === Z_FINISH) {
  19507. status = zlib_deflate.deflateEnd(this.strm);
  19508. this.onEnd(status);
  19509. this.ended = true;
  19510. return status === Z_OK;
  19511. }
  19512. // callback interim results if Z_SYNC_FLUSH.
  19513. if (_mode === Z_SYNC_FLUSH) {
  19514. this.onEnd(Z_OK);
  19515. strm.avail_out = 0;
  19516. return true;
  19517. }
  19518. return true;
  19519. };
  19520. /**
  19521. * Deflate#onData(chunk) -> Void
  19522. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  19523. * on js engine support. When string output requested, each chunk
  19524. * will be string.
  19525. *
  19526. * By default, stores data blocks in `chunks[]` property and glue
  19527. * those in `onEnd`. Override this handler, if you need another behaviour.
  19528. **/
  19529. Deflate.prototype.onData = function(chunk) {
  19530. this.chunks.push(chunk);
  19531. };
  19532. /**
  19533. * Deflate#onEnd(status) -> Void
  19534. * - status (Number): deflate status. 0 (Z_OK) on success,
  19535. * other if not.
  19536. *
  19537. * Called once after you tell deflate that the input stream is
  19538. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  19539. * or if an error happened. By default - join collected chunks,
  19540. * free memory and fill `results` / `err` properties.
  19541. **/
  19542. Deflate.prototype.onEnd = function(status) {
  19543. // On success - join
  19544. if (status === Z_OK) {
  19545. if (this.options.to === 'string') {
  19546. this.result = this.chunks.join('');
  19547. } else {
  19548. this.result = utils.flattenChunks(this.chunks);
  19549. }
  19550. }
  19551. this.chunks = [];
  19552. this.err = status;
  19553. this.msg = this.strm.msg;
  19554. };
  19555. /**
  19556. * deflate(data[, options]) -> Uint8Array|Array|String
  19557. * - data (Uint8Array|Array|String): input data to compress.
  19558. * - options (Object): zlib deflate options.
  19559. *
  19560. * Compress `data` with deflate alrorythm and `options`.
  19561. *
  19562. * Supported options are:
  19563. *
  19564. * - level
  19565. * - windowBits
  19566. * - memLevel
  19567. * - strategy
  19568. *
  19569. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19570. * for more information on these.
  19571. *
  19572. * Sugar (options):
  19573. *
  19574. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  19575. * negative windowBits implicitly.
  19576. * - `to` (String) - if equal to 'string', then result will be "binary string"
  19577. * (each char code [0..255])
  19578. *
  19579. * ##### Example:
  19580. *
  19581. * ```javascript
  19582. * var pako = require('pako')
  19583. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  19584. *
  19585. * console.log(pako.deflate(data));
  19586. * ```
  19587. **/
  19588. function deflate(input, options) {
  19589. var deflator = new Deflate(options);
  19590. deflator.push(input, true);
  19591. // That will never happens, if you don't cheat with options :)
  19592. if (deflator.err) { throw deflator.msg; }
  19593. return deflator.result;
  19594. }
  19595. /**
  19596. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  19597. * - data (Uint8Array|Array|String): input data to compress.
  19598. * - options (Object): zlib deflate options.
  19599. *
  19600. * The same as [[deflate]], but creates raw data, without wrapper
  19601. * (header and adler32 crc).
  19602. **/
  19603. function deflateRaw(input, options) {
  19604. options = options || {};
  19605. options.raw = true;
  19606. return deflate(input, options);
  19607. }
  19608. /**
  19609. * gzip(data[, options]) -> Uint8Array|Array|String
  19610. * - data (Uint8Array|Array|String): input data to compress.
  19611. * - options (Object): zlib deflate options.
  19612. *
  19613. * The same as [[deflate]], but create gzip wrapper instead of
  19614. * deflate one.
  19615. **/
  19616. function gzip(input, options) {
  19617. options = options || {};
  19618. options.gzip = true;
  19619. return deflate(input, options);
  19620. }
  19621. exports.Deflate = Deflate;
  19622. exports.deflate = deflate;
  19623. exports.deflateRaw = deflateRaw;
  19624. exports.gzip = gzip;
  19625. },{"./utils/common":72,"./utils/strings":73,"./zlib/deflate.js":77,"./zlib/messages":82,"./zlib/zstream":84}],71:[function(require,module,exports){
  19626. 'use strict';
  19627. var zlib_inflate = require('./zlib/inflate.js');
  19628. var utils = require('./utils/common');
  19629. var strings = require('./utils/strings');
  19630. var c = require('./zlib/constants');
  19631. var msg = require('./zlib/messages');
  19632. var zstream = require('./zlib/zstream');
  19633. var gzheader = require('./zlib/gzheader');
  19634. var toString = Object.prototype.toString;
  19635. /**
  19636. * class Inflate
  19637. *
  19638. * Generic JS-style wrapper for zlib calls. If you don't need
  19639. * streaming behaviour - use more simple functions: [[inflate]]
  19640. * and [[inflateRaw]].
  19641. **/
  19642. /* internal
  19643. * inflate.chunks -> Array
  19644. *
  19645. * Chunks of output data, if [[Inflate#onData]] not overriden.
  19646. **/
  19647. /**
  19648. * Inflate.result -> Uint8Array|Array|String
  19649. *
  19650. * Uncompressed result, generated by default [[Inflate#onData]]
  19651. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  19652. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  19653. * push a chunk with explicit flush (call [[Inflate#push]] with
  19654. * `Z_SYNC_FLUSH` param).
  19655. **/
  19656. /**
  19657. * Inflate.err -> Number
  19658. *
  19659. * Error code after inflate finished. 0 (Z_OK) on success.
  19660. * Should be checked if broken data possible.
  19661. **/
  19662. /**
  19663. * Inflate.msg -> String
  19664. *
  19665. * Error message, if [[Inflate.err]] != 0
  19666. **/
  19667. /**
  19668. * new Inflate(options)
  19669. * - options (Object): zlib inflate options.
  19670. *
  19671. * Creates new inflator instance with specified params. Throws exception
  19672. * on bad params. Supported options:
  19673. *
  19674. * - `windowBits`
  19675. *
  19676. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19677. * for more information on these.
  19678. *
  19679. * Additional options, for internal needs:
  19680. *
  19681. * - `chunkSize` - size of generated data chunks (16K by default)
  19682. * - `raw` (Boolean) - do raw inflate
  19683. * - `to` (String) - if equal to 'string', then result will be converted
  19684. * from utf8 to utf16 (javascript) string. When string output requested,
  19685. * chunk length can differ from `chunkSize`, depending on content.
  19686. *
  19687. * By default, when no options set, autodetect deflate/gzip data format via
  19688. * wrapper header.
  19689. *
  19690. * ##### Example:
  19691. *
  19692. * ```javascript
  19693. * var pako = require('pako')
  19694. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  19695. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  19696. *
  19697. * var inflate = new pako.Inflate({ level: 3});
  19698. *
  19699. * inflate.push(chunk1, false);
  19700. * inflate.push(chunk2, true); // true -> last chunk
  19701. *
  19702. * if (inflate.err) { throw new Error(inflate.err); }
  19703. *
  19704. * console.log(inflate.result);
  19705. * ```
  19706. **/
  19707. var Inflate = function(options) {
  19708. this.options = utils.assign({
  19709. chunkSize: 16384,
  19710. windowBits: 0,
  19711. to: ''
  19712. }, options || {});
  19713. var opt = this.options;
  19714. // Force window size for `raw` data, if not set directly,
  19715. // because we have no header for autodetect.
  19716. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  19717. opt.windowBits = -opt.windowBits;
  19718. if (opt.windowBits === 0) { opt.windowBits = -15; }
  19719. }
  19720. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  19721. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  19722. !(options && options.windowBits)) {
  19723. opt.windowBits += 32;
  19724. }
  19725. // Gzip header has no info about windows size, we can do autodetect only
  19726. // for deflate. So, if window size not set, force it to max when gzip possible
  19727. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  19728. // bit 3 (16) -> gzipped data
  19729. // bit 4 (32) -> autodetect gzip/deflate
  19730. if ((opt.windowBits & 15) === 0) {
  19731. opt.windowBits |= 15;
  19732. }
  19733. }
  19734. this.err = 0; // error code, if happens (0 = Z_OK)
  19735. this.msg = ''; // error message
  19736. this.ended = false; // used to avoid multiple onEnd() calls
  19737. this.chunks = []; // chunks of compressed data
  19738. this.strm = new zstream();
  19739. this.strm.avail_out = 0;
  19740. var status = zlib_inflate.inflateInit2(
  19741. this.strm,
  19742. opt.windowBits
  19743. );
  19744. if (status !== c.Z_OK) {
  19745. throw new Error(msg[status]);
  19746. }
  19747. this.header = new gzheader();
  19748. zlib_inflate.inflateGetHeader(this.strm, this.header);
  19749. };
  19750. /**
  19751. * Inflate#push(data[, mode]) -> Boolean
  19752. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  19753. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  19754. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  19755. *
  19756. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  19757. * new output chunks. Returns `true` on success. The last data block must have
  19758. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  19759. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  19760. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  19761. *
  19762. * On fail call [[Inflate#onEnd]] with error code and return false.
  19763. *
  19764. * We strongly recommend to use `Uint8Array` on input for best speed (output
  19765. * format is detected automatically). Also, don't skip last param and always
  19766. * use the same type in your code (boolean or number). That will improve JS speed.
  19767. *
  19768. * For regular `Array`-s make sure all elements are [0..255].
  19769. *
  19770. * ##### Example
  19771. *
  19772. * ```javascript
  19773. * push(chunk, false); // push one of data chunks
  19774. * ...
  19775. * push(chunk, true); // push last chunk
  19776. * ```
  19777. **/
  19778. Inflate.prototype.push = function(data, mode) {
  19779. var strm = this.strm;
  19780. var chunkSize = this.options.chunkSize;
  19781. var status, _mode;
  19782. var next_out_utf8, tail, utf8str;
  19783. if (this.ended) { return false; }
  19784. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  19785. // Convert data if needed
  19786. if (typeof data === 'string') {
  19787. // Only binary strings can be decompressed on practice
  19788. strm.input = strings.binstring2buf(data);
  19789. } else if (toString.call(data) === '[object ArrayBuffer]') {
  19790. strm.input = new Uint8Array(data);
  19791. } else {
  19792. strm.input = data;
  19793. }
  19794. strm.next_in = 0;
  19795. strm.avail_in = strm.input.length;
  19796. do {
  19797. if (strm.avail_out === 0) {
  19798. strm.output = new utils.Buf8(chunkSize);
  19799. strm.next_out = 0;
  19800. strm.avail_out = chunkSize;
  19801. }
  19802. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  19803. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  19804. this.onEnd(status);
  19805. this.ended = true;
  19806. return false;
  19807. }
  19808. if (strm.next_out) {
  19809. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  19810. if (this.options.to === 'string') {
  19811. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  19812. tail = strm.next_out - next_out_utf8;
  19813. utf8str = strings.buf2string(strm.output, next_out_utf8);
  19814. // move tail
  19815. strm.next_out = tail;
  19816. strm.avail_out = chunkSize - tail;
  19817. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  19818. this.onData(utf8str);
  19819. } else {
  19820. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  19821. }
  19822. }
  19823. }
  19824. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  19825. if (status === c.Z_STREAM_END) {
  19826. _mode = c.Z_FINISH;
  19827. }
  19828. // Finalize on the last chunk.
  19829. if (_mode === c.Z_FINISH) {
  19830. status = zlib_inflate.inflateEnd(this.strm);
  19831. this.onEnd(status);
  19832. this.ended = true;
  19833. return status === c.Z_OK;
  19834. }
  19835. // callback interim results if Z_SYNC_FLUSH.
  19836. if (_mode === c.Z_SYNC_FLUSH) {
  19837. this.onEnd(c.Z_OK);
  19838. strm.avail_out = 0;
  19839. return true;
  19840. }
  19841. return true;
  19842. };
  19843. /**
  19844. * Inflate#onData(chunk) -> Void
  19845. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  19846. * on js engine support. When string output requested, each chunk
  19847. * will be string.
  19848. *
  19849. * By default, stores data blocks in `chunks[]` property and glue
  19850. * those in `onEnd`. Override this handler, if you need another behaviour.
  19851. **/
  19852. Inflate.prototype.onData = function(chunk) {
  19853. this.chunks.push(chunk);
  19854. };
  19855. /**
  19856. * Inflate#onEnd(status) -> Void
  19857. * - status (Number): inflate status. 0 (Z_OK) on success,
  19858. * other if not.
  19859. *
  19860. * Called either after you tell inflate that the input stream is
  19861. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  19862. * or if an error happened. By default - join collected chunks,
  19863. * free memory and fill `results` / `err` properties.
  19864. **/
  19865. Inflate.prototype.onEnd = function(status) {
  19866. // On success - join
  19867. if (status === c.Z_OK) {
  19868. if (this.options.to === 'string') {
  19869. // Glue & convert here, until we teach pako to send
  19870. // utf8 alligned strings to onData
  19871. this.result = this.chunks.join('');
  19872. } else {
  19873. this.result = utils.flattenChunks(this.chunks);
  19874. }
  19875. }
  19876. this.chunks = [];
  19877. this.err = status;
  19878. this.msg = this.strm.msg;
  19879. };
  19880. /**
  19881. * inflate(data[, options]) -> Uint8Array|Array|String
  19882. * - data (Uint8Array|Array|String): input data to decompress.
  19883. * - options (Object): zlib inflate options.
  19884. *
  19885. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  19886. * format via wrapper header by default. That's why we don't provide
  19887. * separate `ungzip` method.
  19888. *
  19889. * Supported options are:
  19890. *
  19891. * - windowBits
  19892. *
  19893. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19894. * for more information.
  19895. *
  19896. * Sugar (options):
  19897. *
  19898. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  19899. * negative windowBits implicitly.
  19900. * - `to` (String) - if equal to 'string', then result will be converted
  19901. * from utf8 to utf16 (javascript) string. When string output requested,
  19902. * chunk length can differ from `chunkSize`, depending on content.
  19903. *
  19904. *
  19905. * ##### Example:
  19906. *
  19907. * ```javascript
  19908. * var pako = require('pako')
  19909. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  19910. * , output;
  19911. *
  19912. * try {
  19913. * output = pako.inflate(input);
  19914. * } catch (err)
  19915. * console.log(err);
  19916. * }
  19917. * ```
  19918. **/
  19919. function inflate(input, options) {
  19920. var inflator = new Inflate(options);
  19921. inflator.push(input, true);
  19922. // That will never happens, if you don't cheat with options :)
  19923. if (inflator.err) { throw inflator.msg; }
  19924. return inflator.result;
  19925. }
  19926. /**
  19927. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  19928. * - data (Uint8Array|Array|String): input data to decompress.
  19929. * - options (Object): zlib inflate options.
  19930. *
  19931. * The same as [[inflate]], but creates raw data, without wrapper
  19932. * (header and adler32 crc).
  19933. **/
  19934. function inflateRaw(input, options) {
  19935. options = options || {};
  19936. options.raw = true;
  19937. return inflate(input, options);
  19938. }
  19939. /**
  19940. * ungzip(data[, options]) -> Uint8Array|Array|String
  19941. * - data (Uint8Array|Array|String): input data to decompress.
  19942. * - options (Object): zlib inflate options.
  19943. *
  19944. * Just shortcut to [[inflate]], because it autodetects format
  19945. * by header.content. Done for convenience.
  19946. **/
  19947. exports.Inflate = Inflate;
  19948. exports.inflate = inflate;
  19949. exports.inflateRaw = inflateRaw;
  19950. exports.ungzip = inflate;
  19951. },{"./utils/common":72,"./utils/strings":73,"./zlib/constants":75,"./zlib/gzheader":78,"./zlib/inflate.js":80,"./zlib/messages":82,"./zlib/zstream":84}],72:[function(require,module,exports){
  19952. 'use strict';
  19953. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  19954. (typeof Uint16Array !== 'undefined') &&
  19955. (typeof Int32Array !== 'undefined');
  19956. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  19957. var sources = Array.prototype.slice.call(arguments, 1);
  19958. while (sources.length) {
  19959. var source = sources.shift();
  19960. if (!source) { continue; }
  19961. if (typeof source !== 'object') {
  19962. throw new TypeError(source + 'must be non-object');
  19963. }
  19964. for (var p in source) {
  19965. if (source.hasOwnProperty(p)) {
  19966. obj[p] = source[p];
  19967. }
  19968. }
  19969. }
  19970. return obj;
  19971. };
  19972. // reduce buffer size, avoiding mem copy
  19973. exports.shrinkBuf = function (buf, size) {
  19974. if (buf.length === size) { return buf; }
  19975. if (buf.subarray) { return buf.subarray(0, size); }
  19976. buf.length = size;
  19977. return buf;
  19978. };
  19979. var fnTyped = {
  19980. arraySet: function (dest, src, src_offs, len, dest_offs) {
  19981. if (src.subarray && dest.subarray) {
  19982. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  19983. return;
  19984. }
  19985. // Fallback to ordinary array
  19986. for (var i=0; i<len; i++) {
  19987. dest[dest_offs + i] = src[src_offs + i];
  19988. }
  19989. },
  19990. // Join array of chunks to single array.
  19991. flattenChunks: function(chunks) {
  19992. var i, l, len, pos, chunk, result;
  19993. // calculate data length
  19994. len = 0;
  19995. for (i=0, l=chunks.length; i<l; i++) {
  19996. len += chunks[i].length;
  19997. }
  19998. // join chunks
  19999. result = new Uint8Array(len);
  20000. pos = 0;
  20001. for (i=0, l=chunks.length; i<l; i++) {
  20002. chunk = chunks[i];
  20003. result.set(chunk, pos);
  20004. pos += chunk.length;
  20005. }
  20006. return result;
  20007. }
  20008. };
  20009. var fnUntyped = {
  20010. arraySet: function (dest, src, src_offs, len, dest_offs) {
  20011. for (var i=0; i<len; i++) {
  20012. dest[dest_offs + i] = src[src_offs + i];
  20013. }
  20014. },
  20015. // Join array of chunks to single array.
  20016. flattenChunks: function(chunks) {
  20017. return [].concat.apply([], chunks);
  20018. }
  20019. };
  20020. // Enable/Disable typed arrays use, for testing
  20021. //
  20022. exports.setTyped = function (on) {
  20023. if (on) {
  20024. exports.Buf8 = Uint8Array;
  20025. exports.Buf16 = Uint16Array;
  20026. exports.Buf32 = Int32Array;
  20027. exports.assign(exports, fnTyped);
  20028. } else {
  20029. exports.Buf8 = Array;
  20030. exports.Buf16 = Array;
  20031. exports.Buf32 = Array;
  20032. exports.assign(exports, fnUntyped);
  20033. }
  20034. };
  20035. exports.setTyped(TYPED_OK);
  20036. },{}],73:[function(require,module,exports){
  20037. // String encode/decode helpers
  20038. 'use strict';
  20039. var utils = require('./common');
  20040. // Quick check if we can use fast array to bin string conversion
  20041. //
  20042. // - apply(Array) can fail on Android 2.2
  20043. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  20044. //
  20045. var STR_APPLY_OK = true;
  20046. var STR_APPLY_UIA_OK = true;
  20047. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  20048. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  20049. // Table with utf8 lengths (calculated by first byte of sequence)
  20050. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  20051. // because max possible codepoint is 0x10ffff
  20052. var _utf8len = new utils.Buf8(256);
  20053. for (var q=0; q<256; q++) {
  20054. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  20055. }
  20056. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  20057. // convert string to array (typed, when possible)
  20058. exports.string2buf = function (str) {
  20059. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  20060. // count binary size
  20061. for (m_pos = 0; m_pos < str_len; m_pos++) {
  20062. c = str.charCodeAt(m_pos);
  20063. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  20064. c2 = str.charCodeAt(m_pos+1);
  20065. if ((c2 & 0xfc00) === 0xdc00) {
  20066. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  20067. m_pos++;
  20068. }
  20069. }
  20070. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  20071. }
  20072. // allocate buffer
  20073. buf = new utils.Buf8(buf_len);
  20074. // convert
  20075. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  20076. c = str.charCodeAt(m_pos);
  20077. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  20078. c2 = str.charCodeAt(m_pos+1);
  20079. if ((c2 & 0xfc00) === 0xdc00) {
  20080. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  20081. m_pos++;
  20082. }
  20083. }
  20084. if (c < 0x80) {
  20085. /* one byte */
  20086. buf[i++] = c;
  20087. } else if (c < 0x800) {
  20088. /* two bytes */
  20089. buf[i++] = 0xC0 | (c >>> 6);
  20090. buf[i++] = 0x80 | (c & 0x3f);
  20091. } else if (c < 0x10000) {
  20092. /* three bytes */
  20093. buf[i++] = 0xE0 | (c >>> 12);
  20094. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  20095. buf[i++] = 0x80 | (c & 0x3f);
  20096. } else {
  20097. /* four bytes */
  20098. buf[i++] = 0xf0 | (c >>> 18);
  20099. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  20100. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  20101. buf[i++] = 0x80 | (c & 0x3f);
  20102. }
  20103. }
  20104. return buf;
  20105. };
  20106. // Helper (used in 2 places)
  20107. function buf2binstring(buf, len) {
  20108. // use fallback for big arrays to avoid stack overflow
  20109. if (len < 65537) {
  20110. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  20111. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  20112. }
  20113. }
  20114. var result = '';
  20115. for (var i=0; i < len; i++) {
  20116. result += String.fromCharCode(buf[i]);
  20117. }
  20118. return result;
  20119. }
  20120. // Convert byte array to binary string
  20121. exports.buf2binstring = function(buf) {
  20122. return buf2binstring(buf, buf.length);
  20123. };
  20124. // Convert binary string (typed, when possible)
  20125. exports.binstring2buf = function(str) {
  20126. var buf = new utils.Buf8(str.length);
  20127. for (var i=0, len=buf.length; i < len; i++) {
  20128. buf[i] = str.charCodeAt(i);
  20129. }
  20130. return buf;
  20131. };
  20132. // convert array to string
  20133. exports.buf2string = function (buf, max) {
  20134. var i, out, c, c_len;
  20135. var len = max || buf.length;
  20136. // Reserve max possible length (2 words per char)
  20137. // NB: by unknown reasons, Array is significantly faster for
  20138. // String.fromCharCode.apply than Uint16Array.
  20139. var utf16buf = new Array(len*2);
  20140. for (out=0, i=0; i<len;) {
  20141. c = buf[i++];
  20142. // quick process ascii
  20143. if (c < 0x80) { utf16buf[out++] = c; continue; }
  20144. c_len = _utf8len[c];
  20145. // skip 5 & 6 byte codes
  20146. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  20147. // apply mask on first byte
  20148. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  20149. // join the rest
  20150. while (c_len > 1 && i < len) {
  20151. c = (c << 6) | (buf[i++] & 0x3f);
  20152. c_len--;
  20153. }
  20154. // terminated by end of string?
  20155. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  20156. if (c < 0x10000) {
  20157. utf16buf[out++] = c;
  20158. } else {
  20159. c -= 0x10000;
  20160. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  20161. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  20162. }
  20163. }
  20164. return buf2binstring(utf16buf, out);
  20165. };
  20166. // Calculate max possible position in utf8 buffer,
  20167. // that will not break sequence. If that's not possible
  20168. // - (very small limits) return max size as is.
  20169. //
  20170. // buf[] - utf8 bytes array
  20171. // max - length limit (mandatory);
  20172. exports.utf8border = function(buf, max) {
  20173. var pos;
  20174. max = max || buf.length;
  20175. if (max > buf.length) { max = buf.length; }
  20176. // go back from last position, until start of sequence found
  20177. pos = max-1;
  20178. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  20179. // Fuckup - very small and broken sequence,
  20180. // return max, because we should return something anyway.
  20181. if (pos < 0) { return max; }
  20182. // If we came to start of buffer - that means vuffer is too small,
  20183. // return max too.
  20184. if (pos === 0) { return max; }
  20185. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  20186. };
  20187. },{"./common":72}],74:[function(require,module,exports){
  20188. 'use strict';
  20189. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  20190. // It doesn't worth to make additional optimizationa as in original.
  20191. // Small size is preferable.
  20192. function adler32(adler, buf, len, pos) {
  20193. var s1 = (adler & 0xffff) |0,
  20194. s2 = ((adler >>> 16) & 0xffff) |0,
  20195. n = 0;
  20196. while (len !== 0) {
  20197. // Set limit ~ twice less than 5552, to keep
  20198. // s2 in 31-bits, because we force signed ints.
  20199. // in other case %= will fail.
  20200. n = len > 2000 ? 2000 : len;
  20201. len -= n;
  20202. do {
  20203. s1 = (s1 + buf[pos++]) |0;
  20204. s2 = (s2 + s1) |0;
  20205. } while (--n);
  20206. s1 %= 65521;
  20207. s2 %= 65521;
  20208. }
  20209. return (s1 | (s2 << 16)) |0;
  20210. }
  20211. module.exports = adler32;
  20212. },{}],75:[function(require,module,exports){
  20213. module.exports = {
  20214. /* Allowed flush values; see deflate() and inflate() below for details */
  20215. Z_NO_FLUSH: 0,
  20216. Z_PARTIAL_FLUSH: 1,
  20217. Z_SYNC_FLUSH: 2,
  20218. Z_FULL_FLUSH: 3,
  20219. Z_FINISH: 4,
  20220. Z_BLOCK: 5,
  20221. Z_TREES: 6,
  20222. /* Return codes for the compression/decompression functions. Negative values
  20223. * are errors, positive values are used for special but normal events.
  20224. */
  20225. Z_OK: 0,
  20226. Z_STREAM_END: 1,
  20227. Z_NEED_DICT: 2,
  20228. Z_ERRNO: -1,
  20229. Z_STREAM_ERROR: -2,
  20230. Z_DATA_ERROR: -3,
  20231. //Z_MEM_ERROR: -4,
  20232. Z_BUF_ERROR: -5,
  20233. //Z_VERSION_ERROR: -6,
  20234. /* compression levels */
  20235. Z_NO_COMPRESSION: 0,
  20236. Z_BEST_SPEED: 1,
  20237. Z_BEST_COMPRESSION: 9,
  20238. Z_DEFAULT_COMPRESSION: -1,
  20239. Z_FILTERED: 1,
  20240. Z_HUFFMAN_ONLY: 2,
  20241. Z_RLE: 3,
  20242. Z_FIXED: 4,
  20243. Z_DEFAULT_STRATEGY: 0,
  20244. /* Possible values of the data_type field (though see inflate()) */
  20245. Z_BINARY: 0,
  20246. Z_TEXT: 1,
  20247. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  20248. Z_UNKNOWN: 2,
  20249. /* The deflate compression method */
  20250. Z_DEFLATED: 8
  20251. //Z_NULL: null // Use -1 or null inline, depending on var type
  20252. };
  20253. },{}],76:[function(require,module,exports){
  20254. 'use strict';
  20255. // Note: we can't get significant speed boost here.
  20256. // So write code to minimize size - no pregenerated tables
  20257. // and array tools dependencies.
  20258. // Use ordinary array, since untyped makes no boost here
  20259. function makeTable() {
  20260. var c, table = [];
  20261. for (var n =0; n < 256; n++) {
  20262. c = n;
  20263. for (var k =0; k < 8; k++) {
  20264. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  20265. }
  20266. table[n] = c;
  20267. }
  20268. return table;
  20269. }
  20270. // Create table on load. Just 255 signed longs. Not a problem.
  20271. var crcTable = makeTable();
  20272. function crc32(crc, buf, len, pos) {
  20273. var t = crcTable,
  20274. end = pos + len;
  20275. crc = crc ^ (-1);
  20276. for (var i = pos; i < end; i++) {
  20277. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  20278. }
  20279. return (crc ^ (-1)); // >>> 0;
  20280. }
  20281. module.exports = crc32;
  20282. },{}],77:[function(require,module,exports){
  20283. 'use strict';
  20284. var utils = require('../utils/common');
  20285. var trees = require('./trees');
  20286. var adler32 = require('./adler32');
  20287. var crc32 = require('./crc32');
  20288. var msg = require('./messages');
  20289. /* Public constants ==========================================================*/
  20290. /* ===========================================================================*/
  20291. /* Allowed flush values; see deflate() and inflate() below for details */
  20292. var Z_NO_FLUSH = 0;
  20293. var Z_PARTIAL_FLUSH = 1;
  20294. //var Z_SYNC_FLUSH = 2;
  20295. var Z_FULL_FLUSH = 3;
  20296. var Z_FINISH = 4;
  20297. var Z_BLOCK = 5;
  20298. //var Z_TREES = 6;
  20299. /* Return codes for the compression/decompression functions. Negative values
  20300. * are errors, positive values are used for special but normal events.
  20301. */
  20302. var Z_OK = 0;
  20303. var Z_STREAM_END = 1;
  20304. //var Z_NEED_DICT = 2;
  20305. //var Z_ERRNO = -1;
  20306. var Z_STREAM_ERROR = -2;
  20307. var Z_DATA_ERROR = -3;
  20308. //var Z_MEM_ERROR = -4;
  20309. var Z_BUF_ERROR = -5;
  20310. //var Z_VERSION_ERROR = -6;
  20311. /* compression levels */
  20312. //var Z_NO_COMPRESSION = 0;
  20313. //var Z_BEST_SPEED = 1;
  20314. //var Z_BEST_COMPRESSION = 9;
  20315. var Z_DEFAULT_COMPRESSION = -1;
  20316. var Z_FILTERED = 1;
  20317. var Z_HUFFMAN_ONLY = 2;
  20318. var Z_RLE = 3;
  20319. var Z_FIXED = 4;
  20320. var Z_DEFAULT_STRATEGY = 0;
  20321. /* Possible values of the data_type field (though see inflate()) */
  20322. //var Z_BINARY = 0;
  20323. //var Z_TEXT = 1;
  20324. //var Z_ASCII = 1; // = Z_TEXT
  20325. var Z_UNKNOWN = 2;
  20326. /* The deflate compression method */
  20327. var Z_DEFLATED = 8;
  20328. /*============================================================================*/
  20329. var MAX_MEM_LEVEL = 9;
  20330. /* Maximum value for memLevel in deflateInit2 */
  20331. var MAX_WBITS = 15;
  20332. /* 32K LZ77 window */
  20333. var DEF_MEM_LEVEL = 8;
  20334. var LENGTH_CODES = 29;
  20335. /* number of length codes, not counting the special END_BLOCK code */
  20336. var LITERALS = 256;
  20337. /* number of literal bytes 0..255 */
  20338. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  20339. /* number of Literal or Length codes, including the END_BLOCK code */
  20340. var D_CODES = 30;
  20341. /* number of distance codes */
  20342. var BL_CODES = 19;
  20343. /* number of codes used to transfer the bit lengths */
  20344. var HEAP_SIZE = 2*L_CODES + 1;
  20345. /* maximum heap size */
  20346. var MAX_BITS = 15;
  20347. /* All codes must not exceed MAX_BITS bits */
  20348. var MIN_MATCH = 3;
  20349. var MAX_MATCH = 258;
  20350. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  20351. var PRESET_DICT = 0x20;
  20352. var INIT_STATE = 42;
  20353. var EXTRA_STATE = 69;
  20354. var NAME_STATE = 73;
  20355. var COMMENT_STATE = 91;
  20356. var HCRC_STATE = 103;
  20357. var BUSY_STATE = 113;
  20358. var FINISH_STATE = 666;
  20359. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  20360. var BS_BLOCK_DONE = 2; /* block flush performed */
  20361. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  20362. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  20363. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  20364. function err(strm, errorCode) {
  20365. strm.msg = msg[errorCode];
  20366. return errorCode;
  20367. }
  20368. function rank(f) {
  20369. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  20370. }
  20371. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  20372. /* =========================================================================
  20373. * Flush as much pending output as possible. All deflate() output goes
  20374. * through this function so some applications may wish to modify it
  20375. * to avoid allocating a large strm->output buffer and copying into it.
  20376. * (See also read_buf()).
  20377. */
  20378. function flush_pending(strm) {
  20379. var s = strm.state;
  20380. //_tr_flush_bits(s);
  20381. var len = s.pending;
  20382. if (len > strm.avail_out) {
  20383. len = strm.avail_out;
  20384. }
  20385. if (len === 0) { return; }
  20386. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  20387. strm.next_out += len;
  20388. s.pending_out += len;
  20389. strm.total_out += len;
  20390. strm.avail_out -= len;
  20391. s.pending -= len;
  20392. if (s.pending === 0) {
  20393. s.pending_out = 0;
  20394. }
  20395. }
  20396. function flush_block_only (s, last) {
  20397. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  20398. s.block_start = s.strstart;
  20399. flush_pending(s.strm);
  20400. }
  20401. function put_byte(s, b) {
  20402. s.pending_buf[s.pending++] = b;
  20403. }
  20404. /* =========================================================================
  20405. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  20406. * IN assertion: the stream state is correct and there is enough room in
  20407. * pending_buf.
  20408. */
  20409. function putShortMSB(s, b) {
  20410. // put_byte(s, (Byte)(b >> 8));
  20411. // put_byte(s, (Byte)(b & 0xff));
  20412. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  20413. s.pending_buf[s.pending++] = b & 0xff;
  20414. }
  20415. /* ===========================================================================
  20416. * Read a new buffer from the current input stream, update the adler32
  20417. * and total number of bytes read. All deflate() input goes through
  20418. * this function so some applications may wish to modify it to avoid
  20419. * allocating a large strm->input buffer and copying from it.
  20420. * (See also flush_pending()).
  20421. */
  20422. function read_buf(strm, buf, start, size) {
  20423. var len = strm.avail_in;
  20424. if (len > size) { len = size; }
  20425. if (len === 0) { return 0; }
  20426. strm.avail_in -= len;
  20427. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  20428. if (strm.state.wrap === 1) {
  20429. strm.adler = adler32(strm.adler, buf, len, start);
  20430. }
  20431. else if (strm.state.wrap === 2) {
  20432. strm.adler = crc32(strm.adler, buf, len, start);
  20433. }
  20434. strm.next_in += len;
  20435. strm.total_in += len;
  20436. return len;
  20437. }
  20438. /* ===========================================================================
  20439. * Set match_start to the longest match starting at the given string and
  20440. * return its length. Matches shorter or equal to prev_length are discarded,
  20441. * in which case the result is equal to prev_length and match_start is
  20442. * garbage.
  20443. * IN assertions: cur_match is the head of the hash chain for the current
  20444. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  20445. * OUT assertion: the match length is not greater than s->lookahead.
  20446. */
  20447. function longest_match(s, cur_match) {
  20448. var chain_length = s.max_chain_length; /* max hash chain length */
  20449. var scan = s.strstart; /* current string */
  20450. var match; /* matched string */
  20451. var len; /* length of current match */
  20452. var best_len = s.prev_length; /* best match length so far */
  20453. var nice_match = s.nice_match; /* stop if match long enough */
  20454. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  20455. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  20456. var _win = s.window; // shortcut
  20457. var wmask = s.w_mask;
  20458. var prev = s.prev;
  20459. /* Stop when cur_match becomes <= limit. To simplify the code,
  20460. * we prevent matches with the string of window index 0.
  20461. */
  20462. var strend = s.strstart + MAX_MATCH;
  20463. var scan_end1 = _win[scan + best_len - 1];
  20464. var scan_end = _win[scan + best_len];
  20465. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  20466. * It is easy to get rid of this optimization if necessary.
  20467. */
  20468. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  20469. /* Do not waste too much time if we already have a good match: */
  20470. if (s.prev_length >= s.good_match) {
  20471. chain_length >>= 2;
  20472. }
  20473. /* Do not look for matches beyond the end of the input. This is necessary
  20474. * to make deflate deterministic.
  20475. */
  20476. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  20477. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  20478. do {
  20479. // Assert(cur_match < s->strstart, "no future");
  20480. match = cur_match;
  20481. /* Skip to next match if the match length cannot increase
  20482. * or if the match length is less than 2. Note that the checks below
  20483. * for insufficient lookahead only occur occasionally for performance
  20484. * reasons. Therefore uninitialized memory will be accessed, and
  20485. * conditional jumps will be made that depend on those values.
  20486. * However the length of the match is limited to the lookahead, so
  20487. * the output of deflate is not affected by the uninitialized values.
  20488. */
  20489. if (_win[match + best_len] !== scan_end ||
  20490. _win[match + best_len - 1] !== scan_end1 ||
  20491. _win[match] !== _win[scan] ||
  20492. _win[++match] !== _win[scan + 1]) {
  20493. continue;
  20494. }
  20495. /* The check at best_len-1 can be removed because it will be made
  20496. * again later. (This heuristic is not always a win.)
  20497. * It is not necessary to compare scan[2] and match[2] since they
  20498. * are always equal when the other bytes match, given that
  20499. * the hash keys are equal and that HASH_BITS >= 8.
  20500. */
  20501. scan += 2;
  20502. match++;
  20503. // Assert(*scan == *match, "match[2]?");
  20504. /* We check for insufficient lookahead only every 8th comparison;
  20505. * the 256th check will be made at strstart+258.
  20506. */
  20507. do {
  20508. /*jshint noempty:false*/
  20509. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20510. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20511. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20512. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20513. scan < strend);
  20514. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  20515. len = MAX_MATCH - (strend - scan);
  20516. scan = strend - MAX_MATCH;
  20517. if (len > best_len) {
  20518. s.match_start = cur_match;
  20519. best_len = len;
  20520. if (len >= nice_match) {
  20521. break;
  20522. }
  20523. scan_end1 = _win[scan + best_len - 1];
  20524. scan_end = _win[scan + best_len];
  20525. }
  20526. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  20527. if (best_len <= s.lookahead) {
  20528. return best_len;
  20529. }
  20530. return s.lookahead;
  20531. }
  20532. /* ===========================================================================
  20533. * Fill the window when the lookahead becomes insufficient.
  20534. * Updates strstart and lookahead.
  20535. *
  20536. * IN assertion: lookahead < MIN_LOOKAHEAD
  20537. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  20538. * At least one byte has been read, or avail_in == 0; reads are
  20539. * performed for at least two bytes (required for the zip translate_eol
  20540. * option -- not supported here).
  20541. */
  20542. function fill_window(s) {
  20543. var _w_size = s.w_size;
  20544. var p, n, m, more, str;
  20545. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  20546. do {
  20547. more = s.window_size - s.lookahead - s.strstart;
  20548. // JS ints have 32 bit, block below not needed
  20549. /* Deal with !@#$% 64K limit: */
  20550. //if (sizeof(int) <= 2) {
  20551. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  20552. // more = wsize;
  20553. //
  20554. // } else if (more == (unsigned)(-1)) {
  20555. // /* Very unlikely, but possible on 16 bit machine if
  20556. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  20557. // */
  20558. // more--;
  20559. // }
  20560. //}
  20561. /* If the window is almost full and there is insufficient lookahead,
  20562. * move the upper half to the lower one to make room in the upper half.
  20563. */
  20564. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  20565. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  20566. s.match_start -= _w_size;
  20567. s.strstart -= _w_size;
  20568. /* we now have strstart >= MAX_DIST */
  20569. s.block_start -= _w_size;
  20570. /* Slide the hash table (could be avoided with 32 bit values
  20571. at the expense of memory usage). We slide even when level == 0
  20572. to keep the hash table consistent if we switch back to level > 0
  20573. later. (Using level 0 permanently is not an optimal usage of
  20574. zlib, so we don't care about this pathological case.)
  20575. */
  20576. n = s.hash_size;
  20577. p = n;
  20578. do {
  20579. m = s.head[--p];
  20580. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  20581. } while (--n);
  20582. n = _w_size;
  20583. p = n;
  20584. do {
  20585. m = s.prev[--p];
  20586. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  20587. /* If n is not on any hash chain, prev[n] is garbage but
  20588. * its value will never be used.
  20589. */
  20590. } while (--n);
  20591. more += _w_size;
  20592. }
  20593. if (s.strm.avail_in === 0) {
  20594. break;
  20595. }
  20596. /* If there was no sliding:
  20597. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  20598. * more == window_size - lookahead - strstart
  20599. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  20600. * => more >= window_size - 2*WSIZE + 2
  20601. * In the BIG_MEM or MMAP case (not yet supported),
  20602. * window_size == input_size + MIN_LOOKAHEAD &&
  20603. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  20604. * Otherwise, window_size == 2*WSIZE so more >= 2.
  20605. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  20606. */
  20607. //Assert(more >= 2, "more < 2");
  20608. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  20609. s.lookahead += n;
  20610. /* Initialize the hash value now that we have some input: */
  20611. if (s.lookahead + s.insert >= MIN_MATCH) {
  20612. str = s.strstart - s.insert;
  20613. s.ins_h = s.window[str];
  20614. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  20615. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  20616. //#if MIN_MATCH != 3
  20617. // Call update_hash() MIN_MATCH-3 more times
  20618. //#endif
  20619. while (s.insert) {
  20620. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  20621. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  20622. s.prev[str & s.w_mask] = s.head[s.ins_h];
  20623. s.head[s.ins_h] = str;
  20624. str++;
  20625. s.insert--;
  20626. if (s.lookahead + s.insert < MIN_MATCH) {
  20627. break;
  20628. }
  20629. }
  20630. }
  20631. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  20632. * but this is not important since only literal bytes will be emitted.
  20633. */
  20634. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  20635. /* If the WIN_INIT bytes after the end of the current data have never been
  20636. * written, then zero those bytes in order to avoid memory check reports of
  20637. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  20638. * the longest match routines. Update the high water mark for the next
  20639. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  20640. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  20641. */
  20642. // if (s.high_water < s.window_size) {
  20643. // var curr = s.strstart + s.lookahead;
  20644. // var init = 0;
  20645. //
  20646. // if (s.high_water < curr) {
  20647. // /* Previous high water mark below current data -- zero WIN_INIT
  20648. // * bytes or up to end of window, whichever is less.
  20649. // */
  20650. // init = s.window_size - curr;
  20651. // if (init > WIN_INIT)
  20652. // init = WIN_INIT;
  20653. // zmemzero(s->window + curr, (unsigned)init);
  20654. // s->high_water = curr + init;
  20655. // }
  20656. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  20657. // /* High water mark at or above current data, but below current data
  20658. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  20659. // * to end of window, whichever is less.
  20660. // */
  20661. // init = (ulg)curr + WIN_INIT - s->high_water;
  20662. // if (init > s->window_size - s->high_water)
  20663. // init = s->window_size - s->high_water;
  20664. // zmemzero(s->window + s->high_water, (unsigned)init);
  20665. // s->high_water += init;
  20666. // }
  20667. // }
  20668. //
  20669. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  20670. // "not enough room for search");
  20671. }
  20672. /* ===========================================================================
  20673. * Copy without compression as much as possible from the input stream, return
  20674. * the current block state.
  20675. * This function does not insert new strings in the dictionary since
  20676. * uncompressible data is probably not useful. This function is used
  20677. * only for the level=0 compression option.
  20678. * NOTE: this function should be optimized to avoid extra copying from
  20679. * window to pending_buf.
  20680. */
  20681. function deflate_stored(s, flush) {
  20682. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  20683. * to pending_buf_size, and each stored block has a 5 byte header:
  20684. */
  20685. var max_block_size = 0xffff;
  20686. if (max_block_size > s.pending_buf_size - 5) {
  20687. max_block_size = s.pending_buf_size - 5;
  20688. }
  20689. /* Copy as much as possible from input to output: */
  20690. for (;;) {
  20691. /* Fill the window as much as possible: */
  20692. if (s.lookahead <= 1) {
  20693. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  20694. // s->block_start >= (long)s->w_size, "slide too late");
  20695. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  20696. // s.block_start >= s.w_size)) {
  20697. // throw new Error("slide too late");
  20698. // }
  20699. fill_window(s);
  20700. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  20701. return BS_NEED_MORE;
  20702. }
  20703. if (s.lookahead === 0) {
  20704. break;
  20705. }
  20706. /* flush the current block */
  20707. }
  20708. //Assert(s->block_start >= 0L, "block gone");
  20709. // if (s.block_start < 0) throw new Error("block gone");
  20710. s.strstart += s.lookahead;
  20711. s.lookahead = 0;
  20712. /* Emit a stored block if pending_buf will be full: */
  20713. var max_start = s.block_start + max_block_size;
  20714. if (s.strstart === 0 || s.strstart >= max_start) {
  20715. /* strstart == 0 is possible when wraparound on 16-bit machine */
  20716. s.lookahead = s.strstart - max_start;
  20717. s.strstart = max_start;
  20718. /*** FLUSH_BLOCK(s, 0); ***/
  20719. flush_block_only(s, false);
  20720. if (s.strm.avail_out === 0) {
  20721. return BS_NEED_MORE;
  20722. }
  20723. /***/
  20724. }
  20725. /* Flush if we may have to slide, otherwise block_start may become
  20726. * negative and the data will be gone:
  20727. */
  20728. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  20729. /*** FLUSH_BLOCK(s, 0); ***/
  20730. flush_block_only(s, false);
  20731. if (s.strm.avail_out === 0) {
  20732. return BS_NEED_MORE;
  20733. }
  20734. /***/
  20735. }
  20736. }
  20737. s.insert = 0;
  20738. if (flush === Z_FINISH) {
  20739. /*** FLUSH_BLOCK(s, 1); ***/
  20740. flush_block_only(s, true);
  20741. if (s.strm.avail_out === 0) {
  20742. return BS_FINISH_STARTED;
  20743. }
  20744. /***/
  20745. return BS_FINISH_DONE;
  20746. }
  20747. if (s.strstart > s.block_start) {
  20748. /*** FLUSH_BLOCK(s, 0); ***/
  20749. flush_block_only(s, false);
  20750. if (s.strm.avail_out === 0) {
  20751. return BS_NEED_MORE;
  20752. }
  20753. /***/
  20754. }
  20755. return BS_NEED_MORE;
  20756. }
  20757. /* ===========================================================================
  20758. * Compress as much as possible from the input stream, return the current
  20759. * block state.
  20760. * This function does not perform lazy evaluation of matches and inserts
  20761. * new strings in the dictionary only for unmatched strings or for short
  20762. * matches. It is used only for the fast compression options.
  20763. */
  20764. function deflate_fast(s, flush) {
  20765. var hash_head; /* head of the hash chain */
  20766. var bflush; /* set if current block must be flushed */
  20767. for (;;) {
  20768. /* Make sure that we always have enough lookahead, except
  20769. * at the end of the input file. We need MAX_MATCH bytes
  20770. * for the next match, plus MIN_MATCH bytes to insert the
  20771. * string following the next match.
  20772. */
  20773. if (s.lookahead < MIN_LOOKAHEAD) {
  20774. fill_window(s);
  20775. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  20776. return BS_NEED_MORE;
  20777. }
  20778. if (s.lookahead === 0) {
  20779. break; /* flush the current block */
  20780. }
  20781. }
  20782. /* Insert the string window[strstart .. strstart+2] in the
  20783. * dictionary, and set hash_head to the head of the hash chain:
  20784. */
  20785. hash_head = 0/*NIL*/;
  20786. if (s.lookahead >= MIN_MATCH) {
  20787. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20788. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20789. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20790. s.head[s.ins_h] = s.strstart;
  20791. /***/
  20792. }
  20793. /* Find the longest match, discarding those <= prev_length.
  20794. * At this point we have always match_length < MIN_MATCH
  20795. */
  20796. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  20797. /* To simplify the code, we prevent matches with the string
  20798. * of window index 0 (in particular we have to avoid a match
  20799. * of the string with itself at the start of the input file).
  20800. */
  20801. s.match_length = longest_match(s, hash_head);
  20802. /* longest_match() sets match_start */
  20803. }
  20804. if (s.match_length >= MIN_MATCH) {
  20805. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  20806. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  20807. s.match_length - MIN_MATCH, bflush); ***/
  20808. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  20809. s.lookahead -= s.match_length;
  20810. /* Insert new strings in the hash table only if the match length
  20811. * is not too large. This saves time but degrades compression.
  20812. */
  20813. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  20814. s.match_length--; /* string at strstart already in table */
  20815. do {
  20816. s.strstart++;
  20817. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20818. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20819. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20820. s.head[s.ins_h] = s.strstart;
  20821. /***/
  20822. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  20823. * always MIN_MATCH bytes ahead.
  20824. */
  20825. } while (--s.match_length !== 0);
  20826. s.strstart++;
  20827. } else
  20828. {
  20829. s.strstart += s.match_length;
  20830. s.match_length = 0;
  20831. s.ins_h = s.window[s.strstart];
  20832. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  20833. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  20834. //#if MIN_MATCH != 3
  20835. // Call UPDATE_HASH() MIN_MATCH-3 more times
  20836. //#endif
  20837. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  20838. * matter since it will be recomputed at next deflate call.
  20839. */
  20840. }
  20841. } else {
  20842. /* No match, output a literal byte */
  20843. //Tracevv((stderr,"%c", s.window[s.strstart]));
  20844. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  20845. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  20846. s.lookahead--;
  20847. s.strstart++;
  20848. }
  20849. if (bflush) {
  20850. /*** FLUSH_BLOCK(s, 0); ***/
  20851. flush_block_only(s, false);
  20852. if (s.strm.avail_out === 0) {
  20853. return BS_NEED_MORE;
  20854. }
  20855. /***/
  20856. }
  20857. }
  20858. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  20859. if (flush === Z_FINISH) {
  20860. /*** FLUSH_BLOCK(s, 1); ***/
  20861. flush_block_only(s, true);
  20862. if (s.strm.avail_out === 0) {
  20863. return BS_FINISH_STARTED;
  20864. }
  20865. /***/
  20866. return BS_FINISH_DONE;
  20867. }
  20868. if (s.last_lit) {
  20869. /*** FLUSH_BLOCK(s, 0); ***/
  20870. flush_block_only(s, false);
  20871. if (s.strm.avail_out === 0) {
  20872. return BS_NEED_MORE;
  20873. }
  20874. /***/
  20875. }
  20876. return BS_BLOCK_DONE;
  20877. }
  20878. /* ===========================================================================
  20879. * Same as above, but achieves better compression. We use a lazy
  20880. * evaluation for matches: a match is finally adopted only if there is
  20881. * no better match at the next window position.
  20882. */
  20883. function deflate_slow(s, flush) {
  20884. var hash_head; /* head of hash chain */
  20885. var bflush; /* set if current block must be flushed */
  20886. var max_insert;
  20887. /* Process the input block. */
  20888. for (;;) {
  20889. /* Make sure that we always have enough lookahead, except
  20890. * at the end of the input file. We need MAX_MATCH bytes
  20891. * for the next match, plus MIN_MATCH bytes to insert the
  20892. * string following the next match.
  20893. */
  20894. if (s.lookahead < MIN_LOOKAHEAD) {
  20895. fill_window(s);
  20896. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  20897. return BS_NEED_MORE;
  20898. }
  20899. if (s.lookahead === 0) { break; } /* flush the current block */
  20900. }
  20901. /* Insert the string window[strstart .. strstart+2] in the
  20902. * dictionary, and set hash_head to the head of the hash chain:
  20903. */
  20904. hash_head = 0/*NIL*/;
  20905. if (s.lookahead >= MIN_MATCH) {
  20906. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20907. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20908. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20909. s.head[s.ins_h] = s.strstart;
  20910. /***/
  20911. }
  20912. /* Find the longest match, discarding those <= prev_length.
  20913. */
  20914. s.prev_length = s.match_length;
  20915. s.prev_match = s.match_start;
  20916. s.match_length = MIN_MATCH-1;
  20917. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  20918. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  20919. /* To simplify the code, we prevent matches with the string
  20920. * of window index 0 (in particular we have to avoid a match
  20921. * of the string with itself at the start of the input file).
  20922. */
  20923. s.match_length = longest_match(s, hash_head);
  20924. /* longest_match() sets match_start */
  20925. if (s.match_length <= 5 &&
  20926. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  20927. /* If prev_match is also MIN_MATCH, match_start is garbage
  20928. * but we will ignore the current match anyway.
  20929. */
  20930. s.match_length = MIN_MATCH-1;
  20931. }
  20932. }
  20933. /* If there was a match at the previous step and the current
  20934. * match is not better, output the previous match:
  20935. */
  20936. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  20937. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  20938. /* Do not insert strings in hash table beyond this. */
  20939. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  20940. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  20941. s.prev_length - MIN_MATCH, bflush);***/
  20942. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  20943. /* Insert in hash table all strings up to the end of the match.
  20944. * strstart-1 and strstart are already inserted. If there is not
  20945. * enough lookahead, the last two strings are not inserted in
  20946. * the hash table.
  20947. */
  20948. s.lookahead -= s.prev_length-1;
  20949. s.prev_length -= 2;
  20950. do {
  20951. if (++s.strstart <= max_insert) {
  20952. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20953. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20954. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20955. s.head[s.ins_h] = s.strstart;
  20956. /***/
  20957. }
  20958. } while (--s.prev_length !== 0);
  20959. s.match_available = 0;
  20960. s.match_length = MIN_MATCH-1;
  20961. s.strstart++;
  20962. if (bflush) {
  20963. /*** FLUSH_BLOCK(s, 0); ***/
  20964. flush_block_only(s, false);
  20965. if (s.strm.avail_out === 0) {
  20966. return BS_NEED_MORE;
  20967. }
  20968. /***/
  20969. }
  20970. } else if (s.match_available) {
  20971. /* If there was no match at the previous position, output a
  20972. * single literal. If there was a match but the current match
  20973. * is longer, truncate the previous match to a single literal.
  20974. */
  20975. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  20976. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  20977. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  20978. if (bflush) {
  20979. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  20980. flush_block_only(s, false);
  20981. /***/
  20982. }
  20983. s.strstart++;
  20984. s.lookahead--;
  20985. if (s.strm.avail_out === 0) {
  20986. return BS_NEED_MORE;
  20987. }
  20988. } else {
  20989. /* There is no previous match to compare with, wait for
  20990. * the next step to decide.
  20991. */
  20992. s.match_available = 1;
  20993. s.strstart++;
  20994. s.lookahead--;
  20995. }
  20996. }
  20997. //Assert (flush != Z_NO_FLUSH, "no flush?");
  20998. if (s.match_available) {
  20999. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  21000. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  21001. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  21002. s.match_available = 0;
  21003. }
  21004. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  21005. if (flush === Z_FINISH) {
  21006. /*** FLUSH_BLOCK(s, 1); ***/
  21007. flush_block_only(s, true);
  21008. if (s.strm.avail_out === 0) {
  21009. return BS_FINISH_STARTED;
  21010. }
  21011. /***/
  21012. return BS_FINISH_DONE;
  21013. }
  21014. if (s.last_lit) {
  21015. /*** FLUSH_BLOCK(s, 0); ***/
  21016. flush_block_only(s, false);
  21017. if (s.strm.avail_out === 0) {
  21018. return BS_NEED_MORE;
  21019. }
  21020. /***/
  21021. }
  21022. return BS_BLOCK_DONE;
  21023. }
  21024. /* ===========================================================================
  21025. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  21026. * one. Do not maintain a hash table. (It will be regenerated if this run of
  21027. * deflate switches away from Z_RLE.)
  21028. */
  21029. function deflate_rle(s, flush) {
  21030. var bflush; /* set if current block must be flushed */
  21031. var prev; /* byte at distance one to match */
  21032. var scan, strend; /* scan goes up to strend for length of run */
  21033. var _win = s.window;
  21034. for (;;) {
  21035. /* Make sure that we always have enough lookahead, except
  21036. * at the end of the input file. We need MAX_MATCH bytes
  21037. * for the longest run, plus one for the unrolled loop.
  21038. */
  21039. if (s.lookahead <= MAX_MATCH) {
  21040. fill_window(s);
  21041. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  21042. return BS_NEED_MORE;
  21043. }
  21044. if (s.lookahead === 0) { break; } /* flush the current block */
  21045. }
  21046. /* See how many times the previous byte repeats */
  21047. s.match_length = 0;
  21048. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  21049. scan = s.strstart - 1;
  21050. prev = _win[scan];
  21051. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  21052. strend = s.strstart + MAX_MATCH;
  21053. do {
  21054. /*jshint noempty:false*/
  21055. } while (prev === _win[++scan] && prev === _win[++scan] &&
  21056. prev === _win[++scan] && prev === _win[++scan] &&
  21057. prev === _win[++scan] && prev === _win[++scan] &&
  21058. prev === _win[++scan] && prev === _win[++scan] &&
  21059. scan < strend);
  21060. s.match_length = MAX_MATCH - (strend - scan);
  21061. if (s.match_length > s.lookahead) {
  21062. s.match_length = s.lookahead;
  21063. }
  21064. }
  21065. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  21066. }
  21067. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  21068. if (s.match_length >= MIN_MATCH) {
  21069. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  21070. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  21071. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  21072. s.lookahead -= s.match_length;
  21073. s.strstart += s.match_length;
  21074. s.match_length = 0;
  21075. } else {
  21076. /* No match, output a literal byte */
  21077. //Tracevv((stderr,"%c", s->window[s->strstart]));
  21078. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21079. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21080. s.lookahead--;
  21081. s.strstart++;
  21082. }
  21083. if (bflush) {
  21084. /*** FLUSH_BLOCK(s, 0); ***/
  21085. flush_block_only(s, false);
  21086. if (s.strm.avail_out === 0) {
  21087. return BS_NEED_MORE;
  21088. }
  21089. /***/
  21090. }
  21091. }
  21092. s.insert = 0;
  21093. if (flush === Z_FINISH) {
  21094. /*** FLUSH_BLOCK(s, 1); ***/
  21095. flush_block_only(s, true);
  21096. if (s.strm.avail_out === 0) {
  21097. return BS_FINISH_STARTED;
  21098. }
  21099. /***/
  21100. return BS_FINISH_DONE;
  21101. }
  21102. if (s.last_lit) {
  21103. /*** FLUSH_BLOCK(s, 0); ***/
  21104. flush_block_only(s, false);
  21105. if (s.strm.avail_out === 0) {
  21106. return BS_NEED_MORE;
  21107. }
  21108. /***/
  21109. }
  21110. return BS_BLOCK_DONE;
  21111. }
  21112. /* ===========================================================================
  21113. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  21114. * (It will be regenerated if this run of deflate switches away from Huffman.)
  21115. */
  21116. function deflate_huff(s, flush) {
  21117. var bflush; /* set if current block must be flushed */
  21118. for (;;) {
  21119. /* Make sure that we have a literal to write. */
  21120. if (s.lookahead === 0) {
  21121. fill_window(s);
  21122. if (s.lookahead === 0) {
  21123. if (flush === Z_NO_FLUSH) {
  21124. return BS_NEED_MORE;
  21125. }
  21126. break; /* flush the current block */
  21127. }
  21128. }
  21129. /* Output a literal byte */
  21130. s.match_length = 0;
  21131. //Tracevv((stderr,"%c", s->window[s->strstart]));
  21132. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21133. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21134. s.lookahead--;
  21135. s.strstart++;
  21136. if (bflush) {
  21137. /*** FLUSH_BLOCK(s, 0); ***/
  21138. flush_block_only(s, false);
  21139. if (s.strm.avail_out === 0) {
  21140. return BS_NEED_MORE;
  21141. }
  21142. /***/
  21143. }
  21144. }
  21145. s.insert = 0;
  21146. if (flush === Z_FINISH) {
  21147. /*** FLUSH_BLOCK(s, 1); ***/
  21148. flush_block_only(s, true);
  21149. if (s.strm.avail_out === 0) {
  21150. return BS_FINISH_STARTED;
  21151. }
  21152. /***/
  21153. return BS_FINISH_DONE;
  21154. }
  21155. if (s.last_lit) {
  21156. /*** FLUSH_BLOCK(s, 0); ***/
  21157. flush_block_only(s, false);
  21158. if (s.strm.avail_out === 0) {
  21159. return BS_NEED_MORE;
  21160. }
  21161. /***/
  21162. }
  21163. return BS_BLOCK_DONE;
  21164. }
  21165. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  21166. * the desired pack level (0..9). The values given below have been tuned to
  21167. * exclude worst case performance for pathological files. Better values may be
  21168. * found for specific files.
  21169. */
  21170. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  21171. this.good_length = good_length;
  21172. this.max_lazy = max_lazy;
  21173. this.nice_length = nice_length;
  21174. this.max_chain = max_chain;
  21175. this.func = func;
  21176. };
  21177. var configuration_table;
  21178. configuration_table = [
  21179. /* good lazy nice chain */
  21180. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  21181. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  21182. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  21183. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  21184. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  21185. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  21186. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  21187. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  21188. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  21189. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  21190. ];
  21191. /* ===========================================================================
  21192. * Initialize the "longest match" routines for a new zlib stream
  21193. */
  21194. function lm_init(s) {
  21195. s.window_size = 2 * s.w_size;
  21196. /*** CLEAR_HASH(s); ***/
  21197. zero(s.head); // Fill with NIL (= 0);
  21198. /* Set the default configuration parameters:
  21199. */
  21200. s.max_lazy_match = configuration_table[s.level].max_lazy;
  21201. s.good_match = configuration_table[s.level].good_length;
  21202. s.nice_match = configuration_table[s.level].nice_length;
  21203. s.max_chain_length = configuration_table[s.level].max_chain;
  21204. s.strstart = 0;
  21205. s.block_start = 0;
  21206. s.lookahead = 0;
  21207. s.insert = 0;
  21208. s.match_length = s.prev_length = MIN_MATCH - 1;
  21209. s.match_available = 0;
  21210. s.ins_h = 0;
  21211. }
  21212. function DeflateState() {
  21213. this.strm = null; /* pointer back to this zlib stream */
  21214. this.status = 0; /* as the name implies */
  21215. this.pending_buf = null; /* output still pending */
  21216. this.pending_buf_size = 0; /* size of pending_buf */
  21217. this.pending_out = 0; /* next pending byte to output to the stream */
  21218. this.pending = 0; /* nb of bytes in the pending buffer */
  21219. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  21220. this.gzhead = null; /* gzip header information to write */
  21221. this.gzindex = 0; /* where in extra, name, or comment */
  21222. this.method = Z_DEFLATED; /* can only be DEFLATED */
  21223. this.last_flush = -1; /* value of flush param for previous deflate call */
  21224. this.w_size = 0; /* LZ77 window size (32K by default) */
  21225. this.w_bits = 0; /* log2(w_size) (8..16) */
  21226. this.w_mask = 0; /* w_size - 1 */
  21227. this.window = null;
  21228. /* Sliding window. Input bytes are read into the second half of the window,
  21229. * and move to the first half later to keep a dictionary of at least wSize
  21230. * bytes. With this organization, matches are limited to a distance of
  21231. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  21232. * performed with a length multiple of the block size.
  21233. */
  21234. this.window_size = 0;
  21235. /* Actual size of window: 2*wSize, except when the user input buffer
  21236. * is directly used as sliding window.
  21237. */
  21238. this.prev = null;
  21239. /* Link to older string with same hash index. To limit the size of this
  21240. * array to 64K, this link is maintained only for the last 32K strings.
  21241. * An index in this array is thus a window index modulo 32K.
  21242. */
  21243. this.head = null; /* Heads of the hash chains or NIL. */
  21244. this.ins_h = 0; /* hash index of string to be inserted */
  21245. this.hash_size = 0; /* number of elements in hash table */
  21246. this.hash_bits = 0; /* log2(hash_size) */
  21247. this.hash_mask = 0; /* hash_size-1 */
  21248. this.hash_shift = 0;
  21249. /* Number of bits by which ins_h must be shifted at each input
  21250. * step. It must be such that after MIN_MATCH steps, the oldest
  21251. * byte no longer takes part in the hash key, that is:
  21252. * hash_shift * MIN_MATCH >= hash_bits
  21253. */
  21254. this.block_start = 0;
  21255. /* Window position at the beginning of the current output block. Gets
  21256. * negative when the window is moved backwards.
  21257. */
  21258. this.match_length = 0; /* length of best match */
  21259. this.prev_match = 0; /* previous match */
  21260. this.match_available = 0; /* set if previous match exists */
  21261. this.strstart = 0; /* start of string to insert */
  21262. this.match_start = 0; /* start of matching string */
  21263. this.lookahead = 0; /* number of valid bytes ahead in window */
  21264. this.prev_length = 0;
  21265. /* Length of the best match at previous step. Matches not greater than this
  21266. * are discarded. This is used in the lazy match evaluation.
  21267. */
  21268. this.max_chain_length = 0;
  21269. /* To speed up deflation, hash chains are never searched beyond this
  21270. * length. A higher limit improves compression ratio but degrades the
  21271. * speed.
  21272. */
  21273. this.max_lazy_match = 0;
  21274. /* Attempt to find a better match only when the current match is strictly
  21275. * smaller than this value. This mechanism is used only for compression
  21276. * levels >= 4.
  21277. */
  21278. // That's alias to max_lazy_match, don't use directly
  21279. //this.max_insert_length = 0;
  21280. /* Insert new strings in the hash table only if the match length is not
  21281. * greater than this length. This saves time but degrades compression.
  21282. * max_insert_length is used only for compression levels <= 3.
  21283. */
  21284. this.level = 0; /* compression level (1..9) */
  21285. this.strategy = 0; /* favor or force Huffman coding*/
  21286. this.good_match = 0;
  21287. /* Use a faster search when the previous match is longer than this */
  21288. this.nice_match = 0; /* Stop searching when current match exceeds this */
  21289. /* used by trees.c: */
  21290. /* Didn't use ct_data typedef below to suppress compiler warning */
  21291. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  21292. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  21293. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  21294. // Use flat array of DOUBLE size, with interleaved fata,
  21295. // because JS does not support effective
  21296. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  21297. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  21298. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  21299. zero(this.dyn_ltree);
  21300. zero(this.dyn_dtree);
  21301. zero(this.bl_tree);
  21302. this.l_desc = null; /* desc. for literal tree */
  21303. this.d_desc = null; /* desc. for distance tree */
  21304. this.bl_desc = null; /* desc. for bit length tree */
  21305. //ush bl_count[MAX_BITS+1];
  21306. this.bl_count = new utils.Buf16(MAX_BITS+1);
  21307. /* number of codes at each bit length for an optimal tree */
  21308. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  21309. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  21310. zero(this.heap);
  21311. this.heap_len = 0; /* number of elements in the heap */
  21312. this.heap_max = 0; /* element of largest frequency */
  21313. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  21314. * The same heap array is used to build all trees.
  21315. */
  21316. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  21317. zero(this.depth);
  21318. /* Depth of each subtree used as tie breaker for trees of equal frequency
  21319. */
  21320. this.l_buf = 0; /* buffer index for literals or lengths */
  21321. this.lit_bufsize = 0;
  21322. /* Size of match buffer for literals/lengths. There are 4 reasons for
  21323. * limiting lit_bufsize to 64K:
  21324. * - frequencies can be kept in 16 bit counters
  21325. * - if compression is not successful for the first block, all input
  21326. * data is still in the window so we can still emit a stored block even
  21327. * when input comes from standard input. (This can also be done for
  21328. * all blocks if lit_bufsize is not greater than 32K.)
  21329. * - if compression is not successful for a file smaller than 64K, we can
  21330. * even emit a stored file instead of a stored block (saving 5 bytes).
  21331. * This is applicable only for zip (not gzip or zlib).
  21332. * - creating new Huffman trees less frequently may not provide fast
  21333. * adaptation to changes in the input data statistics. (Take for
  21334. * example a binary file with poorly compressible code followed by
  21335. * a highly compressible string table.) Smaller buffer sizes give
  21336. * fast adaptation but have of course the overhead of transmitting
  21337. * trees more frequently.
  21338. * - I can't count above 4
  21339. */
  21340. this.last_lit = 0; /* running index in l_buf */
  21341. this.d_buf = 0;
  21342. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  21343. * the same number of elements. To use different lengths, an extra flag
  21344. * array would be necessary.
  21345. */
  21346. this.opt_len = 0; /* bit length of current block with optimal trees */
  21347. this.static_len = 0; /* bit length of current block with static trees */
  21348. this.matches = 0; /* number of string matches in current block */
  21349. this.insert = 0; /* bytes at end of window left to insert */
  21350. this.bi_buf = 0;
  21351. /* Output buffer. bits are inserted starting at the bottom (least
  21352. * significant bits).
  21353. */
  21354. this.bi_valid = 0;
  21355. /* Number of valid bits in bi_buf. All bits above the last valid bit
  21356. * are always zero.
  21357. */
  21358. // Used for window memory init. We safely ignore it for JS. That makes
  21359. // sense only for pointers and memory check tools.
  21360. //this.high_water = 0;
  21361. /* High water mark offset in window for initialized bytes -- bytes above
  21362. * this are set to zero in order to avoid memory check warnings when
  21363. * longest match routines access bytes past the input. This is then
  21364. * updated to the new high water mark.
  21365. */
  21366. }
  21367. function deflateResetKeep(strm) {
  21368. var s;
  21369. if (!strm || !strm.state) {
  21370. return err(strm, Z_STREAM_ERROR);
  21371. }
  21372. strm.total_in = strm.total_out = 0;
  21373. strm.data_type = Z_UNKNOWN;
  21374. s = strm.state;
  21375. s.pending = 0;
  21376. s.pending_out = 0;
  21377. if (s.wrap < 0) {
  21378. s.wrap = -s.wrap;
  21379. /* was made negative by deflate(..., Z_FINISH); */
  21380. }
  21381. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  21382. strm.adler = (s.wrap === 2) ?
  21383. 0 // crc32(0, Z_NULL, 0)
  21384. :
  21385. 1; // adler32(0, Z_NULL, 0)
  21386. s.last_flush = Z_NO_FLUSH;
  21387. trees._tr_init(s);
  21388. return Z_OK;
  21389. }
  21390. function deflateReset(strm) {
  21391. var ret = deflateResetKeep(strm);
  21392. if (ret === Z_OK) {
  21393. lm_init(strm.state);
  21394. }
  21395. return ret;
  21396. }
  21397. function deflateSetHeader(strm, head) {
  21398. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21399. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  21400. strm.state.gzhead = head;
  21401. return Z_OK;
  21402. }
  21403. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  21404. if (!strm) { // === Z_NULL
  21405. return Z_STREAM_ERROR;
  21406. }
  21407. var wrap = 1;
  21408. if (level === Z_DEFAULT_COMPRESSION) {
  21409. level = 6;
  21410. }
  21411. if (windowBits < 0) { /* suppress zlib wrapper */
  21412. wrap = 0;
  21413. windowBits = -windowBits;
  21414. }
  21415. else if (windowBits > 15) {
  21416. wrap = 2; /* write gzip wrapper instead */
  21417. windowBits -= 16;
  21418. }
  21419. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  21420. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  21421. strategy < 0 || strategy > Z_FIXED) {
  21422. return err(strm, Z_STREAM_ERROR);
  21423. }
  21424. if (windowBits === 8) {
  21425. windowBits = 9;
  21426. }
  21427. /* until 256-byte window bug fixed */
  21428. var s = new DeflateState();
  21429. strm.state = s;
  21430. s.strm = strm;
  21431. s.wrap = wrap;
  21432. s.gzhead = null;
  21433. s.w_bits = windowBits;
  21434. s.w_size = 1 << s.w_bits;
  21435. s.w_mask = s.w_size - 1;
  21436. s.hash_bits = memLevel + 7;
  21437. s.hash_size = 1 << s.hash_bits;
  21438. s.hash_mask = s.hash_size - 1;
  21439. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  21440. s.window = new utils.Buf8(s.w_size * 2);
  21441. s.head = new utils.Buf16(s.hash_size);
  21442. s.prev = new utils.Buf16(s.w_size);
  21443. // Don't need mem init magic for JS.
  21444. //s.high_water = 0; /* nothing written to s->window yet */
  21445. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  21446. s.pending_buf_size = s.lit_bufsize * 4;
  21447. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  21448. s.d_buf = s.lit_bufsize >> 1;
  21449. s.l_buf = (1 + 2) * s.lit_bufsize;
  21450. s.level = level;
  21451. s.strategy = strategy;
  21452. s.method = method;
  21453. return deflateReset(strm);
  21454. }
  21455. function deflateInit(strm, level) {
  21456. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  21457. }
  21458. function deflate(strm, flush) {
  21459. var old_flush, s;
  21460. var beg, val; // for gzip header write only
  21461. if (!strm || !strm.state ||
  21462. flush > Z_BLOCK || flush < 0) {
  21463. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  21464. }
  21465. s = strm.state;
  21466. if (!strm.output ||
  21467. (!strm.input && strm.avail_in !== 0) ||
  21468. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  21469. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  21470. }
  21471. s.strm = strm; /* just in case */
  21472. old_flush = s.last_flush;
  21473. s.last_flush = flush;
  21474. /* Write the header */
  21475. if (s.status === INIT_STATE) {
  21476. if (s.wrap === 2) { // GZIP header
  21477. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  21478. put_byte(s, 31);
  21479. put_byte(s, 139);
  21480. put_byte(s, 8);
  21481. if (!s.gzhead) { // s->gzhead == Z_NULL
  21482. put_byte(s, 0);
  21483. put_byte(s, 0);
  21484. put_byte(s, 0);
  21485. put_byte(s, 0);
  21486. put_byte(s, 0);
  21487. put_byte(s, s.level === 9 ? 2 :
  21488. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  21489. 4 : 0));
  21490. put_byte(s, OS_CODE);
  21491. s.status = BUSY_STATE;
  21492. }
  21493. else {
  21494. put_byte(s, (s.gzhead.text ? 1 : 0) +
  21495. (s.gzhead.hcrc ? 2 : 0) +
  21496. (!s.gzhead.extra ? 0 : 4) +
  21497. (!s.gzhead.name ? 0 : 8) +
  21498. (!s.gzhead.comment ? 0 : 16)
  21499. );
  21500. put_byte(s, s.gzhead.time & 0xff);
  21501. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  21502. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  21503. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  21504. put_byte(s, s.level === 9 ? 2 :
  21505. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  21506. 4 : 0));
  21507. put_byte(s, s.gzhead.os & 0xff);
  21508. if (s.gzhead.extra && s.gzhead.extra.length) {
  21509. put_byte(s, s.gzhead.extra.length & 0xff);
  21510. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  21511. }
  21512. if (s.gzhead.hcrc) {
  21513. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  21514. }
  21515. s.gzindex = 0;
  21516. s.status = EXTRA_STATE;
  21517. }
  21518. }
  21519. else // DEFLATE header
  21520. {
  21521. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  21522. var level_flags = -1;
  21523. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  21524. level_flags = 0;
  21525. } else if (s.level < 6) {
  21526. level_flags = 1;
  21527. } else if (s.level === 6) {
  21528. level_flags = 2;
  21529. } else {
  21530. level_flags = 3;
  21531. }
  21532. header |= (level_flags << 6);
  21533. if (s.strstart !== 0) { header |= PRESET_DICT; }
  21534. header += 31 - (header % 31);
  21535. s.status = BUSY_STATE;
  21536. putShortMSB(s, header);
  21537. /* Save the adler32 of the preset dictionary: */
  21538. if (s.strstart !== 0) {
  21539. putShortMSB(s, strm.adler >>> 16);
  21540. putShortMSB(s, strm.adler & 0xffff);
  21541. }
  21542. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  21543. }
  21544. }
  21545. //#ifdef GZIP
  21546. if (s.status === EXTRA_STATE) {
  21547. if (s.gzhead.extra/* != Z_NULL*/) {
  21548. beg = s.pending; /* start of bytes to update crc */
  21549. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  21550. if (s.pending === s.pending_buf_size) {
  21551. if (s.gzhead.hcrc && s.pending > beg) {
  21552. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21553. }
  21554. flush_pending(strm);
  21555. beg = s.pending;
  21556. if (s.pending === s.pending_buf_size) {
  21557. break;
  21558. }
  21559. }
  21560. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  21561. s.gzindex++;
  21562. }
  21563. if (s.gzhead.hcrc && s.pending > beg) {
  21564. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21565. }
  21566. if (s.gzindex === s.gzhead.extra.length) {
  21567. s.gzindex = 0;
  21568. s.status = NAME_STATE;
  21569. }
  21570. }
  21571. else {
  21572. s.status = NAME_STATE;
  21573. }
  21574. }
  21575. if (s.status === NAME_STATE) {
  21576. if (s.gzhead.name/* != Z_NULL*/) {
  21577. beg = s.pending; /* start of bytes to update crc */
  21578. //int val;
  21579. do {
  21580. if (s.pending === s.pending_buf_size) {
  21581. if (s.gzhead.hcrc && s.pending > beg) {
  21582. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21583. }
  21584. flush_pending(strm);
  21585. beg = s.pending;
  21586. if (s.pending === s.pending_buf_size) {
  21587. val = 1;
  21588. break;
  21589. }
  21590. }
  21591. // JS specific: little magic to add zero terminator to end of string
  21592. if (s.gzindex < s.gzhead.name.length) {
  21593. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  21594. } else {
  21595. val = 0;
  21596. }
  21597. put_byte(s, val);
  21598. } while (val !== 0);
  21599. if (s.gzhead.hcrc && s.pending > beg) {
  21600. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21601. }
  21602. if (val === 0) {
  21603. s.gzindex = 0;
  21604. s.status = COMMENT_STATE;
  21605. }
  21606. }
  21607. else {
  21608. s.status = COMMENT_STATE;
  21609. }
  21610. }
  21611. if (s.status === COMMENT_STATE) {
  21612. if (s.gzhead.comment/* != Z_NULL*/) {
  21613. beg = s.pending; /* start of bytes to update crc */
  21614. //int val;
  21615. do {
  21616. if (s.pending === s.pending_buf_size) {
  21617. if (s.gzhead.hcrc && s.pending > beg) {
  21618. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21619. }
  21620. flush_pending(strm);
  21621. beg = s.pending;
  21622. if (s.pending === s.pending_buf_size) {
  21623. val = 1;
  21624. break;
  21625. }
  21626. }
  21627. // JS specific: little magic to add zero terminator to end of string
  21628. if (s.gzindex < s.gzhead.comment.length) {
  21629. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  21630. } else {
  21631. val = 0;
  21632. }
  21633. put_byte(s, val);
  21634. } while (val !== 0);
  21635. if (s.gzhead.hcrc && s.pending > beg) {
  21636. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21637. }
  21638. if (val === 0) {
  21639. s.status = HCRC_STATE;
  21640. }
  21641. }
  21642. else {
  21643. s.status = HCRC_STATE;
  21644. }
  21645. }
  21646. if (s.status === HCRC_STATE) {
  21647. if (s.gzhead.hcrc) {
  21648. if (s.pending + 2 > s.pending_buf_size) {
  21649. flush_pending(strm);
  21650. }
  21651. if (s.pending + 2 <= s.pending_buf_size) {
  21652. put_byte(s, strm.adler & 0xff);
  21653. put_byte(s, (strm.adler >> 8) & 0xff);
  21654. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  21655. s.status = BUSY_STATE;
  21656. }
  21657. }
  21658. else {
  21659. s.status = BUSY_STATE;
  21660. }
  21661. }
  21662. //#endif
  21663. /* Flush as much pending output as possible */
  21664. if (s.pending !== 0) {
  21665. flush_pending(strm);
  21666. if (strm.avail_out === 0) {
  21667. /* Since avail_out is 0, deflate will be called again with
  21668. * more output space, but possibly with both pending and
  21669. * avail_in equal to zero. There won't be anything to do,
  21670. * but this is not an error situation so make sure we
  21671. * return OK instead of BUF_ERROR at next call of deflate:
  21672. */
  21673. s.last_flush = -1;
  21674. return Z_OK;
  21675. }
  21676. /* Make sure there is something to do and avoid duplicate consecutive
  21677. * flushes. For repeated and useless calls with Z_FINISH, we keep
  21678. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  21679. */
  21680. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  21681. flush !== Z_FINISH) {
  21682. return err(strm, Z_BUF_ERROR);
  21683. }
  21684. /* User must not provide more input after the first FINISH: */
  21685. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  21686. return err(strm, Z_BUF_ERROR);
  21687. }
  21688. /* Start a new block or continue the current one.
  21689. */
  21690. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  21691. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  21692. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  21693. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  21694. configuration_table[s.level].func(s, flush));
  21695. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  21696. s.status = FINISH_STATE;
  21697. }
  21698. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  21699. if (strm.avail_out === 0) {
  21700. s.last_flush = -1;
  21701. /* avoid BUF_ERROR next call, see above */
  21702. }
  21703. return Z_OK;
  21704. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  21705. * of deflate should use the same flush parameter to make sure
  21706. * that the flush is complete. So we don't have to output an
  21707. * empty block here, this will be done at next call. This also
  21708. * ensures that for a very small output buffer, we emit at most
  21709. * one empty block.
  21710. */
  21711. }
  21712. if (bstate === BS_BLOCK_DONE) {
  21713. if (flush === Z_PARTIAL_FLUSH) {
  21714. trees._tr_align(s);
  21715. }
  21716. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  21717. trees._tr_stored_block(s, 0, 0, false);
  21718. /* For a full flush, this empty block will be recognized
  21719. * as a special marker by inflate_sync().
  21720. */
  21721. if (flush === Z_FULL_FLUSH) {
  21722. /*** CLEAR_HASH(s); ***/ /* forget history */
  21723. zero(s.head); // Fill with NIL (= 0);
  21724. if (s.lookahead === 0) {
  21725. s.strstart = 0;
  21726. s.block_start = 0;
  21727. s.insert = 0;
  21728. }
  21729. }
  21730. }
  21731. flush_pending(strm);
  21732. if (strm.avail_out === 0) {
  21733. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  21734. return Z_OK;
  21735. }
  21736. }
  21737. }
  21738. //Assert(strm->avail_out > 0, "bug2");
  21739. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  21740. if (flush !== Z_FINISH) { return Z_OK; }
  21741. if (s.wrap <= 0) { return Z_STREAM_END; }
  21742. /* Write the trailer */
  21743. if (s.wrap === 2) {
  21744. put_byte(s, strm.adler & 0xff);
  21745. put_byte(s, (strm.adler >> 8) & 0xff);
  21746. put_byte(s, (strm.adler >> 16) & 0xff);
  21747. put_byte(s, (strm.adler >> 24) & 0xff);
  21748. put_byte(s, strm.total_in & 0xff);
  21749. put_byte(s, (strm.total_in >> 8) & 0xff);
  21750. put_byte(s, (strm.total_in >> 16) & 0xff);
  21751. put_byte(s, (strm.total_in >> 24) & 0xff);
  21752. }
  21753. else
  21754. {
  21755. putShortMSB(s, strm.adler >>> 16);
  21756. putShortMSB(s, strm.adler & 0xffff);
  21757. }
  21758. flush_pending(strm);
  21759. /* If avail_out is zero, the application will call deflate again
  21760. * to flush the rest.
  21761. */
  21762. if (s.wrap > 0) { s.wrap = -s.wrap; }
  21763. /* write the trailer only once! */
  21764. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  21765. }
  21766. function deflateEnd(strm) {
  21767. var status;
  21768. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  21769. return Z_STREAM_ERROR;
  21770. }
  21771. status = strm.state.status;
  21772. if (status !== INIT_STATE &&
  21773. status !== EXTRA_STATE &&
  21774. status !== NAME_STATE &&
  21775. status !== COMMENT_STATE &&
  21776. status !== HCRC_STATE &&
  21777. status !== BUSY_STATE &&
  21778. status !== FINISH_STATE
  21779. ) {
  21780. return err(strm, Z_STREAM_ERROR);
  21781. }
  21782. strm.state = null;
  21783. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  21784. }
  21785. /* =========================================================================
  21786. * Copy the source state to the destination state
  21787. */
  21788. //function deflateCopy(dest, source) {
  21789. //
  21790. //}
  21791. exports.deflateInit = deflateInit;
  21792. exports.deflateInit2 = deflateInit2;
  21793. exports.deflateReset = deflateReset;
  21794. exports.deflateResetKeep = deflateResetKeep;
  21795. exports.deflateSetHeader = deflateSetHeader;
  21796. exports.deflate = deflate;
  21797. exports.deflateEnd = deflateEnd;
  21798. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  21799. /* Not implemented
  21800. exports.deflateBound = deflateBound;
  21801. exports.deflateCopy = deflateCopy;
  21802. exports.deflateSetDictionary = deflateSetDictionary;
  21803. exports.deflateParams = deflateParams;
  21804. exports.deflatePending = deflatePending;
  21805. exports.deflatePrime = deflatePrime;
  21806. exports.deflateTune = deflateTune;
  21807. */
  21808. },{"../utils/common":72,"./adler32":74,"./crc32":76,"./messages":82,"./trees":83}],78:[function(require,module,exports){
  21809. 'use strict';
  21810. function GZheader() {
  21811. /* true if compressed data believed to be text */
  21812. this.text = 0;
  21813. /* modification time */
  21814. this.time = 0;
  21815. /* extra flags (not used when writing a gzip file) */
  21816. this.xflags = 0;
  21817. /* operating system */
  21818. this.os = 0;
  21819. /* pointer to extra field or Z_NULL if none */
  21820. this.extra = null;
  21821. /* extra field length (valid if extra != Z_NULL) */
  21822. this.extra_len = 0; // Actually, we don't need it in JS,
  21823. // but leave for few code modifications
  21824. //
  21825. // Setup limits is not necessary because in js we should not preallocate memory
  21826. // for inflate use constant limit in 65536 bytes
  21827. //
  21828. /* space at extra (only when reading header) */
  21829. // this.extra_max = 0;
  21830. /* pointer to zero-terminated file name or Z_NULL */
  21831. this.name = '';
  21832. /* space at name (only when reading header) */
  21833. // this.name_max = 0;
  21834. /* pointer to zero-terminated comment or Z_NULL */
  21835. this.comment = '';
  21836. /* space at comment (only when reading header) */
  21837. // this.comm_max = 0;
  21838. /* true if there was or will be a header crc */
  21839. this.hcrc = 0;
  21840. /* true when done reading gzip header (not used when writing a gzip file) */
  21841. this.done = false;
  21842. }
  21843. module.exports = GZheader;
  21844. },{}],79:[function(require,module,exports){
  21845. 'use strict';
  21846. // See state defs from inflate.js
  21847. var BAD = 30; /* got a data error -- remain here until reset */
  21848. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  21849. /*
  21850. Decode literal, length, and distance codes and write out the resulting
  21851. literal and match bytes until either not enough input or output is
  21852. available, an end-of-block is encountered, or a data error is encountered.
  21853. When large enough input and output buffers are supplied to inflate(), for
  21854. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  21855. inflate execution time is spent in this routine.
  21856. Entry assumptions:
  21857. state.mode === LEN
  21858. strm.avail_in >= 6
  21859. strm.avail_out >= 258
  21860. start >= strm.avail_out
  21861. state.bits < 8
  21862. On return, state.mode is one of:
  21863. LEN -- ran out of enough output space or enough available input
  21864. TYPE -- reached end of block code, inflate() to interpret next block
  21865. BAD -- error in block data
  21866. Notes:
  21867. - The maximum input bits used by a length/distance pair is 15 bits for the
  21868. length code, 5 bits for the length extra, 15 bits for the distance code,
  21869. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  21870. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  21871. checking for available input while decoding.
  21872. - The maximum bytes that a single length/distance pair can output is 258
  21873. bytes, which is the maximum length that can be coded. inflate_fast()
  21874. requires strm.avail_out >= 258 for each loop to avoid checking for
  21875. output space.
  21876. */
  21877. module.exports = function inflate_fast(strm, start) {
  21878. var state;
  21879. var _in; /* local strm.input */
  21880. var last; /* have enough input while in < last */
  21881. var _out; /* local strm.output */
  21882. var beg; /* inflate()'s initial strm.output */
  21883. var end; /* while out < end, enough space available */
  21884. //#ifdef INFLATE_STRICT
  21885. var dmax; /* maximum distance from zlib header */
  21886. //#endif
  21887. var wsize; /* window size or zero if not using window */
  21888. var whave; /* valid bytes in the window */
  21889. var wnext; /* window write index */
  21890. var window; /* allocated sliding window, if wsize != 0 */
  21891. var hold; /* local strm.hold */
  21892. var bits; /* local strm.bits */
  21893. var lcode; /* local strm.lencode */
  21894. var dcode; /* local strm.distcode */
  21895. var lmask; /* mask for first level of length codes */
  21896. var dmask; /* mask for first level of distance codes */
  21897. var here; /* retrieved table entry */
  21898. var op; /* code bits, operation, extra bits, or */
  21899. /* window position, window bytes to copy */
  21900. var len; /* match length, unused bytes */
  21901. var dist; /* match distance */
  21902. var from; /* where to copy match from */
  21903. var from_source;
  21904. var input, output; // JS specific, because we have no pointers
  21905. /* copy state to local variables */
  21906. state = strm.state;
  21907. //here = state.here;
  21908. _in = strm.next_in;
  21909. input = strm.input;
  21910. last = _in + (strm.avail_in - 5);
  21911. _out = strm.next_out;
  21912. output = strm.output;
  21913. beg = _out - (start - strm.avail_out);
  21914. end = _out + (strm.avail_out - 257);
  21915. //#ifdef INFLATE_STRICT
  21916. dmax = state.dmax;
  21917. //#endif
  21918. wsize = state.wsize;
  21919. whave = state.whave;
  21920. wnext = state.wnext;
  21921. window = state.window;
  21922. hold = state.hold;
  21923. bits = state.bits;
  21924. lcode = state.lencode;
  21925. dcode = state.distcode;
  21926. lmask = (1 << state.lenbits) - 1;
  21927. dmask = (1 << state.distbits) - 1;
  21928. /* decode literals and length/distances until end-of-block or not enough
  21929. input data or output space */
  21930. top:
  21931. do {
  21932. if (bits < 15) {
  21933. hold += input[_in++] << bits;
  21934. bits += 8;
  21935. hold += input[_in++] << bits;
  21936. bits += 8;
  21937. }
  21938. here = lcode[hold & lmask];
  21939. dolen:
  21940. for (;;) { // Goto emulation
  21941. op = here >>> 24/*here.bits*/;
  21942. hold >>>= op;
  21943. bits -= op;
  21944. op = (here >>> 16) & 0xff/*here.op*/;
  21945. if (op === 0) { /* literal */
  21946. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  21947. // "inflate: literal '%c'\n" :
  21948. // "inflate: literal 0x%02x\n", here.val));
  21949. output[_out++] = here & 0xffff/*here.val*/;
  21950. }
  21951. else if (op & 16) { /* length base */
  21952. len = here & 0xffff/*here.val*/;
  21953. op &= 15; /* number of extra bits */
  21954. if (op) {
  21955. if (bits < op) {
  21956. hold += input[_in++] << bits;
  21957. bits += 8;
  21958. }
  21959. len += hold & ((1 << op) - 1);
  21960. hold >>>= op;
  21961. bits -= op;
  21962. }
  21963. //Tracevv((stderr, "inflate: length %u\n", len));
  21964. if (bits < 15) {
  21965. hold += input[_in++] << bits;
  21966. bits += 8;
  21967. hold += input[_in++] << bits;
  21968. bits += 8;
  21969. }
  21970. here = dcode[hold & dmask];
  21971. dodist:
  21972. for (;;) { // goto emulation
  21973. op = here >>> 24/*here.bits*/;
  21974. hold >>>= op;
  21975. bits -= op;
  21976. op = (here >>> 16) & 0xff/*here.op*/;
  21977. if (op & 16) { /* distance base */
  21978. dist = here & 0xffff/*here.val*/;
  21979. op &= 15; /* number of extra bits */
  21980. if (bits < op) {
  21981. hold += input[_in++] << bits;
  21982. bits += 8;
  21983. if (bits < op) {
  21984. hold += input[_in++] << bits;
  21985. bits += 8;
  21986. }
  21987. }
  21988. dist += hold & ((1 << op) - 1);
  21989. //#ifdef INFLATE_STRICT
  21990. if (dist > dmax) {
  21991. strm.msg = 'invalid distance too far back';
  21992. state.mode = BAD;
  21993. break top;
  21994. }
  21995. //#endif
  21996. hold >>>= op;
  21997. bits -= op;
  21998. //Tracevv((stderr, "inflate: distance %u\n", dist));
  21999. op = _out - beg; /* max distance in output */
  22000. if (dist > op) { /* see if copy from window */
  22001. op = dist - op; /* distance back in window */
  22002. if (op > whave) {
  22003. if (state.sane) {
  22004. strm.msg = 'invalid distance too far back';
  22005. state.mode = BAD;
  22006. break top;
  22007. }
  22008. // (!) This block is disabled in zlib defailts,
  22009. // don't enable it for binary compatibility
  22010. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  22011. // if (len <= op - whave) {
  22012. // do {
  22013. // output[_out++] = 0;
  22014. // } while (--len);
  22015. // continue top;
  22016. // }
  22017. // len -= op - whave;
  22018. // do {
  22019. // output[_out++] = 0;
  22020. // } while (--op > whave);
  22021. // if (op === 0) {
  22022. // from = _out - dist;
  22023. // do {
  22024. // output[_out++] = output[from++];
  22025. // } while (--len);
  22026. // continue top;
  22027. // }
  22028. //#endif
  22029. }
  22030. from = 0; // window index
  22031. from_source = window;
  22032. if (wnext === 0) { /* very common case */
  22033. from += wsize - op;
  22034. if (op < len) { /* some from window */
  22035. len -= op;
  22036. do {
  22037. output[_out++] = window[from++];
  22038. } while (--op);
  22039. from = _out - dist; /* rest from output */
  22040. from_source = output;
  22041. }
  22042. }
  22043. else if (wnext < op) { /* wrap around window */
  22044. from += wsize + wnext - op;
  22045. op -= wnext;
  22046. if (op < len) { /* some from end of window */
  22047. len -= op;
  22048. do {
  22049. output[_out++] = window[from++];
  22050. } while (--op);
  22051. from = 0;
  22052. if (wnext < len) { /* some from start of window */
  22053. op = wnext;
  22054. len -= op;
  22055. do {
  22056. output[_out++] = window[from++];
  22057. } while (--op);
  22058. from = _out - dist; /* rest from output */
  22059. from_source = output;
  22060. }
  22061. }
  22062. }
  22063. else { /* contiguous in window */
  22064. from += wnext - op;
  22065. if (op < len) { /* some from window */
  22066. len -= op;
  22067. do {
  22068. output[_out++] = window[from++];
  22069. } while (--op);
  22070. from = _out - dist; /* rest from output */
  22071. from_source = output;
  22072. }
  22073. }
  22074. while (len > 2) {
  22075. output[_out++] = from_source[from++];
  22076. output[_out++] = from_source[from++];
  22077. output[_out++] = from_source[from++];
  22078. len -= 3;
  22079. }
  22080. if (len) {
  22081. output[_out++] = from_source[from++];
  22082. if (len > 1) {
  22083. output[_out++] = from_source[from++];
  22084. }
  22085. }
  22086. }
  22087. else {
  22088. from = _out - dist; /* copy direct from output */
  22089. do { /* minimum length is three */
  22090. output[_out++] = output[from++];
  22091. output[_out++] = output[from++];
  22092. output[_out++] = output[from++];
  22093. len -= 3;
  22094. } while (len > 2);
  22095. if (len) {
  22096. output[_out++] = output[from++];
  22097. if (len > 1) {
  22098. output[_out++] = output[from++];
  22099. }
  22100. }
  22101. }
  22102. }
  22103. else if ((op & 64) === 0) { /* 2nd level distance code */
  22104. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  22105. continue dodist;
  22106. }
  22107. else {
  22108. strm.msg = 'invalid distance code';
  22109. state.mode = BAD;
  22110. break top;
  22111. }
  22112. break; // need to emulate goto via "continue"
  22113. }
  22114. }
  22115. else if ((op & 64) === 0) { /* 2nd level length code */
  22116. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  22117. continue dolen;
  22118. }
  22119. else if (op & 32) { /* end-of-block */
  22120. //Tracevv((stderr, "inflate: end of block\n"));
  22121. state.mode = TYPE;
  22122. break top;
  22123. }
  22124. else {
  22125. strm.msg = 'invalid literal/length code';
  22126. state.mode = BAD;
  22127. break top;
  22128. }
  22129. break; // need to emulate goto via "continue"
  22130. }
  22131. } while (_in < last && _out < end);
  22132. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  22133. len = bits >> 3;
  22134. _in -= len;
  22135. bits -= len << 3;
  22136. hold &= (1 << bits) - 1;
  22137. /* update state and return */
  22138. strm.next_in = _in;
  22139. strm.next_out = _out;
  22140. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  22141. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  22142. state.hold = hold;
  22143. state.bits = bits;
  22144. return;
  22145. };
  22146. },{}],80:[function(require,module,exports){
  22147. 'use strict';
  22148. var utils = require('../utils/common');
  22149. var adler32 = require('./adler32');
  22150. var crc32 = require('./crc32');
  22151. var inflate_fast = require('./inffast');
  22152. var inflate_table = require('./inftrees');
  22153. var CODES = 0;
  22154. var LENS = 1;
  22155. var DISTS = 2;
  22156. /* Public constants ==========================================================*/
  22157. /* ===========================================================================*/
  22158. /* Allowed flush values; see deflate() and inflate() below for details */
  22159. //var Z_NO_FLUSH = 0;
  22160. //var Z_PARTIAL_FLUSH = 1;
  22161. //var Z_SYNC_FLUSH = 2;
  22162. //var Z_FULL_FLUSH = 3;
  22163. var Z_FINISH = 4;
  22164. var Z_BLOCK = 5;
  22165. var Z_TREES = 6;
  22166. /* Return codes for the compression/decompression functions. Negative values
  22167. * are errors, positive values are used for special but normal events.
  22168. */
  22169. var Z_OK = 0;
  22170. var Z_STREAM_END = 1;
  22171. var Z_NEED_DICT = 2;
  22172. //var Z_ERRNO = -1;
  22173. var Z_STREAM_ERROR = -2;
  22174. var Z_DATA_ERROR = -3;
  22175. var Z_MEM_ERROR = -4;
  22176. var Z_BUF_ERROR = -5;
  22177. //var Z_VERSION_ERROR = -6;
  22178. /* The deflate compression method */
  22179. var Z_DEFLATED = 8;
  22180. /* STATES ====================================================================*/
  22181. /* ===========================================================================*/
  22182. var HEAD = 1; /* i: waiting for magic header */
  22183. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  22184. var TIME = 3; /* i: waiting for modification time (gzip) */
  22185. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  22186. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  22187. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  22188. var NAME = 7; /* i: waiting for end of file name (gzip) */
  22189. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  22190. var HCRC = 9; /* i: waiting for header crc (gzip) */
  22191. var DICTID = 10; /* i: waiting for dictionary check value */
  22192. var DICT = 11; /* waiting for inflateSetDictionary() call */
  22193. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  22194. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  22195. var STORED = 14; /* i: waiting for stored size (length and complement) */
  22196. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  22197. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  22198. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  22199. var LENLENS = 18; /* i: waiting for code length code lengths */
  22200. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  22201. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  22202. var LEN = 21; /* i: waiting for length/lit/eob code */
  22203. var LENEXT = 22; /* i: waiting for length extra bits */
  22204. var DIST = 23; /* i: waiting for distance code */
  22205. var DISTEXT = 24; /* i: waiting for distance extra bits */
  22206. var MATCH = 25; /* o: waiting for output space to copy string */
  22207. var LIT = 26; /* o: waiting for output space to write literal */
  22208. var CHECK = 27; /* i: waiting for 32-bit check value */
  22209. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  22210. var DONE = 29; /* finished check, done -- remain here until reset */
  22211. var BAD = 30; /* got a data error -- remain here until reset */
  22212. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  22213. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  22214. /* ===========================================================================*/
  22215. var ENOUGH_LENS = 852;
  22216. var ENOUGH_DISTS = 592;
  22217. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  22218. var MAX_WBITS = 15;
  22219. /* 32K LZ77 window */
  22220. var DEF_WBITS = MAX_WBITS;
  22221. function ZSWAP32(q) {
  22222. return (((q >>> 24) & 0xff) +
  22223. ((q >>> 8) & 0xff00) +
  22224. ((q & 0xff00) << 8) +
  22225. ((q & 0xff) << 24));
  22226. }
  22227. function InflateState() {
  22228. this.mode = 0; /* current inflate mode */
  22229. this.last = false; /* true if processing last block */
  22230. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  22231. this.havedict = false; /* true if dictionary provided */
  22232. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  22233. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  22234. this.check = 0; /* protected copy of check value */
  22235. this.total = 0; /* protected copy of output count */
  22236. // TODO: may be {}
  22237. this.head = null; /* where to save gzip header information */
  22238. /* sliding window */
  22239. this.wbits = 0; /* log base 2 of requested window size */
  22240. this.wsize = 0; /* window size or zero if not using window */
  22241. this.whave = 0; /* valid bytes in the window */
  22242. this.wnext = 0; /* window write index */
  22243. this.window = null; /* allocated sliding window, if needed */
  22244. /* bit accumulator */
  22245. this.hold = 0; /* input bit accumulator */
  22246. this.bits = 0; /* number of bits in "in" */
  22247. /* for string and stored block copying */
  22248. this.length = 0; /* literal or length of data to copy */
  22249. this.offset = 0; /* distance back to copy string from */
  22250. /* for table and code decoding */
  22251. this.extra = 0; /* extra bits needed */
  22252. /* fixed and dynamic code tables */
  22253. this.lencode = null; /* starting table for length/literal codes */
  22254. this.distcode = null; /* starting table for distance codes */
  22255. this.lenbits = 0; /* index bits for lencode */
  22256. this.distbits = 0; /* index bits for distcode */
  22257. /* dynamic table building */
  22258. this.ncode = 0; /* number of code length code lengths */
  22259. this.nlen = 0; /* number of length code lengths */
  22260. this.ndist = 0; /* number of distance code lengths */
  22261. this.have = 0; /* number of code lengths in lens[] */
  22262. this.next = null; /* next available space in codes[] */
  22263. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  22264. this.work = new utils.Buf16(288); /* work area for code table building */
  22265. /*
  22266. because we don't have pointers in js, we use lencode and distcode directly
  22267. as buffers so we don't need codes
  22268. */
  22269. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  22270. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  22271. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  22272. this.sane = 0; /* if false, allow invalid distance too far */
  22273. this.back = 0; /* bits back of last unprocessed length/lit */
  22274. this.was = 0; /* initial length of match */
  22275. }
  22276. function inflateResetKeep(strm) {
  22277. var state;
  22278. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22279. state = strm.state;
  22280. strm.total_in = strm.total_out = state.total = 0;
  22281. strm.msg = ''; /*Z_NULL*/
  22282. if (state.wrap) { /* to support ill-conceived Java test suite */
  22283. strm.adler = state.wrap & 1;
  22284. }
  22285. state.mode = HEAD;
  22286. state.last = 0;
  22287. state.havedict = 0;
  22288. state.dmax = 32768;
  22289. state.head = null/*Z_NULL*/;
  22290. state.hold = 0;
  22291. state.bits = 0;
  22292. //state.lencode = state.distcode = state.next = state.codes;
  22293. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  22294. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  22295. state.sane = 1;
  22296. state.back = -1;
  22297. //Tracev((stderr, "inflate: reset\n"));
  22298. return Z_OK;
  22299. }
  22300. function inflateReset(strm) {
  22301. var state;
  22302. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22303. state = strm.state;
  22304. state.wsize = 0;
  22305. state.whave = 0;
  22306. state.wnext = 0;
  22307. return inflateResetKeep(strm);
  22308. }
  22309. function inflateReset2(strm, windowBits) {
  22310. var wrap;
  22311. var state;
  22312. /* get the state */
  22313. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22314. state = strm.state;
  22315. /* extract wrap request from windowBits parameter */
  22316. if (windowBits < 0) {
  22317. wrap = 0;
  22318. windowBits = -windowBits;
  22319. }
  22320. else {
  22321. wrap = (windowBits >> 4) + 1;
  22322. if (windowBits < 48) {
  22323. windowBits &= 15;
  22324. }
  22325. }
  22326. /* set number of window bits, free window if different */
  22327. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  22328. return Z_STREAM_ERROR;
  22329. }
  22330. if (state.window !== null && state.wbits !== windowBits) {
  22331. state.window = null;
  22332. }
  22333. /* update state and reset the rest of it */
  22334. state.wrap = wrap;
  22335. state.wbits = windowBits;
  22336. return inflateReset(strm);
  22337. }
  22338. function inflateInit2(strm, windowBits) {
  22339. var ret;
  22340. var state;
  22341. if (!strm) { return Z_STREAM_ERROR; }
  22342. //strm.msg = Z_NULL; /* in case we return an error */
  22343. state = new InflateState();
  22344. //if (state === Z_NULL) return Z_MEM_ERROR;
  22345. //Tracev((stderr, "inflate: allocated\n"));
  22346. strm.state = state;
  22347. state.window = null/*Z_NULL*/;
  22348. ret = inflateReset2(strm, windowBits);
  22349. if (ret !== Z_OK) {
  22350. strm.state = null/*Z_NULL*/;
  22351. }
  22352. return ret;
  22353. }
  22354. function inflateInit(strm) {
  22355. return inflateInit2(strm, DEF_WBITS);
  22356. }
  22357. /*
  22358. Return state with length and distance decoding tables and index sizes set to
  22359. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  22360. If BUILDFIXED is defined, then instead this routine builds the tables the
  22361. first time it's called, and returns those tables the first time and
  22362. thereafter. This reduces the size of the code by about 2K bytes, in
  22363. exchange for a little execution time. However, BUILDFIXED should not be
  22364. used for threaded applications, since the rewriting of the tables and virgin
  22365. may not be thread-safe.
  22366. */
  22367. var virgin = true;
  22368. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  22369. function fixedtables(state) {
  22370. /* build fixed huffman tables if first call (may not be thread safe) */
  22371. if (virgin) {
  22372. var sym;
  22373. lenfix = new utils.Buf32(512);
  22374. distfix = new utils.Buf32(32);
  22375. /* literal/length table */
  22376. sym = 0;
  22377. while (sym < 144) { state.lens[sym++] = 8; }
  22378. while (sym < 256) { state.lens[sym++] = 9; }
  22379. while (sym < 280) { state.lens[sym++] = 7; }
  22380. while (sym < 288) { state.lens[sym++] = 8; }
  22381. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  22382. /* distance table */
  22383. sym = 0;
  22384. while (sym < 32) { state.lens[sym++] = 5; }
  22385. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  22386. /* do this just once */
  22387. virgin = false;
  22388. }
  22389. state.lencode = lenfix;
  22390. state.lenbits = 9;
  22391. state.distcode = distfix;
  22392. state.distbits = 5;
  22393. }
  22394. /*
  22395. Update the window with the last wsize (normally 32K) bytes written before
  22396. returning. If window does not exist yet, create it. This is only called
  22397. when a window is already in use, or when output has been written during this
  22398. inflate call, but the end of the deflate stream has not been reached yet.
  22399. It is also called to create a window for dictionary data when a dictionary
  22400. is loaded.
  22401. Providing output buffers larger than 32K to inflate() should provide a speed
  22402. advantage, since only the last 32K of output is copied to the sliding window
  22403. upon return from inflate(), and since all distances after the first 32K of
  22404. output will fall in the output data, making match copies simpler and faster.
  22405. The advantage may be dependent on the size of the processor's data caches.
  22406. */
  22407. function updatewindow(strm, src, end, copy) {
  22408. var dist;
  22409. var state = strm.state;
  22410. /* if it hasn't been done already, allocate space for the window */
  22411. if (state.window === null) {
  22412. state.wsize = 1 << state.wbits;
  22413. state.wnext = 0;
  22414. state.whave = 0;
  22415. state.window = new utils.Buf8(state.wsize);
  22416. }
  22417. /* copy state->wsize or less output bytes into the circular window */
  22418. if (copy >= state.wsize) {
  22419. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  22420. state.wnext = 0;
  22421. state.whave = state.wsize;
  22422. }
  22423. else {
  22424. dist = state.wsize - state.wnext;
  22425. if (dist > copy) {
  22426. dist = copy;
  22427. }
  22428. //zmemcpy(state->window + state->wnext, end - copy, dist);
  22429. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  22430. copy -= dist;
  22431. if (copy) {
  22432. //zmemcpy(state->window, end - copy, copy);
  22433. utils.arraySet(state.window,src, end - copy, copy, 0);
  22434. state.wnext = copy;
  22435. state.whave = state.wsize;
  22436. }
  22437. else {
  22438. state.wnext += dist;
  22439. if (state.wnext === state.wsize) { state.wnext = 0; }
  22440. if (state.whave < state.wsize) { state.whave += dist; }
  22441. }
  22442. }
  22443. return 0;
  22444. }
  22445. function inflate(strm, flush) {
  22446. var state;
  22447. var input, output; // input/output buffers
  22448. var next; /* next input INDEX */
  22449. var put; /* next output INDEX */
  22450. var have, left; /* available input and output */
  22451. var hold; /* bit buffer */
  22452. var bits; /* bits in bit buffer */
  22453. var _in, _out; /* save starting available input and output */
  22454. var copy; /* number of stored or match bytes to copy */
  22455. var from; /* where to copy match bytes from */
  22456. var from_source;
  22457. var here = 0; /* current decoding table entry */
  22458. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  22459. //var last; /* parent table entry */
  22460. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  22461. var len; /* length to copy for repeats, bits to drop */
  22462. var ret; /* return code */
  22463. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  22464. var opts;
  22465. var n; // temporary var for NEED_BITS
  22466. var order = /* permutation of code lengths */
  22467. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  22468. if (!strm || !strm.state || !strm.output ||
  22469. (!strm.input && strm.avail_in !== 0)) {
  22470. return Z_STREAM_ERROR;
  22471. }
  22472. state = strm.state;
  22473. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  22474. //--- LOAD() ---
  22475. put = strm.next_out;
  22476. output = strm.output;
  22477. left = strm.avail_out;
  22478. next = strm.next_in;
  22479. input = strm.input;
  22480. have = strm.avail_in;
  22481. hold = state.hold;
  22482. bits = state.bits;
  22483. //---
  22484. _in = have;
  22485. _out = left;
  22486. ret = Z_OK;
  22487. inf_leave: // goto emulation
  22488. for (;;) {
  22489. switch (state.mode) {
  22490. case HEAD:
  22491. if (state.wrap === 0) {
  22492. state.mode = TYPEDO;
  22493. break;
  22494. }
  22495. //=== NEEDBITS(16);
  22496. while (bits < 16) {
  22497. if (have === 0) { break inf_leave; }
  22498. have--;
  22499. hold += input[next++] << bits;
  22500. bits += 8;
  22501. }
  22502. //===//
  22503. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  22504. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  22505. //=== CRC2(state.check, hold);
  22506. hbuf[0] = hold & 0xff;
  22507. hbuf[1] = (hold >>> 8) & 0xff;
  22508. state.check = crc32(state.check, hbuf, 2, 0);
  22509. //===//
  22510. //=== INITBITS();
  22511. hold = 0;
  22512. bits = 0;
  22513. //===//
  22514. state.mode = FLAGS;
  22515. break;
  22516. }
  22517. state.flags = 0; /* expect zlib header */
  22518. if (state.head) {
  22519. state.head.done = false;
  22520. }
  22521. if (!(state.wrap & 1) || /* check if zlib header allowed */
  22522. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  22523. strm.msg = 'incorrect header check';
  22524. state.mode = BAD;
  22525. break;
  22526. }
  22527. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  22528. strm.msg = 'unknown compression method';
  22529. state.mode = BAD;
  22530. break;
  22531. }
  22532. //--- DROPBITS(4) ---//
  22533. hold >>>= 4;
  22534. bits -= 4;
  22535. //---//
  22536. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  22537. if (state.wbits === 0) {
  22538. state.wbits = len;
  22539. }
  22540. else if (len > state.wbits) {
  22541. strm.msg = 'invalid window size';
  22542. state.mode = BAD;
  22543. break;
  22544. }
  22545. state.dmax = 1 << len;
  22546. //Tracev((stderr, "inflate: zlib header ok\n"));
  22547. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  22548. state.mode = hold & 0x200 ? DICTID : TYPE;
  22549. //=== INITBITS();
  22550. hold = 0;
  22551. bits = 0;
  22552. //===//
  22553. break;
  22554. case FLAGS:
  22555. //=== NEEDBITS(16); */
  22556. while (bits < 16) {
  22557. if (have === 0) { break inf_leave; }
  22558. have--;
  22559. hold += input[next++] << bits;
  22560. bits += 8;
  22561. }
  22562. //===//
  22563. state.flags = hold;
  22564. if ((state.flags & 0xff) !== Z_DEFLATED) {
  22565. strm.msg = 'unknown compression method';
  22566. state.mode = BAD;
  22567. break;
  22568. }
  22569. if (state.flags & 0xe000) {
  22570. strm.msg = 'unknown header flags set';
  22571. state.mode = BAD;
  22572. break;
  22573. }
  22574. if (state.head) {
  22575. state.head.text = ((hold >> 8) & 1);
  22576. }
  22577. if (state.flags & 0x0200) {
  22578. //=== CRC2(state.check, hold);
  22579. hbuf[0] = hold & 0xff;
  22580. hbuf[1] = (hold >>> 8) & 0xff;
  22581. state.check = crc32(state.check, hbuf, 2, 0);
  22582. //===//
  22583. }
  22584. //=== INITBITS();
  22585. hold = 0;
  22586. bits = 0;
  22587. //===//
  22588. state.mode = TIME;
  22589. /* falls through */
  22590. case TIME:
  22591. //=== NEEDBITS(32); */
  22592. while (bits < 32) {
  22593. if (have === 0) { break inf_leave; }
  22594. have--;
  22595. hold += input[next++] << bits;
  22596. bits += 8;
  22597. }
  22598. //===//
  22599. if (state.head) {
  22600. state.head.time = hold;
  22601. }
  22602. if (state.flags & 0x0200) {
  22603. //=== CRC4(state.check, hold)
  22604. hbuf[0] = hold & 0xff;
  22605. hbuf[1] = (hold >>> 8) & 0xff;
  22606. hbuf[2] = (hold >>> 16) & 0xff;
  22607. hbuf[3] = (hold >>> 24) & 0xff;
  22608. state.check = crc32(state.check, hbuf, 4, 0);
  22609. //===
  22610. }
  22611. //=== INITBITS();
  22612. hold = 0;
  22613. bits = 0;
  22614. //===//
  22615. state.mode = OS;
  22616. /* falls through */
  22617. case OS:
  22618. //=== NEEDBITS(16); */
  22619. while (bits < 16) {
  22620. if (have === 0) { break inf_leave; }
  22621. have--;
  22622. hold += input[next++] << bits;
  22623. bits += 8;
  22624. }
  22625. //===//
  22626. if (state.head) {
  22627. state.head.xflags = (hold & 0xff);
  22628. state.head.os = (hold >> 8);
  22629. }
  22630. if (state.flags & 0x0200) {
  22631. //=== CRC2(state.check, hold);
  22632. hbuf[0] = hold & 0xff;
  22633. hbuf[1] = (hold >>> 8) & 0xff;
  22634. state.check = crc32(state.check, hbuf, 2, 0);
  22635. //===//
  22636. }
  22637. //=== INITBITS();
  22638. hold = 0;
  22639. bits = 0;
  22640. //===//
  22641. state.mode = EXLEN;
  22642. /* falls through */
  22643. case EXLEN:
  22644. if (state.flags & 0x0400) {
  22645. //=== NEEDBITS(16); */
  22646. while (bits < 16) {
  22647. if (have === 0) { break inf_leave; }
  22648. have--;
  22649. hold += input[next++] << bits;
  22650. bits += 8;
  22651. }
  22652. //===//
  22653. state.length = hold;
  22654. if (state.head) {
  22655. state.head.extra_len = hold;
  22656. }
  22657. if (state.flags & 0x0200) {
  22658. //=== CRC2(state.check, hold);
  22659. hbuf[0] = hold & 0xff;
  22660. hbuf[1] = (hold >>> 8) & 0xff;
  22661. state.check = crc32(state.check, hbuf, 2, 0);
  22662. //===//
  22663. }
  22664. //=== INITBITS();
  22665. hold = 0;
  22666. bits = 0;
  22667. //===//
  22668. }
  22669. else if (state.head) {
  22670. state.head.extra = null/*Z_NULL*/;
  22671. }
  22672. state.mode = EXTRA;
  22673. /* falls through */
  22674. case EXTRA:
  22675. if (state.flags & 0x0400) {
  22676. copy = state.length;
  22677. if (copy > have) { copy = have; }
  22678. if (copy) {
  22679. if (state.head) {
  22680. len = state.head.extra_len - state.length;
  22681. if (!state.head.extra) {
  22682. // Use untyped array for more conveniend processing later
  22683. state.head.extra = new Array(state.head.extra_len);
  22684. }
  22685. utils.arraySet(
  22686. state.head.extra,
  22687. input,
  22688. next,
  22689. // extra field is limited to 65536 bytes
  22690. // - no need for additional size check
  22691. copy,
  22692. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  22693. len
  22694. );
  22695. //zmemcpy(state.head.extra + len, next,
  22696. // len + copy > state.head.extra_max ?
  22697. // state.head.extra_max - len : copy);
  22698. }
  22699. if (state.flags & 0x0200) {
  22700. state.check = crc32(state.check, input, copy, next);
  22701. }
  22702. have -= copy;
  22703. next += copy;
  22704. state.length -= copy;
  22705. }
  22706. if (state.length) { break inf_leave; }
  22707. }
  22708. state.length = 0;
  22709. state.mode = NAME;
  22710. /* falls through */
  22711. case NAME:
  22712. if (state.flags & 0x0800) {
  22713. if (have === 0) { break inf_leave; }
  22714. copy = 0;
  22715. do {
  22716. // TODO: 2 or 1 bytes?
  22717. len = input[next + copy++];
  22718. /* use constant limit because in js we should not preallocate memory */
  22719. if (state.head && len &&
  22720. (state.length < 65536 /*state.head.name_max*/)) {
  22721. state.head.name += String.fromCharCode(len);
  22722. }
  22723. } while (len && copy < have);
  22724. if (state.flags & 0x0200) {
  22725. state.check = crc32(state.check, input, copy, next);
  22726. }
  22727. have -= copy;
  22728. next += copy;
  22729. if (len) { break inf_leave; }
  22730. }
  22731. else if (state.head) {
  22732. state.head.name = null;
  22733. }
  22734. state.length = 0;
  22735. state.mode = COMMENT;
  22736. /* falls through */
  22737. case COMMENT:
  22738. if (state.flags & 0x1000) {
  22739. if (have === 0) { break inf_leave; }
  22740. copy = 0;
  22741. do {
  22742. len = input[next + copy++];
  22743. /* use constant limit because in js we should not preallocate memory */
  22744. if (state.head && len &&
  22745. (state.length < 65536 /*state.head.comm_max*/)) {
  22746. state.head.comment += String.fromCharCode(len);
  22747. }
  22748. } while (len && copy < have);
  22749. if (state.flags & 0x0200) {
  22750. state.check = crc32(state.check, input, copy, next);
  22751. }
  22752. have -= copy;
  22753. next += copy;
  22754. if (len) { break inf_leave; }
  22755. }
  22756. else if (state.head) {
  22757. state.head.comment = null;
  22758. }
  22759. state.mode = HCRC;
  22760. /* falls through */
  22761. case HCRC:
  22762. if (state.flags & 0x0200) {
  22763. //=== NEEDBITS(16); */
  22764. while (bits < 16) {
  22765. if (have === 0) { break inf_leave; }
  22766. have--;
  22767. hold += input[next++] << bits;
  22768. bits += 8;
  22769. }
  22770. //===//
  22771. if (hold !== (state.check & 0xffff)) {
  22772. strm.msg = 'header crc mismatch';
  22773. state.mode = BAD;
  22774. break;
  22775. }
  22776. //=== INITBITS();
  22777. hold = 0;
  22778. bits = 0;
  22779. //===//
  22780. }
  22781. if (state.head) {
  22782. state.head.hcrc = ((state.flags >> 9) & 1);
  22783. state.head.done = true;
  22784. }
  22785. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  22786. state.mode = TYPE;
  22787. break;
  22788. case DICTID:
  22789. //=== NEEDBITS(32); */
  22790. while (bits < 32) {
  22791. if (have === 0) { break inf_leave; }
  22792. have--;
  22793. hold += input[next++] << bits;
  22794. bits += 8;
  22795. }
  22796. //===//
  22797. strm.adler = state.check = ZSWAP32(hold);
  22798. //=== INITBITS();
  22799. hold = 0;
  22800. bits = 0;
  22801. //===//
  22802. state.mode = DICT;
  22803. /* falls through */
  22804. case DICT:
  22805. if (state.havedict === 0) {
  22806. //--- RESTORE() ---
  22807. strm.next_out = put;
  22808. strm.avail_out = left;
  22809. strm.next_in = next;
  22810. strm.avail_in = have;
  22811. state.hold = hold;
  22812. state.bits = bits;
  22813. //---
  22814. return Z_NEED_DICT;
  22815. }
  22816. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  22817. state.mode = TYPE;
  22818. /* falls through */
  22819. case TYPE:
  22820. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  22821. /* falls through */
  22822. case TYPEDO:
  22823. if (state.last) {
  22824. //--- BYTEBITS() ---//
  22825. hold >>>= bits & 7;
  22826. bits -= bits & 7;
  22827. //---//
  22828. state.mode = CHECK;
  22829. break;
  22830. }
  22831. //=== NEEDBITS(3); */
  22832. while (bits < 3) {
  22833. if (have === 0) { break inf_leave; }
  22834. have--;
  22835. hold += input[next++] << bits;
  22836. bits += 8;
  22837. }
  22838. //===//
  22839. state.last = (hold & 0x01)/*BITS(1)*/;
  22840. //--- DROPBITS(1) ---//
  22841. hold >>>= 1;
  22842. bits -= 1;
  22843. //---//
  22844. switch ((hold & 0x03)/*BITS(2)*/) {
  22845. case 0: /* stored block */
  22846. //Tracev((stderr, "inflate: stored block%s\n",
  22847. // state.last ? " (last)" : ""));
  22848. state.mode = STORED;
  22849. break;
  22850. case 1: /* fixed block */
  22851. fixedtables(state);
  22852. //Tracev((stderr, "inflate: fixed codes block%s\n",
  22853. // state.last ? " (last)" : ""));
  22854. state.mode = LEN_; /* decode codes */
  22855. if (flush === Z_TREES) {
  22856. //--- DROPBITS(2) ---//
  22857. hold >>>= 2;
  22858. bits -= 2;
  22859. //---//
  22860. break inf_leave;
  22861. }
  22862. break;
  22863. case 2: /* dynamic block */
  22864. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  22865. // state.last ? " (last)" : ""));
  22866. state.mode = TABLE;
  22867. break;
  22868. case 3:
  22869. strm.msg = 'invalid block type';
  22870. state.mode = BAD;
  22871. }
  22872. //--- DROPBITS(2) ---//
  22873. hold >>>= 2;
  22874. bits -= 2;
  22875. //---//
  22876. break;
  22877. case STORED:
  22878. //--- BYTEBITS() ---// /* go to byte boundary */
  22879. hold >>>= bits & 7;
  22880. bits -= bits & 7;
  22881. //---//
  22882. //=== NEEDBITS(32); */
  22883. while (bits < 32) {
  22884. if (have === 0) { break inf_leave; }
  22885. have--;
  22886. hold += input[next++] << bits;
  22887. bits += 8;
  22888. }
  22889. //===//
  22890. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  22891. strm.msg = 'invalid stored block lengths';
  22892. state.mode = BAD;
  22893. break;
  22894. }
  22895. state.length = hold & 0xffff;
  22896. //Tracev((stderr, "inflate: stored length %u\n",
  22897. // state.length));
  22898. //=== INITBITS();
  22899. hold = 0;
  22900. bits = 0;
  22901. //===//
  22902. state.mode = COPY_;
  22903. if (flush === Z_TREES) { break inf_leave; }
  22904. /* falls through */
  22905. case COPY_:
  22906. state.mode = COPY;
  22907. /* falls through */
  22908. case COPY:
  22909. copy = state.length;
  22910. if (copy) {
  22911. if (copy > have) { copy = have; }
  22912. if (copy > left) { copy = left; }
  22913. if (copy === 0) { break inf_leave; }
  22914. //--- zmemcpy(put, next, copy); ---
  22915. utils.arraySet(output, input, next, copy, put);
  22916. //---//
  22917. have -= copy;
  22918. next += copy;
  22919. left -= copy;
  22920. put += copy;
  22921. state.length -= copy;
  22922. break;
  22923. }
  22924. //Tracev((stderr, "inflate: stored end\n"));
  22925. state.mode = TYPE;
  22926. break;
  22927. case TABLE:
  22928. //=== NEEDBITS(14); */
  22929. while (bits < 14) {
  22930. if (have === 0) { break inf_leave; }
  22931. have--;
  22932. hold += input[next++] << bits;
  22933. bits += 8;
  22934. }
  22935. //===//
  22936. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  22937. //--- DROPBITS(5) ---//
  22938. hold >>>= 5;
  22939. bits -= 5;
  22940. //---//
  22941. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  22942. //--- DROPBITS(5) ---//
  22943. hold >>>= 5;
  22944. bits -= 5;
  22945. //---//
  22946. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  22947. //--- DROPBITS(4) ---//
  22948. hold >>>= 4;
  22949. bits -= 4;
  22950. //---//
  22951. //#ifndef PKZIP_BUG_WORKAROUND
  22952. if (state.nlen > 286 || state.ndist > 30) {
  22953. strm.msg = 'too many length or distance symbols';
  22954. state.mode = BAD;
  22955. break;
  22956. }
  22957. //#endif
  22958. //Tracev((stderr, "inflate: table sizes ok\n"));
  22959. state.have = 0;
  22960. state.mode = LENLENS;
  22961. /* falls through */
  22962. case LENLENS:
  22963. while (state.have < state.ncode) {
  22964. //=== NEEDBITS(3);
  22965. while (bits < 3) {
  22966. if (have === 0) { break inf_leave; }
  22967. have--;
  22968. hold += input[next++] << bits;
  22969. bits += 8;
  22970. }
  22971. //===//
  22972. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  22973. //--- DROPBITS(3) ---//
  22974. hold >>>= 3;
  22975. bits -= 3;
  22976. //---//
  22977. }
  22978. while (state.have < 19) {
  22979. state.lens[order[state.have++]] = 0;
  22980. }
  22981. // We have separate tables & no pointers. 2 commented lines below not needed.
  22982. //state.next = state.codes;
  22983. //state.lencode = state.next;
  22984. // Switch to use dynamic table
  22985. state.lencode = state.lendyn;
  22986. state.lenbits = 7;
  22987. opts = {bits: state.lenbits};
  22988. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  22989. state.lenbits = opts.bits;
  22990. if (ret) {
  22991. strm.msg = 'invalid code lengths set';
  22992. state.mode = BAD;
  22993. break;
  22994. }
  22995. //Tracev((stderr, "inflate: code lengths ok\n"));
  22996. state.have = 0;
  22997. state.mode = CODELENS;
  22998. /* falls through */
  22999. case CODELENS:
  23000. while (state.have < state.nlen + state.ndist) {
  23001. for (;;) {
  23002. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  23003. here_bits = here >>> 24;
  23004. here_op = (here >>> 16) & 0xff;
  23005. here_val = here & 0xffff;
  23006. if ((here_bits) <= bits) { break; }
  23007. //--- PULLBYTE() ---//
  23008. if (have === 0) { break inf_leave; }
  23009. have--;
  23010. hold += input[next++] << bits;
  23011. bits += 8;
  23012. //---//
  23013. }
  23014. if (here_val < 16) {
  23015. //--- DROPBITS(here.bits) ---//
  23016. hold >>>= here_bits;
  23017. bits -= here_bits;
  23018. //---//
  23019. state.lens[state.have++] = here_val;
  23020. }
  23021. else {
  23022. if (here_val === 16) {
  23023. //=== NEEDBITS(here.bits + 2);
  23024. n = here_bits + 2;
  23025. while (bits < n) {
  23026. if (have === 0) { break inf_leave; }
  23027. have--;
  23028. hold += input[next++] << bits;
  23029. bits += 8;
  23030. }
  23031. //===//
  23032. //--- DROPBITS(here.bits) ---//
  23033. hold >>>= here_bits;
  23034. bits -= here_bits;
  23035. //---//
  23036. if (state.have === 0) {
  23037. strm.msg = 'invalid bit length repeat';
  23038. state.mode = BAD;
  23039. break;
  23040. }
  23041. len = state.lens[state.have - 1];
  23042. copy = 3 + (hold & 0x03);//BITS(2);
  23043. //--- DROPBITS(2) ---//
  23044. hold >>>= 2;
  23045. bits -= 2;
  23046. //---//
  23047. }
  23048. else if (here_val === 17) {
  23049. //=== NEEDBITS(here.bits + 3);
  23050. n = here_bits + 3;
  23051. while (bits < n) {
  23052. if (have === 0) { break inf_leave; }
  23053. have--;
  23054. hold += input[next++] << bits;
  23055. bits += 8;
  23056. }
  23057. //===//
  23058. //--- DROPBITS(here.bits) ---//
  23059. hold >>>= here_bits;
  23060. bits -= here_bits;
  23061. //---//
  23062. len = 0;
  23063. copy = 3 + (hold & 0x07);//BITS(3);
  23064. //--- DROPBITS(3) ---//
  23065. hold >>>= 3;
  23066. bits -= 3;
  23067. //---//
  23068. }
  23069. else {
  23070. //=== NEEDBITS(here.bits + 7);
  23071. n = here_bits + 7;
  23072. while (bits < n) {
  23073. if (have === 0) { break inf_leave; }
  23074. have--;
  23075. hold += input[next++] << bits;
  23076. bits += 8;
  23077. }
  23078. //===//
  23079. //--- DROPBITS(here.bits) ---//
  23080. hold >>>= here_bits;
  23081. bits -= here_bits;
  23082. //---//
  23083. len = 0;
  23084. copy = 11 + (hold & 0x7f);//BITS(7);
  23085. //--- DROPBITS(7) ---//
  23086. hold >>>= 7;
  23087. bits -= 7;
  23088. //---//
  23089. }
  23090. if (state.have + copy > state.nlen + state.ndist) {
  23091. strm.msg = 'invalid bit length repeat';
  23092. state.mode = BAD;
  23093. break;
  23094. }
  23095. while (copy--) {
  23096. state.lens[state.have++] = len;
  23097. }
  23098. }
  23099. }
  23100. /* handle error breaks in while */
  23101. if (state.mode === BAD) { break; }
  23102. /* check for end-of-block code (better have one) */
  23103. if (state.lens[256] === 0) {
  23104. strm.msg = 'invalid code -- missing end-of-block';
  23105. state.mode = BAD;
  23106. break;
  23107. }
  23108. /* build code tables -- note: do not change the lenbits or distbits
  23109. values here (9 and 6) without reading the comments in inftrees.h
  23110. concerning the ENOUGH constants, which depend on those values */
  23111. state.lenbits = 9;
  23112. opts = {bits: state.lenbits};
  23113. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  23114. // We have separate tables & no pointers. 2 commented lines below not needed.
  23115. // state.next_index = opts.table_index;
  23116. state.lenbits = opts.bits;
  23117. // state.lencode = state.next;
  23118. if (ret) {
  23119. strm.msg = 'invalid literal/lengths set';
  23120. state.mode = BAD;
  23121. break;
  23122. }
  23123. state.distbits = 6;
  23124. //state.distcode.copy(state.codes);
  23125. // Switch to use dynamic table
  23126. state.distcode = state.distdyn;
  23127. opts = {bits: state.distbits};
  23128. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  23129. // We have separate tables & no pointers. 2 commented lines below not needed.
  23130. // state.next_index = opts.table_index;
  23131. state.distbits = opts.bits;
  23132. // state.distcode = state.next;
  23133. if (ret) {
  23134. strm.msg = 'invalid distances set';
  23135. state.mode = BAD;
  23136. break;
  23137. }
  23138. //Tracev((stderr, 'inflate: codes ok\n'));
  23139. state.mode = LEN_;
  23140. if (flush === Z_TREES) { break inf_leave; }
  23141. /* falls through */
  23142. case LEN_:
  23143. state.mode = LEN;
  23144. /* falls through */
  23145. case LEN:
  23146. if (have >= 6 && left >= 258) {
  23147. //--- RESTORE() ---
  23148. strm.next_out = put;
  23149. strm.avail_out = left;
  23150. strm.next_in = next;
  23151. strm.avail_in = have;
  23152. state.hold = hold;
  23153. state.bits = bits;
  23154. //---
  23155. inflate_fast(strm, _out);
  23156. //--- LOAD() ---
  23157. put = strm.next_out;
  23158. output = strm.output;
  23159. left = strm.avail_out;
  23160. next = strm.next_in;
  23161. input = strm.input;
  23162. have = strm.avail_in;
  23163. hold = state.hold;
  23164. bits = state.bits;
  23165. //---
  23166. if (state.mode === TYPE) {
  23167. state.back = -1;
  23168. }
  23169. break;
  23170. }
  23171. state.back = 0;
  23172. for (;;) {
  23173. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  23174. here_bits = here >>> 24;
  23175. here_op = (here >>> 16) & 0xff;
  23176. here_val = here & 0xffff;
  23177. if (here_bits <= bits) { break; }
  23178. //--- PULLBYTE() ---//
  23179. if (have === 0) { break inf_leave; }
  23180. have--;
  23181. hold += input[next++] << bits;
  23182. bits += 8;
  23183. //---//
  23184. }
  23185. if (here_op && (here_op & 0xf0) === 0) {
  23186. last_bits = here_bits;
  23187. last_op = here_op;
  23188. last_val = here_val;
  23189. for (;;) {
  23190. here = state.lencode[last_val +
  23191. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  23192. here_bits = here >>> 24;
  23193. here_op = (here >>> 16) & 0xff;
  23194. here_val = here & 0xffff;
  23195. if ((last_bits + here_bits) <= bits) { break; }
  23196. //--- PULLBYTE() ---//
  23197. if (have === 0) { break inf_leave; }
  23198. have--;
  23199. hold += input[next++] << bits;
  23200. bits += 8;
  23201. //---//
  23202. }
  23203. //--- DROPBITS(last.bits) ---//
  23204. hold >>>= last_bits;
  23205. bits -= last_bits;
  23206. //---//
  23207. state.back += last_bits;
  23208. }
  23209. //--- DROPBITS(here.bits) ---//
  23210. hold >>>= here_bits;
  23211. bits -= here_bits;
  23212. //---//
  23213. state.back += here_bits;
  23214. state.length = here_val;
  23215. if (here_op === 0) {
  23216. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  23217. // "inflate: literal '%c'\n" :
  23218. // "inflate: literal 0x%02x\n", here.val));
  23219. state.mode = LIT;
  23220. break;
  23221. }
  23222. if (here_op & 32) {
  23223. //Tracevv((stderr, "inflate: end of block\n"));
  23224. state.back = -1;
  23225. state.mode = TYPE;
  23226. break;
  23227. }
  23228. if (here_op & 64) {
  23229. strm.msg = 'invalid literal/length code';
  23230. state.mode = BAD;
  23231. break;
  23232. }
  23233. state.extra = here_op & 15;
  23234. state.mode = LENEXT;
  23235. /* falls through */
  23236. case LENEXT:
  23237. if (state.extra) {
  23238. //=== NEEDBITS(state.extra);
  23239. n = state.extra;
  23240. while (bits < n) {
  23241. if (have === 0) { break inf_leave; }
  23242. have--;
  23243. hold += input[next++] << bits;
  23244. bits += 8;
  23245. }
  23246. //===//
  23247. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  23248. //--- DROPBITS(state.extra) ---//
  23249. hold >>>= state.extra;
  23250. bits -= state.extra;
  23251. //---//
  23252. state.back += state.extra;
  23253. }
  23254. //Tracevv((stderr, "inflate: length %u\n", state.length));
  23255. state.was = state.length;
  23256. state.mode = DIST;
  23257. /* falls through */
  23258. case DIST:
  23259. for (;;) {
  23260. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  23261. here_bits = here >>> 24;
  23262. here_op = (here >>> 16) & 0xff;
  23263. here_val = here & 0xffff;
  23264. if ((here_bits) <= bits) { break; }
  23265. //--- PULLBYTE() ---//
  23266. if (have === 0) { break inf_leave; }
  23267. have--;
  23268. hold += input[next++] << bits;
  23269. bits += 8;
  23270. //---//
  23271. }
  23272. if ((here_op & 0xf0) === 0) {
  23273. last_bits = here_bits;
  23274. last_op = here_op;
  23275. last_val = here_val;
  23276. for (;;) {
  23277. here = state.distcode[last_val +
  23278. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  23279. here_bits = here >>> 24;
  23280. here_op = (here >>> 16) & 0xff;
  23281. here_val = here & 0xffff;
  23282. if ((last_bits + here_bits) <= bits) { break; }
  23283. //--- PULLBYTE() ---//
  23284. if (have === 0) { break inf_leave; }
  23285. have--;
  23286. hold += input[next++] << bits;
  23287. bits += 8;
  23288. //---//
  23289. }
  23290. //--- DROPBITS(last.bits) ---//
  23291. hold >>>= last_bits;
  23292. bits -= last_bits;
  23293. //---//
  23294. state.back += last_bits;
  23295. }
  23296. //--- DROPBITS(here.bits) ---//
  23297. hold >>>= here_bits;
  23298. bits -= here_bits;
  23299. //---//
  23300. state.back += here_bits;
  23301. if (here_op & 64) {
  23302. strm.msg = 'invalid distance code';
  23303. state.mode = BAD;
  23304. break;
  23305. }
  23306. state.offset = here_val;
  23307. state.extra = (here_op) & 15;
  23308. state.mode = DISTEXT;
  23309. /* falls through */
  23310. case DISTEXT:
  23311. if (state.extra) {
  23312. //=== NEEDBITS(state.extra);
  23313. n = state.extra;
  23314. while (bits < n) {
  23315. if (have === 0) { break inf_leave; }
  23316. have--;
  23317. hold += input[next++] << bits;
  23318. bits += 8;
  23319. }
  23320. //===//
  23321. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  23322. //--- DROPBITS(state.extra) ---//
  23323. hold >>>= state.extra;
  23324. bits -= state.extra;
  23325. //---//
  23326. state.back += state.extra;
  23327. }
  23328. //#ifdef INFLATE_STRICT
  23329. if (state.offset > state.dmax) {
  23330. strm.msg = 'invalid distance too far back';
  23331. state.mode = BAD;
  23332. break;
  23333. }
  23334. //#endif
  23335. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  23336. state.mode = MATCH;
  23337. /* falls through */
  23338. case MATCH:
  23339. if (left === 0) { break inf_leave; }
  23340. copy = _out - left;
  23341. if (state.offset > copy) { /* copy from window */
  23342. copy = state.offset - copy;
  23343. if (copy > state.whave) {
  23344. if (state.sane) {
  23345. strm.msg = 'invalid distance too far back';
  23346. state.mode = BAD;
  23347. break;
  23348. }
  23349. // (!) This block is disabled in zlib defailts,
  23350. // don't enable it for binary compatibility
  23351. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  23352. // Trace((stderr, "inflate.c too far\n"));
  23353. // copy -= state.whave;
  23354. // if (copy > state.length) { copy = state.length; }
  23355. // if (copy > left) { copy = left; }
  23356. // left -= copy;
  23357. // state.length -= copy;
  23358. // do {
  23359. // output[put++] = 0;
  23360. // } while (--copy);
  23361. // if (state.length === 0) { state.mode = LEN; }
  23362. // break;
  23363. //#endif
  23364. }
  23365. if (copy > state.wnext) {
  23366. copy -= state.wnext;
  23367. from = state.wsize - copy;
  23368. }
  23369. else {
  23370. from = state.wnext - copy;
  23371. }
  23372. if (copy > state.length) { copy = state.length; }
  23373. from_source = state.window;
  23374. }
  23375. else { /* copy from output */
  23376. from_source = output;
  23377. from = put - state.offset;
  23378. copy = state.length;
  23379. }
  23380. if (copy > left) { copy = left; }
  23381. left -= copy;
  23382. state.length -= copy;
  23383. do {
  23384. output[put++] = from_source[from++];
  23385. } while (--copy);
  23386. if (state.length === 0) { state.mode = LEN; }
  23387. break;
  23388. case LIT:
  23389. if (left === 0) { break inf_leave; }
  23390. output[put++] = state.length;
  23391. left--;
  23392. state.mode = LEN;
  23393. break;
  23394. case CHECK:
  23395. if (state.wrap) {
  23396. //=== NEEDBITS(32);
  23397. while (bits < 32) {
  23398. if (have === 0) { break inf_leave; }
  23399. have--;
  23400. // Use '|' insdead of '+' to make sure that result is signed
  23401. hold |= input[next++] << bits;
  23402. bits += 8;
  23403. }
  23404. //===//
  23405. _out -= left;
  23406. strm.total_out += _out;
  23407. state.total += _out;
  23408. if (_out) {
  23409. strm.adler = state.check =
  23410. /*UPDATE(state.check, put - _out, _out);*/
  23411. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  23412. }
  23413. _out = left;
  23414. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  23415. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  23416. strm.msg = 'incorrect data check';
  23417. state.mode = BAD;
  23418. break;
  23419. }
  23420. //=== INITBITS();
  23421. hold = 0;
  23422. bits = 0;
  23423. //===//
  23424. //Tracev((stderr, "inflate: check matches trailer\n"));
  23425. }
  23426. state.mode = LENGTH;
  23427. /* falls through */
  23428. case LENGTH:
  23429. if (state.wrap && state.flags) {
  23430. //=== NEEDBITS(32);
  23431. while (bits < 32) {
  23432. if (have === 0) { break inf_leave; }
  23433. have--;
  23434. hold += input[next++] << bits;
  23435. bits += 8;
  23436. }
  23437. //===//
  23438. if (hold !== (state.total & 0xffffffff)) {
  23439. strm.msg = 'incorrect length check';
  23440. state.mode = BAD;
  23441. break;
  23442. }
  23443. //=== INITBITS();
  23444. hold = 0;
  23445. bits = 0;
  23446. //===//
  23447. //Tracev((stderr, "inflate: length matches trailer\n"));
  23448. }
  23449. state.mode = DONE;
  23450. /* falls through */
  23451. case DONE:
  23452. ret = Z_STREAM_END;
  23453. break inf_leave;
  23454. case BAD:
  23455. ret = Z_DATA_ERROR;
  23456. break inf_leave;
  23457. case MEM:
  23458. return Z_MEM_ERROR;
  23459. case SYNC:
  23460. /* falls through */
  23461. default:
  23462. return Z_STREAM_ERROR;
  23463. }
  23464. }
  23465. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  23466. /*
  23467. Return from inflate(), updating the total counts and the check value.
  23468. If there was no progress during the inflate() call, return a buffer
  23469. error. Call updatewindow() to create and/or update the window state.
  23470. Note: a memory error from inflate() is non-recoverable.
  23471. */
  23472. //--- RESTORE() ---
  23473. strm.next_out = put;
  23474. strm.avail_out = left;
  23475. strm.next_in = next;
  23476. strm.avail_in = have;
  23477. state.hold = hold;
  23478. state.bits = bits;
  23479. //---
  23480. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  23481. (state.mode < CHECK || flush !== Z_FINISH))) {
  23482. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  23483. state.mode = MEM;
  23484. return Z_MEM_ERROR;
  23485. }
  23486. }
  23487. _in -= strm.avail_in;
  23488. _out -= strm.avail_out;
  23489. strm.total_in += _in;
  23490. strm.total_out += _out;
  23491. state.total += _out;
  23492. if (state.wrap && _out) {
  23493. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  23494. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  23495. }
  23496. strm.data_type = state.bits + (state.last ? 64 : 0) +
  23497. (state.mode === TYPE ? 128 : 0) +
  23498. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  23499. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  23500. ret = Z_BUF_ERROR;
  23501. }
  23502. return ret;
  23503. }
  23504. function inflateEnd(strm) {
  23505. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  23506. return Z_STREAM_ERROR;
  23507. }
  23508. var state = strm.state;
  23509. if (state.window) {
  23510. state.window = null;
  23511. }
  23512. strm.state = null;
  23513. return Z_OK;
  23514. }
  23515. function inflateGetHeader(strm, head) {
  23516. var state;
  23517. /* check state */
  23518. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  23519. state = strm.state;
  23520. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  23521. /* save header structure */
  23522. state.head = head;
  23523. head.done = false;
  23524. return Z_OK;
  23525. }
  23526. exports.inflateReset = inflateReset;
  23527. exports.inflateReset2 = inflateReset2;
  23528. exports.inflateResetKeep = inflateResetKeep;
  23529. exports.inflateInit = inflateInit;
  23530. exports.inflateInit2 = inflateInit2;
  23531. exports.inflate = inflate;
  23532. exports.inflateEnd = inflateEnd;
  23533. exports.inflateGetHeader = inflateGetHeader;
  23534. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  23535. /* Not implemented
  23536. exports.inflateCopy = inflateCopy;
  23537. exports.inflateGetDictionary = inflateGetDictionary;
  23538. exports.inflateMark = inflateMark;
  23539. exports.inflatePrime = inflatePrime;
  23540. exports.inflateSetDictionary = inflateSetDictionary;
  23541. exports.inflateSync = inflateSync;
  23542. exports.inflateSyncPoint = inflateSyncPoint;
  23543. exports.inflateUndermine = inflateUndermine;
  23544. */
  23545. },{"../utils/common":72,"./adler32":74,"./crc32":76,"./inffast":79,"./inftrees":81}],81:[function(require,module,exports){
  23546. 'use strict';
  23547. var utils = require('../utils/common');
  23548. var MAXBITS = 15;
  23549. var ENOUGH_LENS = 852;
  23550. var ENOUGH_DISTS = 592;
  23551. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  23552. var CODES = 0;
  23553. var LENS = 1;
  23554. var DISTS = 2;
  23555. var lbase = [ /* Length codes 257..285 base */
  23556. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  23557. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  23558. ];
  23559. var lext = [ /* Length codes 257..285 extra */
  23560. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  23561. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  23562. ];
  23563. var dbase = [ /* Distance codes 0..29 base */
  23564. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  23565. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  23566. 8193, 12289, 16385, 24577, 0, 0
  23567. ];
  23568. var dext = [ /* Distance codes 0..29 extra */
  23569. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  23570. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  23571. 28, 28, 29, 29, 64, 64
  23572. ];
  23573. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  23574. {
  23575. var bits = opts.bits;
  23576. //here = opts.here; /* table entry for duplication */
  23577. var len = 0; /* a code's length in bits */
  23578. var sym = 0; /* index of code symbols */
  23579. var min = 0, max = 0; /* minimum and maximum code lengths */
  23580. var root = 0; /* number of index bits for root table */
  23581. var curr = 0; /* number of index bits for current table */
  23582. var drop = 0; /* code bits to drop for sub-table */
  23583. var left = 0; /* number of prefix codes available */
  23584. var used = 0; /* code entries in table used */
  23585. var huff = 0; /* Huffman code */
  23586. var incr; /* for incrementing code, index */
  23587. var fill; /* index for replicating entries */
  23588. var low; /* low bits for current root entry */
  23589. var mask; /* mask for low root bits */
  23590. var next; /* next available space in table */
  23591. var base = null; /* base value table to use */
  23592. var base_index = 0;
  23593. // var shoextra; /* extra bits table to use */
  23594. var end; /* use base and extra for symbol > end */
  23595. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  23596. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  23597. var extra = null;
  23598. var extra_index = 0;
  23599. var here_bits, here_op, here_val;
  23600. /*
  23601. Process a set of code lengths to create a canonical Huffman code. The
  23602. code lengths are lens[0..codes-1]. Each length corresponds to the
  23603. symbols 0..codes-1. The Huffman code is generated by first sorting the
  23604. symbols by length from short to long, and retaining the symbol order
  23605. for codes with equal lengths. Then the code starts with all zero bits
  23606. for the first code of the shortest length, and the codes are integer
  23607. increments for the same length, and zeros are appended as the length
  23608. increases. For the deflate format, these bits are stored backwards
  23609. from their more natural integer increment ordering, and so when the
  23610. decoding tables are built in the large loop below, the integer codes
  23611. are incremented backwards.
  23612. This routine assumes, but does not check, that all of the entries in
  23613. lens[] are in the range 0..MAXBITS. The caller must assure this.
  23614. 1..MAXBITS is interpreted as that code length. zero means that that
  23615. symbol does not occur in this code.
  23616. The codes are sorted by computing a count of codes for each length,
  23617. creating from that a table of starting indices for each length in the
  23618. sorted table, and then entering the symbols in order in the sorted
  23619. table. The sorted table is work[], with that space being provided by
  23620. the caller.
  23621. The length counts are used for other purposes as well, i.e. finding
  23622. the minimum and maximum length codes, determining if there are any
  23623. codes at all, checking for a valid set of lengths, and looking ahead
  23624. at length counts to determine sub-table sizes when building the
  23625. decoding tables.
  23626. */
  23627. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  23628. for (len = 0; len <= MAXBITS; len++) {
  23629. count[len] = 0;
  23630. }
  23631. for (sym = 0; sym < codes; sym++) {
  23632. count[lens[lens_index + sym]]++;
  23633. }
  23634. /* bound code lengths, force root to be within code lengths */
  23635. root = bits;
  23636. for (max = MAXBITS; max >= 1; max--) {
  23637. if (count[max] !== 0) { break; }
  23638. }
  23639. if (root > max) {
  23640. root = max;
  23641. }
  23642. if (max === 0) { /* no symbols to code at all */
  23643. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  23644. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  23645. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  23646. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  23647. //table.op[opts.table_index] = 64;
  23648. //table.bits[opts.table_index] = 1;
  23649. //table.val[opts.table_index++] = 0;
  23650. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  23651. opts.bits = 1;
  23652. return 0; /* no symbols, but wait for decoding to report error */
  23653. }
  23654. for (min = 1; min < max; min++) {
  23655. if (count[min] !== 0) { break; }
  23656. }
  23657. if (root < min) {
  23658. root = min;
  23659. }
  23660. /* check for an over-subscribed or incomplete set of lengths */
  23661. left = 1;
  23662. for (len = 1; len <= MAXBITS; len++) {
  23663. left <<= 1;
  23664. left -= count[len];
  23665. if (left < 0) {
  23666. return -1;
  23667. } /* over-subscribed */
  23668. }
  23669. if (left > 0 && (type === CODES || max !== 1)) {
  23670. return -1; /* incomplete set */
  23671. }
  23672. /* generate offsets into symbol table for each length for sorting */
  23673. offs[1] = 0;
  23674. for (len = 1; len < MAXBITS; len++) {
  23675. offs[len + 1] = offs[len] + count[len];
  23676. }
  23677. /* sort symbols by length, by symbol order within each length */
  23678. for (sym = 0; sym < codes; sym++) {
  23679. if (lens[lens_index + sym] !== 0) {
  23680. work[offs[lens[lens_index + sym]]++] = sym;
  23681. }
  23682. }
  23683. /*
  23684. Create and fill in decoding tables. In this loop, the table being
  23685. filled is at next and has curr index bits. The code being used is huff
  23686. with length len. That code is converted to an index by dropping drop
  23687. bits off of the bottom. For codes where len is less than drop + curr,
  23688. those top drop + curr - len bits are incremented through all values to
  23689. fill the table with replicated entries.
  23690. root is the number of index bits for the root table. When len exceeds
  23691. root, sub-tables are created pointed to by the root entry with an index
  23692. of the low root bits of huff. This is saved in low to check for when a
  23693. new sub-table should be started. drop is zero when the root table is
  23694. being filled, and drop is root when sub-tables are being filled.
  23695. When a new sub-table is needed, it is necessary to look ahead in the
  23696. code lengths to determine what size sub-table is needed. The length
  23697. counts are used for this, and so count[] is decremented as codes are
  23698. entered in the tables.
  23699. used keeps track of how many table entries have been allocated from the
  23700. provided *table space. It is checked for LENS and DIST tables against
  23701. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  23702. the initial root table size constants. See the comments in inftrees.h
  23703. for more information.
  23704. sym increments through all symbols, and the loop terminates when
  23705. all codes of length max, i.e. all codes, have been processed. This
  23706. routine permits incomplete codes, so another loop after this one fills
  23707. in the rest of the decoding tables with invalid code markers.
  23708. */
  23709. /* set up for code type */
  23710. // poor man optimization - use if-else instead of switch,
  23711. // to avoid deopts in old v8
  23712. if (type === CODES) {
  23713. base = extra = work; /* dummy value--not used */
  23714. end = 19;
  23715. } else if (type === LENS) {
  23716. base = lbase;
  23717. base_index -= 257;
  23718. extra = lext;
  23719. extra_index -= 257;
  23720. end = 256;
  23721. } else { /* DISTS */
  23722. base = dbase;
  23723. extra = dext;
  23724. end = -1;
  23725. }
  23726. /* initialize opts for loop */
  23727. huff = 0; /* starting code */
  23728. sym = 0; /* starting code symbol */
  23729. len = min; /* starting code length */
  23730. next = table_index; /* current table to fill in */
  23731. curr = root; /* current table index bits */
  23732. drop = 0; /* current bits to drop from code for index */
  23733. low = -1; /* trigger new sub-table when len > root */
  23734. used = 1 << root; /* use root table entries */
  23735. mask = used - 1; /* mask for comparing low */
  23736. /* check available table space */
  23737. if ((type === LENS && used > ENOUGH_LENS) ||
  23738. (type === DISTS && used > ENOUGH_DISTS)) {
  23739. return 1;
  23740. }
  23741. var i=0;
  23742. /* process all codes and make table entries */
  23743. for (;;) {
  23744. i++;
  23745. /* create table entry */
  23746. here_bits = len - drop;
  23747. if (work[sym] < end) {
  23748. here_op = 0;
  23749. here_val = work[sym];
  23750. }
  23751. else if (work[sym] > end) {
  23752. here_op = extra[extra_index + work[sym]];
  23753. here_val = base[base_index + work[sym]];
  23754. }
  23755. else {
  23756. here_op = 32 + 64; /* end of block */
  23757. here_val = 0;
  23758. }
  23759. /* replicate for those indices with low len bits equal to huff */
  23760. incr = 1 << (len - drop);
  23761. fill = 1 << curr;
  23762. min = fill; /* save offset to next table */
  23763. do {
  23764. fill -= incr;
  23765. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  23766. } while (fill !== 0);
  23767. /* backwards increment the len-bit code huff */
  23768. incr = 1 << (len - 1);
  23769. while (huff & incr) {
  23770. incr >>= 1;
  23771. }
  23772. if (incr !== 0) {
  23773. huff &= incr - 1;
  23774. huff += incr;
  23775. } else {
  23776. huff = 0;
  23777. }
  23778. /* go to next symbol, update count, len */
  23779. sym++;
  23780. if (--count[len] === 0) {
  23781. if (len === max) { break; }
  23782. len = lens[lens_index + work[sym]];
  23783. }
  23784. /* create new sub-table if needed */
  23785. if (len > root && (huff & mask) !== low) {
  23786. /* if first time, transition to sub-tables */
  23787. if (drop === 0) {
  23788. drop = root;
  23789. }
  23790. /* increment past last table */
  23791. next += min; /* here min is 1 << curr */
  23792. /* determine length of next table */
  23793. curr = len - drop;
  23794. left = 1 << curr;
  23795. while (curr + drop < max) {
  23796. left -= count[curr + drop];
  23797. if (left <= 0) { break; }
  23798. curr++;
  23799. left <<= 1;
  23800. }
  23801. /* check for enough space */
  23802. used += 1 << curr;
  23803. if ((type === LENS && used > ENOUGH_LENS) ||
  23804. (type === DISTS && used > ENOUGH_DISTS)) {
  23805. return 1;
  23806. }
  23807. /* point entry in root table to sub-table */
  23808. low = huff & mask;
  23809. /*table.op[low] = curr;
  23810. table.bits[low] = root;
  23811. table.val[low] = next - opts.table_index;*/
  23812. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  23813. }
  23814. }
  23815. /* fill in remaining table entry if code is incomplete (guaranteed to have
  23816. at most one remaining entry, since if the code is incomplete, the
  23817. maximum code length that was allowed to get this far is one bit) */
  23818. if (huff !== 0) {
  23819. //table.op[next + huff] = 64; /* invalid code marker */
  23820. //table.bits[next + huff] = len - drop;
  23821. //table.val[next + huff] = 0;
  23822. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  23823. }
  23824. /* set return parameters */
  23825. //opts.table_index += used;
  23826. opts.bits = root;
  23827. return 0;
  23828. };
  23829. },{"../utils/common":72}],82:[function(require,module,exports){
  23830. 'use strict';
  23831. module.exports = {
  23832. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  23833. '1': 'stream end', /* Z_STREAM_END 1 */
  23834. '0': '', /* Z_OK 0 */
  23835. '-1': 'file error', /* Z_ERRNO (-1) */
  23836. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  23837. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  23838. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  23839. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  23840. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  23841. };
  23842. },{}],83:[function(require,module,exports){
  23843. 'use strict';
  23844. var utils = require('../utils/common');
  23845. /* Public constants ==========================================================*/
  23846. /* ===========================================================================*/
  23847. //var Z_FILTERED = 1;
  23848. //var Z_HUFFMAN_ONLY = 2;
  23849. //var Z_RLE = 3;
  23850. var Z_FIXED = 4;
  23851. //var Z_DEFAULT_STRATEGY = 0;
  23852. /* Possible values of the data_type field (though see inflate()) */
  23853. var Z_BINARY = 0;
  23854. var Z_TEXT = 1;
  23855. //var Z_ASCII = 1; // = Z_TEXT
  23856. var Z_UNKNOWN = 2;
  23857. /*============================================================================*/
  23858. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  23859. // From zutil.h
  23860. var STORED_BLOCK = 0;
  23861. var STATIC_TREES = 1;
  23862. var DYN_TREES = 2;
  23863. /* The three kinds of block type */
  23864. var MIN_MATCH = 3;
  23865. var MAX_MATCH = 258;
  23866. /* The minimum and maximum match lengths */
  23867. // From deflate.h
  23868. /* ===========================================================================
  23869. * Internal compression state.
  23870. */
  23871. var LENGTH_CODES = 29;
  23872. /* number of length codes, not counting the special END_BLOCK code */
  23873. var LITERALS = 256;
  23874. /* number of literal bytes 0..255 */
  23875. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  23876. /* number of Literal or Length codes, including the END_BLOCK code */
  23877. var D_CODES = 30;
  23878. /* number of distance codes */
  23879. var BL_CODES = 19;
  23880. /* number of codes used to transfer the bit lengths */
  23881. var HEAP_SIZE = 2*L_CODES + 1;
  23882. /* maximum heap size */
  23883. var MAX_BITS = 15;
  23884. /* All codes must not exceed MAX_BITS bits */
  23885. var Buf_size = 16;
  23886. /* size of bit buffer in bi_buf */
  23887. /* ===========================================================================
  23888. * Constants
  23889. */
  23890. var MAX_BL_BITS = 7;
  23891. /* Bit length codes must not exceed MAX_BL_BITS bits */
  23892. var END_BLOCK = 256;
  23893. /* end of block literal code */
  23894. var REP_3_6 = 16;
  23895. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  23896. var REPZ_3_10 = 17;
  23897. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  23898. var REPZ_11_138 = 18;
  23899. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  23900. var extra_lbits = /* extra bits for each length code */
  23901. [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];
  23902. var extra_dbits = /* extra bits for each distance code */
  23903. [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];
  23904. var extra_blbits = /* extra bits for each bit length code */
  23905. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  23906. var bl_order =
  23907. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  23908. /* The lengths of the bit length codes are sent in order of decreasing
  23909. * probability, to avoid transmitting the lengths for unused bit length codes.
  23910. */
  23911. /* ===========================================================================
  23912. * Local data. These are initialized only once.
  23913. */
  23914. // We pre-fill arrays with 0 to avoid uninitialized gaps
  23915. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  23916. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  23917. var static_ltree = new Array((L_CODES+2) * 2);
  23918. zero(static_ltree);
  23919. /* The static literal tree. Since the bit lengths are imposed, there is no
  23920. * need for the L_CODES extra codes used during heap construction. However
  23921. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  23922. * below).
  23923. */
  23924. var static_dtree = new Array(D_CODES * 2);
  23925. zero(static_dtree);
  23926. /* The static distance tree. (Actually a trivial tree since all codes use
  23927. * 5 bits.)
  23928. */
  23929. var _dist_code = new Array(DIST_CODE_LEN);
  23930. zero(_dist_code);
  23931. /* Distance codes. The first 256 values correspond to the distances
  23932. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  23933. * the 15 bit distances.
  23934. */
  23935. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  23936. zero(_length_code);
  23937. /* length code for each normalized match length (0 == MIN_MATCH) */
  23938. var base_length = new Array(LENGTH_CODES);
  23939. zero(base_length);
  23940. /* First normalized length for each code (0 = MIN_MATCH) */
  23941. var base_dist = new Array(D_CODES);
  23942. zero(base_dist);
  23943. /* First normalized distance for each code (0 = distance of 1) */
  23944. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  23945. this.static_tree = static_tree; /* static tree or NULL */
  23946. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  23947. this.extra_base = extra_base; /* base index for extra_bits */
  23948. this.elems = elems; /* max number of elements in the tree */
  23949. this.max_length = max_length; /* max bit length for the codes */
  23950. // show if `static_tree` has data or dummy - needed for monomorphic objects
  23951. this.has_stree = static_tree && static_tree.length;
  23952. };
  23953. var static_l_desc;
  23954. var static_d_desc;
  23955. var static_bl_desc;
  23956. var TreeDesc = function(dyn_tree, stat_desc) {
  23957. this.dyn_tree = dyn_tree; /* the dynamic tree */
  23958. this.max_code = 0; /* largest code with non zero frequency */
  23959. this.stat_desc = stat_desc; /* the corresponding static tree */
  23960. };
  23961. function d_code(dist) {
  23962. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  23963. }
  23964. /* ===========================================================================
  23965. * Output a short LSB first on the stream.
  23966. * IN assertion: there is enough room in pendingBuf.
  23967. */
  23968. function put_short (s, w) {
  23969. // put_byte(s, (uch)((w) & 0xff));
  23970. // put_byte(s, (uch)((ush)(w) >> 8));
  23971. s.pending_buf[s.pending++] = (w) & 0xff;
  23972. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  23973. }
  23974. /* ===========================================================================
  23975. * Send a value on a given number of bits.
  23976. * IN assertion: length <= 16 and value fits in length bits.
  23977. */
  23978. function send_bits(s, value, length) {
  23979. if (s.bi_valid > (Buf_size - length)) {
  23980. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  23981. put_short(s, s.bi_buf);
  23982. s.bi_buf = value >> (Buf_size - s.bi_valid);
  23983. s.bi_valid += length - Buf_size;
  23984. } else {
  23985. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  23986. s.bi_valid += length;
  23987. }
  23988. }
  23989. function send_code(s, c, tree) {
  23990. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  23991. }
  23992. /* ===========================================================================
  23993. * Reverse the first len bits of a code, using straightforward code (a faster
  23994. * method would use a table)
  23995. * IN assertion: 1 <= len <= 15
  23996. */
  23997. function bi_reverse(code, len) {
  23998. var res = 0;
  23999. do {
  24000. res |= code & 1;
  24001. code >>>= 1;
  24002. res <<= 1;
  24003. } while (--len > 0);
  24004. return res >>> 1;
  24005. }
  24006. /* ===========================================================================
  24007. * Flush the bit buffer, keeping at most 7 bits in it.
  24008. */
  24009. function bi_flush(s) {
  24010. if (s.bi_valid === 16) {
  24011. put_short(s, s.bi_buf);
  24012. s.bi_buf = 0;
  24013. s.bi_valid = 0;
  24014. } else if (s.bi_valid >= 8) {
  24015. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  24016. s.bi_buf >>= 8;
  24017. s.bi_valid -= 8;
  24018. }
  24019. }
  24020. /* ===========================================================================
  24021. * Compute the optimal bit lengths for a tree and update the total bit length
  24022. * for the current block.
  24023. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  24024. * above are the tree nodes sorted by increasing frequency.
  24025. * OUT assertions: the field len is set to the optimal bit length, the
  24026. * array bl_count contains the frequencies for each bit length.
  24027. * The length opt_len is updated; static_len is also updated if stree is
  24028. * not null.
  24029. */
  24030. function gen_bitlen(s, desc)
  24031. // deflate_state *s;
  24032. // tree_desc *desc; /* the tree descriptor */
  24033. {
  24034. var tree = desc.dyn_tree;
  24035. var max_code = desc.max_code;
  24036. var stree = desc.stat_desc.static_tree;
  24037. var has_stree = desc.stat_desc.has_stree;
  24038. var extra = desc.stat_desc.extra_bits;
  24039. var base = desc.stat_desc.extra_base;
  24040. var max_length = desc.stat_desc.max_length;
  24041. var h; /* heap index */
  24042. var n, m; /* iterate over the tree elements */
  24043. var bits; /* bit length */
  24044. var xbits; /* extra bits */
  24045. var f; /* frequency */
  24046. var overflow = 0; /* number of elements with bit length too large */
  24047. for (bits = 0; bits <= MAX_BITS; bits++) {
  24048. s.bl_count[bits] = 0;
  24049. }
  24050. /* In a first pass, compute the optimal bit lengths (which may
  24051. * overflow in the case of the bit length tree).
  24052. */
  24053. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  24054. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  24055. n = s.heap[h];
  24056. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  24057. if (bits > max_length) {
  24058. bits = max_length;
  24059. overflow++;
  24060. }
  24061. tree[n*2 + 1]/*.Len*/ = bits;
  24062. /* We overwrite tree[n].Dad which is no longer needed */
  24063. if (n > max_code) { continue; } /* not a leaf node */
  24064. s.bl_count[bits]++;
  24065. xbits = 0;
  24066. if (n >= base) {
  24067. xbits = extra[n-base];
  24068. }
  24069. f = tree[n * 2]/*.Freq*/;
  24070. s.opt_len += f * (bits + xbits);
  24071. if (has_stree) {
  24072. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  24073. }
  24074. }
  24075. if (overflow === 0) { return; }
  24076. // Trace((stderr,"\nbit length overflow\n"));
  24077. /* This happens for example on obj2 and pic of the Calgary corpus */
  24078. /* Find the first bit length which could increase: */
  24079. do {
  24080. bits = max_length-1;
  24081. while (s.bl_count[bits] === 0) { bits--; }
  24082. s.bl_count[bits]--; /* move one leaf down the tree */
  24083. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  24084. s.bl_count[max_length]--;
  24085. /* The brother of the overflow item also moves one step up,
  24086. * but this does not affect bl_count[max_length]
  24087. */
  24088. overflow -= 2;
  24089. } while (overflow > 0);
  24090. /* Now recompute all bit lengths, scanning in increasing frequency.
  24091. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  24092. * lengths instead of fixing only the wrong ones. This idea is taken
  24093. * from 'ar' written by Haruhiko Okumura.)
  24094. */
  24095. for (bits = max_length; bits !== 0; bits--) {
  24096. n = s.bl_count[bits];
  24097. while (n !== 0) {
  24098. m = s.heap[--h];
  24099. if (m > max_code) { continue; }
  24100. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  24101. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  24102. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  24103. tree[m*2 + 1]/*.Len*/ = bits;
  24104. }
  24105. n--;
  24106. }
  24107. }
  24108. }
  24109. /* ===========================================================================
  24110. * Generate the codes for a given tree and bit counts (which need not be
  24111. * optimal).
  24112. * IN assertion: the array bl_count contains the bit length statistics for
  24113. * the given tree and the field len is set for all tree elements.
  24114. * OUT assertion: the field code is set for all tree elements of non
  24115. * zero code length.
  24116. */
  24117. function gen_codes(tree, max_code, bl_count)
  24118. // ct_data *tree; /* the tree to decorate */
  24119. // int max_code; /* largest code with non zero frequency */
  24120. // ushf *bl_count; /* number of codes at each bit length */
  24121. {
  24122. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  24123. var code = 0; /* running code value */
  24124. var bits; /* bit index */
  24125. var n; /* code index */
  24126. /* The distribution counts are first used to generate the code values
  24127. * without bit reversal.
  24128. */
  24129. for (bits = 1; bits <= MAX_BITS; bits++) {
  24130. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  24131. }
  24132. /* Check that the bit counts in bl_count are consistent. The last code
  24133. * must be all ones.
  24134. */
  24135. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  24136. // "inconsistent bit counts");
  24137. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  24138. for (n = 0; n <= max_code; n++) {
  24139. var len = tree[n*2 + 1]/*.Len*/;
  24140. if (len === 0) { continue; }
  24141. /* Now reverse the bits */
  24142. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  24143. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  24144. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  24145. }
  24146. }
  24147. /* ===========================================================================
  24148. * Initialize the various 'constant' tables.
  24149. */
  24150. function tr_static_init() {
  24151. var n; /* iterates over tree elements */
  24152. var bits; /* bit counter */
  24153. var length; /* length value */
  24154. var code; /* code value */
  24155. var dist; /* distance index */
  24156. var bl_count = new Array(MAX_BITS+1);
  24157. /* number of codes at each bit length for an optimal tree */
  24158. // do check in _tr_init()
  24159. //if (static_init_done) return;
  24160. /* For some embedded targets, global variables are not initialized: */
  24161. /*#ifdef NO_INIT_GLOBAL_POINTERS
  24162. static_l_desc.static_tree = static_ltree;
  24163. static_l_desc.extra_bits = extra_lbits;
  24164. static_d_desc.static_tree = static_dtree;
  24165. static_d_desc.extra_bits = extra_dbits;
  24166. static_bl_desc.extra_bits = extra_blbits;
  24167. #endif*/
  24168. /* Initialize the mapping length (0..255) -> length code (0..28) */
  24169. length = 0;
  24170. for (code = 0; code < LENGTH_CODES-1; code++) {
  24171. base_length[code] = length;
  24172. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  24173. _length_code[length++] = code;
  24174. }
  24175. }
  24176. //Assert (length == 256, "tr_static_init: length != 256");
  24177. /* Note that the length 255 (match length 258) can be represented
  24178. * in two different ways: code 284 + 5 bits or code 285, so we
  24179. * overwrite length_code[255] to use the best encoding:
  24180. */
  24181. _length_code[length-1] = code;
  24182. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  24183. dist = 0;
  24184. for (code = 0 ; code < 16; code++) {
  24185. base_dist[code] = dist;
  24186. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  24187. _dist_code[dist++] = code;
  24188. }
  24189. }
  24190. //Assert (dist == 256, "tr_static_init: dist != 256");
  24191. dist >>= 7; /* from now on, all distances are divided by 128 */
  24192. for (; code < D_CODES; code++) {
  24193. base_dist[code] = dist << 7;
  24194. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  24195. _dist_code[256 + dist++] = code;
  24196. }
  24197. }
  24198. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  24199. /* Construct the codes of the static literal tree */
  24200. for (bits = 0; bits <= MAX_BITS; bits++) {
  24201. bl_count[bits] = 0;
  24202. }
  24203. n = 0;
  24204. while (n <= 143) {
  24205. static_ltree[n*2 + 1]/*.Len*/ = 8;
  24206. n++;
  24207. bl_count[8]++;
  24208. }
  24209. while (n <= 255) {
  24210. static_ltree[n*2 + 1]/*.Len*/ = 9;
  24211. n++;
  24212. bl_count[9]++;
  24213. }
  24214. while (n <= 279) {
  24215. static_ltree[n*2 + 1]/*.Len*/ = 7;
  24216. n++;
  24217. bl_count[7]++;
  24218. }
  24219. while (n <= 287) {
  24220. static_ltree[n*2 + 1]/*.Len*/ = 8;
  24221. n++;
  24222. bl_count[8]++;
  24223. }
  24224. /* Codes 286 and 287 do not exist, but we must include them in the
  24225. * tree construction to get a canonical Huffman tree (longest code
  24226. * all ones)
  24227. */
  24228. gen_codes(static_ltree, L_CODES+1, bl_count);
  24229. /* The static distance tree is trivial: */
  24230. for (n = 0; n < D_CODES; n++) {
  24231. static_dtree[n*2 + 1]/*.Len*/ = 5;
  24232. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  24233. }
  24234. // Now data ready and we can init static trees
  24235. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  24236. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  24237. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  24238. //static_init_done = true;
  24239. }
  24240. /* ===========================================================================
  24241. * Initialize a new block.
  24242. */
  24243. function init_block(s) {
  24244. var n; /* iterates over tree elements */
  24245. /* Initialize the trees. */
  24246. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  24247. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  24248. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  24249. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  24250. s.opt_len = s.static_len = 0;
  24251. s.last_lit = s.matches = 0;
  24252. }
  24253. /* ===========================================================================
  24254. * Flush the bit buffer and align the output on a byte boundary
  24255. */
  24256. function bi_windup(s)
  24257. {
  24258. if (s.bi_valid > 8) {
  24259. put_short(s, s.bi_buf);
  24260. } else if (s.bi_valid > 0) {
  24261. //put_byte(s, (Byte)s->bi_buf);
  24262. s.pending_buf[s.pending++] = s.bi_buf;
  24263. }
  24264. s.bi_buf = 0;
  24265. s.bi_valid = 0;
  24266. }
  24267. /* ===========================================================================
  24268. * Copy a stored block, storing first the length and its
  24269. * one's complement if requested.
  24270. */
  24271. function copy_block(s, buf, len, header)
  24272. //DeflateState *s;
  24273. //charf *buf; /* the input data */
  24274. //unsigned len; /* its length */
  24275. //int header; /* true if block header must be written */
  24276. {
  24277. bi_windup(s); /* align on byte boundary */
  24278. if (header) {
  24279. put_short(s, len);
  24280. put_short(s, ~len);
  24281. }
  24282. // while (len--) {
  24283. // put_byte(s, *buf++);
  24284. // }
  24285. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  24286. s.pending += len;
  24287. }
  24288. /* ===========================================================================
  24289. * Compares to subtrees, using the tree depth as tie breaker when
  24290. * the subtrees have equal frequency. This minimizes the worst case length.
  24291. */
  24292. function smaller(tree, n, m, depth) {
  24293. var _n2 = n*2;
  24294. var _m2 = m*2;
  24295. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  24296. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  24297. }
  24298. /* ===========================================================================
  24299. * Restore the heap property by moving down the tree starting at node k,
  24300. * exchanging a node with the smallest of its two sons if necessary, stopping
  24301. * when the heap property is re-established (each father smaller than its
  24302. * two sons).
  24303. */
  24304. function pqdownheap(s, tree, k)
  24305. // deflate_state *s;
  24306. // ct_data *tree; /* the tree to restore */
  24307. // int k; /* node to move down */
  24308. {
  24309. var v = s.heap[k];
  24310. var j = k << 1; /* left son of k */
  24311. while (j <= s.heap_len) {
  24312. /* Set j to the smallest of the two sons: */
  24313. if (j < s.heap_len &&
  24314. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  24315. j++;
  24316. }
  24317. /* Exit if v is smaller than both sons */
  24318. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  24319. /* Exchange v with the smallest son */
  24320. s.heap[k] = s.heap[j];
  24321. k = j;
  24322. /* And continue down the tree, setting j to the left son of k */
  24323. j <<= 1;
  24324. }
  24325. s.heap[k] = v;
  24326. }
  24327. // inlined manually
  24328. // var SMALLEST = 1;
  24329. /* ===========================================================================
  24330. * Send the block data compressed using the given Huffman trees
  24331. */
  24332. function compress_block(s, ltree, dtree)
  24333. // deflate_state *s;
  24334. // const ct_data *ltree; /* literal tree */
  24335. // const ct_data *dtree; /* distance tree */
  24336. {
  24337. var dist; /* distance of matched string */
  24338. var lc; /* match length or unmatched char (if dist == 0) */
  24339. var lx = 0; /* running index in l_buf */
  24340. var code; /* the code to send */
  24341. var extra; /* number of extra bits to send */
  24342. if (s.last_lit !== 0) {
  24343. do {
  24344. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  24345. lc = s.pending_buf[s.l_buf + lx];
  24346. lx++;
  24347. if (dist === 0) {
  24348. send_code(s, lc, ltree); /* send a literal byte */
  24349. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  24350. } else {
  24351. /* Here, lc is the match length - MIN_MATCH */
  24352. code = _length_code[lc];
  24353. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  24354. extra = extra_lbits[code];
  24355. if (extra !== 0) {
  24356. lc -= base_length[code];
  24357. send_bits(s, lc, extra); /* send the extra length bits */
  24358. }
  24359. dist--; /* dist is now the match distance - 1 */
  24360. code = d_code(dist);
  24361. //Assert (code < D_CODES, "bad d_code");
  24362. send_code(s, code, dtree); /* send the distance code */
  24363. extra = extra_dbits[code];
  24364. if (extra !== 0) {
  24365. dist -= base_dist[code];
  24366. send_bits(s, dist, extra); /* send the extra distance bits */
  24367. }
  24368. } /* literal or match pair ? */
  24369. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  24370. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  24371. // "pendingBuf overflow");
  24372. } while (lx < s.last_lit);
  24373. }
  24374. send_code(s, END_BLOCK, ltree);
  24375. }
  24376. /* ===========================================================================
  24377. * Construct one Huffman tree and assigns the code bit strings and lengths.
  24378. * Update the total bit length for the current block.
  24379. * IN assertion: the field freq is set for all tree elements.
  24380. * OUT assertions: the fields len and code are set to the optimal bit length
  24381. * and corresponding code. The length opt_len is updated; static_len is
  24382. * also updated if stree is not null. The field max_code is set.
  24383. */
  24384. function build_tree(s, desc)
  24385. // deflate_state *s;
  24386. // tree_desc *desc; /* the tree descriptor */
  24387. {
  24388. var tree = desc.dyn_tree;
  24389. var stree = desc.stat_desc.static_tree;
  24390. var has_stree = desc.stat_desc.has_stree;
  24391. var elems = desc.stat_desc.elems;
  24392. var n, m; /* iterate over heap elements */
  24393. var max_code = -1; /* largest code with non zero frequency */
  24394. var node; /* new node being created */
  24395. /* Construct the initial heap, with least frequent element in
  24396. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  24397. * heap[0] is not used.
  24398. */
  24399. s.heap_len = 0;
  24400. s.heap_max = HEAP_SIZE;
  24401. for (n = 0; n < elems; n++) {
  24402. if (tree[n * 2]/*.Freq*/ !== 0) {
  24403. s.heap[++s.heap_len] = max_code = n;
  24404. s.depth[n] = 0;
  24405. } else {
  24406. tree[n*2 + 1]/*.Len*/ = 0;
  24407. }
  24408. }
  24409. /* The pkzip format requires that at least one distance code exists,
  24410. * and that at least one bit should be sent even if there is only one
  24411. * possible code. So to avoid special checks later on we force at least
  24412. * two codes of non zero frequency.
  24413. */
  24414. while (s.heap_len < 2) {
  24415. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  24416. tree[node * 2]/*.Freq*/ = 1;
  24417. s.depth[node] = 0;
  24418. s.opt_len--;
  24419. if (has_stree) {
  24420. s.static_len -= stree[node*2 + 1]/*.Len*/;
  24421. }
  24422. /* node is 0 or 1 so it does not have extra bits */
  24423. }
  24424. desc.max_code = max_code;
  24425. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  24426. * establish sub-heaps of increasing lengths:
  24427. */
  24428. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  24429. /* Construct the Huffman tree by repeatedly combining the least two
  24430. * frequent nodes.
  24431. */
  24432. node = elems; /* next internal node of the tree */
  24433. do {
  24434. //pqremove(s, tree, n); /* n = node of least frequency */
  24435. /*** pqremove ***/
  24436. n = s.heap[1/*SMALLEST*/];
  24437. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  24438. pqdownheap(s, tree, 1/*SMALLEST*/);
  24439. /***/
  24440. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  24441. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  24442. s.heap[--s.heap_max] = m;
  24443. /* Create a new node father of n and m */
  24444. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  24445. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  24446. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  24447. /* and insert the new node in the heap */
  24448. s.heap[1/*SMALLEST*/] = node++;
  24449. pqdownheap(s, tree, 1/*SMALLEST*/);
  24450. } while (s.heap_len >= 2);
  24451. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  24452. /* At this point, the fields freq and dad are set. We can now
  24453. * generate the bit lengths.
  24454. */
  24455. gen_bitlen(s, desc);
  24456. /* The field len is now set, we can generate the bit codes */
  24457. gen_codes(tree, max_code, s.bl_count);
  24458. }
  24459. /* ===========================================================================
  24460. * Scan a literal or distance tree to determine the frequencies of the codes
  24461. * in the bit length tree.
  24462. */
  24463. function scan_tree(s, tree, max_code)
  24464. // deflate_state *s;
  24465. // ct_data *tree; /* the tree to be scanned */
  24466. // int max_code; /* and its largest code of non zero frequency */
  24467. {
  24468. var n; /* iterates over all tree elements */
  24469. var prevlen = -1; /* last emitted length */
  24470. var curlen; /* length of current code */
  24471. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  24472. var count = 0; /* repeat count of the current code */
  24473. var max_count = 7; /* max repeat count */
  24474. var min_count = 4; /* min repeat count */
  24475. if (nextlen === 0) {
  24476. max_count = 138;
  24477. min_count = 3;
  24478. }
  24479. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  24480. for (n = 0; n <= max_code; n++) {
  24481. curlen = nextlen;
  24482. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  24483. if (++count < max_count && curlen === nextlen) {
  24484. continue;
  24485. } else if (count < min_count) {
  24486. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  24487. } else if (curlen !== 0) {
  24488. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  24489. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  24490. } else if (count <= 10) {
  24491. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  24492. } else {
  24493. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  24494. }
  24495. count = 0;
  24496. prevlen = curlen;
  24497. if (nextlen === 0) {
  24498. max_count = 138;
  24499. min_count = 3;
  24500. } else if (curlen === nextlen) {
  24501. max_count = 6;
  24502. min_count = 3;
  24503. } else {
  24504. max_count = 7;
  24505. min_count = 4;
  24506. }
  24507. }
  24508. }
  24509. /* ===========================================================================
  24510. * Send a literal or distance tree in compressed form, using the codes in
  24511. * bl_tree.
  24512. */
  24513. function send_tree(s, tree, max_code)
  24514. // deflate_state *s;
  24515. // ct_data *tree; /* the tree to be scanned */
  24516. // int max_code; /* and its largest code of non zero frequency */
  24517. {
  24518. var n; /* iterates over all tree elements */
  24519. var prevlen = -1; /* last emitted length */
  24520. var curlen; /* length of current code */
  24521. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  24522. var count = 0; /* repeat count of the current code */
  24523. var max_count = 7; /* max repeat count */
  24524. var min_count = 4; /* min repeat count */
  24525. /* tree[max_code+1].Len = -1; */ /* guard already set */
  24526. if (nextlen === 0) {
  24527. max_count = 138;
  24528. min_count = 3;
  24529. }
  24530. for (n = 0; n <= max_code; n++) {
  24531. curlen = nextlen;
  24532. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  24533. if (++count < max_count && curlen === nextlen) {
  24534. continue;
  24535. } else if (count < min_count) {
  24536. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  24537. } else if (curlen !== 0) {
  24538. if (curlen !== prevlen) {
  24539. send_code(s, curlen, s.bl_tree);
  24540. count--;
  24541. }
  24542. //Assert(count >= 3 && count <= 6, " 3_6?");
  24543. send_code(s, REP_3_6, s.bl_tree);
  24544. send_bits(s, count-3, 2);
  24545. } else if (count <= 10) {
  24546. send_code(s, REPZ_3_10, s.bl_tree);
  24547. send_bits(s, count-3, 3);
  24548. } else {
  24549. send_code(s, REPZ_11_138, s.bl_tree);
  24550. send_bits(s, count-11, 7);
  24551. }
  24552. count = 0;
  24553. prevlen = curlen;
  24554. if (nextlen === 0) {
  24555. max_count = 138;
  24556. min_count = 3;
  24557. } else if (curlen === nextlen) {
  24558. max_count = 6;
  24559. min_count = 3;
  24560. } else {
  24561. max_count = 7;
  24562. min_count = 4;
  24563. }
  24564. }
  24565. }
  24566. /* ===========================================================================
  24567. * Construct the Huffman tree for the bit lengths and return the index in
  24568. * bl_order of the last bit length code to send.
  24569. */
  24570. function build_bl_tree(s) {
  24571. var max_blindex; /* index of last bit length code of non zero freq */
  24572. /* Determine the bit length frequencies for literal and distance trees */
  24573. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  24574. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  24575. /* Build the bit length tree: */
  24576. build_tree(s, s.bl_desc);
  24577. /* opt_len now includes the length of the tree representations, except
  24578. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  24579. */
  24580. /* Determine the number of bit length codes to send. The pkzip format
  24581. * requires that at least 4 bit length codes be sent. (appnote.txt says
  24582. * 3 but the actual value used is 4.)
  24583. */
  24584. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  24585. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  24586. break;
  24587. }
  24588. }
  24589. /* Update opt_len to include the bit length tree and counts */
  24590. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  24591. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  24592. // s->opt_len, s->static_len));
  24593. return max_blindex;
  24594. }
  24595. /* ===========================================================================
  24596. * Send the header for a block using dynamic Huffman trees: the counts, the
  24597. * lengths of the bit length codes, the literal tree and the distance tree.
  24598. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  24599. */
  24600. function send_all_trees(s, lcodes, dcodes, blcodes)
  24601. // deflate_state *s;
  24602. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  24603. {
  24604. var rank; /* index in bl_order */
  24605. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  24606. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  24607. // "too many codes");
  24608. //Tracev((stderr, "\nbl counts: "));
  24609. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  24610. send_bits(s, dcodes-1, 5);
  24611. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  24612. for (rank = 0; rank < blcodes; rank++) {
  24613. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  24614. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  24615. }
  24616. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  24617. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  24618. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  24619. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  24620. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  24621. }
  24622. /* ===========================================================================
  24623. * Check if the data type is TEXT or BINARY, using the following algorithm:
  24624. * - TEXT if the two conditions below are satisfied:
  24625. * a) There are no non-portable control characters belonging to the
  24626. * "black list" (0..6, 14..25, 28..31).
  24627. * b) There is at least one printable character belonging to the
  24628. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  24629. * - BINARY otherwise.
  24630. * - The following partially-portable control characters form a
  24631. * "gray list" that is ignored in this detection algorithm:
  24632. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  24633. * IN assertion: the fields Freq of dyn_ltree are set.
  24634. */
  24635. function detect_data_type(s) {
  24636. /* black_mask is the bit mask of black-listed bytes
  24637. * set bits 0..6, 14..25, and 28..31
  24638. * 0xf3ffc07f = binary 11110011111111111100000001111111
  24639. */
  24640. var black_mask = 0xf3ffc07f;
  24641. var n;
  24642. /* Check for non-textual ("black-listed") bytes. */
  24643. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  24644. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  24645. return Z_BINARY;
  24646. }
  24647. }
  24648. /* Check for textual ("white-listed") bytes. */
  24649. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  24650. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  24651. return Z_TEXT;
  24652. }
  24653. for (n = 32; n < LITERALS; n++) {
  24654. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  24655. return Z_TEXT;
  24656. }
  24657. }
  24658. /* There are no "black-listed" or "white-listed" bytes:
  24659. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  24660. */
  24661. return Z_BINARY;
  24662. }
  24663. var static_init_done = false;
  24664. /* ===========================================================================
  24665. * Initialize the tree data structures for a new zlib stream.
  24666. */
  24667. function _tr_init(s)
  24668. {
  24669. if (!static_init_done) {
  24670. tr_static_init();
  24671. static_init_done = true;
  24672. }
  24673. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  24674. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  24675. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  24676. s.bi_buf = 0;
  24677. s.bi_valid = 0;
  24678. /* Initialize the first block of the first file: */
  24679. init_block(s);
  24680. }
  24681. /* ===========================================================================
  24682. * Send a stored block
  24683. */
  24684. function _tr_stored_block(s, buf, stored_len, last)
  24685. //DeflateState *s;
  24686. //charf *buf; /* input block */
  24687. //ulg stored_len; /* length of input block */
  24688. //int last; /* one if this is the last block for a file */
  24689. {
  24690. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  24691. copy_block(s, buf, stored_len, true); /* with header */
  24692. }
  24693. /* ===========================================================================
  24694. * Send one empty static block to give enough lookahead for inflate.
  24695. * This takes 10 bits, of which 7 may remain in the bit buffer.
  24696. */
  24697. function _tr_align(s) {
  24698. send_bits(s, STATIC_TREES<<1, 3);
  24699. send_code(s, END_BLOCK, static_ltree);
  24700. bi_flush(s);
  24701. }
  24702. /* ===========================================================================
  24703. * Determine the best encoding for the current block: dynamic trees, static
  24704. * trees or store, and output the encoded block to the zip file.
  24705. */
  24706. function _tr_flush_block(s, buf, stored_len, last)
  24707. //DeflateState *s;
  24708. //charf *buf; /* input block, or NULL if too old */
  24709. //ulg stored_len; /* length of input block */
  24710. //int last; /* one if this is the last block for a file */
  24711. {
  24712. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  24713. var max_blindex = 0; /* index of last bit length code of non zero freq */
  24714. /* Build the Huffman trees unless a stored block is forced */
  24715. if (s.level > 0) {
  24716. /* Check if the file is binary or text */
  24717. if (s.strm.data_type === Z_UNKNOWN) {
  24718. s.strm.data_type = detect_data_type(s);
  24719. }
  24720. /* Construct the literal and distance trees */
  24721. build_tree(s, s.l_desc);
  24722. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  24723. // s->static_len));
  24724. build_tree(s, s.d_desc);
  24725. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  24726. // s->static_len));
  24727. /* At this point, opt_len and static_len are the total bit lengths of
  24728. * the compressed block data, excluding the tree representations.
  24729. */
  24730. /* Build the bit length tree for the above two trees, and get the index
  24731. * in bl_order of the last bit length code to send.
  24732. */
  24733. max_blindex = build_bl_tree(s);
  24734. /* Determine the best encoding. Compute the block lengths in bytes. */
  24735. opt_lenb = (s.opt_len+3+7) >>> 3;
  24736. static_lenb = (s.static_len+3+7) >>> 3;
  24737. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  24738. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  24739. // s->last_lit));
  24740. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  24741. } else {
  24742. // Assert(buf != (char*)0, "lost buf");
  24743. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  24744. }
  24745. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  24746. /* 4: two words for the lengths */
  24747. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  24748. * Otherwise we can't have processed more than WSIZE input bytes since
  24749. * the last block flush, because compression would have been
  24750. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  24751. * transform a block into a stored block.
  24752. */
  24753. _tr_stored_block(s, buf, stored_len, last);
  24754. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  24755. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  24756. compress_block(s, static_ltree, static_dtree);
  24757. } else {
  24758. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  24759. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  24760. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  24761. }
  24762. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  24763. /* The above check is made mod 2^32, for files larger than 512 MB
  24764. * and uLong implemented on 32 bits.
  24765. */
  24766. init_block(s);
  24767. if (last) {
  24768. bi_windup(s);
  24769. }
  24770. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  24771. // s->compressed_len-7*last));
  24772. }
  24773. /* ===========================================================================
  24774. * Save the match info and tally the frequency counts. Return true if
  24775. * the current block must be flushed.
  24776. */
  24777. function _tr_tally(s, dist, lc)
  24778. // deflate_state *s;
  24779. // unsigned dist; /* distance of matched string */
  24780. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  24781. {
  24782. //var out_length, in_length, dcode;
  24783. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  24784. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  24785. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  24786. s.last_lit++;
  24787. if (dist === 0) {
  24788. /* lc is the unmatched char */
  24789. s.dyn_ltree[lc*2]/*.Freq*/++;
  24790. } else {
  24791. s.matches++;
  24792. /* Here, lc is the match length - MIN_MATCH */
  24793. dist--; /* dist = match distance - 1 */
  24794. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  24795. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  24796. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  24797. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  24798. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  24799. }
  24800. // (!) This block is disabled in zlib defailts,
  24801. // don't enable it for binary compatibility
  24802. //#ifdef TRUNCATE_BLOCK
  24803. // /* Try to guess if it is profitable to stop the current block here */
  24804. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  24805. // /* Compute an upper bound for the compressed length */
  24806. // out_length = s.last_lit*8;
  24807. // in_length = s.strstart - s.block_start;
  24808. //
  24809. // for (dcode = 0; dcode < D_CODES; dcode++) {
  24810. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  24811. // }
  24812. // out_length >>>= 3;
  24813. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  24814. // // s->last_lit, in_length, out_length,
  24815. // // 100L - out_length*100L/in_length));
  24816. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  24817. // return true;
  24818. // }
  24819. // }
  24820. //#endif
  24821. return (s.last_lit === s.lit_bufsize-1);
  24822. /* We avoid equality with lit_bufsize because of wraparound at 64K
  24823. * on 16 bit machines and because stored blocks are restricted to
  24824. * 64K-1 bytes.
  24825. */
  24826. }
  24827. exports._tr_init = _tr_init;
  24828. exports._tr_stored_block = _tr_stored_block;
  24829. exports._tr_flush_block = _tr_flush_block;
  24830. exports._tr_tally = _tr_tally;
  24831. exports._tr_align = _tr_align;
  24832. },{"../utils/common":72}],84:[function(require,module,exports){
  24833. 'use strict';
  24834. function ZStream() {
  24835. /* next input byte */
  24836. this.input = null; // JS specific, because we have no pointers
  24837. this.next_in = 0;
  24838. /* number of bytes available at input */
  24839. this.avail_in = 0;
  24840. /* total number of input bytes read so far */
  24841. this.total_in = 0;
  24842. /* next output byte should be put there */
  24843. this.output = null; // JS specific, because we have no pointers
  24844. this.next_out = 0;
  24845. /* remaining free space at output */
  24846. this.avail_out = 0;
  24847. /* total number of bytes output so far */
  24848. this.total_out = 0;
  24849. /* last error message, NULL if no error */
  24850. this.msg = ''/*Z_NULL*/;
  24851. /* not visible by applications */
  24852. this.state = null;
  24853. /* best guess about the data type: binary or text */
  24854. this.data_type = 2/*Z_UNKNOWN*/;
  24855. /* adler32 value of the uncompressed data */
  24856. this.adler = 0;
  24857. }
  24858. module.exports = ZStream;
  24859. },{}],85:[function(require,module,exports){
  24860. module.exports = require('./lib/retry');
  24861. },{"./lib/retry":86}],86:[function(require,module,exports){
  24862. var RetryOperation = require('./retry_operation');
  24863. exports.operation = function(options) {
  24864. var timeouts = exports.timeouts(options);
  24865. return new RetryOperation(timeouts);
  24866. };
  24867. exports.timeouts = function(options) {
  24868. if (options instanceof Array) {
  24869. return [].concat(options);
  24870. }
  24871. var opts = {
  24872. retries: 10,
  24873. factor: 2,
  24874. minTimeout: 1 * 1000,
  24875. maxTimeout: Infinity,
  24876. randomize: false
  24877. };
  24878. for (var key in options) {
  24879. opts[key] = options[key];
  24880. }
  24881. if (opts.minTimeout > opts.maxTimeout) {
  24882. throw new Error('minTimeout is greater than maxTimeout');
  24883. }
  24884. var timeouts = [];
  24885. for (var i = 0; i < opts.retries; i++) {
  24886. timeouts.push(this._createTimeout(i, opts));
  24887. }
  24888. // sort the array numerically ascending
  24889. timeouts.sort(function(a,b) {
  24890. return a - b;
  24891. });
  24892. return timeouts;
  24893. };
  24894. exports._createTimeout = function(attempt, opts) {
  24895. var random = (opts.randomize)
  24896. ? (Math.random() + 1)
  24897. : 1;
  24898. var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
  24899. timeout = Math.min(timeout, opts.maxTimeout);
  24900. return timeout;
  24901. };
  24902. },{"./retry_operation":87}],87:[function(require,module,exports){
  24903. function RetryOperation(timeouts) {
  24904. this._timeouts = timeouts;
  24905. this._fn = null;
  24906. this._errors = [];
  24907. this._attempts = 1;
  24908. this._operationTimeout = null;
  24909. this._operationTimeoutCb = null;
  24910. this._timeout = null;
  24911. }
  24912. module.exports = RetryOperation;
  24913. RetryOperation.prototype.retry = function(err) {
  24914. if (this._timeout) {
  24915. clearTimeout(this._timeout);
  24916. }
  24917. if (!err) {
  24918. return false;
  24919. }
  24920. this._errors.push(err);
  24921. var timeout = this._timeouts.shift();
  24922. if (timeout === undefined) {
  24923. return false;
  24924. }
  24925. this._attempts++;
  24926. var self = this;
  24927. setTimeout(function() {
  24928. self._fn(self._attempts);
  24929. if (self._operationTimeoutCb) {
  24930. self._timeout = setTimeout(function() {
  24931. self._operationTimeoutCb(self._attempts);
  24932. }, self._operationTimeout);
  24933. }
  24934. }, timeout);
  24935. return true;
  24936. };
  24937. RetryOperation.prototype.attempt = function(fn, timeoutOps) {
  24938. this._fn = fn;
  24939. if (timeoutOps) {
  24940. if (timeoutOps.timeout) {
  24941. this._operationTimeout = timeoutOps.timeout;
  24942. }
  24943. if (timeoutOps.cb) {
  24944. this._operationTimeoutCb = timeoutOps.cb;
  24945. }
  24946. }
  24947. this._fn(this._attempts);
  24948. var self = this;
  24949. if (this._operationTimeoutCb) {
  24950. this._timeout = setTimeout(function() {
  24951. self._operationTimeoutCb();
  24952. }, self._operationTimeout);
  24953. }
  24954. };
  24955. RetryOperation.prototype.try = function(fn) {
  24956. console.log('Using RetryOperation.try() is deprecated');
  24957. this.attempt(fn);
  24958. };
  24959. RetryOperation.prototype.start = function(fn) {
  24960. console.log('Using RetryOperation.start() is deprecated');
  24961. this.attempt(fn);
  24962. };
  24963. RetryOperation.prototype.start = RetryOperation.prototype.try;
  24964. RetryOperation.prototype.errors = function() {
  24965. return this._errors;
  24966. };
  24967. RetryOperation.prototype.attempts = function() {
  24968. return this._attempts;
  24969. };
  24970. RetryOperation.prototype.mainError = function() {
  24971. if (this._errors.length === 0) {
  24972. return null;
  24973. }
  24974. var counts = {};
  24975. var mainError = null;
  24976. var mainErrorCount = 0;
  24977. for (var i = 0; i < this._errors.length; i++) {
  24978. var error = this._errors[i];
  24979. var message = error.message;
  24980. var count = (counts[message] || 0) + 1;
  24981. counts[message] = count;
  24982. if (count >= mainErrorCount) {
  24983. mainError = error;
  24984. mainErrorCount = count;
  24985. }
  24986. }
  24987. return mainError;
  24988. };
  24989. },{}],88:[function(require,module,exports){
  24990. module.exports = function arrayEquals(array) {
  24991. // if the other array is a falsy value, return
  24992. if (!array)
  24993. return false;
  24994. // compare lengths - can save a lot of time
  24995. if (this.length != array.length)
  24996. return false;
  24997. for (var i = 0, l = this.length; i < l; i++) {
  24998. // Check if we have nested arrays
  24999. if (this[i] instanceof Array && array[i] instanceof Array) {
  25000. // recurse into the nested arrays
  25001. if (!arrayEquals.apply(this[i], [array[i]]))
  25002. return false;
  25003. } else if (this[i] != array[i]) {
  25004. // Warning - two different object instances will never be equal:
  25005. // {x:20} != {x:20}
  25006. return false;
  25007. }
  25008. }
  25009. return true;
  25010. }
  25011. },{}],89:[function(require,module,exports){
  25012. exports.Interop = require('./interop');
  25013. },{"./interop":90}],90:[function(require,module,exports){
  25014. "use strict";
  25015. var transform = require('./transform');
  25016. var arrayEquals = require('./array-equals');
  25017. function Interop() {
  25018. /**
  25019. * This map holds the most recent Unified Plan offer/answer SDP that was
  25020. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  25021. * the SDP string as values.
  25022. *
  25023. * @type {{}}
  25024. */
  25025. this.cache = {};
  25026. }
  25027. module.exports = Interop;
  25028. /**
  25029. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  25030. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  25031. * application.
  25032. *
  25033. * @param desc
  25034. * @returns {*}
  25035. */
  25036. Interop.prototype.toPlanB = function(desc) {
  25037. //#region Preliminary input validation.
  25038. if (typeof desc !== 'object' || desc === null ||
  25039. typeof desc.sdp !== 'string') {
  25040. console.warn('An empty description was passed as an argument.');
  25041. return desc;
  25042. }
  25043. // Objectify the SDP for easier manipulation.
  25044. var session = transform.parse(desc.sdp);
  25045. // If the SDP contains no media, there's nothing to transform.
  25046. if (typeof session.media === 'undefined' ||
  25047. !Array.isArray(session.media) || session.media.length === 0) {
  25048. console.warn('The description has no media.');
  25049. return desc;
  25050. }
  25051. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  25052. // SDP has a video, an audio and a data "channel" at most.
  25053. if (session.media.length <= 3 && session.media.every(function(m) {
  25054. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  25055. })) {
  25056. console.warn('This description does not look like Unified Plan.');
  25057. return desc;
  25058. }
  25059. //#endregion
  25060. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  25061. // -> Unified Plan transformation.
  25062. this.cache[desc.type] = desc.sdp;
  25063. //#region Convert from Unified Plan to Plan B.
  25064. // We rebuild the session.media array.
  25065. var media = session.media;
  25066. session.media = [];
  25067. // Associative array that maps channel types to channel objects for fast
  25068. // access to channel objects by their type, e.g. type2bl['audio']->channel
  25069. // obj.
  25070. var type2bl = {};
  25071. // Used to build the group:BUNDLE value after the channels construction
  25072. // loop.
  25073. var types = [];
  25074. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  25075. media.forEach(function(unifiedLine) {
  25076. // rtcp-mux is required in the Plan B SDP.
  25077. if ((typeof unifiedLine.rtcpMux !== 'string' ||
  25078. unifiedLine.rtcpMux !== 'rtcp-mux') &&
  25079. unifiedLine.direction !== 'inactive') {
  25080. throw new Error('Cannot convert to Plan B because m-lines ' +
  25081. 'without the rtcp-mux attribute were found.');
  25082. }
  25083. if (unifiedLine.type === 'application') {
  25084. session.media.push(unifiedLine);
  25085. types.push(unifiedLine.mid);
  25086. return;
  25087. }
  25088. // If we don't have a channel for this unifiedLine.type, then use this unifiedLine
  25089. // as the channel basis.
  25090. if (typeof type2bl[unifiedLine.type] === 'undefined') {
  25091. type2bl[unifiedLine.type] = unifiedLine;
  25092. }
  25093. // Add sources to the channel and handle a=msid.
  25094. if (typeof unifiedLine.sources === 'object') {
  25095. Object.keys(unifiedLine.sources).forEach(function(ssrc) {
  25096. if (typeof type2bl[unifiedLine.type].sources !== 'object')
  25097. type2bl[unifiedLine.type].sources = {};
  25098. // Assign the sources to the channel.
  25099. type2bl[unifiedLine.type].sources[ssrc] = unifiedLine.sources[ssrc];
  25100. if (typeof unifiedLine.msid !== 'undefined') {
  25101. // In Plan B the msid is an SSRC attribute. Also, we don't
  25102. // care about the obsolete label and mslabel attributes.
  25103. //
  25104. // Note that it is not guaranteed that the unifiedLine will have
  25105. // an msid. recvonly channels in particular don't have one.
  25106. type2bl[unifiedLine.type].sources[ssrc].msid = unifiedLine.msid;
  25107. }
  25108. // NOTE ssrcs in ssrc groups will share msids, as
  25109. // draft-uberti-rtcweb-plan-00 mandates.
  25110. });
  25111. }
  25112. // Add ssrc groups to the channel.
  25113. if (typeof unifiedLine.ssrcGroups !== 'undefined' &&
  25114. Array.isArray(unifiedLine.ssrcGroups)) {
  25115. // Create the ssrcGroups array, if it's not defined.
  25116. if (typeof type2bl[unifiedLine.type].ssrcGroups === 'undefined' ||
  25117. !Array.isArray(type2bl[unifiedLine.type].ssrcGroups)) {
  25118. type2bl[unifiedLine.type].ssrcGroups = [];
  25119. }
  25120. type2bl[unifiedLine.type].ssrcGroups = type2bl[unifiedLine.type].ssrcGroups.concat(unifiedLine.ssrcGroups);
  25121. }
  25122. if (type2bl[unifiedLine.type] === unifiedLine) {
  25123. // Copy ICE related stuff from the principal media line.
  25124. unifiedLine.candidates = media[0].candidates;
  25125. unifiedLine.iceUfrag = media[0].iceUfrag;
  25126. unifiedLine.icePwd = media[0].icePwd;
  25127. unifiedLine.fingerprint = media[0].fingerprint;
  25128. // Plan B mids are in ['audio', 'video', 'data']
  25129. unifiedLine.mid = unifiedLine.type;
  25130. // Plan B doesn't support/need the bundle-only attribute.
  25131. delete unifiedLine.bundleOnly;
  25132. // In Plan B the msid is an SSRC attribute.
  25133. delete unifiedLine.msid;
  25134. // Used to build the group:BUNDLE value after this loop.
  25135. types.push(unifiedLine.type);
  25136. // Add the channel to the new media array.
  25137. session.media.push(unifiedLine);
  25138. }
  25139. });
  25140. // We regenerate the BUNDLE group with the new mids.
  25141. session.groups.some(function(group) {
  25142. if (group.type === 'BUNDLE') {
  25143. group.mids = types.join(' ');
  25144. return true;
  25145. }
  25146. });
  25147. // msid semantic
  25148. session.msidSemantic = {
  25149. semantic: 'WMS',
  25150. token: '*'
  25151. };
  25152. var resStr = transform.write(session);
  25153. return new RTCSessionDescription({
  25154. type: desc.type,
  25155. sdp: resStr
  25156. });
  25157. //#endregion
  25158. };
  25159. /**
  25160. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  25161. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  25162. * to FF.
  25163. *
  25164. * @param desc
  25165. * @returns {*}
  25166. */
  25167. Interop.prototype.toUnifiedPlan = function(desc) {
  25168. //#region Preliminary input validation.
  25169. if (typeof desc !== 'object' || desc === null ||
  25170. typeof desc.sdp !== 'string') {
  25171. console.warn('An empty description was passed as an argument.');
  25172. return desc;
  25173. }
  25174. var session = transform.parse(desc.sdp);
  25175. // If the SDP contains no media, there's nothing to transform.
  25176. if (typeof session.media === 'undefined' ||
  25177. !Array.isArray(session.media) || session.media.length === 0) {
  25178. console.warn('The description has no media.');
  25179. return desc;
  25180. }
  25181. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  25182. // a video, an audio and a data "channel" at most.
  25183. if (session.media.length > 3 || !session.media.every(function(m) {
  25184. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  25185. })) {
  25186. console.warn('This description does not look like Plan B.');
  25187. return desc;
  25188. }
  25189. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  25190. var mids = [];
  25191. session.media.forEach(function(m) {
  25192. mids.push(m.mid);
  25193. });
  25194. var hasBundle = false;
  25195. if (typeof session.groups !== 'undefined' &&
  25196. Array.isArray(session.groups)) {
  25197. hasBundle = session.groups.every(function(g) {
  25198. return g.type !== 'BUNDLE' ||
  25199. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  25200. });
  25201. }
  25202. if (!hasBundle) {
  25203. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  25204. " are not bundled were found.");
  25205. }
  25206. //#endregion
  25207. //#region Convert from Plan B to Unified Plan.
  25208. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  25209. // rebuild an equivalent Unified Plan offer/answer.
  25210. //
  25211. // For example, if this is a local answer (in Unified Plan style) that we
  25212. // convert to Plan B prior to handing it over to the application (the
  25213. // PeerConnection wrapper called us, for instance, after a successful
  25214. // createAnswer), we want to remember the m-line at which we've seen the
  25215. // (local) SSRC. That's because when the application wants to do call the
  25216. // SLD method, forcing us to do the inverse transformation (from Plan B to
  25217. // Unified Plan), we need to know to which m-line to assign the (local)
  25218. // SSRC. We also need to know all the other m-lines that the original
  25219. // answer had and include them in the transformed answer as well.
  25220. //
  25221. // Another example is if this is a remote offer that we convert to Plan B
  25222. // prior to giving it to the application, we want to remember the mid at
  25223. // which we've seen the (remote) SSRC.
  25224. //
  25225. // In the iteration that follows, we use the cached Unified Plan (if it
  25226. // exists) to assign mids to ssrcs.
  25227. var cached;
  25228. if (typeof this.cache[desc.type] !== 'undefined') {
  25229. cached = transform.parse(this.cache[desc.type]);
  25230. }
  25231. // A helper map that sends mids to m-line objects. We use it later to
  25232. // rebuild the Unified Plan style session.media array.
  25233. var mid2ul = {};
  25234. session.media.forEach(function(bLine) {
  25235. if ((typeof bLine.rtcpMux !== 'string' ||
  25236. bLine.rtcpMux !== 'rtcp-mux') &&
  25237. bLine.direction !== 'inactive') {
  25238. throw new Error("Cannot convert to Unified Plan because m-lines " +
  25239. "without the rtcp-mux attribute were found.");
  25240. }
  25241. if (bLine.type === 'application') {
  25242. mid2ul[bLine.mid] = bLine;
  25243. return;
  25244. }
  25245. // With rtcp-mux and bundle all the channels should have the same ICE
  25246. // stuff.
  25247. var sources = bLine.sources;
  25248. var ssrcGroups = bLine.ssrcGroups;
  25249. var candidates = bLine.candidates;
  25250. var iceUfrag = bLine.iceUfrag;
  25251. var icePwd = bLine.icePwd;
  25252. var fingerprint = bLine.fingerprint;
  25253. var port = bLine.port;
  25254. // We'll use the "bLine" object as a prototype for each new "mLine"
  25255. // that we create, but first we need to clean it up a bit.
  25256. delete bLine.sources;
  25257. delete bLine.ssrcGroups;
  25258. delete bLine.candidates;
  25259. delete bLine.iceUfrag;
  25260. delete bLine.icePwd;
  25261. delete bLine.fingerprint;
  25262. delete bLine.port;
  25263. delete bLine.mid;
  25264. // inverted ssrc group map
  25265. var ssrc2group = {};
  25266. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  25267. ssrcGroups.forEach(function (ssrcGroup) {
  25268. // TODO(gp) find out how to receive simulcast with FF. For the
  25269. // time being, hide it.
  25270. if (ssrcGroup.semantics === 'SIM') {
  25271. return;
  25272. }
  25273. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  25274. Array.isArray(ssrcGroup.ssrcs)) {
  25275. ssrcGroup.ssrcs.forEach(function (ssrc) {
  25276. if (typeof ssrc2group[ssrc] === 'undefined') {
  25277. ssrc2group[ssrc] = [];
  25278. }
  25279. ssrc2group[ssrc].push(ssrcGroup);
  25280. });
  25281. }
  25282. });
  25283. }
  25284. // ssrc to m-line index.
  25285. var ssrc2ml = {};
  25286. if (typeof sources === 'object') {
  25287. // Explode the Plan B channel sources with one m-line per source.
  25288. Object.keys(sources).forEach(function(ssrc) {
  25289. // The (unified) m-line for this SSRC. We either create it from
  25290. // scratch or, if it's a grouped SSRC, we re-use a related
  25291. // mline. In other words, if the source is grouped with another
  25292. // source, put the two together in the same m-line.
  25293. var unifiedLine;
  25294. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  25295. Array.isArray(ssrc2group[ssrc])) {
  25296. ssrc2group[ssrc].some(function (ssrcGroup) {
  25297. // ssrcGroup.ssrcs *is* an Array, no need to check
  25298. // again here.
  25299. return ssrcGroup.ssrcs.some(function (related) {
  25300. if (typeof ssrc2ml[related] === 'object') {
  25301. unifiedLine = ssrc2ml[related];
  25302. return true;
  25303. }
  25304. });
  25305. });
  25306. }
  25307. if (typeof unifiedLine === 'object') {
  25308. // the m-line already exists. Just add the source.
  25309. unifiedLine.sources[ssrc] = sources[ssrc];
  25310. delete sources[ssrc].msid;
  25311. } else {
  25312. // Use the "bLine" as a prototype for the "unifiedLine".
  25313. unifiedLine = Object.create(bLine);
  25314. ssrc2ml[ssrc] = unifiedLine;
  25315. if (typeof sources[ssrc].msid !== 'undefined') {
  25316. // Assign the msid of the source to the m-line. Note
  25317. // that it is not guaranteed that the source will have
  25318. // msid. In particular "recvonly" sources don't have an
  25319. // msid. Note that "recvonly" is a term only defined
  25320. // for m-lines.
  25321. unifiedLine.msid = sources[ssrc].msid;
  25322. delete sources[ssrc].msid;
  25323. }
  25324. // We assign one SSRC per media line.
  25325. unifiedLine.sources = {};
  25326. unifiedLine.sources[ssrc] = sources[ssrc];
  25327. unifiedLine.ssrcGroups = ssrc2group[ssrc];
  25328. // Use the cached Unified Plan SDP (if it exists) to assign
  25329. // SSRCs to mids.
  25330. if (typeof cached !== 'undefined' &&
  25331. typeof cached.media !== 'undefined' &&
  25332. Array.isArray(cached.media)) {
  25333. cached.media.forEach(function (m) {
  25334. if (typeof m.sources === 'object') {
  25335. Object.keys(m.sources).forEach(function (s) {
  25336. if (s === ssrc) {
  25337. unifiedLine.mid = m.mid;
  25338. }
  25339. });
  25340. }
  25341. });
  25342. }
  25343. if (typeof unifiedLine.mid === 'undefined') {
  25344. // If this is an SSRC that we see for the first time
  25345. // assign it a new mid. This is typically the case when
  25346. // this method is called to transform a remote
  25347. // description for the first time or when there is a
  25348. // new SSRC in the remote description because a new
  25349. // peer has joined the conference. Local SSRCs should
  25350. // have already been added to the map in the toPlanB
  25351. // method.
  25352. //
  25353. // Because FF generates answers in Unified Plan style,
  25354. // we MUST already have a cached answer with all the
  25355. // local SSRCs mapped to some m-line/mid.
  25356. if (desc.type === 'answer') {
  25357. throw new Error("An unmapped SSRC was found.");
  25358. }
  25359. unifiedLine.mid = [bLine.type, '-', ssrc].join('');
  25360. }
  25361. // Include the candidates in the 1st media line.
  25362. unifiedLine.candidates = candidates;
  25363. unifiedLine.iceUfrag = iceUfrag;
  25364. unifiedLine.icePwd = icePwd;
  25365. unifiedLine.fingerprint = fingerprint;
  25366. unifiedLine.port = port;
  25367. mid2ul[unifiedLine.mid] = unifiedLine;
  25368. }
  25369. });
  25370. }
  25371. });
  25372. // Rebuild the media array in the right order and add the missing mLines
  25373. // (missing from the Plan B SDP).
  25374. session.media = [];
  25375. mids = []; // reuse
  25376. if (desc.type === 'answer') {
  25377. // The media lines in the answer must match the media lines in the
  25378. // offer. The order is important too. Here we assume that Firefox is the
  25379. // answerer, so we merely have to use the reconstructed (unified) answer
  25380. // to update the cached (unified) answer accordingly.
  25381. //
  25382. // In the general case, one would have to use the cached (unified) offer
  25383. // to find the m-lines that are missing from the reconstructed answer,
  25384. // potentially grabbing them from the cached (unified) answer. One has
  25385. // to be carefull with this approach because inactive m-lines do not
  25386. // always have an mid, making it tricky (impossible?) to find where
  25387. // exactly and which m-lines are missing from the reconstructed answer.
  25388. for (var i = 0; i < cached.media.length; i++) {
  25389. var unifiedLine = cached.media[i];
  25390. if (typeof mid2ul[unifiedLine.mid] === 'undefined') {
  25391. // The mid isn't in the reconstructed (unified) answer.
  25392. // This is either a (unified) m-line containing a remote
  25393. // track only, or a (unified) m-line containing a remote
  25394. // track and a local track that has been removed.
  25395. // In either case, it MUST exist in the cached
  25396. // (unified) answer.
  25397. //
  25398. // In case this is a removed local track, clean-up
  25399. // the (unified) m-line and make sure it's 'recvonly' or
  25400. // 'inactive'.
  25401. delete unifiedLine.msid;
  25402. delete unifiedLine.sources;
  25403. delete unifiedLine.ssrcGroups;
  25404. if (!unifiedLine.direction
  25405. || unifiedLine.direction === 'sendrecv')
  25406. unifiedLine.direction = 'recvonly';
  25407. if (!unifiedLine.direction
  25408. || unifiedLine.direction === 'sendonly')
  25409. unifiedLine.direction = 'inactive';
  25410. } else {
  25411. // This is an (unified) m-line/channel that contains a local
  25412. // track (sendrecv or sendonly channel) or it's a unified
  25413. // recvonly m-line/channel. In either case, since we're
  25414. // going from PlanB -> Unified Plan this m-line MUST
  25415. // exist in the cached answer.
  25416. }
  25417. session.media.push(unifiedLine);
  25418. if (typeof unifiedLine.mid === 'string') {
  25419. // inactive lines don't/may not have an mid.
  25420. mids.push(unifiedLine.mid);
  25421. }
  25422. }
  25423. } else {
  25424. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  25425. // under any circumstances. If we are no longer interested in sending a
  25426. // track, we just remove the msid and ssrc attributes and set it to
  25427. // either a=recvonly (as the reofferer, we must use recvonly if the
  25428. // other side was previously sending on the m-section, but we can also
  25429. // leave the possibility open if it wasn't previously in use), or
  25430. // a=inacive.
  25431. if (typeof cached !== 'undefined' &&
  25432. typeof cached.media !== 'undefined' &&
  25433. Array.isArray(cached.media)) {
  25434. cached.media.forEach(function(unifiedLine) {
  25435. mids.push(unifiedLine.mid);
  25436. if (typeof mid2ul[unifiedLine.mid] !== 'undefined') {
  25437. session.media.push(mid2ul[unifiedLine.mid]);
  25438. } else {
  25439. delete unifiedLine.msid;
  25440. delete unifiedLine.sources;
  25441. delete unifiedLine.ssrcGroups;
  25442. if (!unifiedLine.direction
  25443. || unifiedLine.direction === 'sendrecv')
  25444. unifiedLine.direction = 'recvonly';
  25445. if (!unifiedLine.direction
  25446. || unifiedLine.direction === 'sendonly')
  25447. unifiedLine.direction = 'inactive';
  25448. session.media.push(unifiedLine);
  25449. }
  25450. });
  25451. }
  25452. // Add all the remaining (new) m-lines of the transformed SDP.
  25453. Object.keys(mid2ul).forEach(function(mid) {
  25454. if (mids.indexOf(mid) === -1) {
  25455. mids.push(mid);
  25456. if (typeof mid2ul[mid].direction === 'recvonly') {
  25457. // This is a remote recvonly channel. Add its SSRC to the
  25458. // appropriate sendrecv or sendonly channel.
  25459. // TODO(gp) what if we don't have sendrecv/sendonly channel?
  25460. session.media.some(function (unifiedLine) {
  25461. if ((unifiedLine.direction === 'sendrecv' ||
  25462. unifiedLine.direction === 'sendonly') &&
  25463. unifiedLine.type === mid2ul[mid].type) {
  25464. // mid2ul[mid] shouldn't have any ssrc-groups
  25465. Object.keys(mid2ul[mid].sources).forEach(function (ssrc) {
  25466. unifiedLine.sources[ssrc] = mid2ul[mid].sources[ssrc];
  25467. });
  25468. return true;
  25469. }
  25470. });
  25471. } else {
  25472. session.media.push(mid2ul[mid]);
  25473. }
  25474. }
  25475. });
  25476. }
  25477. // We regenerate the BUNDLE group (since we regenerated the mids)
  25478. session.groups.some(function(group) {
  25479. if (group.type === 'BUNDLE') {
  25480. group.mids = mids.join(' ');
  25481. return true;
  25482. }
  25483. });
  25484. // msid semantic
  25485. session.msidSemantic = {
  25486. semantic: 'WMS',
  25487. token: '*'
  25488. };
  25489. var resStr = transform.write(session);
  25490. // Cache the transformed SDP (Unified Plan) for later re-use in this
  25491. // function.
  25492. this.cache[desc.type] = resStr;
  25493. return new RTCSessionDescription({
  25494. type: desc.type,
  25495. sdp: resStr
  25496. });
  25497. //#endregion
  25498. };
  25499. },{"./array-equals":88,"./transform":91}],91:[function(require,module,exports){
  25500. var transform = require('sdp-transform');
  25501. exports.write = function(session, opts) {
  25502. if (typeof session !== 'undefined' &&
  25503. typeof session.media !== 'undefined' &&
  25504. Array.isArray(session.media)) {
  25505. session.media.forEach(function (mLine) {
  25506. // expand sources to ssrcs
  25507. if (typeof mLine.sources !== 'undefined' &&
  25508. Object.keys(mLine.sources).length !== 0) {
  25509. mLine.ssrcs = [];
  25510. Object.keys(mLine.sources).forEach(function (ssrc) {
  25511. var source = mLine.sources[ssrc];
  25512. Object.keys(source).forEach(function (attribute) {
  25513. mLine.ssrcs.push({
  25514. id: ssrc,
  25515. attribute: attribute,
  25516. value: source[attribute]
  25517. });
  25518. });
  25519. });
  25520. delete mLine.sources;
  25521. }
  25522. // join ssrcs in ssrc groups
  25523. if (typeof mLine.ssrcGroups !== 'undefined' &&
  25524. Array.isArray(mLine.ssrcGroups)) {
  25525. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  25526. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  25527. Array.isArray(ssrcGroup.ssrcs)) {
  25528. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  25529. }
  25530. });
  25531. }
  25532. });
  25533. }
  25534. // join group mids
  25535. if (typeof session !== 'undefined' &&
  25536. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  25537. session.groups.forEach(function (g) {
  25538. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  25539. g.mids = g.mids.join(' ');
  25540. }
  25541. });
  25542. }
  25543. return transform.write(session, opts);
  25544. };
  25545. exports.parse = function(sdp) {
  25546. var session = transform.parse(sdp);
  25547. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  25548. Array.isArray(session.media)) {
  25549. session.media.forEach(function (mLine) {
  25550. // group sources attributes by ssrc
  25551. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  25552. mLine.sources = {};
  25553. mLine.ssrcs.forEach(function (ssrc) {
  25554. if (!mLine.sources[ssrc.id])
  25555. mLine.sources[ssrc.id] = {};
  25556. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  25557. });
  25558. delete mLine.ssrcs;
  25559. }
  25560. // split ssrcs in ssrc groups
  25561. if (typeof mLine.ssrcGroups !== 'undefined' &&
  25562. Array.isArray(mLine.ssrcGroups)) {
  25563. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  25564. if (typeof ssrcGroup.ssrcs === 'string') {
  25565. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  25566. }
  25567. });
  25568. }
  25569. });
  25570. }
  25571. // split group mids
  25572. if (typeof session !== 'undefined' &&
  25573. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  25574. session.groups.forEach(function (g) {
  25575. if (typeof g.mids === 'string') {
  25576. g.mids = g.mids.split(' ');
  25577. }
  25578. });
  25579. }
  25580. return session;
  25581. };
  25582. },{"sdp-transform":95}],92:[function(require,module,exports){
  25583. var transform = require('sdp-transform');
  25584. var transformUtils = require('./transform-utils');
  25585. var parseSsrcs = transformUtils.parseSsrcs;
  25586. var writeSsrcs = transformUtils.writeSsrcs;
  25587. //region Constants
  25588. var DEFAULT_NUM_OF_LAYERS = 3;
  25589. //endregion
  25590. //region Ctor
  25591. function Simulcast(options) {
  25592. this.options = options ? options : {};
  25593. if (!this.options.numOfLayers) {
  25594. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  25595. }
  25596. this.layers = [];
  25597. }
  25598. //endregion
  25599. //region Stateless private utility functions
  25600. /**
  25601. * Returns a random integer between min (included) and max (excluded)
  25602. * Using Math.round() gives a non-uniform distribution!
  25603. * @returns {number}
  25604. */
  25605. function generateSSRC() {
  25606. var min = 0, max = 0xffffffff;
  25607. return Math.floor(Math.random() * (max - min)) + min;
  25608. };
  25609. function processVideo(session, action) {
  25610. if (session == null || !Array.isArray(session.media)) {
  25611. return;
  25612. }
  25613. session.media.forEach(function (mLine) {
  25614. if (mLine.type === 'video') {
  25615. action(mLine);
  25616. }
  25617. });
  25618. }
  25619. function validateDescription(desc)
  25620. {
  25621. return desc && desc != null
  25622. && desc.type && desc.type != ''
  25623. && desc.sdp && desc.sdp != '';
  25624. }
  25625. function explodeRemoteSimulcast(mLine) {
  25626. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  25627. return;
  25628. }
  25629. var sources = parseSsrcs(mLine);
  25630. var order = [];
  25631. // Find the SIM group and explode its sources.
  25632. var j = mLine.ssrcGroups.length;
  25633. while (j--) {
  25634. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  25635. continue;
  25636. }
  25637. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  25638. for (var i = 0; i < simulcastSsrcs.length; i++) {
  25639. var ssrc = simulcastSsrcs[i];
  25640. order.push(ssrc);
  25641. var parts = sources[ssrc].msid.split(' ');
  25642. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  25643. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  25644. // Remove all the groups that this SSRC participates in.
  25645. mLine.ssrcGroups.forEach(function (relatedGroup) {
  25646. if (relatedGroup.semantics === 'SIM') {
  25647. return;
  25648. }
  25649. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  25650. if (relatedSsrcs.indexOf(ssrc) === -1) {
  25651. return;
  25652. }
  25653. // Nuke all the related SSRCs.
  25654. relatedSsrcs.forEach(function (relatedSSRC) {
  25655. sources[relatedSSRC].msid = sources[ssrc].msid;
  25656. sources[relatedSSRC].cname = sources[ssrc].cname;
  25657. if (relatedSSRC !== ssrc) {
  25658. order.push(relatedSSRC);
  25659. }
  25660. });
  25661. // Schedule the related group for nuking.
  25662. })
  25663. }
  25664. mLine.ssrcs = writeSsrcs(sources, order);
  25665. mLine.ssrcGroups.splice(j, 1);
  25666. };
  25667. }
  25668. function squeezeRemoteSimulcast(mLine) {
  25669. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  25670. return;
  25671. }
  25672. var sources = parseSsrcs(mLine);
  25673. // Find the SIM group and nuke it.
  25674. mLine.ssrcGroups.some(function (simulcastGroup) {
  25675. if (simulcastGroup.semantics !== 'SIM') {
  25676. return false;
  25677. }
  25678. // Schedule the SIM group for nuking.
  25679. simulcastGroup.nuke = true;
  25680. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  25681. // Nuke all the higher layer SSRCs.
  25682. for (var i = 1; i < simulcastSsrcs.length; i++) {
  25683. var ssrc = simulcastSsrcs[i];
  25684. delete sources[ssrc];
  25685. // Remove all the groups that this SSRC participates in.
  25686. mLine.ssrcGroups.forEach(function (relatedGroup) {
  25687. if (relatedGroup.semantics === 'SIM') {
  25688. return;
  25689. }
  25690. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  25691. if (relatedSsrcs.indexOf(ssrc) === -1) {
  25692. return;
  25693. }
  25694. // Nuke all the related SSRCs.
  25695. relatedSsrcs.forEach(function (relatedSSRC) {
  25696. delete sources[relatedSSRC];
  25697. });
  25698. // Schedule the related group for nuking.
  25699. relatedGroup.nuke = true;
  25700. })
  25701. }
  25702. return true;
  25703. });
  25704. mLine.ssrcs = writeSsrcs(sources);
  25705. // Nuke all the scheduled groups.
  25706. var i = mLine.ssrcGroups.length;
  25707. while (i--) {
  25708. if (mLine.ssrcGroups[i].nuke) {
  25709. mLine.ssrcGroups.splice(i, 1);
  25710. }
  25711. }
  25712. }
  25713. function removeGoogConference(mLine) {
  25714. if (!mLine || !Array.isArray(mLine.invalid)) {
  25715. return;
  25716. }
  25717. var i = mLine.invalid.length;
  25718. while (i--) {
  25719. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  25720. mLine.invalid.splice(i, 1);
  25721. }
  25722. }
  25723. }
  25724. function assertGoogConference(mLine) {
  25725. if (!mLine) {
  25726. return;
  25727. }
  25728. if (!Array.isArray(mLine.invalid)) {
  25729. mLine.invalid = [];
  25730. }
  25731. if (!mLine.invalid.some(
  25732. function (i) { return i.value === 'x-google-flag:conference' })) {
  25733. mLine.invalid.push({'value': 'x-google-flag:conference'});
  25734. }
  25735. }
  25736. //endregion
  25737. //region "Private" functions
  25738. /**
  25739. *
  25740. * @param mLine
  25741. * @private
  25742. */
  25743. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  25744. if (!mLine || mLine.type !== 'video') {
  25745. return;
  25746. }
  25747. var sources = parseSsrcs(mLine);
  25748. if (Object.keys(sources).length === 0) {
  25749. // no sources, disable simulcast.
  25750. if (this.layers.length !== 0) {
  25751. this.layers = [];
  25752. }
  25753. return;
  25754. }
  25755. // find the base layer (we'll reuse its msid and cname).
  25756. var baseLayerSSRC = Object.keys(sources)[0];
  25757. var baseLayer = sources[baseLayerSSRC];
  25758. // todo(gp) handle screen sharing.
  25759. // check if base CNAME has changed and reinitialise layers.
  25760. if (this.layers.length > 0
  25761. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  25762. this.layers = [];
  25763. }
  25764. // (re)initialise layers
  25765. if (this.layers.length < 1) {
  25766. // first push the base layer.
  25767. this.layers.push({
  25768. ssrc: baseLayerSSRC,
  25769. msid: baseLayer.msid,
  25770. cname: baseLayer.cname
  25771. });
  25772. var rtx = false; // RFC 4588
  25773. if (Array.isArray(mLine.rtp)) {
  25774. rtx = mLine.rtp.some(
  25775. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  25776. }
  25777. if (rtx) {
  25778. this.layers[0].rtx = generateSSRC();
  25779. }
  25780. // now push additional layers.
  25781. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  25782. var layer = { ssrc: generateSSRC() };
  25783. if (rtx) {
  25784. layer.rtx = generateSSRC();
  25785. }
  25786. this.layers.push(layer);
  25787. }
  25788. }
  25789. };
  25790. /**
  25791. *
  25792. * @param mLine
  25793. * @private
  25794. */
  25795. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  25796. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  25797. var sources = {};
  25798. var msid = this.layers[0].msid;
  25799. var cname = this.layers[0].cname;
  25800. var simulcastSsrcs = [];
  25801. var ssrcGroups = [];
  25802. for (var i = 0; i < this.layers.length; i++) {
  25803. var layer = this.layers[i];
  25804. sources[layer.ssrc] = { msid: msid, cname: cname };
  25805. simulcastSsrcs.push(layer.ssrc);
  25806. if (layer.rtx) {
  25807. sources[layer.rtx] = {
  25808. msid: msid,
  25809. cname: cname
  25810. }
  25811. ssrcGroups.push({
  25812. semantics: 'FID',
  25813. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  25814. });
  25815. }
  25816. }
  25817. ssrcGroups.push({
  25818. semantics: 'SIM',
  25819. ssrcs: simulcastSsrcs.join(' ')
  25820. });
  25821. mLine.ssrcGroups = ssrcGroups;
  25822. mLine.ssrcs = writeSsrcs(sources);
  25823. }
  25824. }
  25825. //endregion
  25826. //region "Public" functions
  25827. Simulcast.prototype.isSupported = function () {
  25828. return window.chrome;
  25829. // TODO this needs improvements. For example I doubt that Chrome in Android
  25830. // has simulcast support. Also, only recent versions of Chromium have native
  25831. // simulcast support.
  25832. }
  25833. /**
  25834. *
  25835. * @param desc
  25836. * @returns {RTCSessionDescription}
  25837. */
  25838. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  25839. if (!validateDescription(desc)) {
  25840. return desc;
  25841. }
  25842. var session = transform.parse(desc.sdp);
  25843. var self = this;
  25844. processVideo(session, function (mLine) {
  25845. // Handle simulcast reception.
  25846. if (self.options.explodeRemoteSimulcast) {
  25847. explodeRemoteSimulcast(mLine);
  25848. } else {
  25849. squeezeRemoteSimulcast(mLine);
  25850. }
  25851. // If native simulcast is enabled, we must append the x-goog-conference
  25852. // attribute to the SDP.
  25853. if (self.layers.length < 1) {
  25854. removeGoogConference(mLine);
  25855. } else {
  25856. assertGoogConference(mLine);
  25857. }
  25858. });
  25859. return new RTCSessionDescription({
  25860. type: desc.type,
  25861. sdp: transform.write(session)
  25862. });
  25863. };
  25864. /**
  25865. *
  25866. * @param desc
  25867. * @returns {RTCSessionDescription}
  25868. */
  25869. Simulcast.prototype.mungeLocalDescription = function (desc) {
  25870. if (!validateDescription(desc) || !this.isSupported()) {
  25871. return desc;
  25872. }
  25873. var session = transform.parse(desc.sdp);
  25874. var self = this;
  25875. processVideo(session, function (mLine) {
  25876. // Initialize native simulcast layers, if not already done.
  25877. self._maybeInitializeLayers(mLine);
  25878. // Update the SDP with the simulcast layers.
  25879. self._restoreSimulcastView(mLine);
  25880. });
  25881. return new RTCSessionDescription({
  25882. type: desc.type,
  25883. sdp: transform.write(session)
  25884. });
  25885. };
  25886. //endregion
  25887. module.exports = Simulcast;
  25888. },{"./transform-utils":93,"sdp-transform":95}],93:[function(require,module,exports){
  25889. exports.writeSsrcs = function(sources, order) {
  25890. var ssrcs = [];
  25891. // expand sources to ssrcs
  25892. if (typeof sources !== 'undefined' &&
  25893. Object.keys(sources).length !== 0) {
  25894. if (Array.isArray(order)) {
  25895. for (var i = 0; i < order.length; i++) {
  25896. var ssrc = order[i];
  25897. var source = sources[ssrc];
  25898. Object.keys(source).forEach(function (attribute) {
  25899. ssrcs.push({
  25900. id: ssrc,
  25901. attribute: attribute,
  25902. value: source[attribute]
  25903. });
  25904. });
  25905. }
  25906. } else {
  25907. Object.keys(sources).forEach(function (ssrc) {
  25908. var source = sources[ssrc];
  25909. Object.keys(source).forEach(function (attribute) {
  25910. ssrcs.push({
  25911. id: ssrc,
  25912. attribute: attribute,
  25913. value: source[attribute]
  25914. });
  25915. });
  25916. });
  25917. }
  25918. }
  25919. return ssrcs;
  25920. };
  25921. exports.parseSsrcs = function (mLine) {
  25922. var sources = {};
  25923. // group sources attributes by ssrc.
  25924. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  25925. mLine.ssrcs.forEach(function (ssrc) {
  25926. if (!sources[ssrc.id])
  25927. sources[ssrc.id] = {};
  25928. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  25929. });
  25930. }
  25931. return sources;
  25932. };
  25933. },{}],94:[function(require,module,exports){
  25934. var grammar = module.exports = {
  25935. v: [{
  25936. name: 'version',
  25937. reg: /^(\d*)$/
  25938. }],
  25939. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  25940. // NB: sessionId will be a String in most cases because it is huge
  25941. name: 'origin',
  25942. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  25943. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  25944. format: "%s %s %d %s IP%d %s"
  25945. }],
  25946. // default parsing of these only (though some of these feel outdated)
  25947. s: [{ name: 'name' }],
  25948. i: [{ name: 'description' }],
  25949. u: [{ name: 'uri' }],
  25950. e: [{ name: 'email' }],
  25951. p: [{ name: 'phone' }],
  25952. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  25953. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  25954. //k: [{}], // outdated thing ignored
  25955. t: [{ //t=0 0
  25956. name: 'timing',
  25957. reg: /^(\d*) (\d*)/,
  25958. names: ['start', 'stop'],
  25959. format: "%d %d"
  25960. }],
  25961. c: [{ //c=IN IP4 10.47.197.26
  25962. name: 'connection',
  25963. reg: /^IN IP(\d) (\S*)/,
  25964. names: ['version', 'ip'],
  25965. format: "IN IP%d %s"
  25966. }],
  25967. b: [{ //b=AS:4000
  25968. push: 'bandwidth',
  25969. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  25970. names: ['type', 'limit'],
  25971. format: "%s:%s"
  25972. }],
  25973. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  25974. // NB: special - pushes to session
  25975. // TODO: rtp/fmtp should be filtered by the payloads found here?
  25976. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  25977. names: ['type', 'port', 'protocol', 'payloads'],
  25978. format: "%s %d %s %s"
  25979. }],
  25980. a: [
  25981. { //a=rtpmap:110 opus/48000/2
  25982. push: 'rtp',
  25983. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  25984. names: ['payload', 'codec', 'rate', 'encoding'],
  25985. format: function (o) {
  25986. return (o.encoding) ?
  25987. "rtpmap:%d %s/%s/%s":
  25988. "rtpmap:%d %s/%s";
  25989. }
  25990. },
  25991. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  25992. push: 'fmtp',
  25993. reg: /^fmtp:(\d*) (\S*)/,
  25994. names: ['payload', 'config'],
  25995. format: "fmtp:%d %s"
  25996. },
  25997. { //a=control:streamid=0
  25998. name: 'control',
  25999. reg: /^control:(.*)/,
  26000. format: "control:%s"
  26001. },
  26002. { //a=rtcp:65179 IN IP4 193.84.77.194
  26003. name: 'rtcp',
  26004. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  26005. names: ['port', 'netType', 'ipVer', 'address'],
  26006. format: function (o) {
  26007. return (o.address != null) ?
  26008. "rtcp:%d %s IP%d %s":
  26009. "rtcp:%d";
  26010. }
  26011. },
  26012. { //a=rtcp-fb:98 trr-int 100
  26013. push: 'rtcpFbTrrInt',
  26014. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  26015. names: ['payload', 'value'],
  26016. format: "rtcp-fb:%d trr-int %d"
  26017. },
  26018. { //a=rtcp-fb:98 nack rpsi
  26019. push: 'rtcpFb',
  26020. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  26021. names: ['payload', 'type', 'subtype'],
  26022. format: function (o) {
  26023. return (o.subtype != null) ?
  26024. "rtcp-fb:%s %s %s":
  26025. "rtcp-fb:%s %s";
  26026. }
  26027. },
  26028. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  26029. //a=extmap:1/recvonly URI-gps-string
  26030. push: 'ext',
  26031. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  26032. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  26033. format: function (o) {
  26034. return (o.config != null) ?
  26035. "extmap:%s %s %s":
  26036. "extmap:%s %s";
  26037. }
  26038. },
  26039. {
  26040. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  26041. push: 'crypto',
  26042. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  26043. names: ['id', 'suite', 'config', 'sessionConfig'],
  26044. format: function (o) {
  26045. return (o.sessionConfig != null) ?
  26046. "crypto:%d %s %s %s":
  26047. "crypto:%d %s %s";
  26048. }
  26049. },
  26050. { //a=setup:actpass
  26051. name: 'setup',
  26052. reg: /^setup:(\w*)/,
  26053. format: "setup:%s"
  26054. },
  26055. { //a=mid:1
  26056. name: 'mid',
  26057. reg: /^mid:([^\s]*)/,
  26058. format: "mid:%s"
  26059. },
  26060. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  26061. name: 'msid',
  26062. reg: /^msid:(.*)/,
  26063. format: "msid:%s"
  26064. },
  26065. { //a=ptime:20
  26066. name: 'ptime',
  26067. reg: /^ptime:(\d*)/,
  26068. format: "ptime:%d"
  26069. },
  26070. { //a=maxptime:60
  26071. name: 'maxptime',
  26072. reg: /^maxptime:(\d*)/,
  26073. format: "maxptime:%d"
  26074. },
  26075. { //a=sendrecv
  26076. name: 'direction',
  26077. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  26078. },
  26079. { //a=ice-lite
  26080. name: 'icelite',
  26081. reg: /^(ice-lite)/
  26082. },
  26083. { //a=ice-ufrag:F7gI
  26084. name: 'iceUfrag',
  26085. reg: /^ice-ufrag:(\S*)/,
  26086. format: "ice-ufrag:%s"
  26087. },
  26088. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  26089. name: 'icePwd',
  26090. reg: /^ice-pwd:(\S*)/,
  26091. format: "ice-pwd:%s"
  26092. },
  26093. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  26094. name: 'fingerprint',
  26095. reg: /^fingerprint:(\S*) (\S*)/,
  26096. names: ['type', 'hash'],
  26097. format: "fingerprint:%s %s"
  26098. },
  26099. {
  26100. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  26101. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  26102. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  26103. push:'candidates',
  26104. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  26105. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  26106. format: function (o) {
  26107. var str = "candidate:%s %d %s %d %s %d typ %s";
  26108. // NB: candidate has two optional chunks, so %void middle one if it's missing
  26109. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  26110. if (o.generation != null) {
  26111. str += " generation %d";
  26112. }
  26113. return str;
  26114. }
  26115. },
  26116. { //a=end-of-candidates (keep after the candidates line for readability)
  26117. name: 'endOfCandidates',
  26118. reg: /^(end-of-candidates)/
  26119. },
  26120. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  26121. name: 'remoteCandidates',
  26122. reg: /^remote-candidates:(.*)/,
  26123. format: "remote-candidates:%s"
  26124. },
  26125. { //a=ice-options:google-ice
  26126. name: 'iceOptions',
  26127. reg: /^ice-options:(\S*)/,
  26128. format: "ice-options:%s"
  26129. },
  26130. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  26131. push: "ssrcs",
  26132. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  26133. names: ['id', 'attribute', 'value'],
  26134. format: "ssrc:%d %s:%s"
  26135. },
  26136. { //a=ssrc-group:FEC 1 2
  26137. push: "ssrcGroups",
  26138. reg: /^ssrc-group:(\w*) (.*)/,
  26139. names: ['semantics', 'ssrcs'],
  26140. format: "ssrc-group:%s %s"
  26141. },
  26142. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  26143. name: "msidSemantic",
  26144. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  26145. names: ['semantic', 'token'],
  26146. format: "msid-semantic: %s %s" // space after ":" is not accidental
  26147. },
  26148. { //a=group:BUNDLE audio video
  26149. push: 'groups',
  26150. reg: /^group:(\w*) (.*)/,
  26151. names: ['type', 'mids'],
  26152. format: "group:%s %s"
  26153. },
  26154. { //a=rtcp-mux
  26155. name: 'rtcpMux',
  26156. reg: /^(rtcp-mux)/
  26157. },
  26158. { //a=rtcp-rsize
  26159. name: 'rtcpRsize',
  26160. reg: /^(rtcp-rsize)/
  26161. },
  26162. { // any a= that we don't understand is kepts verbatim on media.invalid
  26163. push: 'invalid',
  26164. names: ["value"]
  26165. }
  26166. ]
  26167. };
  26168. // set sensible defaults to avoid polluting the grammar with boring details
  26169. Object.keys(grammar).forEach(function (key) {
  26170. var objs = grammar[key];
  26171. objs.forEach(function (obj) {
  26172. if (!obj.reg) {
  26173. obj.reg = /(.*)/;
  26174. }
  26175. if (!obj.format) {
  26176. obj.format = "%s";
  26177. }
  26178. });
  26179. });
  26180. },{}],95:[function(require,module,exports){
  26181. var parser = require('./parser');
  26182. var writer = require('./writer');
  26183. exports.write = writer;
  26184. exports.parse = parser.parse;
  26185. exports.parseFmtpConfig = parser.parseFmtpConfig;
  26186. exports.parsePayloads = parser.parsePayloads;
  26187. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  26188. },{"./parser":96,"./writer":97}],96:[function(require,module,exports){
  26189. var toIntIfInt = function (v) {
  26190. return String(Number(v)) === v ? Number(v) : v;
  26191. };
  26192. var attachProperties = function (match, location, names, rawName) {
  26193. if (rawName && !names) {
  26194. location[rawName] = toIntIfInt(match[1]);
  26195. }
  26196. else {
  26197. for (var i = 0; i < names.length; i += 1) {
  26198. if (match[i+1] != null) {
  26199. location[names[i]] = toIntIfInt(match[i+1]);
  26200. }
  26201. }
  26202. }
  26203. };
  26204. var parseReg = function (obj, location, content) {
  26205. var needsBlank = obj.name && obj.names;
  26206. if (obj.push && !location[obj.push]) {
  26207. location[obj.push] = [];
  26208. }
  26209. else if (needsBlank && !location[obj.name]) {
  26210. location[obj.name] = {};
  26211. }
  26212. var keyLocation = obj.push ?
  26213. {} : // blank object that will be pushed
  26214. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  26215. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  26216. if (obj.push) {
  26217. location[obj.push].push(keyLocation);
  26218. }
  26219. };
  26220. var grammar = require('./grammar');
  26221. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  26222. exports.parse = function (sdp) {
  26223. var session = {}
  26224. , media = []
  26225. , location = session; // points at where properties go under (one of the above)
  26226. // parse lines we understand
  26227. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  26228. var type = l[0];
  26229. var content = l.slice(2);
  26230. if (type === 'm') {
  26231. media.push({rtp: [], fmtp: []});
  26232. location = media[media.length-1]; // point at latest media line
  26233. }
  26234. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  26235. var obj = grammar[type][j];
  26236. if (obj.reg.test(content)) {
  26237. return parseReg(obj, location, content);
  26238. }
  26239. }
  26240. });
  26241. session.media = media; // link it up
  26242. return session;
  26243. };
  26244. var fmtpReducer = function (acc, expr) {
  26245. var s = expr.split('=');
  26246. if (s.length === 2) {
  26247. acc[s[0]] = toIntIfInt(s[1]);
  26248. }
  26249. return acc;
  26250. };
  26251. exports.parseFmtpConfig = function (str) {
  26252. return str.split(';').reduce(fmtpReducer, {});
  26253. };
  26254. exports.parsePayloads = function (str) {
  26255. return str.split(' ').map(Number);
  26256. };
  26257. exports.parseRemoteCandidates = function (str) {
  26258. var candidates = [];
  26259. var parts = str.split(' ').map(toIntIfInt);
  26260. for (var i = 0; i < parts.length; i += 3) {
  26261. candidates.push({
  26262. component: parts[i],
  26263. ip: parts[i + 1],
  26264. port: parts[i + 2]
  26265. });
  26266. }
  26267. return candidates;
  26268. };
  26269. },{"./grammar":94}],97:[function(require,module,exports){
  26270. var grammar = require('./grammar');
  26271. // customized util.format - discards excess arguments and can void middle ones
  26272. var formatRegExp = /%[sdv%]/g;
  26273. var format = function (formatStr) {
  26274. var i = 1;
  26275. var args = arguments;
  26276. var len = args.length;
  26277. return formatStr.replace(formatRegExp, function (x) {
  26278. if (i >= len) {
  26279. return x; // missing argument
  26280. }
  26281. var arg = args[i];
  26282. i += 1;
  26283. switch (x) {
  26284. case '%%':
  26285. return '%';
  26286. case '%s':
  26287. return String(arg);
  26288. case '%d':
  26289. return Number(arg);
  26290. case '%v':
  26291. return '';
  26292. }
  26293. });
  26294. // NB: we discard excess arguments - they are typically undefined from makeLine
  26295. };
  26296. var makeLine = function (type, obj, location) {
  26297. var str = obj.format instanceof Function ?
  26298. (obj.format(obj.push ? location : location[obj.name])) :
  26299. obj.format;
  26300. var args = [type + '=' + str];
  26301. if (obj.names) {
  26302. for (var i = 0; i < obj.names.length; i += 1) {
  26303. var n = obj.names[i];
  26304. if (obj.name) {
  26305. args.push(location[obj.name][n]);
  26306. }
  26307. else { // for mLine and push attributes
  26308. args.push(location[obj.names[i]]);
  26309. }
  26310. }
  26311. }
  26312. else {
  26313. args.push(location[obj.name]);
  26314. }
  26315. return format.apply(null, args);
  26316. };
  26317. // RFC specified order
  26318. // TODO: extend this with all the rest
  26319. var defaultOuterOrder = [
  26320. 'v', 'o', 's', 'i',
  26321. 'u', 'e', 'p', 'c',
  26322. 'b', 't', 'r', 'z', 'a'
  26323. ];
  26324. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  26325. module.exports = function (session, opts) {
  26326. opts = opts || {};
  26327. // ensure certain properties exist
  26328. if (session.version == null) {
  26329. session.version = 0; // "v=0" must be there (only defined version atm)
  26330. }
  26331. if (session.name == null) {
  26332. session.name = " "; // "s= " must be there if no meaningful name set
  26333. }
  26334. session.media.forEach(function (mLine) {
  26335. if (mLine.payloads == null) {
  26336. mLine.payloads = "";
  26337. }
  26338. });
  26339. var outerOrder = opts.outerOrder || defaultOuterOrder;
  26340. var innerOrder = opts.innerOrder || defaultInnerOrder;
  26341. var sdp = [];
  26342. // loop through outerOrder for matching properties on session
  26343. outerOrder.forEach(function (type) {
  26344. grammar[type].forEach(function (obj) {
  26345. if (obj.name in session && session[obj.name] != null) {
  26346. sdp.push(makeLine(type, obj, session));
  26347. }
  26348. else if (obj.push in session && session[obj.push] != null) {
  26349. session[obj.push].forEach(function (el) {
  26350. sdp.push(makeLine(type, obj, el));
  26351. });
  26352. }
  26353. });
  26354. });
  26355. // then for each media line, follow the innerOrder
  26356. session.media.forEach(function (mLine) {
  26357. sdp.push(makeLine('m', grammar.m[0], mLine));
  26358. innerOrder.forEach(function (type) {
  26359. grammar[type].forEach(function (obj) {
  26360. if (obj.name in mLine && mLine[obj.name] != null) {
  26361. sdp.push(makeLine(type, obj, mLine));
  26362. }
  26363. else if (obj.push in mLine && mLine[obj.push] != null) {
  26364. mLine[obj.push].forEach(function (el) {
  26365. sdp.push(makeLine(type, obj, el));
  26366. });
  26367. }
  26368. });
  26369. });
  26370. });
  26371. return sdp.join('\r\n') + '\r\n';
  26372. };
  26373. },{"./grammar":94}],98:[function(require,module,exports){
  26374. var MediaStreamType = {
  26375. VIDEO_TYPE: "Video",
  26376. AUDIO_TYPE: "Audio"
  26377. };
  26378. module.exports = MediaStreamType;
  26379. },{}],99:[function(require,module,exports){
  26380. var RTCEvents = {
  26381. RTC_READY: "rtc.ready",
  26382. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  26383. LASTN_CHANGED: "rtc.lastn_changed",
  26384. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  26385. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  26386. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed",
  26387. AUDIO_MUTE: "rtc.audio_mute",
  26388. VIDEO_MUTE: "rtc.video_mute"
  26389. };
  26390. module.exports = RTCEvents;
  26391. },{}],100:[function(require,module,exports){
  26392. var Resolutions = {
  26393. "1080": {
  26394. width: 1920,
  26395. height: 1080,
  26396. order: 7
  26397. },
  26398. "fullhd": {
  26399. width: 1920,
  26400. height: 1080,
  26401. order: 7
  26402. },
  26403. "720": {
  26404. width: 1280,
  26405. height: 720,
  26406. order: 6
  26407. },
  26408. "hd": {
  26409. width: 1280,
  26410. height: 720,
  26411. order: 6
  26412. },
  26413. "960": {
  26414. width: 960,
  26415. height: 720,
  26416. order: 5
  26417. },
  26418. "640": {
  26419. width: 640,
  26420. height: 480,
  26421. order: 4
  26422. },
  26423. "vga": {
  26424. width: 640,
  26425. height: 480,
  26426. order: 4
  26427. },
  26428. "360": {
  26429. width: 640,
  26430. height: 360,
  26431. order: 3
  26432. },
  26433. "320": {
  26434. width: 320,
  26435. height: 240,
  26436. order: 2
  26437. },
  26438. "180": {
  26439. width: 320,
  26440. height: 180,
  26441. order: 1
  26442. }
  26443. };
  26444. module.exports = Resolutions;
  26445. },{}],101:[function(require,module,exports){
  26446. var StreamEventTypes = {
  26447. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  26448. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  26449. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  26450. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  26451. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended",
  26452. EVENT_TYPE_REMOTE_CHANGED: "stream.changed"
  26453. };
  26454. module.exports = StreamEventTypes;
  26455. },{}],102:[function(require,module,exports){
  26456. var UIEvents = {
  26457. NICKNAME_CHANGED: "UI.nickname_changed",
  26458. SELECTED_ENDPOINT: "UI.selected_endpoint",
  26459. PINNED_ENDPOINT: "UI.pinned_endpoint"
  26460. };
  26461. module.exports = UIEvents;
  26462. },{}],103:[function(require,module,exports){
  26463. var AuthenticationEvents = {
  26464. /**
  26465. * Event callback arguments:
  26466. * function(authenticationEnabled, userIdentity)
  26467. * authenticationEnabled - indicates whether authentication has been enabled
  26468. * in this session
  26469. * userIdentity - if user has been logged in then it contains user name. If
  26470. * contains 'null' or 'undefined' then user is not logged in.
  26471. */
  26472. IDENTITY_UPDATED: "authentication.identity_updated"
  26473. };
  26474. module.exports = AuthenticationEvents;
  26475. },{}],104:[function(require,module,exports){
  26476. var CQEvents = {
  26477. LOCALSTATS_UPDATED: "cq.localstats_updated",
  26478. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  26479. STOP: "cq.stop"
  26480. };
  26481. module.exports = CQEvents;
  26482. },{}],105:[function(require,module,exports){
  26483. var DesktopSharingEventTypes = {
  26484. INIT: "ds.init",
  26485. SWITCHING_DONE: "ds.switching_done",
  26486. NEW_STREAM_CREATED: "ds.new_stream_created"
  26487. };
  26488. module.exports = DesktopSharingEventTypes;
  26489. },{}],106:[function(require,module,exports){
  26490. var Events = {
  26491. DTMF_SUPPORT_CHANGED: "members.dtmf_support_changed"
  26492. };
  26493. module.exports = Events;
  26494. },{}],107:[function(require,module,exports){
  26495. module.exports = {
  26496. getLanguages : function () {
  26497. var languages = [];
  26498. for(var lang in this)
  26499. {
  26500. if(typeof this[lang] === "string")
  26501. languages.push(this[lang]);
  26502. }
  26503. return languages;
  26504. },
  26505. EN: "en",
  26506. BG: "bg",
  26507. DE: "de",
  26508. TR: "tr",
  26509. FR: "fr"
  26510. }
  26511. },{}],108:[function(require,module,exports){
  26512. var XMPPEvents = {
  26513. CONNECTION_FAILED: "xmpp.connection.failed",
  26514. CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle",
  26515. CALL_INCOMING: "xmpp.callincoming.jingle",
  26516. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  26517. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  26518. KICKED: "xmpp.kicked",
  26519. BRIDGE_DOWN: "xmpp.bridge_down",
  26520. USER_ID_CHANGED: "xmpp.user_id_changed",
  26521. // We joined the MUC
  26522. MUC_JOINED: "xmpp.muc_joined",
  26523. // A member joined the MUC
  26524. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  26525. // A member left the MUC
  26526. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  26527. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  26528. MUC_DESTROYED: "xmpp.muc_destroyed",
  26529. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  26530. REMOTE_STATS: "xmpp.remote_stats",
  26531. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  26532. PRESENCE_STATUS: "xmpp.presence_status",
  26533. RESERVATION_ERROR: "xmpp.room_reservation_error",
  26534. SUBJECT_CHANGED: "xmpp.subject_changed",
  26535. MESSAGE_RECEIVED: "xmpp.message_received",
  26536. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  26537. PASSWORD_REQUIRED: "xmpp.password_required",
  26538. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  26539. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  26540. ETHERPAD: "xmpp.etherpad",
  26541. DEVICE_AVAILABLE: "xmpp.device_available",
  26542. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  26543. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  26544. AUDIO_MUTED: "xmpp.audio_muted",
  26545. VIDEO_MUTED: "xmpp.video_muted",
  26546. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  26547. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  26548. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  26549. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  26550. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  26551. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  26552. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  26553. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  26554. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  26555. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  26556. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  26557. // xmpp is connected and obtained user media
  26558. READY_TO_JOIN: 'xmpp.ready_to_join'
  26559. };
  26560. module.exports = XMPPEvents;
  26561. },{}],109:[function(require,module,exports){
  26562. // Copyright Joyent, Inc. and other Node contributors.
  26563. //
  26564. // Permission is hereby granted, free of charge, to any person obtaining a
  26565. // copy of this software and associated documentation files (the
  26566. // "Software"), to deal in the Software without restriction, including
  26567. // without limitation the rights to use, copy, modify, merge, publish,
  26568. // distribute, sublicense, and/or sell copies of the Software, and to permit
  26569. // persons to whom the Software is furnished to do so, subject to the
  26570. // following conditions:
  26571. //
  26572. // The above copyright notice and this permission notice shall be included
  26573. // in all copies or substantial portions of the Software.
  26574. //
  26575. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  26576. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26577. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  26578. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  26579. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  26580. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  26581. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  26582. function EventEmitter() {
  26583. this._events = this._events || {};
  26584. this._maxListeners = this._maxListeners || undefined;
  26585. }
  26586. module.exports = EventEmitter;
  26587. // Backwards-compat with node 0.10.x
  26588. EventEmitter.EventEmitter = EventEmitter;
  26589. EventEmitter.prototype._events = undefined;
  26590. EventEmitter.prototype._maxListeners = undefined;
  26591. // By default EventEmitters will print a warning if more than 10 listeners are
  26592. // added to it. This is a useful default which helps finding memory leaks.
  26593. EventEmitter.defaultMaxListeners = 10;
  26594. // Obviously not all Emitters should be limited to 10. This function allows
  26595. // that to be increased. Set to zero for unlimited.
  26596. EventEmitter.prototype.setMaxListeners = function(n) {
  26597. if (!isNumber(n) || n < 0 || isNaN(n))
  26598. throw TypeError('n must be a positive number');
  26599. this._maxListeners = n;
  26600. return this;
  26601. };
  26602. EventEmitter.prototype.emit = function(type) {
  26603. var er, handler, len, args, i, listeners;
  26604. if (!this._events)
  26605. this._events = {};
  26606. // If there is no 'error' event listener then throw.
  26607. if (type === 'error') {
  26608. if (!this._events.error ||
  26609. (isObject(this._events.error) && !this._events.error.length)) {
  26610. er = arguments[1];
  26611. if (er instanceof Error) {
  26612. throw er; // Unhandled 'error' event
  26613. }
  26614. throw TypeError('Uncaught, unspecified "error" event.');
  26615. }
  26616. }
  26617. handler = this._events[type];
  26618. if (isUndefined(handler))
  26619. return false;
  26620. if (isFunction(handler)) {
  26621. switch (arguments.length) {
  26622. // fast cases
  26623. case 1:
  26624. handler.call(this);
  26625. break;
  26626. case 2:
  26627. handler.call(this, arguments[1]);
  26628. break;
  26629. case 3:
  26630. handler.call(this, arguments[1], arguments[2]);
  26631. break;
  26632. // slower
  26633. default:
  26634. len = arguments.length;
  26635. args = new Array(len - 1);
  26636. for (i = 1; i < len; i++)
  26637. args[i - 1] = arguments[i];
  26638. handler.apply(this, args);
  26639. }
  26640. } else if (isObject(handler)) {
  26641. len = arguments.length;
  26642. args = new Array(len - 1);
  26643. for (i = 1; i < len; i++)
  26644. args[i - 1] = arguments[i];
  26645. listeners = handler.slice();
  26646. len = listeners.length;
  26647. for (i = 0; i < len; i++)
  26648. listeners[i].apply(this, args);
  26649. }
  26650. return true;
  26651. };
  26652. EventEmitter.prototype.addListener = function(type, listener) {
  26653. var m;
  26654. if (!isFunction(listener))
  26655. throw TypeError('listener must be a function');
  26656. if (!this._events)
  26657. this._events = {};
  26658. // To avoid recursion in the case that type === "newListener"! Before
  26659. // adding it to the listeners, first emit "newListener".
  26660. if (this._events.newListener)
  26661. this.emit('newListener', type,
  26662. isFunction(listener.listener) ?
  26663. listener.listener : listener);
  26664. if (!this._events[type])
  26665. // Optimize the case of one listener. Don't need the extra array object.
  26666. this._events[type] = listener;
  26667. else if (isObject(this._events[type]))
  26668. // If we've already got an array, just append.
  26669. this._events[type].push(listener);
  26670. else
  26671. // Adding the second element, need to change to array.
  26672. this._events[type] = [this._events[type], listener];
  26673. // Check for listener leak
  26674. if (isObject(this._events[type]) && !this._events[type].warned) {
  26675. var m;
  26676. if (!isUndefined(this._maxListeners)) {
  26677. m = this._maxListeners;
  26678. } else {
  26679. m = EventEmitter.defaultMaxListeners;
  26680. }
  26681. if (m && m > 0 && this._events[type].length > m) {
  26682. this._events[type].warned = true;
  26683. console.error('(node) warning: possible EventEmitter memory ' +
  26684. 'leak detected. %d listeners added. ' +
  26685. 'Use emitter.setMaxListeners() to increase limit.',
  26686. this._events[type].length);
  26687. if (typeof console.trace === 'function') {
  26688. // not supported in IE 10
  26689. console.trace();
  26690. }
  26691. }
  26692. }
  26693. return this;
  26694. };
  26695. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  26696. EventEmitter.prototype.once = function(type, listener) {
  26697. if (!isFunction(listener))
  26698. throw TypeError('listener must be a function');
  26699. var fired = false;
  26700. function g() {
  26701. this.removeListener(type, g);
  26702. if (!fired) {
  26703. fired = true;
  26704. listener.apply(this, arguments);
  26705. }
  26706. }
  26707. g.listener = listener;
  26708. this.on(type, g);
  26709. return this;
  26710. };
  26711. // emits a 'removeListener' event iff the listener was removed
  26712. EventEmitter.prototype.removeListener = function(type, listener) {
  26713. var list, position, length, i;
  26714. if (!isFunction(listener))
  26715. throw TypeError('listener must be a function');
  26716. if (!this._events || !this._events[type])
  26717. return this;
  26718. list = this._events[type];
  26719. length = list.length;
  26720. position = -1;
  26721. if (list === listener ||
  26722. (isFunction(list.listener) && list.listener === listener)) {
  26723. delete this._events[type];
  26724. if (this._events.removeListener)
  26725. this.emit('removeListener', type, listener);
  26726. } else if (isObject(list)) {
  26727. for (i = length; i-- > 0;) {
  26728. if (list[i] === listener ||
  26729. (list[i].listener && list[i].listener === listener)) {
  26730. position = i;
  26731. break;
  26732. }
  26733. }
  26734. if (position < 0)
  26735. return this;
  26736. if (list.length === 1) {
  26737. list.length = 0;
  26738. delete this._events[type];
  26739. } else {
  26740. list.splice(position, 1);
  26741. }
  26742. if (this._events.removeListener)
  26743. this.emit('removeListener', type, listener);
  26744. }
  26745. return this;
  26746. };
  26747. EventEmitter.prototype.removeAllListeners = function(type) {
  26748. var key, listeners;
  26749. if (!this._events)
  26750. return this;
  26751. // not listening for removeListener, no need to emit
  26752. if (!this._events.removeListener) {
  26753. if (arguments.length === 0)
  26754. this._events = {};
  26755. else if (this._events[type])
  26756. delete this._events[type];
  26757. return this;
  26758. }
  26759. // emit removeListener for all listeners on all events
  26760. if (arguments.length === 0) {
  26761. for (key in this._events) {
  26762. if (key === 'removeListener') continue;
  26763. this.removeAllListeners(key);
  26764. }
  26765. this.removeAllListeners('removeListener');
  26766. this._events = {};
  26767. return this;
  26768. }
  26769. listeners = this._events[type];
  26770. if (isFunction(listeners)) {
  26771. this.removeListener(type, listeners);
  26772. } else {
  26773. // LIFO order
  26774. while (listeners.length)
  26775. this.removeListener(type, listeners[listeners.length - 1]);
  26776. }
  26777. delete this._events[type];
  26778. return this;
  26779. };
  26780. EventEmitter.prototype.listeners = function(type) {
  26781. var ret;
  26782. if (!this._events || !this._events[type])
  26783. ret = [];
  26784. else if (isFunction(this._events[type]))
  26785. ret = [this._events[type]];
  26786. else
  26787. ret = this._events[type].slice();
  26788. return ret;
  26789. };
  26790. EventEmitter.listenerCount = function(emitter, type) {
  26791. var ret;
  26792. if (!emitter._events || !emitter._events[type])
  26793. ret = 0;
  26794. else if (isFunction(emitter._events[type]))
  26795. ret = 1;
  26796. else
  26797. ret = emitter._events[type].length;
  26798. return ret;
  26799. };
  26800. function isFunction(arg) {
  26801. return typeof arg === 'function';
  26802. }
  26803. function isNumber(arg) {
  26804. return typeof arg === 'number';
  26805. }
  26806. function isObject(arg) {
  26807. return typeof arg === 'object' && arg !== null;
  26808. }
  26809. function isUndefined(arg) {
  26810. return arg === void 0;
  26811. }
  26812. },{}],110:[function(require,module,exports){
  26813. // shim for using process in browser
  26814. var process = module.exports = {};
  26815. var queue = [];
  26816. var draining = false;
  26817. function drainQueue() {
  26818. if (draining) {
  26819. return;
  26820. }
  26821. draining = true;
  26822. var currentQueue;
  26823. var len = queue.length;
  26824. while(len) {
  26825. currentQueue = queue;
  26826. queue = [];
  26827. var i = -1;
  26828. while (++i < len) {
  26829. currentQueue[i]();
  26830. }
  26831. len = queue.length;
  26832. }
  26833. draining = false;
  26834. }
  26835. process.nextTick = function (fun) {
  26836. queue.push(fun);
  26837. if (!draining) {
  26838. setTimeout(drainQueue, 0);
  26839. }
  26840. };
  26841. process.title = 'browser';
  26842. process.browser = true;
  26843. process.env = {};
  26844. process.argv = [];
  26845. process.version = ''; // empty string to avoid regexp issues
  26846. function noop() {}
  26847. process.on = noop;
  26848. process.addListener = noop;
  26849. process.once = noop;
  26850. process.off = noop;
  26851. process.removeListener = noop;
  26852. process.removeAllListeners = noop;
  26853. process.emit = noop;
  26854. process.binding = function (name) {
  26855. throw new Error('process.binding is not supported');
  26856. };
  26857. // TODO(shtylman)
  26858. process.cwd = function () { return '/' };
  26859. process.chdir = function (dir) {
  26860. throw new Error('process.chdir is not supported');
  26861. };
  26862. process.umask = function() { return 0; };
  26863. },{}]},{},[1])(1)
  26864. });