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

app.bundle.js 987KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936
  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. /*
  3. * Copyright @ 2015 Atlassian Pty Ltd
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /* jshint -W117 */
  18. /* application specific logic */
  19. var APP =
  20. {
  21. init: function () {
  22. this.UI = require("./modules/UI/UI");
  23. this.API = require("./modules/API/API");
  24. this.connectionquality = require("./modules/connectionquality/connectionquality");
  25. this.statistics = require("./modules/statistics/statistics");
  26. this.RTC = require("./modules/RTC/RTC");
  27. this.desktopsharing = require("./modules/desktopsharing/desktopsharing");
  28. this.xmpp = require("./modules/xmpp/xmpp");
  29. this.keyboardshortcut = require("./modules/keyboardshortcut/keyboardshortcut");
  30. this.translation = require("./modules/translation/translation");
  31. this.settings = require("./modules/settings/Settings");
  32. this.DTMF = require("./modules/DTMF/DTMF");
  33. this.members = require("./modules/members/MemberList");
  34. }
  35. };
  36. function init() {
  37. APP.RTC.start();
  38. APP.xmpp.start();
  39. APP.statistics.start();
  40. APP.connectionquality.init();
  41. // Set default desktop sharing method
  42. APP.desktopsharing.init();
  43. APP.keyboardshortcut.init();
  44. APP.members.start();
  45. }
  46. $(document).ready(function () {
  47. var URLPRocessor = require("./modules/URLProcessor/URLProcessor");
  48. URLPRocessor.setConfigParametersFromUrl();
  49. APP.init();
  50. APP.translation.init();
  51. if(APP.API.isEnabled())
  52. APP.API.init();
  53. APP.UI.start(init);
  54. });
  55. $(window).bind('beforeunload', function () {
  56. if(APP.API.isEnabled())
  57. APP.API.dispose();
  58. });
  59. module.exports = APP;
  60. },{"./modules/API/API":2,"./modules/DTMF/DTMF":3,"./modules/RTC/RTC":7,"./modules/UI/UI":9,"./modules/URLProcessor/URLProcessor":36,"./modules/connectionquality/connectionquality":37,"./modules/desktopsharing/desktopsharing":38,"./modules/keyboardshortcut/keyboardshortcut":39,"./modules/members/MemberList":40,"./modules/settings/Settings":41,"./modules/statistics/statistics":44,"./modules/translation/translation":45,"./modules/xmpp/xmpp":59}],2:[function(require,module,exports){
  61. /*
  62. * Copyright @ 2015 Atlassian Pty Ltd
  63. *
  64. * Licensed under the Apache License, Version 2.0 (the "License");
  65. * you may not use this file except in compliance with the License.
  66. * You may obtain a copy of the License at
  67. *
  68. * http://www.apache.org/licenses/LICENSE-2.0
  69. *
  70. * Unless required by applicable law or agreed to in writing, software
  71. * distributed under the License is distributed on an "AS IS" BASIS,
  72. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  73. * See the License for the specific language governing permissions and
  74. * limitations under the License.
  75. */
  76. /**
  77. * Implements API class that communicates with external api class
  78. * and provides interface to access Jitsi Meet features by external
  79. * applications that embed Jitsi Meet
  80. */
  81. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  82. /**
  83. * List of the available commands.
  84. * @type {{
  85. * displayName: inputDisplayNameHandler,
  86. * muteAudio: toggleAudio,
  87. * muteVideo: toggleVideo,
  88. * filmStrip: toggleFilmStrip
  89. * }}
  90. */
  91. var commands =
  92. {
  93. displayName: APP.UI.inputDisplayNameHandler,
  94. muteAudio: APP.UI.toggleAudio,
  95. muteVideo: APP.UI.toggleVideo,
  96. toggleFilmStrip: APP.UI.toggleFilmStrip,
  97. toggleChat: APP.UI.toggleChat,
  98. toggleContactList: APP.UI.toggleContactList
  99. };
  100. /**
  101. * Maps the supported events and their status
  102. * (true it the event is enabled and false if it is disabled)
  103. * @type {{
  104. * incomingMessage: boolean,
  105. * outgoingMessage: boolean,
  106. * displayNameChange: boolean,
  107. * participantJoined: boolean,
  108. * participantLeft: boolean
  109. * }}
  110. */
  111. var events =
  112. {
  113. incomingMessage: false,
  114. outgoingMessage:false,
  115. displayNameChange: false,
  116. participantJoined: false,
  117. participantLeft: false
  118. };
  119. var displayName = {};
  120. /**
  121. * Processes commands from external applicaiton.
  122. * @param message the object with the command
  123. */
  124. function processCommand(message)
  125. {
  126. if(message.action != "execute")
  127. {
  128. console.error("Unknown action of the message");
  129. return;
  130. }
  131. for(var key in message)
  132. {
  133. if(commands[key])
  134. commands[key].apply(null, message[key]);
  135. }
  136. }
  137. /**
  138. * Processes events objects from external applications
  139. * @param event the event
  140. */
  141. function processEvent(event) {
  142. if(!event.action)
  143. {
  144. console.error("Event with no action is received.");
  145. return;
  146. }
  147. var i = 0;
  148. switch(event.action)
  149. {
  150. case "add":
  151. for(; i < event.events.length; i++)
  152. {
  153. events[event.events[i]] = true;
  154. }
  155. break;
  156. case "remove":
  157. for(; i < event.events.length; i++)
  158. {
  159. events[event.events[i]] = false;
  160. }
  161. break;
  162. default:
  163. console.error("Unknown action for event.");
  164. }
  165. }
  166. /**
  167. * Sends message to the external application.
  168. * @param object
  169. */
  170. function sendMessage(object) {
  171. window.parent.postMessage(JSON.stringify(object), "*");
  172. }
  173. /**
  174. * Processes a message event from the external application
  175. * @param event the message event
  176. */
  177. function processMessage(event)
  178. {
  179. var message;
  180. try {
  181. message = JSON.parse(event.data);
  182. } catch (e) {}
  183. if(!message.type)
  184. return;
  185. switch (message.type)
  186. {
  187. case "command":
  188. processCommand(message);
  189. break;
  190. case "event":
  191. processEvent(message);
  192. break;
  193. default:
  194. console.error("Unknown type of the message");
  195. return;
  196. }
  197. }
  198. function setupListeners() {
  199. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, function (from) {
  200. API.triggerEvent("participantJoined", {jid: from});
  201. });
  202. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid) {
  203. if (from != myjid)
  204. API.triggerEvent("incomingMessage",
  205. {"from": from, "nick": nick, "message": txt});
  206. });
  207. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, function (jid) {
  208. API.triggerEvent("participantLeft", {jid: jid});
  209. });
  210. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {
  211. name = displayName[jid];
  212. if(!name || name != newDisplayName) {
  213. API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});
  214. displayName[jid] = newDisplayName;
  215. }
  216. });
  217. APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {
  218. APP.API.triggerEvent("outgoingMessage", {"message": body});
  219. });
  220. }
  221. var API = {
  222. /**
  223. * Check whether the API should be enabled or not.
  224. * @returns {boolean}
  225. */
  226. isEnabled: function () {
  227. var hash = location.hash;
  228. if(hash && hash.indexOf("external") > -1 && window.postMessage)
  229. return true;
  230. return false;
  231. },
  232. /**
  233. * Initializes the APIConnector. Setups message event listeners that will
  234. * receive information from external applications that embed Jitsi Meet.
  235. * It also sends a message to the external application that APIConnector
  236. * is initialized.
  237. */
  238. init: function () {
  239. if (window.addEventListener)
  240. {
  241. window.addEventListener('message',
  242. processMessage, false);
  243. }
  244. else
  245. {
  246. window.attachEvent('onmessage', processMessage);
  247. }
  248. sendMessage({type: "system", loaded: true});
  249. setupListeners();
  250. },
  251. /**
  252. * Checks whether the event is enabled ot not.
  253. * @param name the name of the event.
  254. * @returns {*}
  255. */
  256. isEventEnabled: function (name) {
  257. return events[name];
  258. },
  259. /**
  260. * Sends event object to the external application that has been subscribed
  261. * for that event.
  262. * @param name the name event
  263. * @param object data associated with the event
  264. */
  265. triggerEvent: function (name, object) {
  266. if(this.isEnabled() && this.isEventEnabled(name))
  267. sendMessage({
  268. type: "event", action: "result", event: name, result: object});
  269. },
  270. /**
  271. * Removes the listeners.
  272. */
  273. dispose: function () {
  274. if(window.removeEventListener)
  275. {
  276. window.removeEventListener("message",
  277. processMessage, false);
  278. }
  279. else
  280. {
  281. window.detachEvent('onmessage', processMessage);
  282. }
  283. }
  284. };
  285. module.exports = API;
  286. },{"../../service/xmpp/XMPPEvents":112}],3:[function(require,module,exports){
  287. /*
  288. * Copyright @ 2015 Atlassian Pty Ltd
  289. *
  290. * Licensed under the Apache License, Version 2.0 (the "License");
  291. * you may not use this file except in compliance with the License.
  292. * You may obtain a copy of the License at
  293. *
  294. * http://www.apache.org/licenses/LICENSE-2.0
  295. *
  296. * Unless required by applicable law or agreed to in writing, software
  297. * distributed under the License is distributed on an "AS IS" BASIS,
  298. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  299. * See the License for the specific language governing permissions and
  300. * limitations under the License.
  301. */
  302. /* global APP */
  303. /**
  304. * A module for sending DTMF tones.
  305. */
  306. var DTMFSender;
  307. var initDtmfSender = function() {
  308. // TODO: This needs to reset this if the peerconnection changes
  309. // (e.g. the call is re-made)
  310. if (DTMFSender)
  311. return;
  312. var localAudio = APP.RTC.localAudio;
  313. if (localAudio && localAudio.getTracks().length > 0)
  314. {
  315. var peerconnection
  316. = APP.xmpp.getConnection().jingle.activecall.peerconnection;
  317. if (peerconnection) {
  318. DTMFSender =
  319. peerconnection.peerconnection
  320. .createDTMFSender(localAudio.getTracks()[0]);
  321. console.log("Initialized DTMFSender");
  322. }
  323. else {
  324. console.log("Failed to initialize DTMFSender: no PeerConnection.");
  325. }
  326. }
  327. else {
  328. console.log("Failed to initialize DTMFSender: no audio track.");
  329. }
  330. };
  331. var DTMF = {
  332. sendTones: function (tones, duration, pause) {
  333. if (!DTMFSender)
  334. initDtmfSender();
  335. if (DTMFSender){
  336. DTMFSender.insertDTMF(tones,
  337. (duration || 200),
  338. (pause || 200));
  339. }
  340. }
  341. };
  342. module.exports = DTMF;
  343. },{}],4:[function(require,module,exports){
  344. /*
  345. * Copyright @ 2015 Atlassian Pty Ltd
  346. *
  347. * Licensed under the Apache License, Version 2.0 (the "License");
  348. * you may not use this file except in compliance with the License.
  349. * You may obtain a copy of the License at
  350. *
  351. * http://www.apache.org/licenses/LICENSE-2.0
  352. *
  353. * Unless required by applicable law or agreed to in writing, software
  354. * distributed under the License is distributed on an "AS IS" BASIS,
  355. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  356. * See the License for the specific language governing permissions and
  357. * limitations under the License.
  358. */
  359. /* global Strophe, focusedVideoSrc*/
  360. // cache datachannels to avoid garbage collection
  361. // https://code.google.com/p/chromium/issues/detail?id=405545
  362. var RTCEvents = require("../../service/RTC/RTCEvents");
  363. var _dataChannels = [];
  364. var eventEmitter = null;
  365. var DataChannels =
  366. {
  367. /**
  368. * Callback triggered by PeerConnection when new data channel is opened
  369. * on the bridge.
  370. * @param event the event info object.
  371. */
  372. onDataChannel: function (event)
  373. {
  374. var dataChannel = event.channel;
  375. dataChannel.onopen = function () {
  376. console.info("Data channel opened by the Videobridge!", dataChannel);
  377. // Code sample for sending string and/or binary data
  378. // Sends String message to the bridge
  379. //dataChannel.send("Hello bridge!");
  380. // Sends 12 bytes binary message to the bridge
  381. //dataChannel.send(new ArrayBuffer(12));
  382. // when the data channel becomes available, tell the bridge about video
  383. // selections so that it can do adaptive simulcast,
  384. // we want the notification to trigger even if userJid is undefined,
  385. // or null.
  386. var userJid = APP.UI.getLargeVideoState().userResourceJid;
  387. // we want the notification to trigger even if userJid is undefined,
  388. // or null.
  389. onSelectedEndpointChanged(userJid);
  390. };
  391. dataChannel.onerror = function (error) {
  392. console.error("Data Channel Error:", error, dataChannel);
  393. };
  394. dataChannel.onmessage = function (event) {
  395. var data = event.data;
  396. // JSON
  397. var obj;
  398. try {
  399. obj = JSON.parse(data);
  400. }
  401. catch (e) {
  402. console.error(
  403. "Failed to parse data channel message as JSON: ",
  404. data,
  405. dataChannel);
  406. }
  407. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  408. var colibriClass = obj.colibriClass;
  409. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  410. // Endpoint ID from the Videobridge.
  411. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  412. console.info(
  413. "Data channel new dominant speaker event: ",
  414. dominantSpeakerEndpoint);
  415. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  416. }
  417. else if ("InLastNChangeEvent" === colibriClass)
  418. {
  419. var oldValue = obj.oldValue;
  420. var newValue = obj.newValue;
  421. // Make sure that oldValue and newValue are of type boolean.
  422. var type;
  423. if ((type = typeof oldValue) !== 'boolean') {
  424. if (type === 'string') {
  425. oldValue = (oldValue == "true");
  426. } else {
  427. oldValue = new Boolean(oldValue).valueOf();
  428. }
  429. }
  430. if ((type = typeof newValue) !== 'boolean') {
  431. if (type === 'string') {
  432. newValue = (newValue == "true");
  433. } else {
  434. newValue = new Boolean(newValue).valueOf();
  435. }
  436. }
  437. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  438. }
  439. else if ("LastNEndpointsChangeEvent" === colibriClass)
  440. {
  441. // The new/latest list of last-n endpoint IDs.
  442. var lastNEndpoints = obj.lastNEndpoints;
  443. // The list of endpoint IDs which are entering the list of
  444. // last-n at this time i.e. were not in the old list of last-n
  445. // endpoint IDs.
  446. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  447. var stream = obj.stream;
  448. console.log(
  449. "Data channel new last-n event: ",
  450. lastNEndpoints, endpointsEnteringLastN, obj);
  451. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  452. lastNEndpoints, endpointsEnteringLastN, obj);
  453. }
  454. else
  455. {
  456. console.debug("Data channel JSON-formatted message: ", obj);
  457. }
  458. }
  459. };
  460. dataChannel.onclose = function ()
  461. {
  462. console.info("The Data Channel closed", dataChannel);
  463. var idx = _dataChannels.indexOf(dataChannel);
  464. if (idx > -1)
  465. _dataChannels = _dataChannels.splice(idx, 1);
  466. };
  467. _dataChannels.push(dataChannel);
  468. },
  469. /**
  470. * Binds "ondatachannel" event listener to given PeerConnection instance.
  471. * @param peerConnection WebRTC peer connection instance.
  472. */
  473. init: function (peerConnection, emitter) {
  474. if(!config.openSctp)
  475. return;
  476. peerConnection.ondatachannel = this.onDataChannel;
  477. eventEmitter = emitter;
  478. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  479. // Although it's not a requirement to open separate channels from both bridge
  480. // and peer as single channel can be used for sending and receiving data.
  481. // So either channel opened by the bridge or the one opened here is enough
  482. // for communication with the bridge.
  483. /*var dataChannelOptions =
  484. {
  485. reliable: true
  486. };
  487. var dataChannel
  488. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  489. // Can be used only when is in open state
  490. dataChannel.onopen = function ()
  491. {
  492. dataChannel.send("My channel !!!");
  493. };
  494. dataChannel.onmessage = function (event)
  495. {
  496. var msgData = event.data;
  497. console.info("Got My Data Channel Message:", msgData, dataChannel);
  498. };*/
  499. },
  500. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  501. handlePinnedEndpointEvent: onPinnedEndpointChanged
  502. };
  503. function onSelectedEndpointChanged(userResource)
  504. {
  505. console.log('selected endpoint changed: ', userResource);
  506. if (_dataChannels && _dataChannels.length != 0)
  507. {
  508. _dataChannels.some(function (dataChannel) {
  509. if (dataChannel.readyState == 'open')
  510. {
  511. console.log('sending selected endpoint changed '
  512. + 'notification to the bridge: ', userResource);
  513. dataChannel.send(JSON.stringify({
  514. 'colibriClass': 'SelectedEndpointChangedEvent',
  515. 'selectedEndpoint':
  516. (!userResource || userResource === null)?
  517. null : userResource
  518. }));
  519. return true;
  520. }
  521. });
  522. }
  523. }
  524. function onPinnedEndpointChanged(userResource)
  525. {
  526. console.log('pinned endpoint changed: ', userResource);
  527. if (_dataChannels && _dataChannels.length != 0)
  528. {
  529. _dataChannels.some(function (dataChannel) {
  530. if (dataChannel.readyState == 'open')
  531. {
  532. dataChannel.send(JSON.stringify({
  533. 'colibriClass': 'PinnedEndpointChangedEvent',
  534. 'pinnedEndpoint':
  535. (!userResource || userResource == null)?
  536. null : userResource
  537. }));
  538. return true;
  539. }
  540. });
  541. }
  542. }
  543. module.exports = DataChannels;
  544. },{"../../service/RTC/RTCEvents":103}],5:[function(require,module,exports){
  545. /*
  546. * Copyright @ 2015 Atlassian Pty Ltd
  547. *
  548. * Licensed under the Apache License, Version 2.0 (the "License");
  549. * you may not use this file except in compliance with the License.
  550. * You may obtain a copy of the License at
  551. *
  552. * http://www.apache.org/licenses/LICENSE-2.0
  553. *
  554. * Unless required by applicable law or agreed to in writing, software
  555. * distributed under the License is distributed on an "AS IS" BASIS,
  556. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  557. * See the License for the specific language governing permissions and
  558. * limitations under the License.
  559. */
  560. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  561. function LocalStream(stream, type, eventEmitter, videoType, isGUMStream)
  562. {
  563. this.stream = stream;
  564. this.eventEmitter = eventEmitter;
  565. this.type = type;
  566. this.videoType = videoType;
  567. this.isGUMStream = true;
  568. if(isGUMStream === false)
  569. this.isGUMStream = isGUMStream;
  570. var self = this;
  571. if(type == "audio")
  572. {
  573. this.getTracks = function () {
  574. return self.stream.getAudioTracks();
  575. };
  576. }
  577. else
  578. {
  579. this.getTracks = function () {
  580. return self.stream.getVideoTracks();
  581. };
  582. }
  583. this.stream.onended = function()
  584. {
  585. self.streamEnded();
  586. };
  587. }
  588. LocalStream.prototype.streamEnded = function () {
  589. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  590. }
  591. LocalStream.prototype.getOriginalStream = function()
  592. {
  593. return this.stream;
  594. }
  595. LocalStream.prototype.isAudioStream = function () {
  596. return this.type === "audio";
  597. };
  598. LocalStream.prototype.setMute = function(mute)
  599. {
  600. if((window.location.protocol != "https:" && this.isGUMStream) ||
  601. (this.isAudioStream() && this.isGUMStream) || this.videoType === "screen")
  602. {
  603. var tracks = this.getTracks();
  604. for (var idx = 0; idx < tracks.length; idx++) {
  605. tracks[idx].enabled = mute;
  606. }
  607. }
  608. else
  609. {
  610. if(mute === false) {
  611. APP.xmpp.removeStream(this.stream);
  612. this.stream.stop();
  613. }
  614. else
  615. {
  616. var self = this;
  617. APP.RTC.rtcUtils.obtainAudioAndVideoPermissions(
  618. (this.isAudioStream() ? ["audio"] : ["video"]),
  619. function (stream) {
  620. if(self.isAudioStream())
  621. {
  622. APP.RTC.changeLocalAudio(stream, function () {});
  623. }
  624. else
  625. {
  626. APP.RTC.changeLocalVideo(stream, false, function () {});
  627. }
  628. });
  629. }
  630. }
  631. };
  632. LocalStream.prototype.isMuted = function () {
  633. var tracks = [];
  634. if(this.type == "audio")
  635. {
  636. tracks = this.stream.getAudioTracks();
  637. }
  638. else
  639. {
  640. if(this.stream.ended)
  641. return true;
  642. tracks = this.stream.getVideoTracks();
  643. }
  644. for (var idx = 0; idx < tracks.length; idx++) {
  645. if(tracks[idx].enabled)
  646. return false;
  647. }
  648. return true;
  649. }
  650. LocalStream.prototype.getId = function () {
  651. return this.stream.getTracks()[0].id;
  652. }
  653. module.exports = LocalStream;
  654. },{"../../service/RTC/StreamEventTypes.js":105}],6:[function(require,module,exports){
  655. /*
  656. * Copyright @ 2015 Atlassian Pty Ltd
  657. *
  658. * Licensed under the Apache License, Version 2.0 (the "License");
  659. * you may not use this file except in compliance with the License.
  660. * You may obtain a copy of the License at
  661. *
  662. * http://www.apache.org/licenses/LICENSE-2.0
  663. *
  664. * Unless required by applicable law or agreed to in writing, software
  665. * distributed under the License is distributed on an "AS IS" BASIS,
  666. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  667. * See the License for the specific language governing permissions and
  668. * limitations under the License.
  669. */
  670. ////These lines should be uncommented when require works in app.js
  671. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  672. var StreamEventType = require("../../service/RTC/StreamEventTypes");
  673. /**
  674. * Creates a MediaStream object for the given data, session id and ssrc.
  675. * It is a wrapper class for the MediaStream.
  676. *
  677. * @param data the data object from which we obtain the stream,
  678. * the peerjid, etc.
  679. * @param sid the session id
  680. * @param ssrc the ssrc corresponding to this MediaStream
  681. *
  682. * @constructor
  683. */
  684. function MediaStream(data, sid, ssrc, browser, eventEmitter) {
  685. // XXX(gp) to minimize headaches in the future, we should build our
  686. // abstractions around tracks and not streams. ORTC is track based API.
  687. // Mozilla expects m-lines to represent media tracks.
  688. //
  689. // Practically, what I'm saying is that we should have a MediaTrack class
  690. // and not a MediaStream class.
  691. //
  692. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  693. // a track might have an associated RTX and FEC sources.
  694. this.sid = sid;
  695. this.stream = data.stream;
  696. this.peerjid = data.peerjid;
  697. this.ssrc = ssrc;
  698. this.type = (this.stream.getVideoTracks().length > 0)?
  699. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  700. this.videoType = null;
  701. this.muted = false;
  702. this.eventEmitter = eventEmitter;
  703. }
  704. MediaStream.prototype.getOriginalStream = function()
  705. {
  706. return this.stream;
  707. };
  708. MediaStream.prototype.setMute = function (value)
  709. {
  710. this.stream.muted = value;
  711. this.muted = value;
  712. };
  713. MediaStream.prototype.setVideoType = function (value) {
  714. if(this.videoType === value)
  715. return;
  716. this.videoType = value;
  717. this.eventEmitter.emit(StreamEventType.EVENT_TYPE_REMOTE_CHANGED,
  718. this.peerjid);
  719. };
  720. module.exports = MediaStream;
  721. },{"../../service/RTC/MediaStreamTypes":101,"../../service/RTC/StreamEventTypes":105}],7:[function(require,module,exports){
  722. /*
  723. * Copyright @ 2015 Atlassian Pty Ltd
  724. *
  725. * Licensed under the Apache License, Version 2.0 (the "License");
  726. * you may not use this file except in compliance with the License.
  727. * You may obtain a copy of the License at
  728. *
  729. * http://www.apache.org/licenses/LICENSE-2.0
  730. *
  731. * Unless required by applicable law or agreed to in writing, software
  732. * distributed under the License is distributed on an "AS IS" BASIS,
  733. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  734. * See the License for the specific language governing permissions and
  735. * limitations under the License.
  736. */
  737. var EventEmitter = require("events");
  738. var RTCUtils = require("./RTCUtils.js");
  739. var LocalStream = require("./LocalStream.js");
  740. var DataChannels = require("./DataChannels");
  741. var MediaStream = require("./MediaStream.js");
  742. var DesktopSharingEventTypes
  743. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  744. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  745. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  746. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  747. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  748. var UIEvents = require("../../service/UI/UIEvents");
  749. var eventEmitter = new EventEmitter();
  750. function getMediaStreamUsage()
  751. {
  752. var result = {
  753. audio: true,
  754. video: true
  755. };
  756. /** There are some issues with the desktop sharing
  757. * when this property is enabled.
  758. * WARNING: We must change the implementation to start video/audio if we
  759. * receive from the focus that the peer is not muted.
  760. var isSecureConnection = window.location.protocol == "https:";
  761. if(config.disableEarlyMediaPermissionRequests || !isSecureConnection)
  762. {
  763. result = {
  764. audio: false,
  765. video: false
  766. };
  767. }
  768. **/
  769. return result;
  770. }
  771. var RTC = {
  772. rtcUtils: null,
  773. devices: {
  774. audio: true,
  775. video: true
  776. },
  777. localStreams: [],
  778. remoteStreams: {},
  779. localAudio: null,
  780. localVideo: null,
  781. addStreamListener: function (listener, eventType) {
  782. eventEmitter.on(eventType, listener);
  783. },
  784. addListener: function (type, listener) {
  785. eventEmitter.on(type, listener);
  786. },
  787. removeStreamListener: function (listener, eventType) {
  788. if(!(eventType instanceof StreamEventTypes))
  789. throw "Illegal argument";
  790. eventEmitter.removeListener(eventType, listener);
  791. },
  792. createLocalStream: function (stream, type, change, videoType, isMuted, isGUMStream) {
  793. var localStream = new LocalStream(stream, type, eventEmitter, videoType, isGUMStream);
  794. //in firefox we have only one stream object
  795. if(this.localStreams.length == 0 ||
  796. this.localStreams[0].getOriginalStream() != stream)
  797. this.localStreams.push(localStream);
  798. if(isMuted === true)
  799. localStream.setMute(false);
  800. if(type == "audio")
  801. {
  802. this.localAudio = localStream;
  803. }
  804. else
  805. {
  806. this.localVideo = localStream;
  807. }
  808. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  809. if(change)
  810. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  811. eventEmitter.emit(eventType, localStream, isMuted);
  812. return localStream;
  813. },
  814. removeLocalStream: function (stream) {
  815. for(var i = 0; i < this.localStreams.length; i++)
  816. {
  817. if(this.localStreams[i].getOriginalStream() === stream) {
  818. delete this.localStreams[i];
  819. return;
  820. }
  821. }
  822. },
  823. createRemoteStream: function (data, sid, thessrc) {
  824. var remoteStream = new MediaStream(data, sid, thessrc,
  825. this.getBrowserType(), eventEmitter);
  826. var jid = data.peerjid || APP.xmpp.myJid();
  827. if(!this.remoteStreams[jid]) {
  828. this.remoteStreams[jid] = {};
  829. }
  830. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  831. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  832. return remoteStream;
  833. },
  834. getBrowserType: function () {
  835. return this.rtcUtils.browser;
  836. },
  837. getPCConstraints: function () {
  838. return this.rtcUtils.pc_constraints;
  839. },
  840. getUserMediaWithConstraints:function(um, success_callback,
  841. failure_callback, resolution,
  842. bandwidth, fps, desktopStream)
  843. {
  844. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  845. failure_callback, resolution, bandwidth, fps, desktopStream);
  846. },
  847. attachMediaStream: function (element, stream) {
  848. this.rtcUtils.attachMediaStream(element, stream);
  849. },
  850. getStreamID: function (stream) {
  851. return this.rtcUtils.getStreamID(stream);
  852. },
  853. getVideoSrc: function (element) {
  854. return this.rtcUtils.getVideoSrc(element);
  855. },
  856. setVideoSrc: function (element, src) {
  857. this.rtcUtils.setVideoSrc(element, src);
  858. },
  859. dispose: function() {
  860. if (this.rtcUtils) {
  861. this.rtcUtils = null;
  862. }
  863. },
  864. stop: function () {
  865. this.dispose();
  866. },
  867. start: function () {
  868. var self = this;
  869. APP.desktopsharing.addListener(
  870. function (stream, isUsingScreenStream, callback) {
  871. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  872. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  873. APP.xmpp.addListener(XMPPEvents.STREAMS_CHANGED, function (jid, changedStreams) {
  874. for(var i = 0; i < changedStreams.length; i++) {
  875. var type = changedStreams[i].type;
  876. if (type != "audio") {
  877. var peerStreams = self.remoteStreams[jid];
  878. if(!peerStreams)
  879. continue;
  880. var videoStream = peerStreams[MediaStreamType.VIDEO_TYPE];
  881. if(!videoStream)
  882. continue;
  883. videoStream.setVideoType(changedStreams[i].type);
  884. }
  885. }
  886. });
  887. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  888. DataChannels.init(event.peerconnection, eventEmitter);
  889. });
  890. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  891. DataChannels.handleSelectedEndpointEvent);
  892. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  893. DataChannels.handlePinnedEndpointEvent);
  894. this.rtcUtils = new RTCUtils(this);
  895. this.rtcUtils.obtainAudioAndVideoPermissions(
  896. null, null, getMediaStreamUsage());
  897. },
  898. muteRemoteVideoStream: function (jid, value) {
  899. var stream;
  900. if(this.remoteStreams[jid] &&
  901. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE])
  902. {
  903. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  904. }
  905. if(!stream)
  906. return true;
  907. if (value != stream.muted) {
  908. stream.setMute(value);
  909. return true;
  910. }
  911. return false;
  912. },
  913. switchVideoStreams: function (new_stream) {
  914. this.localVideo.stream = new_stream;
  915. this.localStreams = [];
  916. //in firefox we have only one stream object
  917. if (this.localAudio.getOriginalStream() != new_stream)
  918. this.localStreams.push(this.localAudio);
  919. this.localStreams.push(this.localVideo);
  920. },
  921. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  922. var oldStream = this.localVideo.getOriginalStream();
  923. var type = (isUsingScreenStream? "screen" : "video");
  924. var localCallback = callback;
  925. if(this.localVideo.isMuted() && this.localVideo.videoType !== type)
  926. {
  927. localCallback = function() {
  928. APP.xmpp.setVideoMute(false, APP.UI.setVideoMuteButtonsState);
  929. callback();
  930. };
  931. }
  932. var videoStream = this.rtcUtils.createStream(stream, true);
  933. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  934. // Stop the stream to trigger onended event for old stream
  935. oldStream.stop();
  936. APP.xmpp.switchStreams(videoStream, oldStream,localCallback);
  937. },
  938. changeLocalAudio: function (stream, callback) {
  939. var oldStream = this.localAudio.getOriginalStream();
  940. var newStream = this.rtcUtils.createStream(stream);
  941. this.localAudio = this.createLocalStream(newStream, "audio", true);
  942. // Stop the stream to trigger onended event for old stream
  943. oldStream.stop();
  944. APP.xmpp.switchStreams(newStream, oldStream, callback, true);
  945. },
  946. /**
  947. * Checks if video identified by given src is desktop stream.
  948. * @param videoSrc eg.
  949. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  950. * @returns {boolean}
  951. */
  952. isVideoSrcDesktop: function (jid) {
  953. if(!jid)
  954. return false;
  955. var isDesktop = false;
  956. var stream = null;
  957. if (APP.xmpp.myJid() === jid) {
  958. // local video
  959. stream = this.localVideo;
  960. } else {
  961. var peerStreams = this.remoteStreams[jid];
  962. if(!peerStreams)
  963. return false;
  964. stream = peerStreams[MediaStreamType.VIDEO_TYPE];
  965. }
  966. if(stream)
  967. isDesktop = (stream.videoType === "screen");
  968. return isDesktop;
  969. },
  970. setVideoMute: function(mute, callback, options) {
  971. if(!this.localVideo)
  972. return;
  973. if (mute == APP.RTC.localVideo.isMuted())
  974. {
  975. APP.xmpp.sendVideoInfoPresence(mute);
  976. if(callback)
  977. callback(mute);
  978. }
  979. else
  980. {
  981. APP.RTC.localVideo.setMute(!mute);
  982. APP.xmpp.setVideoMute(
  983. mute,
  984. callback,
  985. options);
  986. }
  987. },
  988. setDeviceAvailability: function (devices) {
  989. if(!devices)
  990. return;
  991. if(devices.audio === true || devices.audio === false)
  992. this.devices.audio = devices.audio;
  993. if(devices.video === true || devices.video === false)
  994. this.devices.video = devices.video;
  995. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  996. }
  997. };
  998. module.exports = RTC;
  999. },{"../../service/RTC/MediaStreamTypes":101,"../../service/RTC/RTCEvents.js":103,"../../service/RTC/StreamEventTypes.js":105,"../../service/UI/UIEvents":106,"../../service/desktopsharing/DesktopSharingEventTypes":109,"../../service/xmpp/XMPPEvents":112,"./DataChannels":4,"./LocalStream.js":5,"./MediaStream.js":6,"./RTCUtils.js":8,"events":62}],8:[function(require,module,exports){
  1000. /*
  1001. * Copyright @ 2015 Atlassian Pty Ltd
  1002. *
  1003. * Licensed under the Apache License, Version 2.0 (the "License");
  1004. * you may not use this file except in compliance with the License.
  1005. * You may obtain a copy of the License at
  1006. *
  1007. * http://www.apache.org/licenses/LICENSE-2.0
  1008. *
  1009. * Unless required by applicable law or agreed to in writing, software
  1010. * distributed under the License is distributed on an "AS IS" BASIS,
  1011. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1012. * See the License for the specific language governing permissions and
  1013. * limitations under the License.
  1014. */
  1015. var RTCBrowserType = require("../../service/RTC/RTCBrowserType.js");
  1016. var Resolutions = require("../../service/RTC/Resolutions");
  1017. var currentResolution = null;
  1018. function getPreviousResolution(resolution) {
  1019. if(!Resolutions[resolution])
  1020. return null;
  1021. var order = Resolutions[resolution].order;
  1022. var res = null;
  1023. var resName = null;
  1024. for(var i in Resolutions)
  1025. {
  1026. var tmp = Resolutions[i];
  1027. if(res == null || (res.order < tmp.order && tmp.order < order))
  1028. {
  1029. resName = i;
  1030. res = tmp;
  1031. }
  1032. }
  1033. return resName;
  1034. }
  1035. function setResolutionConstraints(constraints, resolution, isAndroid)
  1036. {
  1037. if (resolution && !constraints.video || isAndroid) {
  1038. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  1039. }
  1040. if(Resolutions[resolution])
  1041. {
  1042. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1043. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1044. }
  1045. else
  1046. {
  1047. if (isAndroid) {
  1048. constraints.video.mandatory.minWidth = 320;
  1049. constraints.video.mandatory.minHeight = 240;
  1050. constraints.video.mandatory.maxFrameRate = 15;
  1051. }
  1052. }
  1053. if (constraints.video.mandatory.minWidth)
  1054. constraints.video.mandatory.maxWidth = constraints.video.mandatory.minWidth;
  1055. if (constraints.video.mandatory.minHeight)
  1056. constraints.video.mandatory.maxHeight = constraints.video.mandatory.minHeight;
  1057. }
  1058. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  1059. {
  1060. var constraints = {audio: false, video: false};
  1061. if (um.indexOf('video') >= 0) {
  1062. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  1063. }
  1064. if (um.indexOf('audio') >= 0) {
  1065. constraints.audio = { mandatory: {}, optional: []};// same behaviour as true
  1066. }
  1067. if (um.indexOf('screen') >= 0) {
  1068. constraints.video = {
  1069. mandatory: {
  1070. chromeMediaSource: "screen",
  1071. googLeakyBucket: true,
  1072. maxWidth: window.screen.width,
  1073. maxHeight: window.screen.height,
  1074. maxFrameRate: 3
  1075. },
  1076. optional: []
  1077. };
  1078. }
  1079. if (um.indexOf('desktop') >= 0) {
  1080. constraints.video = {
  1081. mandatory: {
  1082. chromeMediaSource: "desktop",
  1083. chromeMediaSourceId: desktopStream,
  1084. googLeakyBucket: true,
  1085. maxWidth: window.screen.width,
  1086. maxHeight: window.screen.height,
  1087. maxFrameRate: 3
  1088. },
  1089. optional: []
  1090. };
  1091. }
  1092. if (constraints.audio) {
  1093. // if it is good enough for hangouts...
  1094. constraints.audio.optional.push(
  1095. {googEchoCancellation: true},
  1096. {googAutoGainControl: true},
  1097. {googNoiseSupression: true},
  1098. {googHighpassFilter: true},
  1099. {googNoisesuppression2: true},
  1100. {googEchoCancellation2: true},
  1101. {googAutoGainControl2: true}
  1102. );
  1103. }
  1104. if (constraints.video) {
  1105. constraints.video.optional.push(
  1106. {googNoiseReduction: false} // chrome 37 workaround for issue 3807, reenable in M38
  1107. );
  1108. if (um.indexOf('video') >= 0) {
  1109. constraints.video.optional.push(
  1110. {googLeakyBucket: true}
  1111. );
  1112. }
  1113. }
  1114. if (um.indexOf('video') >= 0) {
  1115. setResolutionConstraints(constraints, resolution, isAndroid);
  1116. }
  1117. if (bandwidth) { // doesn't work currently, see webrtc issue 1846
  1118. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};//same behaviour as true
  1119. constraints.video.optional.push({bandwidth: bandwidth});
  1120. }
  1121. if (fps) { // for some cameras it might be necessary to request 30fps
  1122. // so they choose 30fps mjpg over 10fps yuy2
  1123. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};// same behaviour as true;
  1124. constraints.video.mandatory.minFrameRate = fps;
  1125. }
  1126. return constraints;
  1127. }
  1128. function RTCUtils(RTCService)
  1129. {
  1130. this.service = RTCService;
  1131. if (navigator.mozGetUserMedia) {
  1132. console.log('This appears to be Firefox');
  1133. var version = parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1134. if (version >= 40
  1135. && config.useBundle && config.useRtcpMux) {
  1136. this.peerconnection = mozRTCPeerConnection;
  1137. this.browser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  1138. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1139. this.pc_constraints = {};
  1140. this.attachMediaStream = function (element, stream) {
  1141. // srcObject is being standardized and FF will eventually
  1142. // support that unprefixed. FF also supports the
  1143. // "element.src = URL.createObjectURL(...)" combo, but that
  1144. // will be deprecated in favour of srcObject.
  1145. //
  1146. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1147. // https://github.com/webrtc/samples/issues/302
  1148. if(!element[0])
  1149. return;
  1150. element[0].mozSrcObject = stream;
  1151. element[0].play();
  1152. };
  1153. this.getStreamID = function (stream) {
  1154. var tracks = stream.getVideoTracks();
  1155. if(!tracks || tracks.length == 0)
  1156. {
  1157. tracks = stream.getAudioTracks();
  1158. }
  1159. return tracks[0].id.replace(/[\{,\}]/g,"");
  1160. };
  1161. this.getVideoSrc = function (element) {
  1162. if(!element)
  1163. return null;
  1164. return element.mozSrcObject;
  1165. };
  1166. this.setVideoSrc = function (element, src) {
  1167. if(element)
  1168. element.mozSrcObject = src;
  1169. };
  1170. RTCSessionDescription = mozRTCSessionDescription;
  1171. RTCIceCandidate = mozRTCIceCandidate;
  1172. } else {
  1173. window.location.href = 'unsupported_browser.html';
  1174. return;
  1175. }
  1176. } else if (navigator.webkitGetUserMedia) {
  1177. console.log('This appears to be Chrome');
  1178. this.peerconnection = webkitRTCPeerConnection;
  1179. this.browser = RTCBrowserType.RTC_BROWSER_CHROME;
  1180. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1181. this.attachMediaStream = function (element, stream) {
  1182. element.attr('src', webkitURL.createObjectURL(stream));
  1183. };
  1184. this.getStreamID = function (stream) {
  1185. // streams from FF endpoints have the characters '{' and '}'
  1186. // that make jQuery choke.
  1187. return stream.id.replace(/[\{,\}]/g,"");
  1188. };
  1189. this.getVideoSrc = function (element) {
  1190. if(!element)
  1191. return null;
  1192. return element.getAttribute("src");
  1193. };
  1194. this.setVideoSrc = function (element, src) {
  1195. if(element)
  1196. element.setAttribute("src", src);
  1197. };
  1198. // DTLS should now be enabled by default but..
  1199. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  1200. if (navigator.userAgent.indexOf('Android') != -1) {
  1201. this.pc_constraints = {}; // disable DTLS on Android
  1202. }
  1203. if (!webkitMediaStream.prototype.getVideoTracks) {
  1204. webkitMediaStream.prototype.getVideoTracks = function () {
  1205. return this.videoTracks;
  1206. };
  1207. }
  1208. if (!webkitMediaStream.prototype.getAudioTracks) {
  1209. webkitMediaStream.prototype.getAudioTracks = function () {
  1210. return this.audioTracks;
  1211. };
  1212. }
  1213. }
  1214. else
  1215. {
  1216. try { console.log('Browser does not appear to be WebRTC-capable'); } catch (e) { }
  1217. window.location.href = 'unsupported_browser.html';
  1218. return;
  1219. }
  1220. }
  1221. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1222. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1223. desktopStream)
  1224. {
  1225. currentResolution = resolution;
  1226. // Check if we are running on Android device
  1227. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1228. var constraints = getConstraints(
  1229. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1230. var isFF = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
  1231. var self = this;
  1232. try {
  1233. this.getUserMedia(constraints,
  1234. function (stream) {
  1235. console.log('onUserMediaSuccess');
  1236. self.setAvailableDevices(um, true);
  1237. success_callback(stream);
  1238. },
  1239. function (error) {
  1240. self.setAvailableDevices(um, false);
  1241. console.warn('Failed to get access to local media. Error ',
  1242. error, constraints);
  1243. if (failure_callback) {
  1244. failure_callback(error);
  1245. }
  1246. });
  1247. } catch (e) {
  1248. console.error('GUM failed: ', e);
  1249. if(failure_callback) {
  1250. failure_callback(e);
  1251. }
  1252. }
  1253. };
  1254. RTCUtils.prototype.setAvailableDevices = function (um, available) {
  1255. var devices = {};
  1256. if(um.indexOf("video") != -1)
  1257. {
  1258. devices.video = available;
  1259. }
  1260. if(um.indexOf("audio") != -1)
  1261. {
  1262. devices.audio = available;
  1263. }
  1264. this.service.setDeviceAvailability(devices);
  1265. }
  1266. /**
  1267. * We ask for audio and video combined stream in order to get permissions and
  1268. * not to ask twice.
  1269. */
  1270. RTCUtils.prototype.obtainAudioAndVideoPermissions =
  1271. function(devices, callback, usageOptions)
  1272. {
  1273. var self = this;
  1274. // Get AV
  1275. var successCallback = function (stream) {
  1276. if(callback)
  1277. callback(stream, usageOptions);
  1278. else
  1279. self.successCallback(stream, usageOptions);
  1280. };
  1281. if(!devices)
  1282. devices = ['audio', 'video'];
  1283. var newDevices = [];
  1284. if(usageOptions)
  1285. for(var i = 0; i < devices.length; i++)
  1286. {
  1287. var device = devices[i];
  1288. if(usageOptions[device] === true)
  1289. newDevices.push(device);
  1290. }
  1291. else
  1292. newDevices = devices;
  1293. if(newDevices.length === 0)
  1294. {
  1295. successCallback();
  1296. return;
  1297. }
  1298. if (navigator.mozGetUserMedia) {
  1299. // With FF we can't split the stream into audio and video because FF
  1300. // doesn't support media stream constructors. So, we need to get the
  1301. // audio stream separately from the video stream using two distinct GUM
  1302. // calls. Not very user friendly :-( but we don't have many other
  1303. // options neither.
  1304. //
  1305. // Note that we pack those 2 streams in a single object and pass it to
  1306. // the successCallback method.
  1307. self.getUserMediaWithConstraints(
  1308. ['audio'],
  1309. function (audioStream) {
  1310. self.getUserMediaWithConstraints(
  1311. ['video'],
  1312. function (videoStream) {
  1313. return self.successCallback({
  1314. audioStream: audioStream,
  1315. videoStream: videoStream
  1316. });
  1317. },
  1318. function (error) {
  1319. console.error('failed to obtain video stream - stop',
  1320. error);
  1321. return self.successCallback(null);
  1322. },
  1323. config.resolution || '360');
  1324. },
  1325. function (error) {
  1326. console.error('failed to obtain audio stream - stop',
  1327. error);
  1328. return self.successCallback(null);
  1329. }
  1330. );
  1331. } else {
  1332. this.getUserMediaWithConstraints(
  1333. newDevices,
  1334. function (stream) {
  1335. successCallback(stream);
  1336. },
  1337. function (error) {
  1338. self.errorCallback(error);
  1339. },
  1340. config.resolution || '360');
  1341. }
  1342. }
  1343. RTCUtils.prototype.successCallback = function (stream, usageOptions) {
  1344. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1345. // an object with two properties: audioStream, videoStream.
  1346. if(stream && !navigator.mozGetUserMedia)
  1347. console.log('got', stream, stream.getAudioTracks().length,
  1348. stream.getVideoTracks().length);
  1349. this.handleLocalStream(stream, usageOptions);
  1350. };
  1351. RTCUtils.prototype.errorCallback = function (error) {
  1352. var self = this;
  1353. console.error('failed to obtain audio/video stream - trying audio only', error);
  1354. var resolution = getPreviousResolution(currentResolution);
  1355. if(typeof error == "object" && error.constraintName && error.name
  1356. && (error.name == "ConstraintNotSatisfiedError" ||
  1357. error.name == "OverconstrainedError") &&
  1358. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1359. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1360. && resolution != null)
  1361. {
  1362. self.getUserMediaWithConstraints(['audio', 'video'],
  1363. function (stream) {
  1364. return self.successCallback(stream);
  1365. }, function (error) {
  1366. return self.errorCallback(error);
  1367. }, resolution);
  1368. }
  1369. else
  1370. {
  1371. self.getUserMediaWithConstraints(
  1372. ['audio'],
  1373. function (stream) {
  1374. return self.successCallback(stream);
  1375. },
  1376. function (error) {
  1377. console.error('failed to obtain audio/video stream - stop',
  1378. error);
  1379. return self.successCallback(null);
  1380. }
  1381. );
  1382. }
  1383. }
  1384. RTCUtils.prototype.handleLocalStream = function(stream, usageOptions)
  1385. {
  1386. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1387. // an object with two properties: audioStream, videoStream.
  1388. var audioStream, videoStream;
  1389. if(window.webkitMediaStream)
  1390. {
  1391. audioStream = new webkitMediaStream();
  1392. videoStream = new webkitMediaStream();
  1393. if(stream) {
  1394. var audioTracks = stream.getAudioTracks();
  1395. for (var i = 0; i < audioTracks.length; i++) {
  1396. audioStream.addTrack(audioTracks[i]);
  1397. }
  1398. var videoTracks = stream.getVideoTracks();
  1399. for (i = 0; i < videoTracks.length; i++) {
  1400. videoStream.addTrack(videoTracks[i]);
  1401. }
  1402. }
  1403. }
  1404. else
  1405. {//firefox
  1406. audioStream = stream.audioStream;
  1407. videoStream = stream.videoStream;
  1408. }
  1409. var audioMuted = (usageOptions && usageOptions.audio === false),
  1410. videoMuted = (usageOptions && usageOptions.video === false);
  1411. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  1412. videoGUM = (!usageOptions || usageOptions.video !== false);
  1413. this.service.createLocalStream(audioStream, "audio", null, null,
  1414. audioMuted, audioGUM);
  1415. this.service.createLocalStream(videoStream, "video", null, null,
  1416. videoMuted, videoGUM);
  1417. };
  1418. RTCUtils.prototype.createStream = function(stream, isVideo)
  1419. {
  1420. var newStream = null;
  1421. if(window.webkitMediaStream)
  1422. {
  1423. newStream = new webkitMediaStream();
  1424. if(newStream)
  1425. {
  1426. var tracks = (isVideo? stream.getVideoTracks() : stream.getAudioTracks());
  1427. for (i = 0; i < tracks.length; i++) {
  1428. newStream.addTrack(tracks[i]);
  1429. }
  1430. }
  1431. }
  1432. else
  1433. newStream = stream;
  1434. return newStream;
  1435. };
  1436. module.exports = RTCUtils;
  1437. },{"../../service/RTC/RTCBrowserType.js":102,"../../service/RTC/Resolutions":104}],9:[function(require,module,exports){
  1438. /*
  1439. * Copyright @ 2015 Atlassian Pty Ltd
  1440. *
  1441. * Licensed under the Apache License, Version 2.0 (the "License");
  1442. * you may not use this file except in compliance with the License.
  1443. * You may obtain a copy of the License at
  1444. *
  1445. * http://www.apache.org/licenses/LICENSE-2.0
  1446. *
  1447. * Unless required by applicable law or agreed to in writing, software
  1448. * distributed under the License is distributed on an "AS IS" BASIS,
  1449. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1450. * See the License for the specific language governing permissions and
  1451. * limitations under the License.
  1452. */
  1453. var UI = {};
  1454. var VideoLayout = require("./videolayout/VideoLayout.js");
  1455. var AudioLevels = require("./audio_levels/AudioLevels.js");
  1456. var Prezi = require("./prezi/Prezi.js");
  1457. var Etherpad = require("./etherpad/Etherpad.js");
  1458. var Chat = require("./side_pannels/chat/Chat.js");
  1459. var Toolbar = require("./toolbars/Toolbar");
  1460. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  1461. var BottomToolbar = require("./toolbars/BottomToolbar");
  1462. var ContactList = require("./side_pannels/contactlist/ContactList");
  1463. var Avatar = require("./avatar/Avatar");
  1464. var EventEmitter = require("events");
  1465. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  1466. var Settings = require("./../settings/Settings");
  1467. var PanelToggler = require("./side_pannels/SidePanelToggler");
  1468. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  1469. UI.messageHandler = require("./util/MessageHandler");
  1470. var messageHandler = UI.messageHandler;
  1471. var Authentication = require("./authentication/Authentication");
  1472. var UIUtil = require("./util/UIUtil");
  1473. var NicknameHandler = require("./util/NicknameHandler");
  1474. var CQEvents = require("../../service/connectionquality/CQEvents");
  1475. var DesktopSharingEventTypes
  1476. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1477. var RTCEvents = require("../../service/RTC/RTCEvents");
  1478. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  1479. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  1480. var MemberEvents = require("../../service/members/Events");
  1481. var eventEmitter = new EventEmitter();
  1482. var roomName = null;
  1483. function notifyForInitialMute()
  1484. {
  1485. messageHandler.notify(null, "notify.mutedTitle", "connected",
  1486. "notify.muted", null, {timeOut: 120000});
  1487. }
  1488. function setupPrezi()
  1489. {
  1490. $("#reloadPresentationLink").click(function()
  1491. {
  1492. Prezi.reloadPresentation();
  1493. });
  1494. }
  1495. function setupChat()
  1496. {
  1497. Chat.init();
  1498. $("#toggle_smileys").click(function() {
  1499. Chat.toggleSmileys();
  1500. });
  1501. }
  1502. function setupToolbars() {
  1503. Toolbar.init(UI);
  1504. Toolbar.setupButtonsFromConfig();
  1505. BottomToolbar.init();
  1506. }
  1507. function streamHandler(stream, isMuted) {
  1508. switch (stream.type)
  1509. {
  1510. case "audio":
  1511. VideoLayout.changeLocalAudio(stream, isMuted);
  1512. break;
  1513. case "video":
  1514. VideoLayout.changeLocalVideo(stream, isMuted);
  1515. break;
  1516. case "stream":
  1517. VideoLayout.changeLocalStream(stream, isMuted);
  1518. break;
  1519. }
  1520. }
  1521. function onXmppConnectionFailed(stropheErrorMsg) {
  1522. var title = APP.translation.generateTranslatonHTML(
  1523. "dialog.error");
  1524. var message;
  1525. if (stropheErrorMsg) {
  1526. message = APP.translation.generateTranslatonHTML(
  1527. "dialog.connectErrorWithMsg", {msg: stropheErrorMsg});
  1528. } else {
  1529. message = APP.translation.generateTranslatonHTML(
  1530. "dialog.connectError");
  1531. }
  1532. messageHandler.openDialog(
  1533. title, message, true, {}, function (e, v, m, f) { return false; });
  1534. }
  1535. function onDisposeConference(unload) {
  1536. Toolbar.showAuthenticateButton(false);
  1537. }
  1538. function onDisplayNameChanged(jid, displayName) {
  1539. ContactList.onDisplayNameChange(jid, displayName);
  1540. SettingsMenu.onDisplayNameChange(jid, displayName);
  1541. VideoLayout.onDisplayNameChanged(jid, displayName);
  1542. }
  1543. function registerListeners() {
  1544. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  1545. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  1546. APP.RTC.addStreamListener(function (stream) {
  1547. VideoLayout.onRemoteStreamAdded(stream);
  1548. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  1549. APP.RTC.addStreamListener(function (jid) {
  1550. VideoLayout.onVideoTypeChanged(jid);
  1551. }, StreamEventTypes.EVENT_TYPE_REMOTE_CHANGED);
  1552. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  1553. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (resourceJid) {
  1554. VideoLayout.onDominantSpeakerChanged(resourceJid);
  1555. });
  1556. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1557. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  1558. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  1559. endpointsEnteringLastN, stream);
  1560. });
  1561. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED,
  1562. function (devices) {
  1563. VideoLayout.setDeviceAvailabilityIcons(null, devices);
  1564. })
  1565. APP.statistics.addAudioLevelListener(function(jid, audioLevel)
  1566. {
  1567. var resourceJid;
  1568. if(jid === APP.statistics.LOCAL_JID)
  1569. {
  1570. resourceJid = AudioLevels.LOCAL_LEVEL;
  1571. if(APP.RTC.localAudio.isMuted())
  1572. {
  1573. audioLevel = 0;
  1574. }
  1575. }
  1576. else
  1577. {
  1578. resourceJid = Strophe.getResourceFromJid(jid);
  1579. }
  1580. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  1581. UI.getLargeVideoState().userResourceJid);
  1582. });
  1583. APP.desktopsharing.addListener(function () {
  1584. ToolbarToggler.showDesktopSharingButton();
  1585. }, DesktopSharingEventTypes.INIT);
  1586. APP.desktopsharing.addListener(
  1587. Toolbar.changeDesktopSharingButtonState,
  1588. DesktopSharingEventTypes.SWITCHING_DONE);
  1589. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  1590. VideoLayout.updateLocalConnectionStats);
  1591. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  1592. VideoLayout.updateConnectionStats);
  1593. APP.connectionquality.addListener(CQEvents.STOP,
  1594. VideoLayout.onStatsStop);
  1595. APP.xmpp.addListener(XMPPEvents.CONNECTION_FAILED, onXmppConnectionFailed);
  1596. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  1597. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  1598. messageHandler.openMessageDialog(
  1599. 'dialog.serviceUnavailable',
  1600. 'dialog.gracefulShutdown'
  1601. );
  1602. });
  1603. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  1604. var title = APP.translation.generateTranslatonHTML(
  1605. "dialog.reservationError");
  1606. var message = APP.translation.generateTranslatonHTML(
  1607. "dialog.reservationErrorMsg", {code: code, msg: msg});
  1608. messageHandler.openDialog(
  1609. title,
  1610. message,
  1611. true, {},
  1612. function (event, value, message, formVals)
  1613. {
  1614. return false;
  1615. }
  1616. );
  1617. });
  1618. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  1619. messageHandler.openMessageDialog("dialog.sessTerminated",
  1620. "dialog.kickMessage");
  1621. });
  1622. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  1623. //FIXME: use Session Terminated from translation, but
  1624. // 'reason' text comes from XMPP packet and is not translated
  1625. var title = APP.translation.generateTranslatonHTML("dialog.sessTerminated");
  1626. messageHandler.openDialog(
  1627. title, reason, true, {},
  1628. function (event, value, message, formVals)
  1629. {
  1630. return false;
  1631. }
  1632. );
  1633. });
  1634. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  1635. messageHandler.showError("dialog.error",
  1636. "dialog.bridgeUnavailable");
  1637. });
  1638. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  1639. Avatar.setUserAvatar(from, id);
  1640. });
  1641. APP.xmpp.addListener(XMPPEvents.STREAMS_CHANGED, function (jid, changedStreams) {
  1642. for(stream in changedStreams)
  1643. {
  1644. // might need to update the direction if participant just went from sendrecv to recvonly
  1645. if (stream.type === 'video' || stream.type === 'screen') {
  1646. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  1647. switch (stream.direction) {
  1648. case 'sendrecv':
  1649. el.show();
  1650. break;
  1651. case 'recvonly':
  1652. el.hide();
  1653. // FIXME: Check if we have to change large video
  1654. //VideoLayout.updateLargeVideo(el);
  1655. break;
  1656. }
  1657. }
  1658. }
  1659. });
  1660. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  1661. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  1662. APP.xmpp.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, onLocalRoleChanged);
  1663. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  1664. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  1665. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  1666. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  1667. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  1668. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  1669. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordRequired);
  1670. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  1671. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  1672. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED,
  1673. onAuthenticationRequired);
  1674. APP.xmpp.addListener(XMPPEvents.DEVICE_AVAILABLE,
  1675. function (resource, devices) {
  1676. VideoLayout.setDeviceAvailabilityIcons(resource, devices);
  1677. });
  1678. APP.members.addListener(MemberEvents.DTMF_SUPPORT_CHANGED,
  1679. onDtmfSupportChanged);
  1680. APP.xmpp.addListener(XMPPEvents.START_MUTED, function (audio, video) {
  1681. SettingsMenu.setStartMuted(audio, video);
  1682. });
  1683. }
  1684. /**
  1685. * Mutes/unmutes the local video.
  1686. *
  1687. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  1688. * @param options an object which specifies optional arguments such as the
  1689. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  1690. * specifies whether the method was initiated in response to a user command (in
  1691. * contrast to an automatic decision taken by the application logic)
  1692. */
  1693. function setVideoMute(mute, options) {
  1694. APP.RTC.setVideoMute(mute,
  1695. UI.setVideoMuteButtonsState,
  1696. options);
  1697. }
  1698. function bindEvents()
  1699. {
  1700. /**
  1701. * Resizes and repositions videos in full screen mode.
  1702. */
  1703. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1704. function () {
  1705. VideoLayout.resizeLargeVideoContainer();
  1706. VideoLayout.positionLarge();
  1707. }
  1708. );
  1709. $(window).resize(function () {
  1710. VideoLayout.resizeLargeVideoContainer();
  1711. VideoLayout.positionLarge();
  1712. });
  1713. }
  1714. UI.start = function (init) {
  1715. document.title = interfaceConfig.APP_NAME;
  1716. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1717. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1718. {
  1719. $("#videoconference_page").hide();
  1720. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1721. setupWelcomePage();
  1722. return;
  1723. }
  1724. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  1725. var leftWatermarkDiv
  1726. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  1727. leftWatermarkDiv.css({display: 'block'});
  1728. leftWatermarkDiv.parent().get(0).href
  1729. = interfaceConfig.JITSI_WATERMARK_LINK;
  1730. }
  1731. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1732. var rightWatermarkDiv
  1733. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  1734. rightWatermarkDiv.css({display: 'block'});
  1735. rightWatermarkDiv.parent().get(0).href
  1736. = interfaceConfig.BRAND_WATERMARK_LINK;
  1737. rightWatermarkDiv.get(0).style.backgroundImage
  1738. = "url(images/rightwatermark.png)";
  1739. }
  1740. if (interfaceConfig.SHOW_POWERED_BY) {
  1741. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  1742. }
  1743. $("#welcome_page").hide();
  1744. VideoLayout.resizeLargeVideoContainer();
  1745. $("#videospace").mousemove(function () {
  1746. return ToolbarToggler.showToolbar();
  1747. });
  1748. // Set the defaults for prompt dialogs.
  1749. jQuery.prompt.setDefaults({persistent: false});
  1750. VideoLayout.init(eventEmitter);
  1751. AudioLevels.init();
  1752. NicknameHandler.init(eventEmitter);
  1753. registerListeners();
  1754. bindEvents();
  1755. setupPrezi();
  1756. setupToolbars();
  1757. setupChat();
  1758. document.title = interfaceConfig.APP_NAME;
  1759. $("#downloadlog").click(function (event) {
  1760. dump(event.target);
  1761. });
  1762. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1763. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1764. {
  1765. $("#videoconference_page").hide();
  1766. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1767. setupWelcomePage();
  1768. return;
  1769. }
  1770. $("#welcome_page").hide();
  1771. // Display notice message at the top of the toolbar
  1772. if (config.noticeMessage) {
  1773. $('#noticeText').text(config.noticeMessage);
  1774. $('#notice').css({display: 'block'});
  1775. }
  1776. document.getElementById('largeVideo').volume = 0;
  1777. if (!$('#settings').is(':visible')) {
  1778. console.log('init');
  1779. init();
  1780. } else {
  1781. loginInfo.onsubmit = function (e) {
  1782. if (e.preventDefault) e.preventDefault();
  1783. $('#settings').hide();
  1784. init();
  1785. };
  1786. }
  1787. toastr.options = {
  1788. "closeButton": true,
  1789. "debug": false,
  1790. "positionClass": "notification-bottom-right",
  1791. "onclick": null,
  1792. "showDuration": "300",
  1793. "hideDuration": "1000",
  1794. "timeOut": "2000",
  1795. "extendedTimeOut": "1000",
  1796. "showEasing": "swing",
  1797. "hideEasing": "linear",
  1798. "showMethod": "fadeIn",
  1799. "hideMethod": "fadeOut",
  1800. "reposition": function() {
  1801. if(PanelToggler.isVisible()) {
  1802. $("#toast-container").addClass("notification-bottom-right-center");
  1803. } else {
  1804. $("#toast-container").removeClass("notification-bottom-right-center");
  1805. }
  1806. },
  1807. "newestOnTop": false
  1808. };
  1809. SettingsMenu.init();
  1810. };
  1811. function chatAddError(errorMessage, originalText)
  1812. {
  1813. return Chat.chatAddError(errorMessage, originalText);
  1814. };
  1815. function chatSetSubject(text)
  1816. {
  1817. return Chat.chatSetSubject(text);
  1818. };
  1819. function updateChatConversation(from, displayName, message) {
  1820. return Chat.updateChatConversation(from, displayName, message);
  1821. };
  1822. function onMucJoined(jid, info) {
  1823. Toolbar.updateRoomUrl(window.location.href);
  1824. var meHTML = APP.translation.generateTranslatonHTML("me");
  1825. $("#localNick").html(Strophe.getResourceFromJid(jid) + " (" + meHTML + ")");
  1826. var settings = Settings.getSettings();
  1827. // Add myself to the contact list.
  1828. ContactList.addContact(jid, settings.email || settings.uid);
  1829. // Once we've joined the muc show the toolbar
  1830. ToolbarToggler.showToolbar();
  1831. var displayName = !config.displayJids
  1832. ? info.displayName : Strophe.getResourceFromJid(jid);
  1833. if (displayName)
  1834. onDisplayNameChanged('localVideoContainer', displayName);
  1835. VideoLayout.mucJoined();
  1836. }
  1837. function initEtherpad(name) {
  1838. Etherpad.init(name);
  1839. }
  1840. function onMucMemberLeft(jid) {
  1841. console.log('left.muc', jid);
  1842. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  1843. '>.displayname').html();
  1844. messageHandler.notify(displayName,'notify.somebody',
  1845. 'disconnected',
  1846. 'notify.disconnected');
  1847. if(!config.startAudioMuted ||
  1848. config.startAudioMuted > APP.members.size())
  1849. UIUtil.playSoundNotification('userLeft');
  1850. // Need to call this with a slight delay, otherwise the element couldn't be
  1851. // found for some reason.
  1852. // XXX(gp) it works fine without the timeout for me (with Chrome 38).
  1853. window.setTimeout(function () {
  1854. var container = document.getElementById(
  1855. 'participant_' + Strophe.getResourceFromJid(jid));
  1856. if (container) {
  1857. ContactList.removeContact(jid);
  1858. VideoLayout.removeConnectionIndicator(jid);
  1859. // hide here, wait for video to close before removing
  1860. $(container).hide();
  1861. VideoLayout.resizeThumbnails();
  1862. }
  1863. }, 10);
  1864. VideoLayout.participantLeft(jid);
  1865. };
  1866. function onLocalRoleChanged(jid, info, pres, isModerator)
  1867. {
  1868. console.info("My role changed, new role: " + info.role);
  1869. onModeratorStatusChanged(isModerator);
  1870. VideoLayout.showModeratorIndicator();
  1871. SettingsMenu.onRoleChanged();
  1872. if (isModerator) {
  1873. Authentication.closeAuthenticationWindow();
  1874. messageHandler.notify(null, "notify.me",
  1875. 'connected', "notify.moderator");
  1876. }
  1877. }
  1878. function onModeratorStatusChanged(isModerator) {
  1879. Toolbar.showSipCallButton(isModerator);
  1880. Toolbar.showRecordingButton(
  1881. isModerator); //&&
  1882. // FIXME:
  1883. // Recording visible if
  1884. // there are at least 2(+ 1 focus) participants
  1885. //Object.keys(connection.emuc.members).length >= 3);
  1886. }
  1887. function onPasswordRequired(callback) {
  1888. // password is required
  1889. Toolbar.lockLockButton();
  1890. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1891. message += APP.translation.translateString(
  1892. "dialog.passwordRequired");
  1893. message += '</h2>' +
  1894. '<input name="lockKey" type="text" data-i18n=' +
  1895. '"[placeholder]dialog.password" placeholder="' +
  1896. APP.translation.translateString("dialog.password") +
  1897. '" autofocus>';
  1898. messageHandler.openTwoButtonDialog(null, null, null, message,
  1899. true,
  1900. "dialog.Ok",
  1901. function (e, v, m, f) {},
  1902. null,
  1903. function (e, v, m, f) {
  1904. if (v) {
  1905. var lockKey = f.lockKey;
  1906. if (lockKey) {
  1907. Toolbar.setSharedKey(lockKey);
  1908. callback(lockKey);
  1909. }
  1910. }
  1911. },
  1912. ':input:first'
  1913. );
  1914. }
  1915. /**
  1916. * The dialpad button is shown iff there is at least one member that supports
  1917. * DTMF (e.g. jigasi).
  1918. */
  1919. function onDtmfSupportChanged(dtmfSupport) {
  1920. //TODO: enable when the UI is ready
  1921. //Toolbar.showDialPadButton(dtmfSupport);
  1922. }
  1923. function onMucMemberJoined(jid, id, displayName) {
  1924. messageHandler.notify(displayName,'notify.somebody',
  1925. 'connected',
  1926. 'notify.connected');
  1927. if(!config.startAudioMuted ||
  1928. config.startAudioMuted > APP.members.size())
  1929. UIUtil.playSoundNotification('userJoined');
  1930. // Add Peer's container
  1931. VideoLayout.ensurePeerContainerExists(jid,id);
  1932. }
  1933. function onMucPresenceStatus( jid, info) {
  1934. VideoLayout.setPresenceStatus(
  1935. 'participant_' + Strophe.getResourceFromJid(jid), info.status);
  1936. }
  1937. function onMucRoleChanged(role, displayName) {
  1938. VideoLayout.showModeratorIndicator();
  1939. if (role === 'moderator') {
  1940. var messageKey, messageOptions = {};
  1941. if (!displayName) {
  1942. messageKey = "notify.grantedToUnknown";
  1943. }
  1944. else
  1945. {
  1946. messageKey = "notify.grantedTo";
  1947. messageOptions = {to: displayName};
  1948. }
  1949. messageHandler.notify(
  1950. displayName,'notify.somebody',
  1951. 'connected', messageKey,
  1952. messageOptions);
  1953. }
  1954. }
  1955. function onAuthenticationRequired(intervalCallback) {
  1956. Authentication.openAuthenticationDialog(
  1957. roomName, intervalCallback, function () {
  1958. Toolbar.authenticateClicked();
  1959. });
  1960. };
  1961. function onLastNChanged(oldValue, newValue) {
  1962. if (config.muteLocalVideoIfNotInLastN) {
  1963. setVideoMute(!newValue, { 'byUser': false });
  1964. }
  1965. }
  1966. UI.toggleSmileys = function () {
  1967. Chat.toggleSmileys();
  1968. };
  1969. UI.getSettings = function () {
  1970. return Settings.getSettings();
  1971. };
  1972. UI.toggleFilmStrip = function () {
  1973. return BottomToolbar.toggleFilmStrip();
  1974. };
  1975. UI.toggleChat = function () {
  1976. return BottomToolbar.toggleChat();
  1977. };
  1978. UI.toggleContactList = function () {
  1979. return BottomToolbar.toggleContactList();
  1980. };
  1981. UI.inputDisplayNameHandler = function (value) {
  1982. VideoLayout.inputDisplayNameHandler(value);
  1983. };
  1984. UI.getLargeVideoState = function()
  1985. {
  1986. return VideoLayout.getLargeVideoState();
  1987. };
  1988. UI.generateRoomName = function() {
  1989. if(roomName)
  1990. return roomName;
  1991. var roomnode = null;
  1992. var path = window.location.pathname;
  1993. // determinde the room node from the url
  1994. // TODO: just the roomnode or the whole bare jid?
  1995. if (config.getroomnode && typeof config.getroomnode === 'function') {
  1996. // custom function might be responsible for doing the pushstate
  1997. roomnode = config.getroomnode(path);
  1998. } else {
  1999. /* fall back to default strategy
  2000. * this is making assumptions about how the URL->room mapping happens.
  2001. * It currently assumes deployment at root, with a rewrite like the
  2002. * following one (for nginx):
  2003. location ~ ^/([a-zA-Z0-9]+)$ {
  2004. rewrite ^/(.*)$ / break;
  2005. }
  2006. */
  2007. if (path.length > 1) {
  2008. roomnode = path.substr(1).toLowerCase();
  2009. } else {
  2010. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  2011. roomnode = word.toLowerCase();
  2012. window.history.pushState('VideoChat',
  2013. 'Room: ' + word, window.location.pathname + word);
  2014. }
  2015. }
  2016. roomName = roomnode + '@' + config.hosts.muc;
  2017. return roomName;
  2018. };
  2019. UI.connectionIndicatorShowMore = function(id)
  2020. {
  2021. return VideoLayout.connectionIndicators[id].showMore();
  2022. };
  2023. UI.showLoginPopup = function(callback)
  2024. {
  2025. console.log('password is required');
  2026. var message = '<h2 data-i18n="dialog.passwordRequired">';
  2027. message += APP.translation.translateString(
  2028. "dialog.passwordRequired");
  2029. message += '</h2>' +
  2030. '<input name="username" type="text" ' +
  2031. 'placeholder="user@domain.net" autofocus>' +
  2032. '<input name="password" ' +
  2033. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  2034. ' placeholder="user password">';
  2035. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  2036. true,
  2037. "dialog.Ok",
  2038. function (e, v, m, f) {
  2039. if (v) {
  2040. if (f.username !== null && f.password != null) {
  2041. callback(f.username, f.password);
  2042. }
  2043. }
  2044. },
  2045. null, null, ':input:first'
  2046. );
  2047. }
  2048. UI.checkForNicknameAndJoin = function () {
  2049. Authentication.closeAuthenticationDialog();
  2050. Authentication.stopInterval();
  2051. var nick = null;
  2052. if (config.useNicks) {
  2053. nick = window.prompt('Your nickname (optional)');
  2054. }
  2055. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  2056. };
  2057. function dump(elem, filename) {
  2058. elem = elem.parentNode;
  2059. elem.download = filename || 'meetlog.json';
  2060. elem.href = 'data:application/json;charset=utf-8,\n';
  2061. var data = APP.xmpp.populateData();
  2062. var metadata = {};
  2063. metadata.time = new Date();
  2064. metadata.url = window.location.href;
  2065. metadata.ua = navigator.userAgent;
  2066. var log = APP.xmpp.getLogger();
  2067. if (log) {
  2068. metadata.xmpp = log;
  2069. }
  2070. data.metadata = metadata;
  2071. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  2072. return false;
  2073. }
  2074. UI.getRoomName = function () {
  2075. return roomName;
  2076. };
  2077. UI.setInitialMuteFromFocus = function (muteAudio, muteVideo) {
  2078. if(muteAudio || muteVideo) notifyForInitialMute();
  2079. if(muteAudio) UI.setAudioMuted(true);
  2080. if(muteVideo) UI.setVideoMute(true);
  2081. }
  2082. /**
  2083. * Mutes/unmutes the local video.
  2084. */
  2085. UI.toggleVideo = function () {
  2086. setVideoMute(!APP.RTC.localVideo.isMuted());
  2087. };
  2088. /**
  2089. * Mutes / unmutes audio for the local participant.
  2090. */
  2091. UI.toggleAudio = function() {
  2092. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  2093. };
  2094. /**
  2095. * Sets muted audio state for the local participant.
  2096. */
  2097. UI.setAudioMuted = function (mute, earlyMute) {
  2098. var audioMute = null;
  2099. if(earlyMute)
  2100. audioMute = function (mute, cb) {
  2101. return APP.xmpp.sendAudioInfoPresence(mute, cb);
  2102. };
  2103. else
  2104. audioMute = function (mute, cb) {
  2105. return APP.xmpp.setAudioMute(mute, cb);
  2106. }
  2107. if(!audioMute(mute, function () {
  2108. VideoLayout.showLocalAudioIndicator(mute);
  2109. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  2110. }))
  2111. {
  2112. // We still click the button.
  2113. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  2114. return;
  2115. }
  2116. }
  2117. UI.addListener = function (type, listener) {
  2118. eventEmitter.on(type, listener);
  2119. }
  2120. UI.clickOnVideo = function (videoNumber) {
  2121. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  2122. if (remoteVideos.length > videoNumber) {
  2123. remoteVideos[videoNumber].click();
  2124. }
  2125. }
  2126. //Used by torture
  2127. UI.showToolbar = function () {
  2128. return ToolbarToggler.showToolbar();
  2129. }
  2130. //Used by torture
  2131. UI.dockToolbar = function (isDock) {
  2132. return ToolbarToggler.dockToolbar(isDock);
  2133. }
  2134. UI.setVideoMuteButtonsState = function (mute) {
  2135. var video = $('#video');
  2136. var communicativeClass = "icon-camera";
  2137. var muteClass = "icon-camera icon-camera-disabled";
  2138. if (mute) {
  2139. video.removeClass(communicativeClass);
  2140. video.addClass(muteClass);
  2141. } else {
  2142. video.removeClass(muteClass);
  2143. video.addClass(communicativeClass);
  2144. }
  2145. }
  2146. UI.setVideoMute = setVideoMute;
  2147. module.exports = UI;
  2148. },{"../../service/RTC/RTCEvents":103,"../../service/RTC/StreamEventTypes":105,"../../service/connectionquality/CQEvents":108,"../../service/desktopsharing/DesktopSharingEventTypes":109,"../../service/members/Events":110,"../../service/xmpp/XMPPEvents":112,"./../settings/Settings":41,"./audio_levels/AudioLevels.js":10,"./authentication/Authentication":12,"./avatar/Avatar":14,"./etherpad/Etherpad.js":15,"./prezi/Prezi.js":16,"./side_pannels/SidePanelToggler":18,"./side_pannels/chat/Chat.js":19,"./side_pannels/contactlist/ContactList":23,"./side_pannels/settings/SettingsMenu":24,"./toolbars/BottomToolbar":25,"./toolbars/Toolbar":26,"./toolbars/ToolbarToggler":27,"./util/MessageHandler":29,"./util/NicknameHandler":30,"./util/UIUtil":31,"./videolayout/VideoLayout.js":33,"./welcome_page/RoomnameGenerator":34,"./welcome_page/WelcomePage":35,"events":62}],10:[function(require,module,exports){
  2149. /*
  2150. * Copyright @ 2015 Atlassian Pty Ltd
  2151. *
  2152. * Licensed under the Apache License, Version 2.0 (the "License");
  2153. * you may not use this file except in compliance with the License.
  2154. * You may obtain a copy of the License at
  2155. *
  2156. * http://www.apache.org/licenses/LICENSE-2.0
  2157. *
  2158. * Unless required by applicable law or agreed to in writing, software
  2159. * distributed under the License is distributed on an "AS IS" BASIS,
  2160. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2161. * See the License for the specific language governing permissions and
  2162. * limitations under the License.
  2163. */
  2164. var CanvasUtil = require("./CanvasUtils");
  2165. var ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  2166. function initActiveSpeakerAudioLevels() {
  2167. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  2168. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  2169. // Draw a circle.
  2170. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  2171. // Add a shadow around the circle
  2172. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  2173. ASDrawContext.shadowOffsetX = 0;
  2174. ASDrawContext.shadowOffsetY = 0;
  2175. }
  2176. /**
  2177. * The audio Levels plugin.
  2178. */
  2179. var AudioLevels = (function(my) {
  2180. var audioLevelCanvasCache = {};
  2181. my.LOCAL_LEVEL = 'local';
  2182. my.init = function () {
  2183. initActiveSpeakerAudioLevels();
  2184. }
  2185. /**
  2186. * Updates the audio level canvas for the given peerJid. If the canvas
  2187. * didn't exist we create it.
  2188. */
  2189. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  2190. var resourceJid = null;
  2191. var videoSpanId = null;
  2192. if (!peerJid)
  2193. videoSpanId = 'localVideoContainer';
  2194. else {
  2195. resourceJid = Strophe.getResourceFromJid(peerJid);
  2196. videoSpanId = 'participant_' + resourceJid;
  2197. }
  2198. var videoSpan = document.getElementById(videoSpanId);
  2199. if (!videoSpan) {
  2200. if (resourceJid)
  2201. console.error("No video element for jid", resourceJid);
  2202. else
  2203. console.error("No video element for local video.");
  2204. return;
  2205. }
  2206. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  2207. var videoSpaceWidth = $('#remoteVideos').width();
  2208. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  2209. var thumbnailWidth = thumbnailSize[0];
  2210. var thumbnailHeight = thumbnailSize[1];
  2211. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  2212. audioLevelCanvas = document.createElement('canvas');
  2213. audioLevelCanvas.className = "audiolevel";
  2214. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  2215. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  2216. resizeAudioLevelCanvas( audioLevelCanvas,
  2217. thumbnailWidth,
  2218. thumbnailHeight);
  2219. videoSpan.appendChild(audioLevelCanvas);
  2220. } else {
  2221. audioLevelCanvas = audioLevelCanvas.get(0);
  2222. resizeAudioLevelCanvas( audioLevelCanvas,
  2223. thumbnailWidth,
  2224. thumbnailHeight);
  2225. }
  2226. };
  2227. /**
  2228. * Updates the audio level UI for the given resourceJid.
  2229. *
  2230. * @param resourceJid the resource jid indicating the video element for
  2231. * which we draw the audio level
  2232. * @param audioLevel the newAudio level to render
  2233. */
  2234. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  2235. drawAudioLevelCanvas(resourceJid, audioLevel);
  2236. var videoSpanId = getVideoSpanId(resourceJid);
  2237. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  2238. if (!audioLevelCanvas)
  2239. return;
  2240. var drawContext = audioLevelCanvas.getContext('2d');
  2241. var canvasCache = audioLevelCanvasCache[resourceJid];
  2242. drawContext.clearRect (0, 0,
  2243. audioLevelCanvas.width, audioLevelCanvas.height);
  2244. drawContext.drawImage(canvasCache, 0, 0);
  2245. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  2246. if(!APP.xmpp.myJid()) {
  2247. return;
  2248. }
  2249. resourceJid = APP.xmpp.myResource();
  2250. }
  2251. if(resourceJid === largeVideoResourceJid) {
  2252. window.requestAnimationFrame(function () {
  2253. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  2254. });
  2255. }
  2256. };
  2257. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  2258. if($("#activeSpeaker").css("visibility") == "hidden")
  2259. return;
  2260. ASDrawContext.clearRect(0, 0, 300, 300);
  2261. if(audioLevel == 0)
  2262. return;
  2263. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  2264. // Fill the shape.
  2265. ASDrawContext.fill();
  2266. };
  2267. /**
  2268. * Resizes the given audio level canvas to match the given thumbnail size.
  2269. */
  2270. function resizeAudioLevelCanvas(audioLevelCanvas,
  2271. thumbnailWidth,
  2272. thumbnailHeight) {
  2273. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  2274. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  2275. }
  2276. /**
  2277. * Draws the audio level canvas into the cached canvas object.
  2278. *
  2279. * @param resourceJid the resource jid indicating the video element for
  2280. * which we draw the audio level
  2281. * @param audioLevel the newAudio level to render
  2282. */
  2283. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  2284. if (!audioLevelCanvasCache[resourceJid]) {
  2285. var videoSpanId = getVideoSpanId(resourceJid);
  2286. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  2287. /*
  2288. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  2289. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  2290. * error. Since audio levels are frequently updated, the errors have
  2291. * been observed to pile into the console, strain the CPU.
  2292. */
  2293. if (audioLevelCanvasOrig)
  2294. {
  2295. audioLevelCanvasCache[resourceJid]
  2296. = CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  2297. }
  2298. }
  2299. var canvas = audioLevelCanvasCache[resourceJid];
  2300. if (!canvas)
  2301. return;
  2302. var drawContext = canvas.getContext('2d');
  2303. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  2304. var shadowLevel = getShadowLevel(audioLevel);
  2305. if (shadowLevel > 0)
  2306. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  2307. CanvasUtil.drawRoundRectGlow( drawContext,
  2308. interfaceConfig.CANVAS_EXTRA/2, interfaceConfig.CANVAS_EXTRA/2,
  2309. canvas.width - interfaceConfig.CANVAS_EXTRA,
  2310. canvas.height - interfaceConfig.CANVAS_EXTRA,
  2311. interfaceConfig.CANVAS_RADIUS,
  2312. interfaceConfig.SHADOW_COLOR,
  2313. shadowLevel);
  2314. }
  2315. /**
  2316. * Returns the shadow/glow level for the given audio level.
  2317. *
  2318. * @param audioLevel the audio level from which we determine the shadow
  2319. * level
  2320. */
  2321. function getShadowLevel (audioLevel) {
  2322. var shadowLevel = 0;
  2323. if (audioLevel <= 0.3) {
  2324. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  2325. }
  2326. else if (audioLevel <= 0.6) {
  2327. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  2328. }
  2329. else {
  2330. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  2331. }
  2332. return shadowLevel;
  2333. }
  2334. /**
  2335. * Returns the video span id corresponding to the given resourceJid or local
  2336. * user.
  2337. */
  2338. function getVideoSpanId(resourceJid) {
  2339. var videoSpanId = null;
  2340. if (resourceJid === AudioLevels.LOCAL_LEVEL
  2341. || (APP.xmpp.myResource() && resourceJid
  2342. === APP.xmpp.myResource()))
  2343. videoSpanId = 'localVideoContainer';
  2344. else
  2345. videoSpanId = 'participant_' + resourceJid;
  2346. return videoSpanId;
  2347. }
  2348. /**
  2349. * Indicates that the remote video has been resized.
  2350. */
  2351. $(document).bind('remotevideo.resized', function (event, width, height) {
  2352. var resized = false;
  2353. $('#remoteVideos>span>canvas').each(function() {
  2354. var canvas = $(this).get(0);
  2355. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  2356. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  2357. resized = true;
  2358. }
  2359. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  2360. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  2361. resized = true;
  2362. }
  2363. });
  2364. if (resized)
  2365. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  2366. audioLevelCanvasCache[resourceJid].width
  2367. = width + interfaceConfig.CANVAS_EXTRA;
  2368. audioLevelCanvasCache[resourceJid].height
  2369. = height + interfaceConfig.CANVAS_EXTRA;
  2370. });
  2371. });
  2372. return my;
  2373. })(AudioLevels || {});
  2374. module.exports = AudioLevels;
  2375. },{"./CanvasUtils":11}],11:[function(require,module,exports){
  2376. /*
  2377. * Copyright @ 2015 Atlassian Pty Ltd
  2378. *
  2379. * Licensed under the Apache License, Version 2.0 (the "License");
  2380. * you may not use this file except in compliance with the License.
  2381. * You may obtain a copy of the License at
  2382. *
  2383. * http://www.apache.org/licenses/LICENSE-2.0
  2384. *
  2385. * Unless required by applicable law or agreed to in writing, software
  2386. * distributed under the License is distributed on an "AS IS" BASIS,
  2387. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2388. * See the License for the specific language governing permissions and
  2389. * limitations under the License.
  2390. */
  2391. /**
  2392. * Utility class for drawing canvas shapes.
  2393. */
  2394. var CanvasUtil = (function(my) {
  2395. /**
  2396. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  2397. * of the glow.
  2398. *
  2399. * @param drawContext the context of the canvas to draw to
  2400. * @param x the x coordinate of the round rectangle
  2401. * @param y the y coordinate of the round rectangle
  2402. * @param w the width of the round rectangle
  2403. * @param h the height of the round rectangle
  2404. * @param glowColor the color of the glow
  2405. * @param glowWidth the width of the glow
  2406. */
  2407. my.drawRoundRectGlow
  2408. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  2409. // Save the previous state of the context.
  2410. drawContext.save();
  2411. if (w < 2 * r) r = w / 2;
  2412. if (h < 2 * r) r = h / 2;
  2413. // Draw a round rectangle.
  2414. drawContext.beginPath();
  2415. drawContext.moveTo(x+r, y);
  2416. drawContext.arcTo(x+w, y, x+w, y+h, r);
  2417. drawContext.arcTo(x+w, y+h, x, y+h, r);
  2418. drawContext.arcTo(x, y+h, x, y, r);
  2419. drawContext.arcTo(x, y, x+w, y, r);
  2420. drawContext.closePath();
  2421. // Add a shadow around the rectangle
  2422. drawContext.shadowColor = glowColor;
  2423. drawContext.shadowBlur = glowWidth;
  2424. drawContext.shadowOffsetX = 0;
  2425. drawContext.shadowOffsetY = 0;
  2426. // Fill the shape.
  2427. drawContext.fill();
  2428. drawContext.save();
  2429. drawContext.restore();
  2430. // 1) Uncomment this line to use Composite Operation, which is doing the
  2431. // same as the clip function below and is also antialiasing the round
  2432. // border, but is said to be less fast performance wise.
  2433. // drawContext.globalCompositeOperation='destination-out';
  2434. drawContext.beginPath();
  2435. drawContext.moveTo(x+r, y);
  2436. drawContext.arcTo(x+w, y, x+w, y+h, r);
  2437. drawContext.arcTo(x+w, y+h, x, y+h, r);
  2438. drawContext.arcTo(x, y+h, x, y, r);
  2439. drawContext.arcTo(x, y, x+w, y, r);
  2440. drawContext.closePath();
  2441. // 2) Uncomment this line to use Composite Operation, which is doing the
  2442. // same as the clip function below and is also antialiasing the round
  2443. // border, but is said to be less fast performance wise.
  2444. // drawContext.fill();
  2445. // Comment these two lines if choosing to do the same with composite
  2446. // operation above 1 and 2.
  2447. drawContext.clip();
  2448. drawContext.clearRect(0, 0, 277, 200);
  2449. // Restore the previous context state.
  2450. drawContext.restore();
  2451. };
  2452. /**
  2453. * Clones the given canvas.
  2454. *
  2455. * @return the new cloned canvas.
  2456. */
  2457. my.cloneCanvas = function (oldCanvas) {
  2458. /*
  2459. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  2460. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  2461. * levels are frequently updated, the errors have been observed to pile
  2462. * into the console, strain the CPU.
  2463. */
  2464. if (!oldCanvas)
  2465. return oldCanvas;
  2466. //create a new canvas
  2467. var newCanvas = document.createElement('canvas');
  2468. var context = newCanvas.getContext('2d');
  2469. //set dimensions
  2470. newCanvas.width = oldCanvas.width;
  2471. newCanvas.height = oldCanvas.height;
  2472. //apply the old canvas to the new one
  2473. context.drawImage(oldCanvas, 0, 0);
  2474. //return the new canvas
  2475. return newCanvas;
  2476. };
  2477. return my;
  2478. })(CanvasUtil || {});
  2479. module.exports = CanvasUtil;
  2480. },{}],12:[function(require,module,exports){
  2481. /*
  2482. * Copyright @ 2015 Atlassian Pty Ltd
  2483. *
  2484. * Licensed under the Apache License, Version 2.0 (the "License");
  2485. * you may not use this file except in compliance with the License.
  2486. * You may obtain a copy of the License at
  2487. *
  2488. * http://www.apache.org/licenses/LICENSE-2.0
  2489. *
  2490. * Unless required by applicable law or agreed to in writing, software
  2491. * distributed under the License is distributed on an "AS IS" BASIS,
  2492. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2493. * See the License for the specific language governing permissions and
  2494. * limitations under the License.
  2495. */
  2496. /* global $, APP*/
  2497. var LoginDialog = require('./LoginDialog');
  2498. var Moderator = require('../../xmpp/moderator');
  2499. /* Initial "authentication required" dialog */
  2500. var authDialog = null;
  2501. /* Loop retry ID that wits for other user to create the room */
  2502. var authRetryId = null;
  2503. var authenticationWindow = null;
  2504. var Authentication = {
  2505. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  2506. // This is the loop that will wait for the room to be created by
  2507. // someone else. 'auth_required.moderator' will bring us back here.
  2508. authRetryId = window.setTimeout(intervalCallback, 5000);
  2509. // Show prompt only if it's not open
  2510. if (authDialog !== null) {
  2511. return;
  2512. }
  2513. // extract room name from 'room@muc.server.net'
  2514. var room = roomName.substr(0, roomName.indexOf('@'));
  2515. var title
  2516. = APP.translation.generateTranslatonHTML("dialog.WaitingForHost");
  2517. var msg
  2518. = APP.translation.generateTranslatonHTML(
  2519. "dialog.WaitForHostMsg", {room: room});
  2520. var buttonTxt
  2521. = APP.translation.generateTranslatonHTML("dialog.IamHost");
  2522. var buttons = [];
  2523. buttons.push({title: buttonTxt, value: "authNow"});
  2524. authDialog = APP.UI.messageHandler.openDialog(
  2525. title,
  2526. msg,
  2527. true,
  2528. buttons,
  2529. function (onSubmitEvent, submitValue) {
  2530. // Do not close the dialog yet
  2531. onSubmitEvent.preventDefault();
  2532. // Open login popup
  2533. if (submitValue === 'authNow') {
  2534. callback();
  2535. }
  2536. }
  2537. );
  2538. },
  2539. closeAuthenticationWindow: function () {
  2540. if (authenticationWindow) {
  2541. authenticationWindow.close();
  2542. authenticationWindow = null;
  2543. }
  2544. },
  2545. xmppAuthenticate: function () {
  2546. var loginDialog = LoginDialog.show(
  2547. function (connection, state) {
  2548. if (!state) {
  2549. // User cancelled
  2550. loginDialog.close();
  2551. return;
  2552. } else if (state == APP.xmpp.Status.CONNECTED) {
  2553. loginDialog.close();
  2554. Authentication.stopInterval();
  2555. Authentication.closeAuthenticationDialog();
  2556. // Close the connection as anonymous one will be used
  2557. // to create the conference. Session-id will authorize
  2558. // the request.
  2559. connection.disconnect();
  2560. var roomName = APP.UI.generateRoomName();
  2561. Moderator.allocateConferenceFocus(roomName, function () {
  2562. // If it's not "on the fly" authentication now join
  2563. // the conference room
  2564. if (!APP.xmpp.getMUCJoined()) {
  2565. APP.UI.checkForNicknameAndJoin();
  2566. }
  2567. });
  2568. }
  2569. }, true);
  2570. },
  2571. focusAuthenticationWindow: function () {
  2572. // If auth window exists just bring it to the front
  2573. if (authenticationWindow) {
  2574. authenticationWindow.focus();
  2575. return;
  2576. }
  2577. },
  2578. closeAuthenticationDialog: function () {
  2579. // Close authentication dialog if opened
  2580. if (authDialog) {
  2581. authDialog.close();
  2582. authDialog = null;
  2583. }
  2584. },
  2585. createAuthenticationWindow: function (callback, url) {
  2586. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  2587. url, 910, 660,
  2588. // On closed
  2589. function () {
  2590. // Close authentication dialog if opened
  2591. Authentication.closeAuthenticationDialog();
  2592. callback();
  2593. authenticationWindow = null;
  2594. });
  2595. return authenticationWindow;
  2596. },
  2597. stopInterval: function () {
  2598. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  2599. if (authRetryId) {
  2600. window.clearTimeout(authRetryId);
  2601. authRetryId = null;
  2602. }
  2603. }
  2604. };
  2605. module.exports = Authentication;
  2606. },{"../../xmpp/moderator":51,"./LoginDialog":13}],13:[function(require,module,exports){
  2607. /*
  2608. * Copyright @ 2015 Atlassian Pty Ltd
  2609. *
  2610. * Licensed under the Apache License, Version 2.0 (the "License");
  2611. * you may not use this file except in compliance with the License.
  2612. * You may obtain a copy of the License at
  2613. *
  2614. * http://www.apache.org/licenses/LICENSE-2.0
  2615. *
  2616. * Unless required by applicable law or agreed to in writing, software
  2617. * distributed under the License is distributed on an "AS IS" BASIS,
  2618. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2619. * See the License for the specific language governing permissions and
  2620. * limitations under the License.
  2621. */
  2622. /* global $, APP, config*/
  2623. var XMPP = require('../../xmpp/xmpp');
  2624. var Moderator = require('../../xmpp/moderator');
  2625. //FIXME: use LoginDialog to add retries to XMPP.connect method used when
  2626. // anonymous domain is not enabled
  2627. /**
  2628. * Creates new <tt>Dialog</tt> instance.
  2629. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt> called
  2630. * when we either fail to connect or succeed(check Strophe.Status).
  2631. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to Jicofo
  2632. * in order to create session-id after the connection is established.
  2633. * @constructor
  2634. */
  2635. function Dialog(callback, obtainSession) {
  2636. var self = this;
  2637. var stop = false;
  2638. var connection = APP.xmpp.createConnection();
  2639. var message = '<h2 data-i18n="dialog.passwordRequired">';
  2640. message += APP.translation.translateString("dialog.passwordRequired");
  2641. message += '</h2>' +
  2642. '<input name="username" type="text" ' +
  2643. 'placeholder="user@domain.net" autofocus>' +
  2644. '<input name="password" ' +
  2645. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  2646. ' placeholder="user password">';
  2647. var okButton = APP.translation.generateTranslatonHTML("dialog.Ok");
  2648. var cancelButton = APP.translation.generateTranslatonHTML("dialog.Cancel");
  2649. var states = {
  2650. login: {
  2651. html: message,
  2652. buttons: [
  2653. { title: okButton, value: true},
  2654. { title: cancelButton, value: false}
  2655. ],
  2656. focus: ':input:first',
  2657. submit: function (e, v, m, f) {
  2658. e.preventDefault();
  2659. if (v) {
  2660. var jid = f.username;
  2661. var password = f.password;
  2662. if (jid && password) {
  2663. stop = false;
  2664. connection.reset();
  2665. connDialog.goToState('connecting');
  2666. connection.connect(jid, password, stateHandler);
  2667. }
  2668. } else {
  2669. // User cancelled
  2670. stop = true;
  2671. callback();
  2672. }
  2673. }
  2674. },
  2675. connecting: {
  2676. title: APP.translation.translateString('dialog.connecting'),
  2677. html: '<div id="connectionStatus"></div>',
  2678. buttons: [],
  2679. defaultButton: 0
  2680. },
  2681. finished: {
  2682. title: APP.translation.translateString('dialog.error'),
  2683. html: '<div id="errorMessage"></div>',
  2684. buttons: [
  2685. {
  2686. title: APP.translation.translateString('dialog.retry'),
  2687. value: 'retry'
  2688. },
  2689. {
  2690. title: APP.translation.translateString('dialog.Cancel'),
  2691. value: 'cancel'
  2692. },
  2693. ],
  2694. defaultButton: 0,
  2695. submit: function (e, v, m, f) {
  2696. e.preventDefault();
  2697. if (v === 'retry')
  2698. connDialog.goToState('login');
  2699. else
  2700. callback();
  2701. }
  2702. }
  2703. };
  2704. var connDialog
  2705. = APP.UI.messageHandler.openDialogWithStates(states,
  2706. { persistent: true, closeText: '' }, null);
  2707. var stateHandler = function (status, message) {
  2708. if (stop) {
  2709. return;
  2710. }
  2711. var translateKey = "connection." + XMPP.getStatusString(status);
  2712. var statusStr = APP.translation.translateString(translateKey);
  2713. // Display current state
  2714. var connectionStatus =
  2715. connDialog.getState('connecting').find('#connectionStatus');
  2716. connectionStatus.text(statusStr);
  2717. switch (status) {
  2718. case XMPP.Status.CONNECTED:
  2719. stop = true;
  2720. if (!obtainSession) {
  2721. callback(connection, status);
  2722. return;
  2723. }
  2724. // Obtaining session-id status
  2725. connectionStatus.text(
  2726. APP.translation.translateString(
  2727. 'connection.FETCH_SESSION_ID'));
  2728. // Authenticate with Jicofo and obtain session-id
  2729. var roomName = APP.UI.generateRoomName();
  2730. // Jicofo will return new session-id when connected
  2731. // from authenticated domain
  2732. connection.sendIQ(
  2733. Moderator.createConferenceIq(roomName),
  2734. function (result) {
  2735. connectionStatus.text(
  2736. APP.translation.translateString(
  2737. 'connection.GOT_SESSION_ID'));
  2738. stop = true;
  2739. // Parse session-id
  2740. Moderator.parseSessionId(result);
  2741. callback(connection, status);
  2742. },
  2743. function (error) {
  2744. console.error("Auth on the fly failed", error);
  2745. stop = true;
  2746. var errorMsg =
  2747. APP.translation.translateString(
  2748. 'connection.GET_SESSION_ID_ERROR') +
  2749. $(error).find('>error').attr('code');
  2750. self.displayError(errorMsg);
  2751. connection.disconnect();
  2752. });
  2753. break;
  2754. case XMPP.Status.AUTHFAIL:
  2755. case XMPP.Status.CONNFAIL:
  2756. case XMPP.Status.DISCONNECTED:
  2757. stop = true;
  2758. callback(connection, status);
  2759. var errorMessage = statusStr;
  2760. if (message)
  2761. {
  2762. errorMessage += ': ' + message;
  2763. }
  2764. self.displayError(errorMessage);
  2765. break;
  2766. default:
  2767. break;
  2768. }
  2769. };
  2770. /**
  2771. * Displays error message in 'finished' state which allows either to cancel
  2772. * or retry.
  2773. * @param message the final message to be displayed.
  2774. */
  2775. this.displayError = function (message) {
  2776. var finishedState = connDialog.getState('finished');
  2777. var errorMessageElem = finishedState.find('#errorMessage');
  2778. errorMessageElem.text(message);
  2779. connDialog.goToState('finished');
  2780. };
  2781. /**
  2782. * Closes LoginDialog.
  2783. */
  2784. this.close = function () {
  2785. stop = true;
  2786. connDialog.close();
  2787. };
  2788. }
  2789. var LoginDialog = {
  2790. /**
  2791. * Displays login prompt used to establish new XMPP connection. Given
  2792. * <tt>callback(Strophe.Connection, Strophe.Status)</tt> function will be
  2793. * called when we connect successfully(status === CONNECTED) or when we fail
  2794. * to do so. On connection failure program can call Dialog.close() method in
  2795. * order to cancel or do nothing to let the user retry.
  2796. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt>
  2797. * called when we either fail to connect or succeed(check
  2798. * Strophe.Status).
  2799. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to
  2800. * Jicofo in order to create session-id after the connection is
  2801. * established.
  2802. * @returns {Dialog}
  2803. */
  2804. show: function (callback, obtainSession) {
  2805. return new Dialog(callback, obtainSession);
  2806. }
  2807. };
  2808. module.exports = LoginDialog;
  2809. },{"../../xmpp/moderator":51,"../../xmpp/xmpp":59}],14:[function(require,module,exports){
  2810. /*
  2811. * Copyright @ 2015 Atlassian Pty Ltd
  2812. *
  2813. * Licensed under the Apache License, Version 2.0 (the "License");
  2814. * you may not use this file except in compliance with the License.
  2815. * You may obtain a copy of the License at
  2816. *
  2817. * http://www.apache.org/licenses/LICENSE-2.0
  2818. *
  2819. * Unless required by applicable law or agreed to in writing, software
  2820. * distributed under the License is distributed on an "AS IS" BASIS,
  2821. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2822. * See the License for the specific language governing permissions and
  2823. * limitations under the License.
  2824. */
  2825. var Settings = require("../../settings/Settings");
  2826. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  2827. var users = {};
  2828. var activeSpeakerJid;
  2829. function setVisibility(selector, show) {
  2830. if (selector && selector.length > 0) {
  2831. selector.css("visibility", show ? "visible" : "hidden");
  2832. }
  2833. }
  2834. function isUserMuted(jid) {
  2835. // XXX(gp) we may want to rename this method to something like
  2836. // isUserStreaming, for example.
  2837. if (jid && jid != APP.xmpp.myJid()) {
  2838. var resource = Strophe.getResourceFromJid(jid);
  2839. if (!require("../videolayout/VideoLayout").isInLastN(resource)) {
  2840. return true;
  2841. }
  2842. }
  2843. if(jid && jid == APP.xmpp.myJid())
  2844. {
  2845. var localVideo = APP.RTC.localVideo;
  2846. return (!localVideo || localVideo.isMuted());
  2847. }
  2848. if (!APP.RTC.remoteStreams[jid] || !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  2849. return null;
  2850. }
  2851. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  2852. }
  2853. function getGravatarUrl(id, size) {
  2854. if(id === APP.xmpp.myJid() || !id) {
  2855. id = Settings.getSettings().uid;
  2856. }
  2857. return 'https://www.gravatar.com/avatar/' +
  2858. MD5.hexdigest(id.trim().toLowerCase()) +
  2859. "?d=wavatar&size=" + (size || "30");
  2860. }
  2861. var Avatar = {
  2862. /**
  2863. * Sets the user's avatar in the settings menu(if local user), contact list
  2864. * and thumbnail
  2865. * @param jid jid of the user
  2866. * @param id email or userID to be used as a hash
  2867. */
  2868. setUserAvatar: function (jid, id) {
  2869. if (id) {
  2870. if (users[jid] === id) {
  2871. return;
  2872. }
  2873. users[jid] = id;
  2874. }
  2875. var thumbUrl = getGravatarUrl(users[jid] || jid, 100);
  2876. var contactListUrl = getGravatarUrl(users[jid] || jid);
  2877. var resourceJid = Strophe.getResourceFromJid(jid);
  2878. var thumbnail = $('#participant_' + resourceJid);
  2879. var avatar = $('#avatar_' + resourceJid);
  2880. // set the avatar in the settings menu if it is local user and get the
  2881. // local video container
  2882. if (jid === APP.xmpp.myJid()) {
  2883. $('#avatar').get(0).src = thumbUrl;
  2884. thumbnail = $('#localVideoContainer');
  2885. }
  2886. // set the avatar in the contact list
  2887. var contact = $('#' + resourceJid + '>img');
  2888. if (contact && contact.length > 0) {
  2889. contact.get(0).src = contactListUrl;
  2890. }
  2891. // set the avatar in the thumbnail
  2892. if (avatar && avatar.length > 0) {
  2893. avatar[0].src = thumbUrl;
  2894. } else {
  2895. if (thumbnail && thumbnail.length > 0) {
  2896. avatar = document.createElement('img');
  2897. avatar.id = 'avatar_' + resourceJid;
  2898. avatar.className = 'userAvatar';
  2899. avatar.src = thumbUrl;
  2900. thumbnail.append(avatar);
  2901. }
  2902. }
  2903. //if the user is the current active speaker - update the active speaker
  2904. // avatar
  2905. if (jid === activeSpeakerJid) {
  2906. this.updateActiveSpeakerAvatarSrc(jid);
  2907. }
  2908. },
  2909. /**
  2910. * Hides or shows the user's avatar
  2911. * @param jid jid of the user
  2912. * @param show whether we should show the avatar or not
  2913. * video because there is no dominant speaker and no focused speaker
  2914. */
  2915. showUserAvatar: function (jid, show) {
  2916. if (users[jid]) {
  2917. var resourceJid = Strophe.getResourceFromJid(jid);
  2918. var video = $('#participant_' + resourceJid + '>video');
  2919. var avatar = $('#avatar_' + resourceJid);
  2920. if (jid === APP.xmpp.myJid()) {
  2921. video = $('#localVideoWrapper>video');
  2922. }
  2923. if (show === undefined || show === null) {
  2924. show = isUserMuted(jid);
  2925. }
  2926. //if the user is the currently focused, the dominant speaker or if
  2927. //there is no focused and no dominant speaker and the large video is
  2928. //currently shown
  2929. if (activeSpeakerJid === jid && require("../videolayout/VideoLayout").isLargeVideoOnTop()) {
  2930. setVisibility($("#largeVideo"), !show);
  2931. setVisibility($('#activeSpeaker'), show);
  2932. setVisibility(avatar, false);
  2933. setVisibility(video, false);
  2934. } else {
  2935. if (video && video.length > 0) {
  2936. setVisibility(video, !show);
  2937. }
  2938. setVisibility(avatar, show);
  2939. }
  2940. }
  2941. },
  2942. /**
  2943. * Updates the src of the active speaker avatar
  2944. * @param jid of the current active speaker
  2945. */
  2946. updateActiveSpeakerAvatarSrc: function (jid) {
  2947. if (!jid) {
  2948. jid = APP.xmpp.findJidFromResource(
  2949. require("../videolayout/VideoLayout").getLargeVideoState().userResourceJid);
  2950. }
  2951. var avatar = $("#activeSpeakerAvatar")[0];
  2952. var url = getGravatarUrl(users[jid],
  2953. interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE);
  2954. if (jid === activeSpeakerJid && avatar.src === url) {
  2955. return;
  2956. }
  2957. activeSpeakerJid = jid;
  2958. var isMuted = isUserMuted(jid);
  2959. if (jid && isMuted !== null) {
  2960. avatar.src = url;
  2961. setVisibility($("#largeVideo"), !isMuted);
  2962. Avatar.showUserAvatar(jid, isMuted);
  2963. }
  2964. }
  2965. };
  2966. module.exports = Avatar;
  2967. },{"../../../service/RTC/MediaStreamTypes":101,"../../settings/Settings":41,"../videolayout/VideoLayout":33}],15:[function(require,module,exports){
  2968. /*
  2969. * Copyright @ 2015 Atlassian Pty Ltd
  2970. *
  2971. * Licensed under the Apache License, Version 2.0 (the "License");
  2972. * you may not use this file except in compliance with the License.
  2973. * You may obtain a copy of the License at
  2974. *
  2975. * http://www.apache.org/licenses/LICENSE-2.0
  2976. *
  2977. * Unless required by applicable law or agreed to in writing, software
  2978. * distributed under the License is distributed on an "AS IS" BASIS,
  2979. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2980. * See the License for the specific language governing permissions and
  2981. * limitations under the License.
  2982. */
  2983. /* global $, config,
  2984. setLargeVideoVisible, Util */
  2985. var VideoLayout = require("../videolayout/VideoLayout");
  2986. var Prezi = require("../prezi/Prezi");
  2987. var UIUtil = require("../util/UIUtil");
  2988. var etherpadName = null;
  2989. var etherpadIFrame = null;
  2990. var domain = null;
  2991. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  2992. /**
  2993. * Resizes the etherpad.
  2994. */
  2995. function resize() {
  2996. if ($('#etherpad>iframe').length) {
  2997. var remoteVideos = $('#remoteVideos');
  2998. var availableHeight
  2999. = window.innerHeight - remoteVideos.outerHeight();
  3000. var availableWidth = UIUtil.getAvailableVideoWidth();
  3001. $('#etherpad>iframe').width(availableWidth);
  3002. $('#etherpad>iframe').height(availableHeight);
  3003. }
  3004. }
  3005. /**
  3006. * Creates the Etherpad button and adds it to the toolbar.
  3007. */
  3008. function enableEtherpadButton() {
  3009. if (!$('#etherpadButton').is(":visible"))
  3010. $('#etherpadButton').css({display: 'inline-block'});
  3011. }
  3012. /**
  3013. * Creates the IFrame for the etherpad.
  3014. */
  3015. function createIFrame() {
  3016. etherpadIFrame = document.createElement('iframe');
  3017. etherpadIFrame.src = domain + etherpadName + options;
  3018. etherpadIFrame.frameBorder = 0;
  3019. etherpadIFrame.scrolling = "no";
  3020. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  3021. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  3022. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  3023. document.getElementById('etherpad').appendChild(etherpadIFrame);
  3024. etherpadIFrame.onload = function() {
  3025. document.domain = document.domain;
  3026. bubbleIframeMouseMove(etherpadIFrame);
  3027. setTimeout(function() {
  3028. // the iframes inside of the etherpad are
  3029. // not yet loaded when the etherpad iframe is loaded
  3030. var outer = etherpadIFrame.
  3031. contentDocument.getElementsByName("ace_outer")[0];
  3032. bubbleIframeMouseMove(outer);
  3033. var inner = outer.
  3034. contentDocument.getElementsByName("ace_inner")[0];
  3035. bubbleIframeMouseMove(inner);
  3036. }, 2000);
  3037. };
  3038. }
  3039. function bubbleIframeMouseMove(iframe){
  3040. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  3041. iframe.contentWindow.onmousemove = function(e){
  3042. if(existingOnMouseMove) existingOnMouseMove(e);
  3043. var evt = document.createEvent("MouseEvents");
  3044. var boundingClientRect = iframe.getBoundingClientRect();
  3045. evt.initMouseEvent(
  3046. "mousemove",
  3047. true, // bubbles
  3048. false, // not cancelable
  3049. window,
  3050. e.detail,
  3051. e.screenX,
  3052. e.screenY,
  3053. e.clientX + boundingClientRect.left,
  3054. e.clientY + boundingClientRect.top,
  3055. e.ctrlKey,
  3056. e.altKey,
  3057. e.shiftKey,
  3058. e.metaKey,
  3059. e.button,
  3060. null // no related element
  3061. );
  3062. iframe.dispatchEvent(evt);
  3063. };
  3064. }
  3065. /**
  3066. * On video selected event.
  3067. */
  3068. $(document).bind('video.selected', function (event, isPresentation) {
  3069. if (config.etherpad_base && etherpadIFrame && etherpadIFrame.style.visibility !== 'hidden')
  3070. Etherpad.toggleEtherpad(isPresentation);
  3071. });
  3072. var Etherpad = {
  3073. /**
  3074. * Initializes the etherpad.
  3075. */
  3076. init: function (name) {
  3077. if (config.etherpad_base && !etherpadName && name) {
  3078. domain = config.etherpad_base;
  3079. etherpadName = name;
  3080. enableEtherpadButton();
  3081. /**
  3082. * Resizes the etherpad, when the window is resized.
  3083. */
  3084. $(window).resize(function () {
  3085. resize();
  3086. });
  3087. }
  3088. },
  3089. /**
  3090. * Opens/hides the Etherpad.
  3091. */
  3092. toggleEtherpad: function (isPresentation) {
  3093. if (!etherpadIFrame)
  3094. createIFrame();
  3095. var largeVideo = null;
  3096. if (Prezi.isPresentationVisible())
  3097. largeVideo = $('#presentation>iframe');
  3098. else
  3099. largeVideo = $('#largeVideo');
  3100. if ($('#etherpad>iframe').css('visibility') === 'hidden') {
  3101. $('#activeSpeaker').css('visibility', 'hidden');
  3102. largeVideo.fadeOut(300, function () {
  3103. if (Prezi.isPresentationVisible()) {
  3104. largeVideo.css({opacity: '0'});
  3105. } else {
  3106. VideoLayout.setLargeVideoVisible(false);
  3107. }
  3108. });
  3109. $('#etherpad>iframe').fadeIn(300, function () {
  3110. document.body.style.background = '#eeeeee';
  3111. $('#etherpad>iframe').css({visibility: 'visible'});
  3112. $('#etherpad').css({zIndex: 2});
  3113. });
  3114. }
  3115. else if ($('#etherpad>iframe')) {
  3116. $('#etherpad>iframe').fadeOut(300, function () {
  3117. $('#etherpad>iframe').css({visibility: 'hidden'});
  3118. $('#etherpad').css({zIndex: 0});
  3119. document.body.style.background = 'black';
  3120. });
  3121. if (!isPresentation) {
  3122. $('#largeVideo').fadeIn(300, function () {
  3123. VideoLayout.setLargeVideoVisible(true);
  3124. });
  3125. }
  3126. }
  3127. resize();
  3128. },
  3129. isVisible: function() {
  3130. var etherpadIframe = $('#etherpad>iframe');
  3131. return etherpadIframe && etherpadIframe.is(':visible');
  3132. }
  3133. };
  3134. module.exports = Etherpad;
  3135. },{"../prezi/Prezi":16,"../util/UIUtil":31,"../videolayout/VideoLayout":33}],16:[function(require,module,exports){
  3136. /*
  3137. * Copyright @ 2015 Atlassian Pty Ltd
  3138. *
  3139. * Licensed under the Apache License, Version 2.0 (the "License");
  3140. * you may not use this file except in compliance with the License.
  3141. * You may obtain a copy of the License at
  3142. *
  3143. * http://www.apache.org/licenses/LICENSE-2.0
  3144. *
  3145. * Unless required by applicable law or agreed to in writing, software
  3146. * distributed under the License is distributed on an "AS IS" BASIS,
  3147. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3148. * See the License for the specific language governing permissions and
  3149. * limitations under the License.
  3150. */
  3151. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  3152. var UIUtil = require("../util/UIUtil");
  3153. var VideoLayout = require("../videolayout/VideoLayout");
  3154. var messageHandler = require("../util/MessageHandler");
  3155. var PreziPlayer = require("./PreziPlayer");
  3156. var preziPlayer = null;
  3157. var Prezi = {
  3158. /**
  3159. * Reloads the current presentation.
  3160. */
  3161. reloadPresentation: function() {
  3162. var iframe = document.getElementById(preziPlayer.options.preziId);
  3163. iframe.src = iframe.src;
  3164. },
  3165. /**
  3166. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  3167. * otherwise.
  3168. */
  3169. isPresentationVisible: function () {
  3170. return ($('#presentation>iframe') != null
  3171. && $('#presentation>iframe').css('opacity') == 1);
  3172. },
  3173. /**
  3174. * Opens the Prezi dialog, from which the user could choose a presentation
  3175. * to load.
  3176. */
  3177. openPreziDialog: function() {
  3178. var myprezi = APP.xmpp.getPrezi();
  3179. if (myprezi) {
  3180. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  3181. null,
  3182. "dialog.removePreziMsg",
  3183. null,
  3184. false,
  3185. "dialog.Remove",
  3186. function(e,v,m,f) {
  3187. if(v) {
  3188. APP.xmpp.removePreziFromPresence();
  3189. }
  3190. }
  3191. );
  3192. }
  3193. else if (preziPlayer != null) {
  3194. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  3195. null, "dialog.sharePreziMsg",
  3196. null,
  3197. false,
  3198. "dialog.Ok",
  3199. function(e,v,m,f) {
  3200. $.prompt.close();
  3201. }
  3202. );
  3203. }
  3204. else {
  3205. var html = APP.translation.generateTranslatonHTML(
  3206. "dialog.sharePreziTitle");
  3207. var cancelButton = APP.translation.generateTranslatonHTML(
  3208. "dialog.Cancel");
  3209. var shareButton = APP.translation.generateTranslatonHTML(
  3210. "dialog.Share");
  3211. var backButton = APP.translation.generateTranslatonHTML(
  3212. "dialog.Back");
  3213. var buttons = [];
  3214. var buttons1 = [];
  3215. // Cancel button to both states
  3216. buttons.push({title: cancelButton, value: false});
  3217. buttons1.push({title: cancelButton, value: false});
  3218. // Share button
  3219. buttons.push({title: shareButton, value: true});
  3220. // Back button
  3221. buttons1.push({title: backButton, value: true});
  3222. var linkError = APP.translation.generateTranslatonHTML(
  3223. "dialog.preziLinkError");
  3224. var defaultUrl = APP.translation.translateString("defaultPreziLink",
  3225. {url: "http://prezi.com/wz7vhjycl7e6/my-prezi"});
  3226. var openPreziState = {
  3227. state0: {
  3228. html: '<h2>' + html + '</h2>' +
  3229. '<input name="preziUrl" type="text" ' +
  3230. 'data-i18n="[placeholder]defaultPreziLink" data-i18n-options=\'' +
  3231. JSON.stringify({"url": "http://prezi.com/wz7vhjycl7e6/my-prezi"}) +
  3232. '\' placeholder="' + defaultUrl + '" autofocus>',
  3233. persistent: false,
  3234. buttons: buttons,
  3235. focus: ':input:first',
  3236. defaultButton: 0,
  3237. submit: function (e, v, m, f) {
  3238. e.preventDefault();
  3239. if(v)
  3240. {
  3241. var preziUrl = f.preziUrl;
  3242. if (preziUrl)
  3243. {
  3244. var urlValue
  3245. = encodeURI(UIUtil.escapeHtml(preziUrl));
  3246. if (urlValue.indexOf('http://prezi.com/') != 0
  3247. && urlValue.indexOf('https://prezi.com/') != 0)
  3248. {
  3249. $.prompt.goToState('state1');
  3250. return false;
  3251. }
  3252. else {
  3253. var presIdTmp = urlValue.substring(
  3254. urlValue.indexOf("prezi.com/") + 10);
  3255. if (!isAlphanumeric(presIdTmp)
  3256. || presIdTmp.indexOf('/') < 2) {
  3257. $.prompt.goToState('state1');
  3258. return false;
  3259. }
  3260. else {
  3261. APP.xmpp.addToPresence("prezi", urlValue);
  3262. $.prompt.close();
  3263. }
  3264. }
  3265. }
  3266. }
  3267. else
  3268. $.prompt.close();
  3269. }
  3270. },
  3271. state1: {
  3272. html: '<h2>' + html + '</h2>' +
  3273. linkError,
  3274. persistent: false,
  3275. buttons: buttons1,
  3276. focus: ':input:first',
  3277. defaultButton: 1,
  3278. submit: function (e, v, m, f) {
  3279. e.preventDefault();
  3280. if (v === 0)
  3281. $.prompt.close();
  3282. else
  3283. $.prompt.goToState('state0');
  3284. }
  3285. }
  3286. };
  3287. messageHandler.openDialogWithStates(openPreziState);
  3288. }
  3289. }
  3290. };
  3291. /**
  3292. * A new presentation has been added.
  3293. *
  3294. * @param event the event indicating the add of a presentation
  3295. * @param jid the jid from which the presentation was added
  3296. * @param presUrl url of the presentation
  3297. * @param currentSlide the current slide to which we should move
  3298. */
  3299. function presentationAdded(event, jid, presUrl, currentSlide) {
  3300. console.log("presentation added", presUrl);
  3301. var presId = getPresentationId(presUrl);
  3302. var elementId = 'participant_'
  3303. + Strophe.getResourceFromJid(jid)
  3304. + '_' + presId;
  3305. // We explicitly don't specify the peer jid here, because we don't want
  3306. // this video to be dealt with as a peer related one (for example we
  3307. // don't want to show a mute/kick menu for this one, etc.).
  3308. VideoLayout.addRemoteVideoContainer(null, elementId);
  3309. VideoLayout.resizeThumbnails();
  3310. var controlsEnabled = false;
  3311. if (jid === APP.xmpp.myJid())
  3312. controlsEnabled = true;
  3313. setPresentationVisible(true);
  3314. $('#largeVideoContainer').hover(
  3315. function (event) {
  3316. if (Prezi.isPresentationVisible()) {
  3317. var reloadButtonRight = window.innerWidth
  3318. - $('#presentation>iframe').offset().left
  3319. - $('#presentation>iframe').width();
  3320. $('#reloadPresentation').css({ right: reloadButtonRight,
  3321. display:'inline-block'});
  3322. }
  3323. },
  3324. function (event) {
  3325. if (!Prezi.isPresentationVisible())
  3326. $('#reloadPresentation').css({display:'none'});
  3327. else {
  3328. var e = event.toElement || event.relatedTarget;
  3329. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  3330. $('#reloadPresentation').css({display:'none'});
  3331. }
  3332. });
  3333. preziPlayer = new PreziPlayer(
  3334. 'presentation',
  3335. {preziId: presId,
  3336. width: getPresentationWidth(),
  3337. height: getPresentationHeihgt(),
  3338. controls: controlsEnabled,
  3339. debug: true
  3340. });
  3341. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  3342. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  3343. console.log("prezi status", event.value);
  3344. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  3345. if (jid != APP.xmpp.myJid())
  3346. preziPlayer.flyToStep(currentSlide);
  3347. }
  3348. });
  3349. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  3350. console.log("event value", event.value);
  3351. APP.xmpp.addToPresence("preziSlide", event.value);
  3352. });
  3353. $("#" + elementId).css( 'background-image',
  3354. 'url(../images/avatarprezi.png)');
  3355. $("#" + elementId).click(
  3356. function () {
  3357. setPresentationVisible(true);
  3358. }
  3359. );
  3360. };
  3361. /**
  3362. * A presentation has been removed.
  3363. *
  3364. * @param event the event indicating the remove of a presentation
  3365. * @param jid the jid for which the presentation was removed
  3366. * @param the url of the presentation
  3367. */
  3368. function presentationRemoved(event, jid, presUrl) {
  3369. console.log('presentation removed', presUrl);
  3370. var presId = getPresentationId(presUrl);
  3371. setPresentationVisible(false);
  3372. $('#participant_'
  3373. + Strophe.getResourceFromJid(jid)
  3374. + '_' + presId).remove();
  3375. $('#presentation>iframe').remove();
  3376. if (preziPlayer != null) {
  3377. preziPlayer.destroy();
  3378. preziPlayer = null;
  3379. }
  3380. };
  3381. /**
  3382. * Indicates if the given string is an alphanumeric string.
  3383. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  3384. * purpose of checking URIs.
  3385. */
  3386. function isAlphanumeric(unsafeText) {
  3387. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  3388. return regex.test(unsafeText);
  3389. }
  3390. /**
  3391. * Returns the presentation id from the given url.
  3392. */
  3393. function getPresentationId (presUrl) {
  3394. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  3395. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  3396. }
  3397. /**
  3398. * Returns the presentation width.
  3399. */
  3400. function getPresentationWidth() {
  3401. var availableWidth = UIUtil.getAvailableVideoWidth();
  3402. var availableHeight = getPresentationHeihgt();
  3403. var aspectRatio = 16.0 / 9.0;
  3404. if (availableHeight < availableWidth / aspectRatio) {
  3405. availableWidth = Math.floor(availableHeight * aspectRatio);
  3406. }
  3407. return availableWidth;
  3408. }
  3409. /**
  3410. * Returns the presentation height.
  3411. */
  3412. function getPresentationHeihgt() {
  3413. var remoteVideos = $('#remoteVideos');
  3414. return window.innerHeight - remoteVideos.outerHeight();
  3415. }
  3416. /**
  3417. * Resizes the presentation iframe.
  3418. */
  3419. function resize() {
  3420. if ($('#presentation>iframe')) {
  3421. $('#presentation>iframe').width(getPresentationWidth());
  3422. $('#presentation>iframe').height(getPresentationHeihgt());
  3423. }
  3424. }
  3425. /**
  3426. * Shows/hides a presentation.
  3427. */
  3428. function setPresentationVisible(visible) {
  3429. var prezi = $('#presentation>iframe');
  3430. if (visible) {
  3431. // Trigger the video.selected event to indicate a change in the
  3432. // large video.
  3433. $(document).trigger("video.selected", [true]);
  3434. $('#largeVideo').fadeOut(300);
  3435. prezi.fadeIn(300, function() {
  3436. prezi.css({opacity:'1'});
  3437. ToolbarToggler.dockToolbar(true);
  3438. VideoLayout.setLargeVideoVisible(false);
  3439. });
  3440. $('#activeSpeaker').css('visibility', 'hidden');
  3441. }
  3442. else {
  3443. if (prezi.css('opacity') == '1') {
  3444. prezi.fadeOut(300, function () {
  3445. prezi.css({opacity:'0'});
  3446. $('#reloadPresentation').css({display:'none'});
  3447. $('#largeVideo').fadeIn(300, function() {
  3448. VideoLayout.setLargeVideoVisible(true);
  3449. ToolbarToggler.dockToolbar(false);
  3450. });
  3451. });
  3452. }
  3453. }
  3454. }
  3455. /**
  3456. * Presentation has been removed.
  3457. */
  3458. $(document).bind('presentationremoved.muc', presentationRemoved);
  3459. /**
  3460. * Presentation has been added.
  3461. */
  3462. $(document).bind('presentationadded.muc', presentationAdded);
  3463. /*
  3464. * Indicates presentation slide change.
  3465. */
  3466. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  3467. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  3468. preziPlayer.flyToStep(current);
  3469. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  3470. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  3471. preziPlayer.flyToStep(current, i);
  3472. }
  3473. }
  3474. });
  3475. /**
  3476. * On video selected event.
  3477. */
  3478. $(document).bind('video.selected', function (event, isPresentation) {
  3479. if (!isPresentation && $('#presentation>iframe')) {
  3480. setPresentationVisible(false);
  3481. }
  3482. });
  3483. $(window).resize(function () {
  3484. resize();
  3485. });
  3486. module.exports = Prezi;
  3487. },{"../toolbars/ToolbarToggler":27,"../util/MessageHandler":29,"../util/UIUtil":31,"../videolayout/VideoLayout":33,"./PreziPlayer":17}],17:[function(require,module,exports){
  3488. /*
  3489. * Copyright @ 2015 Atlassian Pty Ltd
  3490. *
  3491. * Licensed under the Apache License, Version 2.0 (the "License");
  3492. * you may not use this file except in compliance with the License.
  3493. * You may obtain a copy of the License at
  3494. *
  3495. * http://www.apache.org/licenses/LICENSE-2.0
  3496. *
  3497. * Unless required by applicable law or agreed to in writing, software
  3498. * distributed under the License is distributed on an "AS IS" BASIS,
  3499. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3500. * See the License for the specific language governing permissions and
  3501. * limitations under the License.
  3502. */
  3503. (function() {
  3504. "use strict";
  3505. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  3506. window.PreziPlayer = (function() {
  3507. PreziPlayer.API_VERSION = 1;
  3508. PreziPlayer.CURRENT_STEP = 'currentStep';
  3509. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  3510. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  3511. PreziPlayer.STATUS_LOADING = 'loading';
  3512. PreziPlayer.STATUS_READY = 'ready';
  3513. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  3514. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  3515. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  3516. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  3517. PreziPlayer.EVENT_STATUS = "statusChange";
  3518. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  3519. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  3520. PreziPlayer.domain = "https://prezi.com";
  3521. PreziPlayer.path = "/player/";
  3522. PreziPlayer.players = {};
  3523. PreziPlayer.binded_methods = ['changesHandler'];
  3524. PreziPlayer.createMultiplePlayers = function(optionArray){
  3525. for(var i=0; i<optionArray.length; i++) {
  3526. var optionSet = optionArray[i];
  3527. new PreziPlayer(optionSet.id, optionSet);
  3528. };
  3529. };
  3530. PreziPlayer.messageReceived = function(event){
  3531. var message, item, player;
  3532. try {
  3533. message = JSON.parse(event.data);
  3534. if (message.id && (player = PreziPlayer.players[message.id])) {
  3535. if (player.options.debug === true) {
  3536. if (console && console.log)
  3537. console.log('received', message);
  3538. }
  3539. if (message.type === "changes") {
  3540. player.changesHandler(message);
  3541. }
  3542. for (var i = 0; i < player.callbacks.length; i++) {
  3543. item = player.callbacks[i];
  3544. if (item && message.type === item.event) {
  3545. item.callback(message);
  3546. }
  3547. }
  3548. }
  3549. } catch (e) { }
  3550. };
  3551. function PreziPlayer(id, options) {
  3552. var params, paramString = "", _this = this;
  3553. if (PreziPlayer.players[id]){
  3554. PreziPlayer.players[id].destroy();
  3555. }
  3556. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  3557. var method_name = PreziPlayer.binded_methods[i];
  3558. _this[method_name] = __bind(_this[method_name], _this);
  3559. };
  3560. options = options || {};
  3561. this.options = options;
  3562. this.values = {'status': PreziPlayer.STATUS_LOADING};
  3563. this.values[PreziPlayer.CURRENT_STEP] = 0;
  3564. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  3565. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  3566. this.callbacks = [];
  3567. this.id = id;
  3568. this.embedTo = document.getElementById(id);
  3569. if (!this.embedTo) {
  3570. throw "The element id is not available.";
  3571. }
  3572. this.iframe = document.createElement('iframe');
  3573. params = [
  3574. { name: 'oid', value: options.preziId },
  3575. { name: 'explorable', value: options.explorable ? 1 : 0 },
  3576. { name: 'controls', value: options.controls ? 1 : 0 }
  3577. ];
  3578. for(var i=0; i<params.length; i++) {
  3579. var param = params[i];
  3580. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  3581. };
  3582. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  3583. this.iframe.frameBorder = 0;
  3584. this.iframe.scrolling = "no";
  3585. this.iframe.width = options.width || 640;
  3586. this.iframe.height = options.height || 480;
  3587. this.embedTo.innerHTML = '';
  3588. // JITSI: IN CASE SOMETHING GOES WRONG.
  3589. try {
  3590. this.embedTo.appendChild(this.iframe);
  3591. }
  3592. catch (err) {
  3593. console.log("CATCH ERROR");
  3594. }
  3595. // JITSI: Increase interval from 200 to 500, which fixes prezi
  3596. // crashes for us.
  3597. this.initPollInterval = setInterval(function(){
  3598. _this.sendMessage({'action': 'init'});
  3599. }, 500);
  3600. PreziPlayer.players[id] = this;
  3601. }
  3602. PreziPlayer.prototype.changesHandler = function(message) {
  3603. var key, value, j, item;
  3604. if (this.initPollInterval) {
  3605. clearInterval(this.initPollInterval);
  3606. this.initPollInterval = false;
  3607. }
  3608. for (key in message.data) {
  3609. if (message.data.hasOwnProperty(key)){
  3610. value = message.data[key];
  3611. this.values[key] = value;
  3612. for (j=0; j<this.callbacks.length; j++) {
  3613. item = this.callbacks[j];
  3614. if (item && item.event === key + "Change"){
  3615. item.callback({type: item.event, value: value});
  3616. }
  3617. }
  3618. }
  3619. }
  3620. };
  3621. PreziPlayer.prototype.destroy = function() {
  3622. if (this.initPollInterval) {
  3623. clearInterval(this.initPollInterval);
  3624. this.initPollInterval = false;
  3625. }
  3626. this.embedTo.innerHTML = '';
  3627. };
  3628. PreziPlayer.prototype.sendMessage = function(message) {
  3629. if (this.options.debug === true) {
  3630. if (console && console.log) console.log('sent', message);
  3631. }
  3632. message.version = PreziPlayer.API_VERSION;
  3633. message.id = this.id;
  3634. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  3635. };
  3636. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  3637. PreziPlayer.prototype.flyToNextStep = function() {
  3638. return this.sendMessage({
  3639. 'action': 'present',
  3640. 'data': ['moveToNextStep']
  3641. });
  3642. };
  3643. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  3644. PreziPlayer.prototype.flyToPreviousStep = function() {
  3645. return this.sendMessage({
  3646. 'action': 'present',
  3647. 'data': ['moveToPrevStep']
  3648. });
  3649. };
  3650. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  3651. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  3652. var obj = this;
  3653. // check animation_step
  3654. if (animation_step > 0 &&
  3655. obj.values.animationCountOnSteps &&
  3656. obj.values.animationCountOnSteps[step] <= animation_step) {
  3657. animation_step = obj.values.animationCountOnSteps[step];
  3658. }
  3659. // jump to animation steps by calling flyToNextStep()
  3660. function doAnimationSteps() {
  3661. if (obj.values.isMoving == true) {
  3662. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  3663. return;
  3664. }
  3665. while (animation_step-- > 0) {
  3666. obj.flyToNextStep(); // do the animation steps
  3667. }
  3668. }
  3669. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  3670. // jump to the step
  3671. return this.sendMessage({
  3672. 'action': 'present',
  3673. 'data': ['moveToStep', step]
  3674. });
  3675. };
  3676. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  3677. PreziPlayer.prototype.flyToObject = function(objectId) {
  3678. return this.sendMessage({
  3679. 'action': 'present',
  3680. 'data': ['moveToObject', objectId]
  3681. });
  3682. };
  3683. PreziPlayer.prototype.play = function(defaultDelay) {
  3684. return this.sendMessage({
  3685. 'action': 'present',
  3686. 'data': ['startAutoPlay', defaultDelay]
  3687. });
  3688. };
  3689. PreziPlayer.prototype.stop = function() {
  3690. return this.sendMessage({
  3691. 'action': 'present',
  3692. 'data': ['stopAutoPlay']
  3693. });
  3694. };
  3695. PreziPlayer.prototype.pause = function(defaultDelay) {
  3696. return this.sendMessage({
  3697. 'action': 'present',
  3698. 'data': ['pauseAutoPlay', defaultDelay]
  3699. });
  3700. };
  3701. PreziPlayer.prototype.getCurrentStep = function() {
  3702. return this.values.currentStep;
  3703. };
  3704. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  3705. return this.values.currentAnimationStep;
  3706. };
  3707. PreziPlayer.prototype.getCurrentObject = function() {
  3708. return this.values.currentObject;
  3709. };
  3710. PreziPlayer.prototype.getStatus = function() {
  3711. return this.values.status;
  3712. };
  3713. PreziPlayer.prototype.isPlaying = function() {
  3714. return this.values.isAutoPlaying;
  3715. };
  3716. PreziPlayer.prototype.getStepCount = function() {
  3717. return this.values.stepCount;
  3718. };
  3719. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  3720. return this.values.animationCountOnSteps;
  3721. };
  3722. PreziPlayer.prototype.getTitle = function() {
  3723. return this.values.title;
  3724. };
  3725. PreziPlayer.prototype.setDimensions = function(dims) {
  3726. for (var parameter in dims) {
  3727. this.iframe[parameter] = dims[parameter];
  3728. }
  3729. }
  3730. PreziPlayer.prototype.getDimensions = function() {
  3731. return {
  3732. width: parseInt(this.iframe.width, 10),
  3733. height: parseInt(this.iframe.height, 10)
  3734. }
  3735. }
  3736. PreziPlayer.prototype.on = function(event, callback) {
  3737. this.callbacks.push({
  3738. event: event,
  3739. callback: callback
  3740. });
  3741. };
  3742. PreziPlayer.prototype.off = function(event, callback) {
  3743. var j, item;
  3744. if (event === undefined) {
  3745. this.callbacks = [];
  3746. }
  3747. j = this.callbacks.length;
  3748. while (j--) {
  3749. item = this.callbacks[j];
  3750. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  3751. this.callbacks.splice(j, 1);
  3752. }
  3753. }
  3754. };
  3755. if (window.addEventListener) {
  3756. window.addEventListener('message', PreziPlayer.messageReceived, false);
  3757. } else {
  3758. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  3759. }
  3760. return PreziPlayer;
  3761. })();
  3762. })();
  3763. module.exports = PreziPlayer;
  3764. },{}],18:[function(require,module,exports){
  3765. /*
  3766. * Copyright @ 2015 Atlassian Pty Ltd
  3767. *
  3768. * Licensed under the Apache License, Version 2.0 (the "License");
  3769. * you may not use this file except in compliance with the License.
  3770. * You may obtain a copy of the License at
  3771. *
  3772. * http://www.apache.org/licenses/LICENSE-2.0
  3773. *
  3774. * Unless required by applicable law or agreed to in writing, software
  3775. * distributed under the License is distributed on an "AS IS" BASIS,
  3776. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3777. * See the License for the specific language governing permissions and
  3778. * limitations under the License.
  3779. */
  3780. var Chat = require("./chat/Chat");
  3781. var ContactList = require("./contactlist/ContactList");
  3782. var Settings = require("./../../settings/Settings");
  3783. var SettingsMenu = require("./settings/SettingsMenu");
  3784. var VideoLayout = require("../videolayout/VideoLayout");
  3785. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  3786. var UIUtil = require("../util/UIUtil");
  3787. /**
  3788. * Toggler for the chat, contact list, settings menu, etc..
  3789. */
  3790. var PanelToggler = (function(my) {
  3791. var currentlyOpen = null;
  3792. var buttons = {
  3793. '#chatspace': '#chatBottomButton',
  3794. '#contactlist': '#contactListButton',
  3795. '#settingsmenu': '#settingsButton'
  3796. };
  3797. /**
  3798. * Resizes the video area
  3799. * @param isClosing whether the side panel is going to be closed or is going to open / remain opened
  3800. * @param completeFunction a function to be called when the video space is resized
  3801. */
  3802. var resizeVideoArea = function(isClosing, completeFunction) {
  3803. var videospace = $('#videospace');
  3804. var panelSize = isClosing ? [0, 0] : PanelToggler.getPanelSize();
  3805. var videospaceWidth = window.innerWidth - panelSize[0];
  3806. var videospaceHeight = window.innerHeight;
  3807. var videoSize
  3808. = VideoLayout.getVideoSize(null, null, videospaceWidth, videospaceHeight);
  3809. var videoWidth = videoSize[0];
  3810. var videoHeight = videoSize[1];
  3811. var videoPosition = VideoLayout.getVideoPosition(videoWidth,
  3812. videoHeight,
  3813. videospaceWidth,
  3814. videospaceHeight);
  3815. var horizontalIndent = videoPosition[0];
  3816. var verticalIndent = videoPosition[1];
  3817. var thumbnailSize = VideoLayout.calculateThumbnailSize(videospaceWidth);
  3818. var thumbnailsWidth = thumbnailSize[0];
  3819. var thumbnailsHeight = thumbnailSize[1];
  3820. //for chat
  3821. videospace.animate({
  3822. right: panelSize[0],
  3823. width: videospaceWidth,
  3824. height: videospaceHeight
  3825. },
  3826. {
  3827. queue: false,
  3828. duration: 500,
  3829. complete: completeFunction
  3830. });
  3831. $('#remoteVideos').animate({
  3832. height: thumbnailsHeight
  3833. },
  3834. {
  3835. queue: false,
  3836. duration: 500
  3837. });
  3838. $('#remoteVideos>span').animate({
  3839. height: thumbnailsHeight,
  3840. width: thumbnailsWidth
  3841. },
  3842. {
  3843. queue: false,
  3844. duration: 500,
  3845. complete: function () {
  3846. $(document).trigger(
  3847. "remotevideo.resized",
  3848. [thumbnailsWidth,
  3849. thumbnailsHeight]);
  3850. }
  3851. });
  3852. $('#largeVideoContainer').animate({
  3853. width: videospaceWidth,
  3854. height: videospaceHeight
  3855. },
  3856. {
  3857. queue: false,
  3858. duration: 500
  3859. });
  3860. $('#largeVideo').animate({
  3861. width: videoWidth,
  3862. height: videoHeight,
  3863. top: verticalIndent,
  3864. bottom: verticalIndent,
  3865. left: horizontalIndent,
  3866. right: horizontalIndent
  3867. },
  3868. {
  3869. queue: false,
  3870. duration: 500
  3871. });
  3872. };
  3873. /**
  3874. * Toggles the windows in the side panel
  3875. * @param object the window that should be shown
  3876. * @param selector the selector for the element containing the panel
  3877. * @param onOpenComplete function to be called when the panel is opened
  3878. * @param onOpen function to be called if the window is going to be opened
  3879. * @param onClose function to be called if the window is going to be closed
  3880. */
  3881. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  3882. UIUtil.buttonClick(buttons[selector], "active");
  3883. if (object.isVisible()) {
  3884. $("#toast-container").animate({
  3885. right: '5px'
  3886. },
  3887. {
  3888. queue: false,
  3889. duration: 500
  3890. });
  3891. $(selector).hide("slide", {
  3892. direction: "right",
  3893. queue: false,
  3894. duration: 500
  3895. });
  3896. if(typeof onClose === "function") {
  3897. onClose();
  3898. }
  3899. currentlyOpen = null;
  3900. }
  3901. else {
  3902. // Undock the toolbar when the chat is shown and if we're in a
  3903. // video mode.
  3904. if (VideoLayout.isLargeVideoVisible()) {
  3905. ToolbarToggler.dockToolbar(false);
  3906. }
  3907. if(currentlyOpen) {
  3908. var current = $(currentlyOpen);
  3909. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  3910. current.css('z-index', 4);
  3911. setTimeout(function () {
  3912. current.css('display', 'none');
  3913. current.css('z-index', 5);
  3914. }, 500);
  3915. }
  3916. $("#toast-container").animate({
  3917. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  3918. },
  3919. {
  3920. queue: false,
  3921. duration: 500
  3922. });
  3923. $(selector).show("slide", {
  3924. direction: "right",
  3925. queue: false,
  3926. duration: 500,
  3927. complete: onOpenComplete
  3928. });
  3929. if(typeof onOpen === "function") {
  3930. onOpen();
  3931. }
  3932. currentlyOpen = selector;
  3933. }
  3934. };
  3935. /**
  3936. * Opens / closes the chat area.
  3937. */
  3938. my.toggleChat = function() {
  3939. var chatCompleteFunction = Chat.isVisible() ?
  3940. function() {} : function () {
  3941. Chat.scrollChatToBottom();
  3942. $('#chatspace').trigger('shown');
  3943. };
  3944. resizeVideoArea(Chat.isVisible(), chatCompleteFunction);
  3945. toggle(Chat,
  3946. '#chatspace',
  3947. function () {
  3948. // Request the focus in the nickname field or the chat input field.
  3949. if ($('#nickname').css('visibility') === 'visible') {
  3950. $('#nickinput').focus();
  3951. } else {
  3952. $('#usermsg').focus();
  3953. }
  3954. },
  3955. null,
  3956. Chat.resizeChat,
  3957. null);
  3958. };
  3959. /**
  3960. * Opens / closes the contact list area.
  3961. */
  3962. my.toggleContactList = function () {
  3963. var completeFunction = ContactList.isVisible() ?
  3964. function() {} : function () { $('#contactlist').trigger('shown');};
  3965. resizeVideoArea(ContactList.isVisible(), completeFunction);
  3966. toggle(ContactList,
  3967. '#contactlist',
  3968. null,
  3969. function() {
  3970. ContactList.setVisualNotification(false);
  3971. },
  3972. null);
  3973. };
  3974. /**
  3975. * Opens / closes the settings menu
  3976. */
  3977. my.toggleSettingsMenu = function() {
  3978. resizeVideoArea(SettingsMenu.isVisible(), function (){});
  3979. toggle(SettingsMenu,
  3980. '#settingsmenu',
  3981. null,
  3982. function() {
  3983. var settings = Settings.getSettings();
  3984. $('#setDisplayName').get(0).value = settings.displayName;
  3985. $('#setEmail').get(0).value = settings.email;
  3986. },
  3987. null);
  3988. };
  3989. /**
  3990. * Returns the size of the side panel.
  3991. */
  3992. my.getPanelSize = function () {
  3993. var availableHeight = window.innerHeight;
  3994. var availableWidth = window.innerWidth;
  3995. var panelWidth = 200;
  3996. if (availableWidth * 0.2 < 200) {
  3997. panelWidth = availableWidth * 0.2;
  3998. }
  3999. return [panelWidth, availableHeight];
  4000. };
  4001. my.isVisible = function() {
  4002. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  4003. };
  4004. return my;
  4005. }(PanelToggler || {}));
  4006. module.exports = PanelToggler;
  4007. },{"../toolbars/ToolbarToggler":27,"../util/UIUtil":31,"../videolayout/VideoLayout":33,"./../../settings/Settings":41,"./chat/Chat":19,"./contactlist/ContactList":23,"./settings/SettingsMenu":24}],19:[function(require,module,exports){
  4008. /*
  4009. * Copyright @ 2015 Atlassian Pty Ltd
  4010. *
  4011. * Licensed under the Apache License, Version 2.0 (the "License");
  4012. * you may not use this file except in compliance with the License.
  4013. * You may obtain a copy of the License at
  4014. *
  4015. * http://www.apache.org/licenses/LICENSE-2.0
  4016. *
  4017. * Unless required by applicable law or agreed to in writing, software
  4018. * distributed under the License is distributed on an "AS IS" BASIS,
  4019. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4020. * See the License for the specific language governing permissions and
  4021. * limitations under the License.
  4022. */
  4023. /* global $, Util, nickname:true */
  4024. var Replacement = require("./Replacement");
  4025. var CommandsProcessor = require("./Commands");
  4026. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  4027. var smileys = require("./smileys.json").smileys;
  4028. var NicknameHandler = require("../../util/NicknameHandler");
  4029. var UIUtil = require("../../util/UIUtil");
  4030. var UIEvents = require("../../../../service/UI/UIEvents");
  4031. var notificationInterval = false;
  4032. var unreadMessages = 0;
  4033. /**
  4034. * Shows/hides a visual notification, indicating that a message has arrived.
  4035. */
  4036. function setVisualNotification(show) {
  4037. var unreadMsgElement = document.getElementById('unreadMessages');
  4038. var unreadMsgBottomElement
  4039. = document.getElementById('bottomUnreadMessages');
  4040. var glower = $('#chatButton');
  4041. var bottomGlower = $('#chatBottomButton');
  4042. if (unreadMessages) {
  4043. unreadMsgElement.innerHTML = unreadMessages.toString();
  4044. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  4045. ToolbarToggler.dockToolbar(true);
  4046. var chatButtonElement
  4047. = document.getElementById('chatButton').parentNode;
  4048. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  4049. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  4050. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  4051. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  4052. unreadMsgElement.setAttribute(
  4053. 'style',
  4054. 'top:' + topIndent +
  4055. '; left:' + leftIndent + ';');
  4056. var chatBottomButtonElement
  4057. = document.getElementById('chatBottomButton').parentNode;
  4058. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  4059. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  4060. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  4061. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  4062. unreadMsgBottomElement.setAttribute(
  4063. 'style',
  4064. 'top:' + bottomTopIndent +
  4065. '; left:' + bottomLeftIndent + ';');
  4066. if (!glower.hasClass('icon-chat-simple')) {
  4067. glower.removeClass('icon-chat');
  4068. glower.addClass('icon-chat-simple');
  4069. }
  4070. }
  4071. else {
  4072. unreadMsgElement.innerHTML = '';
  4073. unreadMsgBottomElement.innerHTML = '';
  4074. glower.removeClass('icon-chat-simple');
  4075. glower.addClass('icon-chat');
  4076. }
  4077. if (show && !notificationInterval) {
  4078. notificationInterval = window.setInterval(function () {
  4079. glower.toggleClass('active');
  4080. bottomGlower.toggleClass('active glowing');
  4081. }, 800);
  4082. }
  4083. else if (!show && notificationInterval) {
  4084. window.clearInterval(notificationInterval);
  4085. notificationInterval = false;
  4086. glower.removeClass('active');
  4087. bottomGlower.removeClass('glowing');
  4088. bottomGlower.addClass('active');
  4089. }
  4090. }
  4091. /**
  4092. * Returns the current time in the format it is shown to the user
  4093. * @returns {string}
  4094. */
  4095. function getCurrentTime() {
  4096. var now = new Date();
  4097. var hour = now.getHours();
  4098. var minute = now.getMinutes();
  4099. var second = now.getSeconds();
  4100. if(hour.toString().length === 1) {
  4101. hour = '0'+hour;
  4102. }
  4103. if(minute.toString().length === 1) {
  4104. minute = '0'+minute;
  4105. }
  4106. if(second.toString().length === 1) {
  4107. second = '0'+second;
  4108. }
  4109. return hour+':'+minute+':'+second;
  4110. }
  4111. function toggleSmileys()
  4112. {
  4113. var smileys = $('#smileysContainer');
  4114. if(!smileys.is(':visible')) {
  4115. smileys.show("slide", { direction: "down", duration: 300});
  4116. } else {
  4117. smileys.hide("slide", { direction: "down", duration: 300});
  4118. }
  4119. $('#usermsg').focus();
  4120. }
  4121. function addClickFunction(smiley, number) {
  4122. smiley.onclick = function addSmileyToMessage() {
  4123. var usermsg = $('#usermsg');
  4124. var message = usermsg.val();
  4125. message += smileys['smiley' + number];
  4126. usermsg.val(message);
  4127. usermsg.get(0).setSelectionRange(message.length, message.length);
  4128. toggleSmileys();
  4129. usermsg.focus();
  4130. };
  4131. }
  4132. /**
  4133. * Adds the smileys container to the chat
  4134. */
  4135. function addSmileys() {
  4136. var smileysContainer = document.createElement('div');
  4137. smileysContainer.id = 'smileysContainer';
  4138. for(var i = 1; i <= 21; i++) {
  4139. var smileyContainer = document.createElement('div');
  4140. smileyContainer.id = 'smiley' + i;
  4141. smileyContainer.className = 'smileyContainer';
  4142. var smiley = document.createElement('img');
  4143. smiley.src = 'images/smileys/smiley' + i + '.svg';
  4144. smiley.className = 'smiley';
  4145. addClickFunction(smiley, i);
  4146. smileyContainer.appendChild(smiley);
  4147. smileysContainer.appendChild(smileyContainer);
  4148. }
  4149. $("#chatspace").append(smileysContainer);
  4150. }
  4151. /**
  4152. * Resizes the chat conversation.
  4153. */
  4154. function resizeChatConversation() {
  4155. var msgareaHeight = $('#usermsg').outerHeight();
  4156. var chatspace = $('#chatspace');
  4157. var width = chatspace.width();
  4158. var chat = $('#chatconversation');
  4159. var smileys = $('#smileysarea');
  4160. smileys.height(msgareaHeight);
  4161. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  4162. $('#smileysContainer').css('bottom', msgareaHeight);
  4163. chat.width(width - 10);
  4164. chat.height(window.innerHeight - 15 - msgareaHeight);
  4165. }
  4166. /**
  4167. * Chat related user interface.
  4168. */
  4169. var Chat = (function (my) {
  4170. /**
  4171. * Initializes chat related interface.
  4172. */
  4173. my.init = function () {
  4174. if(NicknameHandler.getNickname())
  4175. Chat.setChatConversationMode(true);
  4176. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  4177. function (nickname) {
  4178. Chat.setChatConversationMode(true);
  4179. });
  4180. $('#nickinput').keydown(function (event) {
  4181. if (event.keyCode === 13) {
  4182. event.preventDefault();
  4183. var val = UIUtil.escapeHtml(this.value);
  4184. this.value = '';
  4185. if (!NicknameHandler.getNickname()) {
  4186. NicknameHandler.setNickname(val);
  4187. return;
  4188. }
  4189. }
  4190. });
  4191. $('#usermsg').keydown(function (event) {
  4192. if (event.keyCode === 13) {
  4193. event.preventDefault();
  4194. var value = this.value;
  4195. $('#usermsg').val('').trigger('autosize.resize');
  4196. this.focus();
  4197. var command = new CommandsProcessor(value);
  4198. if(command.isCommand())
  4199. {
  4200. command.processCommand();
  4201. }
  4202. else
  4203. {
  4204. var message = UIUtil.escapeHtml(value);
  4205. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  4206. }
  4207. }
  4208. });
  4209. var onTextAreaResize = function () {
  4210. resizeChatConversation();
  4211. Chat.scrollChatToBottom();
  4212. };
  4213. $('#usermsg').autosize({callback: onTextAreaResize});
  4214. $("#chatspace").bind("shown",
  4215. function () {
  4216. unreadMessages = 0;
  4217. setVisualNotification(false);
  4218. });
  4219. addSmileys();
  4220. };
  4221. /**
  4222. * Appends the given message to the chat conversation.
  4223. */
  4224. my.updateChatConversation = function (from, displayName, message) {
  4225. var divClassName = '';
  4226. if (APP.xmpp.myJid() === from) {
  4227. divClassName = "localuser";
  4228. }
  4229. else {
  4230. divClassName = "remoteuser";
  4231. if (!Chat.isVisible()) {
  4232. unreadMessages++;
  4233. UIUtil.playSoundNotification('chatNotification');
  4234. setVisualNotification(true);
  4235. }
  4236. }
  4237. // replace links and smileys
  4238. // Strophe already escapes special symbols on sending,
  4239. // so we escape here only tags to avoid double &amp;
  4240. var escMessage = message.replace(/</g, '&lt;').
  4241. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  4242. var escDisplayName = UIUtil.escapeHtml(displayName);
  4243. message = Replacement.processReplacements(escMessage);
  4244. var messageContainer =
  4245. '<div class="chatmessage">'+
  4246. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  4247. '<div class="username ' + divClassName +'">' + escDisplayName +
  4248. '</div>' + '<div class="timestamp">' + getCurrentTime() +
  4249. '</div>' + '<div class="usermessage">' + message + '</div>' +
  4250. '</div>';
  4251. $('#chatconversation').append(messageContainer);
  4252. $('#chatconversation').animate(
  4253. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  4254. };
  4255. /**
  4256. * Appends error message to the conversation
  4257. * @param errorMessage the received error message.
  4258. * @param originalText the original message.
  4259. */
  4260. my.chatAddError = function(errorMessage, originalText)
  4261. {
  4262. errorMessage = UIUtil.escapeHtml(errorMessage);
  4263. originalText = UIUtil.escapeHtml(originalText);
  4264. $('#chatconversation').append(
  4265. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  4266. (originalText? (' \"'+ originalText + '\"') : "") +
  4267. ' was not sent.' +
  4268. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  4269. $('#chatconversation').animate(
  4270. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  4271. };
  4272. /**
  4273. * Sets the subject to the UI
  4274. * @param subject the subject
  4275. */
  4276. my.chatSetSubject = function(subject)
  4277. {
  4278. if(subject)
  4279. subject = subject.trim();
  4280. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  4281. if(subject === "")
  4282. {
  4283. $("#subject").css({display: "none"});
  4284. }
  4285. else
  4286. {
  4287. $("#subject").css({display: "block"});
  4288. }
  4289. };
  4290. /**
  4291. * Sets the chat conversation mode.
  4292. */
  4293. my.setChatConversationMode = function (isConversationMode) {
  4294. if (isConversationMode) {
  4295. $('#nickname').css({visibility: 'hidden'});
  4296. $('#chatconversation').css({visibility: 'visible'});
  4297. $('#usermsg').css({visibility: 'visible'});
  4298. $('#smileysarea').css({visibility: 'visible'});
  4299. $('#usermsg').focus();
  4300. }
  4301. };
  4302. /**
  4303. * Resizes the chat area.
  4304. */
  4305. my.resizeChat = function () {
  4306. var chatSize = require("../SidePanelToggler").getPanelSize();
  4307. $('#chatspace').width(chatSize[0]);
  4308. $('#chatspace').height(chatSize[1]);
  4309. resizeChatConversation();
  4310. };
  4311. /**
  4312. * Indicates if the chat is currently visible.
  4313. */
  4314. my.isVisible = function () {
  4315. return $('#chatspace').is(":visible");
  4316. };
  4317. /**
  4318. * Shows and hides the window with the smileys
  4319. */
  4320. my.toggleSmileys = toggleSmileys;
  4321. /**
  4322. * Scrolls chat to the bottom.
  4323. */
  4324. my.scrollChatToBottom = function() {
  4325. setTimeout(function () {
  4326. $('#chatconversation').scrollTop(
  4327. $('#chatconversation')[0].scrollHeight);
  4328. }, 5);
  4329. };
  4330. return my;
  4331. }(Chat || {}));
  4332. module.exports = Chat;
  4333. },{"../../../../service/UI/UIEvents":106,"../../toolbars/ToolbarToggler":27,"../../util/NicknameHandler":30,"../../util/UIUtil":31,"../SidePanelToggler":18,"./Commands":20,"./Replacement":21,"./smileys.json":22}],20:[function(require,module,exports){
  4334. /*
  4335. * Copyright @ 2015 Atlassian Pty Ltd
  4336. *
  4337. * Licensed under the Apache License, Version 2.0 (the "License");
  4338. * you may not use this file except in compliance with the License.
  4339. * You may obtain a copy of the License at
  4340. *
  4341. * http://www.apache.org/licenses/LICENSE-2.0
  4342. *
  4343. * Unless required by applicable law or agreed to in writing, software
  4344. * distributed under the License is distributed on an "AS IS" BASIS,
  4345. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4346. * See the License for the specific language governing permissions and
  4347. * limitations under the License.
  4348. */
  4349. var UIUtil = require("../../util/UIUtil");
  4350. /**
  4351. * List with supported commands. The keys are the names of the commands and
  4352. * the value is the function that processes the message.
  4353. * @type {{String: function}}
  4354. */
  4355. var commands = {
  4356. "topic" : processTopic
  4357. };
  4358. /**
  4359. * Extracts the command from the message.
  4360. * @param message the received message
  4361. * @returns {string} the command
  4362. */
  4363. function getCommand(message)
  4364. {
  4365. if(message)
  4366. {
  4367. for(var command in commands)
  4368. {
  4369. if(message.indexOf("/" + command) == 0)
  4370. return command;
  4371. }
  4372. }
  4373. return "";
  4374. };
  4375. /**
  4376. * Processes the data for topic command.
  4377. * @param commandArguments the arguments of the topic command.
  4378. */
  4379. function processTopic(commandArguments)
  4380. {
  4381. var topic = UIUtil.escapeHtml(commandArguments);
  4382. APP.xmpp.setSubject(topic);
  4383. }
  4384. /**
  4385. * Constructs new CommandProccessor instance from a message that
  4386. * handles commands received via chat messages.
  4387. * @param message the message
  4388. * @constructor
  4389. */
  4390. function CommandsProcessor(message)
  4391. {
  4392. var command = getCommand(message);
  4393. /**
  4394. * Returns the name of the command.
  4395. * @returns {String} the command
  4396. */
  4397. this.getCommand = function()
  4398. {
  4399. return command;
  4400. };
  4401. var messageArgument = message.substr(command.length + 2);
  4402. /**
  4403. * Returns the arguments of the command.
  4404. * @returns {string}
  4405. */
  4406. this.getArgument = function()
  4407. {
  4408. return messageArgument;
  4409. };
  4410. }
  4411. /**
  4412. * Checks whether this instance is valid command or not.
  4413. * @returns {boolean}
  4414. */
  4415. CommandsProcessor.prototype.isCommand = function()
  4416. {
  4417. if(this.getCommand())
  4418. return true;
  4419. return false;
  4420. };
  4421. /**
  4422. * Processes the command.
  4423. */
  4424. CommandsProcessor.prototype.processCommand = function()
  4425. {
  4426. if(!this.isCommand())
  4427. return;
  4428. commands[this.getCommand()](this.getArgument());
  4429. };
  4430. module.exports = CommandsProcessor;
  4431. },{"../../util/UIUtil":31}],21:[function(require,module,exports){
  4432. /*
  4433. * Copyright @ 2015 Atlassian Pty Ltd
  4434. *
  4435. * Licensed under the Apache License, Version 2.0 (the "License");
  4436. * you may not use this file except in compliance with the License.
  4437. * You may obtain a copy of the License at
  4438. *
  4439. * http://www.apache.org/licenses/LICENSE-2.0
  4440. *
  4441. * Unless required by applicable law or agreed to in writing, software
  4442. * distributed under the License is distributed on an "AS IS" BASIS,
  4443. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4444. * See the License for the specific language governing permissions and
  4445. * limitations under the License.
  4446. */
  4447. var Smileys = require("./smileys.json");
  4448. /**
  4449. * Processes links and smileys in "body"
  4450. */
  4451. function processReplacements(body)
  4452. {
  4453. //make links clickable
  4454. body = linkify(body);
  4455. //add smileys
  4456. body = smilify(body);
  4457. return body;
  4458. }
  4459. /**
  4460. * Finds and replaces all links in the links in "body"
  4461. * with their <a href=""></a>
  4462. */
  4463. function linkify(inputText)
  4464. {
  4465. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  4466. //URLs starting with http://, https://, or ftp://
  4467. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  4468. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  4469. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  4470. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  4471. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  4472. //Change email addresses to mailto:: links.
  4473. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  4474. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  4475. return replacedText;
  4476. }
  4477. /**
  4478. * Replaces common smiley strings with images
  4479. */
  4480. function smilify(body)
  4481. {
  4482. if(!body) {
  4483. return body;
  4484. }
  4485. var regexs = Smileys["regexs"];
  4486. for(var smiley in regexs) {
  4487. if(regexs.hasOwnProperty(smiley)) {
  4488. body = body.replace(regexs[smiley],
  4489. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  4490. }
  4491. }
  4492. return body;
  4493. }
  4494. module.exports = {
  4495. processReplacements: processReplacements,
  4496. linkify: linkify
  4497. };
  4498. },{"./smileys.json":22}],22:[function(require,module,exports){
  4499. module.exports={
  4500. "smileys": {
  4501. "smiley1": ":)",
  4502. "smiley2": ":(",
  4503. "smiley3": ":D",
  4504. "smiley4": "(y)",
  4505. "smiley5": " :P",
  4506. "smiley6": "(wave)",
  4507. "smiley7": "(blush)",
  4508. "smiley8": "(chuckle)",
  4509. "smiley9": "(shocked)",
  4510. "smiley10": ":*",
  4511. "smiley11": "(n)",
  4512. "smiley12": "(search)",
  4513. "smiley13": " <3",
  4514. "smiley14": "(oops)",
  4515. "smiley15": "(angry)",
  4516. "smiley16": "(angel)",
  4517. "smiley17": "(sick)",
  4518. "smiley18": ";(",
  4519. "smiley19": "(bomb)",
  4520. "smiley20": "(clap)",
  4521. "smiley21": " ;)"
  4522. },
  4523. "regexs": {
  4524. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  4525. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  4526. "smiley1": /(:-\)|:\))/gi,
  4527. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  4528. "smiley5": /(:-P|:P|:-p|:p)/gi,
  4529. "smiley6": /(\(wave\))/gi,
  4530. "smiley7": /(\(blush\))/gi,
  4531. "smiley8": /(\(chuckle\))/gi,
  4532. "smiley9": /(:-0|\(shocked\))/gi,
  4533. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  4534. "smiley11": /(\(n\))/gi,
  4535. "smiley12": /(\(search\))/g,
  4536. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  4537. "smiley14": /(\(oops\))/gi,
  4538. "smiley15": /(\(angry\))/gi,
  4539. "smiley16": /(\(angel\))/gi,
  4540. "smiley17": /(\(sick\))/gi,
  4541. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  4542. "smiley19": /(\(bomb\))/gi,
  4543. "smiley20": /(\(clap\))/gi,
  4544. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  4545. }
  4546. }
  4547. },{}],23:[function(require,module,exports){
  4548. /*
  4549. * Copyright @ 2015 Atlassian Pty Ltd
  4550. *
  4551. * Licensed under the Apache License, Version 2.0 (the "License");
  4552. * you may not use this file except in compliance with the License.
  4553. * You may obtain a copy of the License at
  4554. *
  4555. * http://www.apache.org/licenses/LICENSE-2.0
  4556. *
  4557. * Unless required by applicable law or agreed to in writing, software
  4558. * distributed under the License is distributed on an "AS IS" BASIS,
  4559. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4560. * See the License for the specific language governing permissions and
  4561. * limitations under the License.
  4562. */
  4563. var numberOfContacts = 0;
  4564. var notificationInterval;
  4565. /**
  4566. * Updates the number of participants in the contact list button and sets
  4567. * the glow
  4568. * @param delta indicates whether a new user has joined (1) or someone has
  4569. * left(-1)
  4570. */
  4571. function updateNumberOfParticipants(delta) {
  4572. //when the user is alone we don't show the number of participants
  4573. if(numberOfContacts === 0) {
  4574. $("#numberOfParticipants").text('');
  4575. numberOfContacts += delta;
  4576. } else if(numberOfContacts !== 0 && !ContactList.isVisible()) {
  4577. ContactList.setVisualNotification(true);
  4578. numberOfContacts += delta;
  4579. $("#numberOfParticipants").text(numberOfContacts);
  4580. }
  4581. }
  4582. /**
  4583. * Creates the avatar element.
  4584. *
  4585. * @return the newly created avatar element
  4586. */
  4587. function createAvatar(id) {
  4588. var avatar = document.createElement('img');
  4589. avatar.className = "icon-avatar avatar";
  4590. avatar.src = "https://www.gravatar.com/avatar/" + id + "?d=wavatar&size=30";
  4591. return avatar;
  4592. }
  4593. /**
  4594. * Creates the display name paragraph.
  4595. *
  4596. * @param displayName the display name to set
  4597. */
  4598. function createDisplayNameParagraph(key, displayName) {
  4599. var p = document.createElement('p');
  4600. if(displayName)
  4601. p.innerText = displayName;
  4602. else if(key)
  4603. {
  4604. p.setAttribute("data-i18n",key);
  4605. p.innerText = APP.translation.translateString(key);
  4606. }
  4607. return p;
  4608. }
  4609. function stopGlowing(glower) {
  4610. window.clearInterval(notificationInterval);
  4611. notificationInterval = false;
  4612. glower.removeClass('glowing');
  4613. if (!ContactList.isVisible()) {
  4614. glower.removeClass('active');
  4615. }
  4616. }
  4617. /**
  4618. * Contact list.
  4619. */
  4620. var ContactList = {
  4621. /**
  4622. * Indicates if the chat is currently visible.
  4623. *
  4624. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  4625. * otherwise
  4626. */
  4627. isVisible: function () {
  4628. return $('#contactlist').is(":visible");
  4629. },
  4630. /**
  4631. * Adds a contact for the given peerJid if such doesn't yet exist.
  4632. *
  4633. * @param peerJid the peerJid corresponding to the contact
  4634. * @param id the user's email or userId used to get the user's avatar
  4635. */
  4636. ensureAddContact: function (peerJid, id) {
  4637. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4638. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4639. if (!contact || contact.length <= 0)
  4640. ContactList.addContact(peerJid, id);
  4641. },
  4642. /**
  4643. * Adds a contact for the given peer jid.
  4644. *
  4645. * @param peerJid the jid of the contact to add
  4646. * @param id the email or userId of the user
  4647. */
  4648. addContact: function (peerJid, id) {
  4649. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4650. var contactlist = $('#contactlist>ul');
  4651. var newContact = document.createElement('li');
  4652. newContact.id = resourceJid;
  4653. newContact.className = "clickable";
  4654. newContact.onclick = function (event) {
  4655. if (event.currentTarget.className === "clickable") {
  4656. $(ContactList).trigger('contactclicked', [peerJid]);
  4657. }
  4658. };
  4659. newContact.appendChild(createAvatar(id));
  4660. newContact.appendChild(createDisplayNameParagraph("participant"));
  4661. var clElement = contactlist.get(0);
  4662. if (resourceJid === APP.xmpp.myResource()
  4663. && $('#contactlist>ul .title')[0].nextSibling.nextSibling) {
  4664. clElement.insertBefore(newContact,
  4665. $('#contactlist>ul .title')[0].nextSibling.nextSibling);
  4666. }
  4667. else {
  4668. clElement.appendChild(newContact);
  4669. }
  4670. updateNumberOfParticipants(1);
  4671. },
  4672. /**
  4673. * Removes a contact for the given peer jid.
  4674. *
  4675. * @param peerJid the peerJid corresponding to the contact to remove
  4676. */
  4677. removeContact: function (peerJid) {
  4678. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4679. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4680. if (contact && contact.length > 0) {
  4681. var contactlist = $('#contactlist>ul');
  4682. contactlist.get(0).removeChild(contact.get(0));
  4683. updateNumberOfParticipants(-1);
  4684. }
  4685. },
  4686. setVisualNotification: function (show, stopGlowingIn) {
  4687. var glower = $('#contactListButton');
  4688. if (show && !notificationInterval) {
  4689. notificationInterval = window.setInterval(function () {
  4690. glower.toggleClass('active glowing');
  4691. }, 800);
  4692. }
  4693. else if (!show && notificationInterval) {
  4694. stopGlowing(glower);
  4695. }
  4696. if (stopGlowingIn) {
  4697. setTimeout(function () {
  4698. stopGlowing(glower);
  4699. }, stopGlowingIn);
  4700. }
  4701. },
  4702. setClickable: function (resourceJid, isClickable) {
  4703. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4704. if (isClickable) {
  4705. contact.addClass('clickable');
  4706. } else {
  4707. contact.removeClass('clickable');
  4708. }
  4709. },
  4710. onDisplayNameChange: function (peerJid, displayName) {
  4711. if (peerJid === 'localVideoContainer')
  4712. peerJid = APP.xmpp.myJid();
  4713. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4714. var contactName = $('#contactlist #' + resourceJid + '>p');
  4715. if (contactName && displayName && displayName.length > 0)
  4716. contactName.html(displayName);
  4717. }
  4718. };
  4719. module.exports = ContactList;
  4720. },{}],24:[function(require,module,exports){
  4721. /*
  4722. * Copyright @ 2015 Atlassian Pty Ltd
  4723. *
  4724. * Licensed under the Apache License, Version 2.0 (the "License");
  4725. * you may not use this file except in compliance with the License.
  4726. * You may obtain a copy of the License at
  4727. *
  4728. * http://www.apache.org/licenses/LICENSE-2.0
  4729. *
  4730. * Unless required by applicable law or agreed to in writing, software
  4731. * distributed under the License is distributed on an "AS IS" BASIS,
  4732. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4733. * See the License for the specific language governing permissions and
  4734. * limitations under the License.
  4735. */
  4736. var Avatar = require("../../avatar/Avatar");
  4737. var Settings = require("./../../../settings/Settings");
  4738. var UIUtil = require("../../util/UIUtil");
  4739. var languages = require("../../../../service/translation/languages");
  4740. function generateLanguagesSelectBox()
  4741. {
  4742. var currentLang = APP.translation.getCurrentLanguage();
  4743. var html = "<select id=\"languages_selectbox\">";
  4744. var langArray = languages.getLanguages();
  4745. for(var i = 0; i < langArray.length; i++)
  4746. {
  4747. var lang = langArray[i];
  4748. html += "<option ";
  4749. if(lang === currentLang)
  4750. html += "selected ";
  4751. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  4752. html += "</option>";
  4753. }
  4754. return html + "</select>";
  4755. }
  4756. var SettingsMenu = {
  4757. init: function () {
  4758. $("#startMutedOptions").before(generateLanguagesSelectBox());
  4759. APP.translation.translateElement($("#languages_selectbox"));
  4760. $('#settingsmenu>input').keyup(function(event){
  4761. if(event.keyCode === 13) {//enter
  4762. SettingsMenu.update();
  4763. }
  4764. });
  4765. if(APP.xmpp.isModerator())
  4766. {
  4767. $("#startMutedOptions").css("display", "block");
  4768. }
  4769. else
  4770. {
  4771. $("#startMutedOptions").css("display", "none");
  4772. }
  4773. $("#updateSettings").click(function () {
  4774. SettingsMenu.update();
  4775. });
  4776. },
  4777. onRoleChanged: function () {
  4778. if(APP.xmpp.isModerator())
  4779. {
  4780. $("#startMutedOptions").css("display", "block");
  4781. }
  4782. else
  4783. {
  4784. $("#startMutedOptions").css("display", "none");
  4785. }
  4786. },
  4787. setStartMuted: function (audio, video) {
  4788. $("#startAudioMuted").attr("checked", audio);
  4789. $("#startVideoMuted").attr("checked", video);
  4790. },
  4791. update: function() {
  4792. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  4793. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  4794. if(newDisplayName) {
  4795. var displayName = Settings.setDisplayName(newDisplayName);
  4796. APP.xmpp.addToPresence("displayName", displayName, true);
  4797. }
  4798. var language = $("#languages_selectbox").val();
  4799. APP.translation.setLanguage(language);
  4800. Settings.setLanguage(language);
  4801. APP.xmpp.addToPresence("email", newEmail);
  4802. var email = Settings.setEmail(newEmail);
  4803. var startAudioMuted = ($("#startAudioMuted").is(":checked"));
  4804. var startVideoMuted = ($("#startVideoMuted").is(":checked"));
  4805. APP.xmpp.addToPresence("startMuted",
  4806. [startAudioMuted, startVideoMuted]);
  4807. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  4808. },
  4809. isVisible: function() {
  4810. return $('#settingsmenu').is(':visible');
  4811. },
  4812. setDisplayName: function(newDisplayName) {
  4813. var displayName = Settings.setDisplayName(newDisplayName);
  4814. $('#setDisplayName').get(0).value = displayName;
  4815. },
  4816. onDisplayNameChange: function(peerJid, newDisplayName) {
  4817. if(peerJid === 'localVideoContainer' ||
  4818. peerJid === APP.xmpp.myJid()) {
  4819. this.setDisplayName(newDisplayName);
  4820. }
  4821. }
  4822. };
  4823. module.exports = SettingsMenu;
  4824. },{"../../../../service/translation/languages":111,"../../avatar/Avatar":14,"../../util/UIUtil":31,"./../../../settings/Settings":41}],25:[function(require,module,exports){
  4825. /*
  4826. * Copyright @ 2015 Atlassian Pty Ltd
  4827. *
  4828. * Licensed under the Apache License, Version 2.0 (the "License");
  4829. * you may not use this file except in compliance with the License.
  4830. * You may obtain a copy of the License at
  4831. *
  4832. * http://www.apache.org/licenses/LICENSE-2.0
  4833. *
  4834. * Unless required by applicable law or agreed to in writing, software
  4835. * distributed under the License is distributed on an "AS IS" BASIS,
  4836. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4837. * See the License for the specific language governing permissions and
  4838. * limitations under the License.
  4839. */
  4840. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4841. var buttonHandlers = {
  4842. "bottom_toolbar_contact_list": function () {
  4843. BottomToolbar.toggleContactList();
  4844. },
  4845. "bottom_toolbar_film_strip": function () {
  4846. BottomToolbar.toggleFilmStrip();
  4847. },
  4848. "bottom_toolbar_chat": function () {
  4849. BottomToolbar.toggleChat();
  4850. }
  4851. };
  4852. var BottomToolbar = (function (my) {
  4853. my.init = function () {
  4854. for(var k in buttonHandlers)
  4855. $("#" + k).click(buttonHandlers[k]);
  4856. };
  4857. my.toggleChat = function() {
  4858. PanelToggler.toggleChat();
  4859. };
  4860. my.toggleContactList = function() {
  4861. PanelToggler.toggleContactList();
  4862. };
  4863. my.toggleFilmStrip = function() {
  4864. var filmstrip = $("#remoteVideos");
  4865. filmstrip.toggleClass("hidden");
  4866. };
  4867. $(document).bind("remotevideo.resized", function (event, width, height) {
  4868. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  4869. $('#bottomToolbar').css({bottom: bottom + 'px'});
  4870. });
  4871. return my;
  4872. }(BottomToolbar || {}));
  4873. module.exports = BottomToolbar;
  4874. },{"../side_pannels/SidePanelToggler":18}],26:[function(require,module,exports){
  4875. /*
  4876. * Copyright @ 2015 Atlassian Pty Ltd
  4877. *
  4878. * Licensed under the Apache License, Version 2.0 (the "License");
  4879. * you may not use this file except in compliance with the License.
  4880. * You may obtain a copy of the License at
  4881. *
  4882. * http://www.apache.org/licenses/LICENSE-2.0
  4883. *
  4884. * Unless required by applicable law or agreed to in writing, software
  4885. * distributed under the License is distributed on an "AS IS" BASIS,
  4886. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4887. * See the License for the specific language governing permissions and
  4888. * limitations under the License.
  4889. */
  4890. /* global APP,$, buttonClick, config, lockRoom,
  4891. setSharedKey, Util */
  4892. var messageHandler = require("../util/MessageHandler");
  4893. var BottomToolbar = require("./BottomToolbar");
  4894. var Prezi = require("../prezi/Prezi");
  4895. var Etherpad = require("../etherpad/Etherpad");
  4896. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4897. var Authentication = require("../authentication/Authentication");
  4898. var UIUtil = require("../util/UIUtil");
  4899. var AuthenticationEvents
  4900. = require("../../../service/authentication/AuthenticationEvents");
  4901. var roomUrl = null;
  4902. var sharedKey = '';
  4903. var UI = null;
  4904. var buttonHandlers =
  4905. {
  4906. "toolbar_button_mute": function () {
  4907. return APP.UI.toggleAudio();
  4908. },
  4909. "toolbar_button_camera": function () {
  4910. return APP.UI.toggleVideo();
  4911. },
  4912. /*"toolbar_button_authentication": function () {
  4913. return Toolbar.authenticateClicked();
  4914. },*/
  4915. "toolbar_button_record": function () {
  4916. return toggleRecording();
  4917. },
  4918. "toolbar_button_security": function () {
  4919. return Toolbar.openLockDialog();
  4920. },
  4921. "toolbar_button_link": function () {
  4922. return Toolbar.openLinkDialog();
  4923. },
  4924. "toolbar_button_chat": function () {
  4925. return BottomToolbar.toggleChat();
  4926. },
  4927. "toolbar_button_prezi": function () {
  4928. return Prezi.openPreziDialog();
  4929. },
  4930. "toolbar_button_etherpad": function () {
  4931. return Etherpad.toggleEtherpad(0);
  4932. },
  4933. "toolbar_button_desktopsharing": function () {
  4934. return APP.desktopsharing.toggleScreenSharing();
  4935. },
  4936. "toolbar_button_fullScreen": function()
  4937. {
  4938. UIUtil.buttonClick("#fullScreen", "icon-full-screen icon-exit-full-screen");
  4939. return Toolbar.toggleFullScreen();
  4940. },
  4941. "toolbar_button_sip": function () {
  4942. return callSipButtonClicked();
  4943. },
  4944. "toolbar_button_dialpad": function () {
  4945. return dialpadButtonClicked();
  4946. },
  4947. "toolbar_button_settings": function () {
  4948. PanelToggler.toggleSettingsMenu();
  4949. },
  4950. "toolbar_button_hangup": function () {
  4951. return hangup();
  4952. },
  4953. "toolbar_button_login": function () {
  4954. Toolbar.authenticateClicked();
  4955. },
  4956. "toolbar_button_logout": function () {
  4957. // Ask for confirmation
  4958. messageHandler.openTwoButtonDialog(
  4959. "dialog.logoutTitle",
  4960. null,
  4961. "dialog.logoutQuestion",
  4962. null,
  4963. false,
  4964. "dialog.Yes",
  4965. function (evt, yes) {
  4966. if (yes) {
  4967. APP.xmpp.logout(function (url) {
  4968. if (url) {
  4969. window.location.href = url;
  4970. } else {
  4971. hangup();
  4972. }
  4973. });
  4974. }
  4975. });
  4976. }
  4977. };
  4978. function hangup() {
  4979. APP.xmpp.disposeConference();
  4980. if(config.enableWelcomePage)
  4981. {
  4982. setTimeout(function()
  4983. {
  4984. window.localStorage.welcomePageDisabled = false;
  4985. window.location.pathname = "/";
  4986. }, 10000);
  4987. }
  4988. var title = APP.translation.generateTranslatonHTML(
  4989. "dialog.sessTerminated");
  4990. var msg = APP.translation.generateTranslatonHTML(
  4991. "dialog.hungUp");
  4992. var button = APP.translation.generateTranslatonHTML(
  4993. "dialog.joinAgain");
  4994. var buttons = [];
  4995. buttons.push({title: button, value: true});
  4996. UI.messageHandler.openDialog(
  4997. title,
  4998. msg,
  4999. true,
  5000. buttons,
  5001. function(event, value, message, formVals)
  5002. {
  5003. window.location.reload();
  5004. return false;
  5005. }
  5006. );
  5007. }
  5008. /**
  5009. * Starts or stops the recording for the conference.
  5010. */
  5011. function toggleRecording() {
  5012. APP.xmpp.toggleRecording(function (callback) {
  5013. var msg = APP.translation.generateTranslatonHTML(
  5014. "dialog.recordingToken");
  5015. var token = APP.translation.translateString("dialog.token");
  5016. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  5017. '<h2>' + msg + '</h2>' +
  5018. '<input name="recordingToken" type="text" ' +
  5019. ' data-i18n="[placeholder]dialog.token" ' +
  5020. 'placeholder="' + token + '" autofocus>',
  5021. false,
  5022. "dialog.Save",
  5023. function (e, v, m, f) {
  5024. if (v) {
  5025. var token = f.recordingToken;
  5026. if (token) {
  5027. callback(UIUtil.escapeHtml(token));
  5028. }
  5029. }
  5030. },
  5031. null,
  5032. function () { },
  5033. ':input:first'
  5034. );
  5035. }, Toolbar.setRecordingButtonState, Toolbar.setRecordingButtonState);
  5036. }
  5037. /**
  5038. * Locks / unlocks the room.
  5039. */
  5040. function lockRoom(lock) {
  5041. var currentSharedKey = '';
  5042. if (lock)
  5043. currentSharedKey = sharedKey;
  5044. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  5045. // password is required
  5046. if (sharedKey)
  5047. {
  5048. console.log('set room password');
  5049. Toolbar.lockLockButton();
  5050. }
  5051. else
  5052. {
  5053. console.log('removed room password');
  5054. Toolbar.unlockLockButton();
  5055. }
  5056. }, function (err) {
  5057. console.warn('setting password failed', err);
  5058. messageHandler.showError("dialog.lockTitle",
  5059. "dialog.lockMessage");
  5060. Toolbar.setSharedKey('');
  5061. }, function () {
  5062. console.warn('room passwords not supported');
  5063. messageHandler.showError("dialog.warning",
  5064. "dialog.passwordNotSupported");
  5065. Toolbar.setSharedKey('');
  5066. });
  5067. };
  5068. /**
  5069. * Invite participants to conference.
  5070. */
  5071. function inviteParticipants() {
  5072. if (roomUrl === null)
  5073. return;
  5074. var sharedKeyText = "";
  5075. if (sharedKey && sharedKey.length > 0) {
  5076. sharedKeyText =
  5077. APP.translation.translateString("email.sharedKey",
  5078. {sharedKey: sharedKey});
  5079. sharedKeyText = sharedKeyText.replace(/\n/g, "%0D%0A");
  5080. }
  5081. var supportedBrowsers = "Chromium, Google Chrome " +
  5082. APP.translation.translateString("email.and") + " Opera";
  5083. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  5084. var subject = APP.translation.translateString("email.subject",
  5085. {appName:interfaceConfig.APP_NAME, conferenceName: conferenceName});
  5086. var body = APP.translation.translateString("email.body",
  5087. {appName:interfaceConfig.APP_NAME, sharedKeyText: sharedKeyText,
  5088. roomUrl: roomUrl, supportedBrowsers: supportedBrowsers});
  5089. body = body.replace(/\n/g, "%0D%0A");
  5090. if (window.localStorage.displayname) {
  5091. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  5092. }
  5093. if (interfaceConfig.INVITATION_POWERED_BY) {
  5094. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  5095. }
  5096. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  5097. }
  5098. function dialpadButtonClicked()
  5099. {
  5100. //TODO show the dialpad window
  5101. }
  5102. function callSipButtonClicked()
  5103. {
  5104. var defaultNumber
  5105. = config.defaultSipNumber ? config.defaultSipNumber : '';
  5106. var sipMsg = APP.translation.generateTranslatonHTML(
  5107. "dialog.sipMsg");
  5108. messageHandler.openTwoButtonDialog(null, null, null,
  5109. '<h2>' + sipMsg + '</h2>' +
  5110. '<input name="sipNumber" type="text"' +
  5111. ' value="' + defaultNumber + '" autofocus>',
  5112. false,
  5113. "dialog.Dial",
  5114. function (e, v, m, f) {
  5115. if (v) {
  5116. var numberInput = f.sipNumber;
  5117. if (numberInput) {
  5118. APP.xmpp.dial(
  5119. numberInput, 'fromnumber', UI.getRoomName(), sharedKey);
  5120. }
  5121. }
  5122. },
  5123. null, null, ':input:first'
  5124. );
  5125. }
  5126. var Toolbar = (function (my) {
  5127. my.init = function (ui) {
  5128. for(var k in buttonHandlers)
  5129. $("#" + k).click(buttonHandlers[k]);
  5130. UI = ui;
  5131. // Update login info
  5132. APP.xmpp.addListener(
  5133. AuthenticationEvents.IDENTITY_UPDATED,
  5134. function (authenticationEnabled, userIdentity) {
  5135. var loggedIn = false;
  5136. if (userIdentity) {
  5137. loggedIn = true;
  5138. }
  5139. Toolbar.showAuthenticateButton(authenticationEnabled);
  5140. if (authenticationEnabled) {
  5141. Toolbar.setAuthenticatedIdentity(userIdentity);
  5142. Toolbar.showLoginButton(!loggedIn);
  5143. Toolbar.showLogoutButton(loggedIn);
  5144. }
  5145. }
  5146. );
  5147. },
  5148. /**
  5149. * Sets shared key
  5150. * @param sKey the shared key
  5151. */
  5152. my.setSharedKey = function (sKey) {
  5153. sharedKey = sKey;
  5154. };
  5155. my.authenticateClicked = function () {
  5156. Authentication.focusAuthenticationWindow();
  5157. if (!APP.xmpp.isExternalAuthEnabled()) {
  5158. Authentication.xmppAuthenticate();
  5159. return;
  5160. }
  5161. // Get authentication URL
  5162. if (!APP.xmpp.getMUCJoined()) {
  5163. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  5164. // If conference has not been started yet - redirect to login page
  5165. window.location.href = url;
  5166. });
  5167. } else {
  5168. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  5169. // Otherwise - open popup with authentication URL
  5170. var authenticationWindow = Authentication.createAuthenticationWindow(
  5171. function () {
  5172. // On popup closed - retry room allocation
  5173. APP.xmpp.allocateConferenceFocus(
  5174. APP.UI.getRoomName(),
  5175. function () { console.info("AUTH DONE"); }
  5176. );
  5177. }, url);
  5178. if (!authenticationWindow) {
  5179. messageHandler.openMessageDialog(
  5180. null, "dialog.popupError");
  5181. }
  5182. });
  5183. }
  5184. };
  5185. /**
  5186. * Updates the room invite url.
  5187. */
  5188. my.updateRoomUrl = function (newRoomUrl) {
  5189. roomUrl = newRoomUrl;
  5190. // If the invite dialog has been already opened we update the information.
  5191. var inviteLink = document.getElementById('inviteLinkRef');
  5192. if (inviteLink) {
  5193. inviteLink.value = roomUrl;
  5194. inviteLink.select();
  5195. $('#inviteLinkRef').parent()
  5196. .find('button[value=true]').prop('disabled', false);
  5197. }
  5198. };
  5199. /**
  5200. * Disables and enables some of the buttons.
  5201. */
  5202. my.setupButtonsFromConfig = function () {
  5203. if (config.disablePrezi)
  5204. {
  5205. $("#prezi_button").css({display: "none"});
  5206. }
  5207. };
  5208. /**
  5209. * Opens the lock room dialog.
  5210. */
  5211. my.openLockDialog = function () {
  5212. // Only the focus is able to set a shared key.
  5213. if (!APP.xmpp.isModerator()) {
  5214. if (sharedKey) {
  5215. messageHandler.openMessageDialog(null,
  5216. "dialog.passwordError");
  5217. } else {
  5218. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  5219. }
  5220. } else {
  5221. if (sharedKey) {
  5222. messageHandler.openTwoButtonDialog(null, null,
  5223. "dialog.passwordCheck",
  5224. null,
  5225. false,
  5226. "dialog.Remove",
  5227. function (e, v) {
  5228. if (v) {
  5229. Toolbar.setSharedKey('');
  5230. lockRoom(false);
  5231. }
  5232. });
  5233. } else {
  5234. var msg = APP.translation.generateTranslatonHTML(
  5235. "dialog.passwordMsg");
  5236. var yourPassword = APP.translation.translateString(
  5237. "dialog.yourPassword");
  5238. messageHandler.openTwoButtonDialog(null, null, null,
  5239. '<h2>' + msg + '</h2>' +
  5240. '<input name="lockKey" type="text"' +
  5241. ' data-i18n="[placeholder]dialog.yourPassword" ' +
  5242. 'placeholder="' + yourPassword + '" autofocus>',
  5243. false,
  5244. "dialog.Save",
  5245. function (e, v, m, f) {
  5246. if (v) {
  5247. var lockKey = f.lockKey;
  5248. if (lockKey) {
  5249. Toolbar.setSharedKey(
  5250. UIUtil.escapeHtml(lockKey));
  5251. lockRoom(true);
  5252. }
  5253. }
  5254. },
  5255. null, null, 'input:first'
  5256. );
  5257. }
  5258. }
  5259. };
  5260. /**
  5261. * Opens the invite link dialog.
  5262. */
  5263. my.openLinkDialog = function () {
  5264. var inviteAttreibutes;
  5265. if (roomUrl === null) {
  5266. inviteAttreibutes = 'data-i18n="[value]roomUrlDefaultMsg" value="' +
  5267. APP.translation.translateString("roomUrlDefaultMsg") + '"';
  5268. } else {
  5269. inviteAttreibutes = "value=\"" + encodeURI(roomUrl) + "\"";
  5270. }
  5271. messageHandler.openTwoButtonDialog("dialog.shareLink",
  5272. null, null,
  5273. '<input id="inviteLinkRef" type="text" ' +
  5274. inviteAttreibutes + ' onclick="this.select();" readonly>',
  5275. false,
  5276. "dialog.Invite",
  5277. function (e, v) {
  5278. if (v) {
  5279. if (roomUrl) {
  5280. inviteParticipants();
  5281. }
  5282. }
  5283. },
  5284. function (event) {
  5285. if (roomUrl) {
  5286. document.getElementById('inviteLinkRef').select();
  5287. } else {
  5288. if (event && event.target)
  5289. $(event.target)
  5290. .find('button[value=true]').prop('disabled', true);
  5291. }
  5292. }
  5293. );
  5294. };
  5295. /**
  5296. * Opens the settings dialog.
  5297. * FIXME: not used ?
  5298. */
  5299. my.openSettingsDialog = function () {
  5300. var settings1 = APP.translation.generateTranslatonHTML(
  5301. "dialog.settings1");
  5302. var settings2 = APP.translation.generateTranslatonHTML(
  5303. "dialog.settings2");
  5304. var settings3 = APP.translation.generateTranslatonHTML(
  5305. "dialog.settings3");
  5306. var yourPassword = APP.translation.translateString(
  5307. "dialog.yourPassword");
  5308. messageHandler.openTwoButtonDialog(null,
  5309. '<h2>' + settings1 + '</h2>' +
  5310. '<input type="checkbox" id="initMuted">' +
  5311. settings2 + '<br/>' +
  5312. '<input type="checkbox" id="requireNicknames">' +
  5313. settings3 +
  5314. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  5315. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  5316. null,
  5317. null,
  5318. false,
  5319. "dialog.Save",
  5320. function () {
  5321. document.getElementById('lockKey').focus();
  5322. },
  5323. function (e, v) {
  5324. if (v) {
  5325. if ($('#initMuted').is(":checked")) {
  5326. // it is checked
  5327. }
  5328. if ($('#requireNicknames').is(":checked")) {
  5329. // it is checked
  5330. }
  5331. /*
  5332. var lockKey = document.getElementById('lockKey');
  5333. if (lockKey.value) {
  5334. setSharedKey(lockKey.value);
  5335. lockRoom(true);
  5336. }
  5337. */
  5338. }
  5339. }
  5340. );
  5341. };
  5342. /**
  5343. * Toggles the application in and out of full screen mode
  5344. * (a.k.a. presentation mode in Chrome).
  5345. */
  5346. my.toggleFullScreen = function () {
  5347. var fsElement = document.documentElement;
  5348. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  5349. //Enter Full Screen
  5350. if (fsElement.mozRequestFullScreen) {
  5351. fsElement.mozRequestFullScreen();
  5352. }
  5353. else {
  5354. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  5355. }
  5356. } else {
  5357. //Exit Full Screen
  5358. if (document.mozCancelFullScreen) {
  5359. document.mozCancelFullScreen();
  5360. } else {
  5361. document.webkitCancelFullScreen();
  5362. }
  5363. }
  5364. };
  5365. /**
  5366. * Unlocks the lock button state.
  5367. */
  5368. my.unlockLockButton = function () {
  5369. if ($("#lockIcon").hasClass("icon-security-locked"))
  5370. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  5371. };
  5372. /**
  5373. * Updates the lock button state to locked.
  5374. */
  5375. my.lockLockButton = function () {
  5376. if ($("#lockIcon").hasClass("icon-security"))
  5377. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  5378. };
  5379. /**
  5380. * Shows or hides authentication button
  5381. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  5382. */
  5383. my.showAuthenticateButton = function (show) {
  5384. if (show) {
  5385. $('#authentication').css({display: "inline"});
  5386. }
  5387. else {
  5388. $('#authentication').css({display: "none"});
  5389. }
  5390. };
  5391. // Shows or hides the 'recording' button.
  5392. my.showRecordingButton = function (show) {
  5393. if (!config.enableRecording) {
  5394. return;
  5395. }
  5396. if (show) {
  5397. $('#recording').css({display: "inline"});
  5398. }
  5399. else {
  5400. $('#recording').css({display: "none"});
  5401. }
  5402. };
  5403. // Sets the state of the recording button
  5404. my.setRecordingButtonState = function (isRecording) {
  5405. var selector = $('#recordButton');
  5406. if (isRecording) {
  5407. selector.removeClass("icon-recEnable");
  5408. selector.addClass("icon-recEnable active");
  5409. } else {
  5410. selector.removeClass("icon-recEnable active");
  5411. selector.addClass("icon-recEnable");
  5412. }
  5413. };
  5414. // Shows or hides SIP calls button
  5415. my.showSipCallButton = function (show) {
  5416. if (APP.xmpp.isSipGatewayEnabled() && show) {
  5417. $('#sipCallButton').css({display: "inline-block"});
  5418. } else {
  5419. $('#sipCallButton').css({display: "none"});
  5420. }
  5421. };
  5422. // Shows or hides the dialpad button
  5423. my.showDialPadButton = function (show) {
  5424. if (show) {
  5425. $('#dialPadButton').css({display: "inline-block"});
  5426. } else {
  5427. $('#dialPadButton').css({display: "none"});
  5428. }
  5429. };
  5430. /**
  5431. * Displays user authenticated identity name(login).
  5432. * @param authIdentity identity name to be displayed.
  5433. */
  5434. my.setAuthenticatedIdentity = function (authIdentity) {
  5435. if (authIdentity) {
  5436. var selector = $('#toolbar_auth_identity');
  5437. selector.css({display: "list-item"});
  5438. selector.text(authIdentity);
  5439. } else {
  5440. $('#toolbar_auth_identity').css({display: "none"});
  5441. }
  5442. };
  5443. /**
  5444. * Shows/hides login button.
  5445. * @param show <tt>true</tt> to show
  5446. */
  5447. my.showLoginButton = function (show) {
  5448. if (show) {
  5449. $('#toolbar_button_login').css({display: "list-item"});
  5450. } else {
  5451. $('#toolbar_button_login').css({display: "none"});
  5452. }
  5453. };
  5454. /**
  5455. * Shows/hides logout button.
  5456. * @param show <tt>true</tt> to show
  5457. */
  5458. my.showLogoutButton = function (show) {
  5459. if (show) {
  5460. $('#toolbar_button_logout').css({display: "list-item"});
  5461. } else {
  5462. $('#toolbar_button_logout').css({display: "none"});
  5463. }
  5464. };
  5465. /**
  5466. * Sets the state of the button. The button has blue glow if desktop
  5467. * streaming is active.
  5468. * @param active the state of the desktop streaming.
  5469. */
  5470. my.changeDesktopSharingButtonState = function (active) {
  5471. var button = $("#desktopsharing > a");
  5472. if (active)
  5473. {
  5474. button.addClass("glow");
  5475. }
  5476. else
  5477. {
  5478. button.removeClass("glow");
  5479. }
  5480. };
  5481. return my;
  5482. }(Toolbar || {}));
  5483. module.exports = Toolbar;
  5484. },{"../../../service/authentication/AuthenticationEvents":107,"../authentication/Authentication":12,"../etherpad/Etherpad":15,"../prezi/Prezi":16,"../side_pannels/SidePanelToggler":18,"../util/MessageHandler":29,"../util/UIUtil":31,"./BottomToolbar":25}],27:[function(require,module,exports){
  5485. /*
  5486. * Copyright @ 2015 Atlassian Pty Ltd
  5487. *
  5488. * Licensed under the Apache License, Version 2.0 (the "License");
  5489. * you may not use this file except in compliance with the License.
  5490. * You may obtain a copy of the License at
  5491. *
  5492. * http://www.apache.org/licenses/LICENSE-2.0
  5493. *
  5494. * Unless required by applicable law or agreed to in writing, software
  5495. * distributed under the License is distributed on an "AS IS" BASIS,
  5496. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5497. * See the License for the specific language governing permissions and
  5498. * limitations under the License.
  5499. */
  5500. /* global $, interfaceConfig, Moderator, DesktopStreaming.showDesktopSharingButton */
  5501. var toolbarTimeoutObject,
  5502. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  5503. function showDesktopSharingButton() {
  5504. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  5505. $('#desktopsharing').css({display: "inline"});
  5506. } else {
  5507. $('#desktopsharing').css({display: "none"});
  5508. }
  5509. }
  5510. /**
  5511. * Hides the toolbar.
  5512. */
  5513. function hideToolbar() {
  5514. if(config.alwaysVisibleToolbar)
  5515. return;
  5516. var header = $("#header"),
  5517. bottomToolbar = $("#bottomToolbar");
  5518. var isToolbarHover = false;
  5519. header.find('*').each(function () {
  5520. var id = $(this).attr('id');
  5521. if ($("#" + id + ":hover").length > 0) {
  5522. isToolbarHover = true;
  5523. }
  5524. });
  5525. if ($("#bottomToolbar:hover").length > 0) {
  5526. isToolbarHover = true;
  5527. }
  5528. clearTimeout(toolbarTimeoutObject);
  5529. toolbarTimeoutObject = null;
  5530. if (!isToolbarHover) {
  5531. header.hide("slide", { direction: "up", duration: 300});
  5532. $('#subject').animate({top: "-=40"}, 300);
  5533. if ($("#remoteVideos").hasClass("hidden")) {
  5534. bottomToolbar.hide(
  5535. "slide", {direction: "right", duration: 300});
  5536. }
  5537. }
  5538. else {
  5539. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  5540. }
  5541. }
  5542. var ToolbarToggler = {
  5543. /**
  5544. * Shows the main toolbar.
  5545. */
  5546. showToolbar: function () {
  5547. var header = $("#header"),
  5548. bottomToolbar = $("#bottomToolbar");
  5549. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  5550. header.show("slide", { direction: "up", duration: 300});
  5551. $('#subject').animate({top: "+=40"}, 300);
  5552. if (!bottomToolbar.is(":visible")) {
  5553. bottomToolbar.show(
  5554. "slide", {direction: "right", duration: 300});
  5555. }
  5556. if (toolbarTimeoutObject) {
  5557. clearTimeout(toolbarTimeoutObject);
  5558. toolbarTimeoutObject = null;
  5559. }
  5560. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  5561. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  5562. }
  5563. if (APP.xmpp.isModerator())
  5564. {
  5565. // TODO: Enable settings functionality.
  5566. // Need to uncomment the settings button in index.html.
  5567. // $('#settingsButton').css({visibility:"visible"});
  5568. }
  5569. // Show/hide desktop sharing button
  5570. showDesktopSharingButton();
  5571. },
  5572. /**
  5573. * Docks/undocks the toolbar.
  5574. *
  5575. * @param isDock indicates what operation to perform
  5576. */
  5577. dockToolbar: function (isDock) {
  5578. if (isDock) {
  5579. // First make sure the toolbar is shown.
  5580. if (!$('#header').is(':visible')) {
  5581. this.showToolbar();
  5582. }
  5583. // Then clear the time out, to dock the toolbar.
  5584. if (toolbarTimeoutObject) {
  5585. clearTimeout(toolbarTimeoutObject);
  5586. toolbarTimeoutObject = null;
  5587. }
  5588. }
  5589. else {
  5590. if (!$('#header').is(':visible')) {
  5591. this.showToolbar();
  5592. }
  5593. else {
  5594. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  5595. }
  5596. }
  5597. },
  5598. showDesktopSharingButton: showDesktopSharingButton
  5599. };
  5600. module.exports = ToolbarToggler;
  5601. },{}],28:[function(require,module,exports){
  5602. /*
  5603. * Copyright @ 2015 Atlassian Pty Ltd
  5604. *
  5605. * Licensed under the Apache License, Version 2.0 (the "License");
  5606. * you may not use this file except in compliance with the License.
  5607. * You may obtain a copy of the License at
  5608. *
  5609. * http://www.apache.org/licenses/LICENSE-2.0
  5610. *
  5611. * Unless required by applicable law or agreed to in writing, software
  5612. * distributed under the License is distributed on an "AS IS" BASIS,
  5613. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5614. * See the License for the specific language governing permissions and
  5615. * limitations under the License.
  5616. */
  5617. var JitsiPopover = (function () {
  5618. /**
  5619. * Constructs new JitsiPopover and attaches it to the element
  5620. * @param element jquery selector
  5621. * @param options the options for the popover.
  5622. * @constructor
  5623. */
  5624. function JitsiPopover(element, options)
  5625. {
  5626. this.options = {
  5627. skin: "white",
  5628. content: ""
  5629. };
  5630. if(options)
  5631. {
  5632. if(options.skin)
  5633. this.options.skin = options.skin;
  5634. if(options.content)
  5635. this.options.content = options.content;
  5636. }
  5637. this.elementIsHovered = false;
  5638. this.popoverIsHovered = false;
  5639. this.popoverShown = false;
  5640. element.data("jitsi_popover", this);
  5641. this.element = element;
  5642. this.template = ' <div class="jitsipopover ' + this.options.skin +
  5643. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  5644. '<div class="jitsiPopupmenuPadding"></div></div>';
  5645. var self = this;
  5646. this.element.on("mouseenter", function () {
  5647. self.elementIsHovered = true;
  5648. self.show();
  5649. }).on("mouseleave", function () {
  5650. self.elementIsHovered = false;
  5651. setTimeout(function () {
  5652. self.hide();
  5653. }, 10);
  5654. });
  5655. }
  5656. /**
  5657. * Shows the popover
  5658. */
  5659. JitsiPopover.prototype.show = function () {
  5660. this.createPopover();
  5661. this.popoverShown = true;
  5662. };
  5663. /**
  5664. * Hides the popover
  5665. */
  5666. JitsiPopover.prototype.hide = function () {
  5667. if(!this.elementIsHovered && !this.popoverIsHovered && this.popoverShown)
  5668. {
  5669. this.forceHide();
  5670. }
  5671. };
  5672. /**
  5673. * Hides the popover
  5674. */
  5675. JitsiPopover.prototype.forceHide = function () {
  5676. $(".jitsipopover").remove();
  5677. this.popoverShown = false;
  5678. };
  5679. /**
  5680. * Creates the popover html
  5681. */
  5682. JitsiPopover.prototype.createPopover = function () {
  5683. $("body").append(this.template);
  5684. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  5685. var self = this;
  5686. $(".jitsipopover").on("mouseenter", function () {
  5687. self.popoverIsHovered = true;
  5688. }).on("mouseleave", function () {
  5689. self.popoverIsHovered = false;
  5690. self.hide();
  5691. });
  5692. this.refreshPosition();
  5693. };
  5694. /**
  5695. * Refreshes the position of the popover
  5696. */
  5697. JitsiPopover.prototype.refreshPosition = function () {
  5698. $(".jitsipopover").position({
  5699. my: "bottom",
  5700. at: "top",
  5701. collision: "fit",
  5702. of: this.element,
  5703. using: function (position, elements) {
  5704. var calcLeft = elements.target.left - elements.element.left + elements.target.width/2;
  5705. $(".jitsipopover").css({top: position.top, left: position.left, display: "table"});
  5706. $(".jitsipopover > .arrow").css({left: calcLeft});
  5707. $(".jitsipopover > .jitsiPopupmenuPadding").css({left: calcLeft - 50});
  5708. }
  5709. });
  5710. };
  5711. /**
  5712. * Updates the content of popover.
  5713. * @param content new content
  5714. */
  5715. JitsiPopover.prototype.updateContent = function (content) {
  5716. this.options.content = content;
  5717. if(!this.popoverShown)
  5718. return;
  5719. $(".jitsipopover").remove();
  5720. this.createPopover();
  5721. };
  5722. return JitsiPopover;
  5723. })();
  5724. module.exports = JitsiPopover;
  5725. },{}],29:[function(require,module,exports){
  5726. /*
  5727. * Copyright @ 2015 Atlassian Pty Ltd
  5728. *
  5729. * Licensed under the Apache License, Version 2.0 (the "License");
  5730. * you may not use this file except in compliance with the License.
  5731. * You may obtain a copy of the License at
  5732. *
  5733. * http://www.apache.org/licenses/LICENSE-2.0
  5734. *
  5735. * Unless required by applicable law or agreed to in writing, software
  5736. * distributed under the License is distributed on an "AS IS" BASIS,
  5737. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5738. * See the License for the specific language governing permissions and
  5739. * limitations under the License.
  5740. */
  5741. /* global $, APP, jQuery, toastr */
  5742. var messageHandler = (function(my) {
  5743. /**
  5744. * Shows a message to the user.
  5745. *
  5746. * @param titleString the title of the message
  5747. * @param messageString the text of the message
  5748. */
  5749. my.openMessageDialog = function(titleKey, messageKey) {
  5750. var title = null;
  5751. if(titleKey)
  5752. {
  5753. title = APP.translation.generateTranslatonHTML(titleKey);
  5754. }
  5755. var message = APP.translation.generateTranslatonHTML(messageKey);
  5756. $.prompt(message,
  5757. {
  5758. title: title,
  5759. persistent: false
  5760. }
  5761. );
  5762. };
  5763. /**
  5764. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  5765. *
  5766. * @param titleString the title of the message
  5767. * @param msgString the text of the message
  5768. * @param persistent boolean value which determines whether the message is persistent or not
  5769. * @param leftButton the fist button's text
  5770. * @param submitFunction function to be called on submit
  5771. * @param loadedFunction function to be called after the prompt is fully loaded
  5772. * @param closeFunction function to be called after the prompt is closed
  5773. * @param focus optional focus selector or button index to be focused after
  5774. * the dialog is opened
  5775. * @param defaultButton index of default button which will be activated when
  5776. * the user press 'enter'. Indexed from 0.
  5777. */
  5778. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  5779. persistent, leftButtonKey, submitFunction, loadedFunction,
  5780. closeFunction, focus, defaultButton)
  5781. {
  5782. var buttons = [];
  5783. var leftButton = APP.translation.generateTranslatonHTML(leftButtonKey);
  5784. buttons.push({ title: leftButton, value: true});
  5785. var cancelButton
  5786. = APP.translation.generateTranslatonHTML("dialog.Cancel");
  5787. buttons.push({title: cancelButton, value: false});
  5788. var message = msgString, title = titleString;
  5789. if (titleKey)
  5790. {
  5791. title = APP.translation.generateTranslatonHTML(titleKey);
  5792. }
  5793. if (msgKey) {
  5794. message = APP.translation.generateTranslatonHTML(msgKey);
  5795. }
  5796. $.prompt(message, {
  5797. title: title,
  5798. persistent: false,
  5799. buttons: buttons,
  5800. defaultButton: defaultButton,
  5801. focus: focus,
  5802. loaded: loadedFunction,
  5803. submit: submitFunction,
  5804. close: closeFunction
  5805. });
  5806. };
  5807. /**
  5808. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  5809. *
  5810. * @param titleString the title of the message
  5811. * @param msgString the text of the message
  5812. * @param persistent boolean value which determines whether the message is persistent or not
  5813. * @param buttons object with the buttons. The keys must be the name of the button and value is the value
  5814. * that will be passed to submitFunction
  5815. * @param submitFunction function to be called on submit
  5816. * @param loadedFunction function to be called after the prompt is fully loaded
  5817. */
  5818. my.openDialog = function (titleString, msgString, persistent, buttons,
  5819. submitFunction, loadedFunction) {
  5820. var args = {
  5821. title: titleString,
  5822. persistent: persistent,
  5823. buttons: buttons,
  5824. defaultButton: 1,
  5825. loaded: loadedFunction,
  5826. submit: submitFunction
  5827. };
  5828. if (persistent) {
  5829. args.closeText = '';
  5830. }
  5831. return new Impromptu(msgString, args);
  5832. };
  5833. /**
  5834. * Closes currently opened dialog.
  5835. */
  5836. my.closeDialog = function () {
  5837. $.prompt.close();
  5838. };
  5839. /**
  5840. * Shows a dialog with different states to the user.
  5841. *
  5842. * @param statesObject object containing all the states of the dialog
  5843. */
  5844. my.openDialogWithStates = function (statesObject, options) {
  5845. return new Impromptu(statesObject, options);
  5846. };
  5847. /**
  5848. * Opens new popup window for given <tt>url</tt> centered over current
  5849. * window.
  5850. *
  5851. * @param url the URL to be displayed in the popup window
  5852. * @param w the width of the popup window
  5853. * @param h the height of the popup window
  5854. * @param onPopupClosed optional callback function called when popup window
  5855. * has been closed.
  5856. *
  5857. * @returns popup window object if opened successfully or undefined
  5858. * in case we failed to open it(popup blocked)
  5859. */
  5860. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  5861. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  5862. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  5863. var popup = window.open(
  5864. url, '_blank',
  5865. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  5866. if (popup && onPopupClosed) {
  5867. var pollTimer = window.setInterval(function () {
  5868. if (popup.closed !== false) {
  5869. window.clearInterval(pollTimer);
  5870. onPopupClosed();
  5871. }
  5872. }, 200);
  5873. }
  5874. return popup;
  5875. };
  5876. /**
  5877. * Shows a dialog prompting the user to send an error report.
  5878. *
  5879. * @param titleString the title of the message
  5880. * @param msgString the text of the message
  5881. * @param error the error that is being reported
  5882. */
  5883. my.openReportDialog = function(titleKey, msgKey, error) {
  5884. my.openMessageDialog(titleKey, msgKey);
  5885. console.log(error);
  5886. //FIXME send the error to the server
  5887. };
  5888. /**
  5889. * Shows an error dialog to the user.
  5890. * @param title the title of the message
  5891. * @param message the text of the messafe
  5892. */
  5893. my.showError = function(titleKey, msgKey) {
  5894. if(!titleKey) {
  5895. titleKey = "dialog.oops";
  5896. }
  5897. if(!msgKey)
  5898. {
  5899. msgKey = "dialog.defaultError";
  5900. }
  5901. messageHandler.openMessageDialog(titleKey, msgKey);
  5902. };
  5903. my.notify = function(displayName, displayNameKey,
  5904. cls, messageKey, messageArguments, options) {
  5905. var displayNameSpan = '<span class="nickname" ';
  5906. if(displayName)
  5907. {
  5908. displayNameSpan += ">" + displayName;
  5909. }
  5910. else
  5911. {
  5912. displayNameSpan += "data-i18n='" + displayNameKey +
  5913. "'>" + APP.translation.translateString(displayNameKey);
  5914. }
  5915. displayNameSpan += "</span>";
  5916. toastr.info(
  5917. displayNameSpan + '<br>' +
  5918. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  5919. (messageArguments?
  5920. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  5921. : "") + ">" +
  5922. APP.translation.translateString(messageKey,
  5923. messageArguments) +
  5924. '</span>', null, options);
  5925. };
  5926. return my;
  5927. }(messageHandler || {}));
  5928. module.exports = messageHandler;
  5929. },{}],30:[function(require,module,exports){
  5930. /*
  5931. * Copyright @ 2015 Atlassian Pty Ltd
  5932. *
  5933. * Licensed under the Apache License, Version 2.0 (the "License");
  5934. * you may not use this file except in compliance with the License.
  5935. * You may obtain a copy of the License at
  5936. *
  5937. * http://www.apache.org/licenses/LICENSE-2.0
  5938. *
  5939. * Unless required by applicable law or agreed to in writing, software
  5940. * distributed under the License is distributed on an "AS IS" BASIS,
  5941. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5942. * See the License for the specific language governing permissions and
  5943. * limitations under the License.
  5944. */
  5945. var UIEvents = require("../../../service/UI/UIEvents");
  5946. var nickname = null;
  5947. var eventEmitter = null;
  5948. var NickanameHandler = {
  5949. init: function (emitter) {
  5950. eventEmitter = emitter;
  5951. var storedDisplayName = window.localStorage.displayname;
  5952. if (storedDisplayName) {
  5953. nickname = storedDisplayName;
  5954. }
  5955. },
  5956. setNickname: function (newNickname) {
  5957. if (!newNickname || nickname === newNickname)
  5958. return;
  5959. nickname = newNickname;
  5960. window.localStorage.displayname = nickname;
  5961. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  5962. },
  5963. getNickname: function () {
  5964. return nickname;
  5965. },
  5966. addListener: function (type, listener) {
  5967. eventEmitter.on(type, listener);
  5968. }
  5969. };
  5970. module.exports = NickanameHandler;
  5971. },{"../../../service/UI/UIEvents":106}],31:[function(require,module,exports){
  5972. /*
  5973. * Copyright @ 2015 Atlassian Pty Ltd
  5974. *
  5975. * Licensed under the Apache License, Version 2.0 (the "License");
  5976. * you may not use this file except in compliance with the License.
  5977. * You may obtain a copy of the License at
  5978. *
  5979. * http://www.apache.org/licenses/LICENSE-2.0
  5980. *
  5981. * Unless required by applicable law or agreed to in writing, software
  5982. * distributed under the License is distributed on an "AS IS" BASIS,
  5983. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5984. * See the License for the specific language governing permissions and
  5985. * limitations under the License.
  5986. *
  5987. * Created by hristo on 12/22/14.
  5988. */
  5989. module.exports = {
  5990. /**
  5991. * Returns the available video width.
  5992. */
  5993. getAvailableVideoWidth: function () {
  5994. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5995. var rightPanelWidth
  5996. = PanelToggler.isVisible() ? PanelToggler.getPanelSize()[0] : 0;
  5997. return window.innerWidth - rightPanelWidth;
  5998. },
  5999. /**
  6000. * Changes the style class of the element given by id.
  6001. */
  6002. buttonClick: function(id, classname) {
  6003. $(id).toggleClass(classname); // add the class to the clicked element
  6004. },
  6005. /**
  6006. * Returns the text width for the given element.
  6007. *
  6008. * @param el the element
  6009. */
  6010. getTextWidth: function (el) {
  6011. return (el.clientWidth + 1);
  6012. },
  6013. /**
  6014. * Returns the text height for the given element.
  6015. *
  6016. * @param el the element
  6017. */
  6018. getTextHeight: function (el) {
  6019. return (el.clientHeight + 1);
  6020. },
  6021. /**
  6022. * Plays the sound given by id.
  6023. *
  6024. * @param id the identifier of the audio element.
  6025. */
  6026. playSoundNotification: function (id) {
  6027. document.getElementById(id).play();
  6028. },
  6029. /**
  6030. * Escapes the given text.
  6031. */
  6032. escapeHtml: function (unsafeText) {
  6033. return $('<div/>').text(unsafeText).html();
  6034. },
  6035. imageToGrayScale: function (canvas) {
  6036. var context = canvas.getContext('2d');
  6037. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  6038. var pixels = imgData.data;
  6039. for (var i = 0, n = pixels.length; i < n; i += 4) {
  6040. var grayscale
  6041. = pixels[i] * .3 + pixels[i+1] * .59 + pixels[i+2] * .11;
  6042. pixels[i ] = grayscale; // red
  6043. pixels[i+1] = grayscale; // green
  6044. pixels[i+2] = grayscale; // blue
  6045. // pixels[i+3] is alpha
  6046. }
  6047. // redraw the image in black & white
  6048. context.putImageData(imgData, 0, 0);
  6049. },
  6050. setTooltip: function (element, key, position) {
  6051. element.setAttribute("data-i18n", "[data-content]" + key);
  6052. element.setAttribute("data-toggle", "popover");
  6053. element.setAttribute("data-placement", position);
  6054. element.setAttribute("data-html", true);
  6055. element.setAttribute("data-container", "body");
  6056. }
  6057. };
  6058. },{"../side_pannels/SidePanelToggler":18}],32:[function(require,module,exports){
  6059. /*
  6060. * Copyright @ 2015 Atlassian Pty Ltd
  6061. *
  6062. * Licensed under the Apache License, Version 2.0 (the "License");
  6063. * you may not use this file except in compliance with the License.
  6064. * You may obtain a copy of the License at
  6065. *
  6066. * http://www.apache.org/licenses/LICENSE-2.0
  6067. *
  6068. * Unless required by applicable law or agreed to in writing, software
  6069. * distributed under the License is distributed on an "AS IS" BASIS,
  6070. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6071. * See the License for the specific language governing permissions and
  6072. * limitations under the License.
  6073. */
  6074. var JitsiPopover = require("../util/JitsiPopover");
  6075. /**
  6076. * Constructs new connection indicator.
  6077. * @param videoContainer the video container associated with the indicator.
  6078. * @constructor
  6079. */
  6080. function ConnectionIndicator(videoContainer, jid, VideoLayout)
  6081. {
  6082. this.videoContainer = videoContainer;
  6083. this.bandwidth = null;
  6084. this.packetLoss = null;
  6085. this.bitrate = null;
  6086. this.showMoreValue = false;
  6087. this.resolution = null;
  6088. this.transport = [];
  6089. this.popover = null;
  6090. this.jid = jid;
  6091. this.create();
  6092. this.videoLayout = VideoLayout;
  6093. }
  6094. /**
  6095. * Values for the connection quality
  6096. * @type {{98: string,
  6097. * 81: string,
  6098. * 64: string,
  6099. * 47: string,
  6100. * 30: string,
  6101. * 0: string}}
  6102. */
  6103. ConnectionIndicator.connectionQualityValues = {
  6104. 98: "18px", //full
  6105. 81: "15px",//4 bars
  6106. 64: "11px",//3 bars
  6107. 47: "7px",//2 bars
  6108. 30: "3px",//1 bar
  6109. 0: "0px"//empty
  6110. };
  6111. ConnectionIndicator.getIP = function(value)
  6112. {
  6113. return value.substring(0, value.lastIndexOf(":"));
  6114. };
  6115. ConnectionIndicator.getPort = function(value)
  6116. {
  6117. return value.substring(value.lastIndexOf(":") + 1, value.length);
  6118. };
  6119. ConnectionIndicator.getStringFromArray = function (array) {
  6120. var res = "";
  6121. for(var i = 0; i < array.length; i++)
  6122. {
  6123. res += (i === 0? "" : ", ") + array[i];
  6124. }
  6125. return res;
  6126. };
  6127. /**
  6128. * Generates the html content.
  6129. * @returns {string} the html content.
  6130. */
  6131. ConnectionIndicator.prototype.generateText = function () {
  6132. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  6133. var translate = APP.translation.translateString;
  6134. if(this.bitrate === null)
  6135. {
  6136. downloadBitrate = "N/A";
  6137. uploadBitrate = "N/A";
  6138. }
  6139. else
  6140. {
  6141. downloadBitrate =
  6142. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  6143. uploadBitrate =
  6144. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  6145. }
  6146. if(this.packetLoss === null)
  6147. {
  6148. packetLoss = "N/A";
  6149. }
  6150. else
  6151. {
  6152. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  6153. (this.packetLoss.download !== null? this.packetLoss.download : "N/A") +
  6154. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  6155. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") + "%";
  6156. }
  6157. var resolutionValue = null;
  6158. if(this.resolution && this.jid != null)
  6159. {
  6160. var keys = Object.keys(this.resolution);
  6161. for(var ssrc in this.resolution)
  6162. {
  6163. resolutionValue = this.resolution[ssrc];
  6164. }
  6165. }
  6166. if(this.jid === null)
  6167. {
  6168. resolution = "";
  6169. if(this.resolution === null || !Object.keys(this.resolution) ||
  6170. Object.keys(this.resolution).length === 0)
  6171. {
  6172. resolution = "N/A";
  6173. }
  6174. else
  6175. for(i in this.resolution)
  6176. {
  6177. resolutionValue = this.resolution[i];
  6178. if(resolutionValue)
  6179. {
  6180. if(resolutionValue.height &&
  6181. resolutionValue.width)
  6182. {
  6183. resolution += (resolution === ""? "" : ", ") +
  6184. resolutionValue.width + "x" +
  6185. resolutionValue.height;
  6186. }
  6187. }
  6188. }
  6189. }
  6190. else if(!resolutionValue ||
  6191. !resolutionValue.height ||
  6192. !resolutionValue.width)
  6193. {
  6194. resolution = "N/A";
  6195. }
  6196. else
  6197. {
  6198. resolution = resolutionValue.width + "x" + resolutionValue.height;
  6199. }
  6200. var result = "<table style='width:100%'>" +
  6201. "<tr>" +
  6202. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  6203. translate("connectionindicator.bitrate") + "</span></td>" +
  6204. "<td><span class='jitsipopover_green'>&darr;</span>" +
  6205. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  6206. uploadBitrate + "</td>" +
  6207. "</tr><tr>" +
  6208. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  6209. translate("connectionindicator.packetloss") + "</span></td>" +
  6210. "<td>" + packetLoss + "</td>" +
  6211. "</tr><tr>" +
  6212. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  6213. translate("connectionindicator.resolution") + "</span></td>" +
  6214. "<td>" + resolution + "</td></tr></table>";
  6215. if(this.videoContainer.id == "localVideoContainer") {
  6216. result += "<div class=\"jitsipopover_showmore\" " +
  6217. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  6218. this.videoContainer.id + "')\" data-i18n='connectionindicator." +
  6219. (this.showMoreValue ? "less" : "more") + "'>" +
  6220. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  6221. "</div><br />";
  6222. }
  6223. if(this.showMoreValue)
  6224. {
  6225. var downloadBandwidth, uploadBandwidth, transport;
  6226. if(this.bandwidth === null)
  6227. {
  6228. downloadBandwidth = "N/A";
  6229. uploadBandwidth = "N/A";
  6230. }
  6231. else
  6232. {
  6233. downloadBandwidth = this.bandwidth.download?
  6234. this.bandwidth.download + " Kbps" :
  6235. "N/A";
  6236. uploadBandwidth = this.bandwidth.upload?
  6237. this.bandwidth.upload + " Kbps" :
  6238. "N/A";
  6239. }
  6240. if(!this.transport || this.transport.length === 0)
  6241. {
  6242. transport = "<tr>" +
  6243. "<td><span class='jitsipopover_blue' " +
  6244. "data-i18n='connectionindicator.address'>" +
  6245. translate("connectionindicator.address") + "</span></td>" +
  6246. "<td> N/A</td></tr>";
  6247. }
  6248. else
  6249. {
  6250. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  6251. for(i = 0; i < this.transport.length; i++)
  6252. {
  6253. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  6254. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  6255. var localIP =
  6256. ConnectionIndicator.getIP(this.transport[i].localip);
  6257. var localPort =
  6258. ConnectionIndicator.getPort(this.transport[i].localip);
  6259. if(data.remoteIP.indexOf(ip) == -1)
  6260. {
  6261. data.remoteIP.push(ip);
  6262. }
  6263. if(data.remotePort.indexOf(port) == -1)
  6264. {
  6265. data.remotePort.push(port);
  6266. }
  6267. if(data.localIP.indexOf(localIP) == -1)
  6268. {
  6269. data.localIP.push(localIP);
  6270. }
  6271. if(data.localPort.indexOf(localPort) == -1)
  6272. {
  6273. data.localPort.push(localPort);
  6274. }
  6275. }
  6276. var local_address_key = "connectionindicator.localaddress";
  6277. var remote_address_key = "connectionindicator.remoteaddress";
  6278. var localTransport =
  6279. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  6280. local_address_key +"' data-i18n-options='" +
  6281. JSON.stringify({count: data.localIP.length}) + "'>" +
  6282. translate(local_address_key, {count: data.localIP.length}) +
  6283. "</span></td><td> " +
  6284. ConnectionIndicator.getStringFromArray(data.localIP) +
  6285. "</td></tr>";
  6286. transport =
  6287. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  6288. remote_address_key + "' data-i18n-options='" +
  6289. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  6290. translate(remote_address_key,
  6291. {count: data.remoteIP.length}) +
  6292. "</span></td><td> " +
  6293. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  6294. "</td></tr>";
  6295. var key_remote = "connectionindicator.remoteport",
  6296. key_local = "connectionindicator.localport";
  6297. transport += "<tr>" +
  6298. "<td>" +
  6299. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  6300. "' data-i18n-options='" +
  6301. JSON.stringify({count: this.transport.length}) + "'>" +
  6302. translate(key_remote, {count: this.transport.length}) +
  6303. "</span></td><td>";
  6304. localTransport += "<tr>" +
  6305. "<td>" +
  6306. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  6307. "' data-i18n-options='" +
  6308. JSON.stringify({count: this.transport.length}) + "'>" +
  6309. translate(key_local, {count: this.transport.length}) +
  6310. "</span></td><td>";
  6311. transport +=
  6312. ConnectionIndicator.getStringFromArray(data.remotePort);
  6313. localTransport +=
  6314. ConnectionIndicator.getStringFromArray(data.localPort);
  6315. transport += "</td></tr>";
  6316. transport += localTransport + "</td></tr>";
  6317. transport +="<tr>" +
  6318. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  6319. translate("connectionindicator.transport") + "</span></td>" +
  6320. "<td>" + this.transport[0].type + "</td></tr>";
  6321. }
  6322. result += "<table style='width:100%'>" +
  6323. "<tr>" +
  6324. "<td>" +
  6325. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  6326. translate("connectionindicator.bandwidth") + "</span>" +
  6327. "</td><td>" +
  6328. "<span class='jitsipopover_green'>&darr;</span>" +
  6329. downloadBandwidth +
  6330. " <span class='jitsipopover_orange'>&uarr;</span>" +
  6331. uploadBandwidth + "</td></tr>";
  6332. result += transport + "</table>";
  6333. }
  6334. return result;
  6335. };
  6336. /**
  6337. * Shows or hide the additional information.
  6338. */
  6339. ConnectionIndicator.prototype.showMore = function () {
  6340. this.showMoreValue = !this.showMoreValue;
  6341. this.updatePopoverData();
  6342. };
  6343. function createIcon(classes)
  6344. {
  6345. var icon = document.createElement("span");
  6346. for(var i in classes)
  6347. {
  6348. icon.classList.add(classes[i]);
  6349. }
  6350. icon.appendChild(
  6351. document.createElement("i")).classList.add("icon-connection");
  6352. return icon;
  6353. }
  6354. /**
  6355. * Creates the indicator
  6356. */
  6357. ConnectionIndicator.prototype.create = function () {
  6358. this.connectionIndicatorContainer = document.createElement("div");
  6359. this.connectionIndicatorContainer.className = "connectionindicator";
  6360. this.connectionIndicatorContainer.style.display = "none";
  6361. this.videoContainer.appendChild(this.connectionIndicatorContainer);
  6362. this.popover = new JitsiPopover(
  6363. $("#" + this.videoContainer.id + " > .connectionindicator"),
  6364. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  6365. APP.translation.translateString("connectionindicator.na") + "</div>",
  6366. skin: "black"});
  6367. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  6368. createIcon(["connection", "connection_empty"]));
  6369. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  6370. createIcon(["connection", "connection_full"]));
  6371. };
  6372. /**
  6373. * Removes the indicator
  6374. */
  6375. ConnectionIndicator.prototype.remove = function()
  6376. {
  6377. this.connectionIndicatorContainer.remove();
  6378. this.popover.forceHide();
  6379. };
  6380. /**
  6381. * Updates the data of the indicator
  6382. * @param percent the percent of connection quality
  6383. * @param object the statistics data.
  6384. */
  6385. ConnectionIndicator.prototype.updateConnectionQuality =
  6386. function (percent, object) {
  6387. if(percent === null)
  6388. {
  6389. this.connectionIndicatorContainer.style.display = "none";
  6390. this.popover.forceHide();
  6391. return;
  6392. }
  6393. else
  6394. {
  6395. if(this.connectionIndicatorContainer.style.display == "none") {
  6396. this.connectionIndicatorContainer.style.display = "block";
  6397. this.videoLayout.updateMutePosition(this.videoContainer.id);
  6398. }
  6399. }
  6400. this.bandwidth = object.bandwidth;
  6401. this.bitrate = object.bitrate;
  6402. this.packetLoss = object.packetLoss;
  6403. this.transport = object.transport;
  6404. if(object.resolution)
  6405. {
  6406. this.resolution = object.resolution;
  6407. }
  6408. for(var quality in ConnectionIndicator.connectionQualityValues)
  6409. {
  6410. if(percent >= quality)
  6411. {
  6412. this.fullIcon.style.width =
  6413. ConnectionIndicator.connectionQualityValues[quality];
  6414. }
  6415. }
  6416. this.updatePopoverData();
  6417. };
  6418. /**
  6419. * Updates the resolution
  6420. * @param resolution the new resolution
  6421. */
  6422. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  6423. this.resolution = resolution;
  6424. this.updatePopoverData();
  6425. };
  6426. /**
  6427. * Updates the content of the popover
  6428. */
  6429. ConnectionIndicator.prototype.updatePopoverData = function () {
  6430. this.popover.updateContent(
  6431. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  6432. APP.translation.translateElement($(".connection_info"));
  6433. };
  6434. /**
  6435. * Hides the popover
  6436. */
  6437. ConnectionIndicator.prototype.hide = function () {
  6438. this.popover.forceHide();
  6439. };
  6440. /**
  6441. * Hides the indicator
  6442. */
  6443. ConnectionIndicator.prototype.hideIndicator = function () {
  6444. this.connectionIndicatorContainer.style.display = "none";
  6445. if(this.popover)
  6446. this.popover.forceHide();
  6447. };
  6448. module.exports = ConnectionIndicator;
  6449. },{"../util/JitsiPopover":28}],33:[function(require,module,exports){
  6450. /*
  6451. * Copyright @ 2015 Atlassian Pty Ltd
  6452. *
  6453. * Licensed under the Apache License, Version 2.0 (the "License");
  6454. * you may not use this file except in compliance with the License.
  6455. * You may obtain a copy of the License at
  6456. *
  6457. * http://www.apache.org/licenses/LICENSE-2.0
  6458. *
  6459. * Unless required by applicable law or agreed to in writing, software
  6460. * distributed under the License is distributed on an "AS IS" BASIS,
  6461. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6462. * See the License for the specific language governing permissions and
  6463. * limitations under the License.
  6464. */
  6465. var AudioLevels = require("../audio_levels/AudioLevels");
  6466. var Avatar = require("../avatar/Avatar");
  6467. var Chat = require("../side_pannels/chat/Chat");
  6468. var ContactList = require("../side_pannels/contactlist/ContactList");
  6469. var UIUtil = require("../util/UIUtil");
  6470. var ConnectionIndicator = require("./ConnectionIndicator");
  6471. var NicknameHandler = require("../util/NicknameHandler");
  6472. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  6473. var UIEvents = require("../../../service/UI/UIEvents");
  6474. var currentDominantSpeaker = null;
  6475. var lastNCount = config.channelLastN;
  6476. var localLastNCount = config.channelLastN;
  6477. var localLastNSet = [];
  6478. var lastNEndpointsCache = [];
  6479. var lastNPickupJid = null;
  6480. var largeVideoState = {
  6481. updateInProgress: false,
  6482. newSrc: ''
  6483. };
  6484. var eventEmitter = null;
  6485. /**
  6486. * Currently focused video "src"(displayed in large video).
  6487. * @type {String}
  6488. */
  6489. var focusedVideoInfo = null;
  6490. var mutedAudios = {};
  6491. var flipXLocalVideo = true;
  6492. var currentVideoWidth = null;
  6493. var currentVideoHeight = null;
  6494. var localVideoSrc = null;
  6495. function videoactive( videoelem) {
  6496. if (videoelem.attr('id').indexOf('mixedmslabel') === -1) {
  6497. // ignore mixedmslabela0 and v0
  6498. videoelem.show();
  6499. VideoLayout.resizeThumbnails();
  6500. var videoParent = videoelem.parent();
  6501. var parentResourceJid = null;
  6502. if (videoParent)
  6503. parentResourceJid
  6504. = VideoLayout.getPeerContainerResourceJid(videoParent[0]);
  6505. // Update the large video to the last added video only if there's no
  6506. // current dominant, focused speaker or prezi playing or update it to
  6507. // the current dominant speaker.
  6508. if ((!focusedVideoInfo &&
  6509. !VideoLayout.getDominantSpeakerResourceJid() &&
  6510. !require("../prezi/Prezi").isPresentationVisible()) ||
  6511. (parentResourceJid &&
  6512. VideoLayout.getDominantSpeakerResourceJid() === parentResourceJid)) {
  6513. VideoLayout.updateLargeVideo(
  6514. APP.RTC.getVideoSrc(videoelem[0]),
  6515. 1,
  6516. parentResourceJid);
  6517. }
  6518. VideoLayout.showModeratorIndicator();
  6519. }
  6520. }
  6521. function waitForRemoteVideo(selector, ssrc, stream, jid) {
  6522. // XXX(gp) so, every call to this function is *always* preceded by a call
  6523. // to the RTC.attachMediaStream() function but that call is *not* followed
  6524. // by an update to the videoSrcToSsrc map!
  6525. //
  6526. // The above way of doing things results in video SRCs that don't correspond
  6527. // to any SSRC for a short period of time (to be more precise, for as long
  6528. // the waitForRemoteVideo takes to complete). This causes problems (see
  6529. // bellow).
  6530. //
  6531. // I'm wondering why we need to do that; i.e. why call RTC.attachMediaStream()
  6532. // a second time in here and only then update the videoSrcToSsrc map? Why
  6533. // not simply update the videoSrcToSsrc map when the RTC.attachMediaStream()
  6534. // is called the first time? I actually do that in the lastN changed event
  6535. // handler because the "orphan" video SRC is causing troubles there. The
  6536. // purpose of this method would then be to fire the "videoactive.jingle".
  6537. //
  6538. // Food for though I guess :-)
  6539. if (selector.removed || !selector.parent().is(":visible")) {
  6540. console.warn("Media removed before had started", selector);
  6541. return;
  6542. }
  6543. if (stream.id === 'mixedmslabel') return;
  6544. if (selector[0].currentTime > 0) {
  6545. APP.RTC.attachMediaStream(selector, stream); // FIXME: why do i have to do this for FF?
  6546. videoactive(selector);
  6547. } else {
  6548. setTimeout(function () {
  6549. waitForRemoteVideo(selector, ssrc, stream, jid);
  6550. }, 250);
  6551. }
  6552. }
  6553. /**
  6554. * Returns an array of the video horizontal and vertical indents,
  6555. * so that if fits its parent.
  6556. *
  6557. * @return an array with 2 elements, the horizontal indent and the vertical
  6558. * indent
  6559. */
  6560. function getCameraVideoPosition(videoWidth,
  6561. videoHeight,
  6562. videoSpaceWidth,
  6563. videoSpaceHeight) {
  6564. // Parent height isn't completely calculated when we position the video in
  6565. // full screen mode and this is why we use the screen height in this case.
  6566. // Need to think it further at some point and implement it properly.
  6567. var isFullScreen = document.fullScreen ||
  6568. document.mozFullScreen ||
  6569. document.webkitIsFullScreen;
  6570. if (isFullScreen)
  6571. videoSpaceHeight = window.innerHeight;
  6572. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  6573. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  6574. return [horizontalIndent, verticalIndent];
  6575. }
  6576. /**
  6577. * Returns an array of the video horizontal and vertical indents.
  6578. * Centers horizontally and top aligns vertically.
  6579. *
  6580. * @return an array with 2 elements, the horizontal indent and the vertical
  6581. * indent
  6582. */
  6583. function getDesktopVideoPosition(videoWidth,
  6584. videoHeight,
  6585. videoSpaceWidth,
  6586. videoSpaceHeight) {
  6587. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  6588. var verticalIndent = 0;// Top aligned
  6589. return [horizontalIndent, verticalIndent];
  6590. }
  6591. /**
  6592. * Returns an array of the video dimensions, so that it covers the screen.
  6593. * It leaves no empty areas, but some parts of the video might not be visible.
  6594. *
  6595. * @return an array with 2 elements, the video width and the video height
  6596. */
  6597. function getCameraVideoSize(videoWidth,
  6598. videoHeight,
  6599. videoSpaceWidth,
  6600. videoSpaceHeight) {
  6601. if (!videoWidth)
  6602. videoWidth = currentVideoWidth;
  6603. if (!videoHeight)
  6604. videoHeight = currentVideoHeight;
  6605. var aspectRatio = videoWidth / videoHeight;
  6606. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  6607. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  6608. if (availableWidth / aspectRatio < videoSpaceHeight) {
  6609. availableHeight = videoSpaceHeight;
  6610. availableWidth = availableHeight * aspectRatio;
  6611. }
  6612. if (availableHeight * aspectRatio < videoSpaceWidth) {
  6613. availableWidth = videoSpaceWidth;
  6614. availableHeight = availableWidth / aspectRatio;
  6615. }
  6616. return [availableWidth, availableHeight];
  6617. }
  6618. /**
  6619. * Sets the display name for the given video span id.
  6620. */
  6621. function setDisplayName(videoSpanId, displayName, key) {
  6622. if (!$('#' + videoSpanId).length) {
  6623. console.warn(
  6624. "Unable to set displayName - " + videoSpanId + " does not exist");
  6625. return;
  6626. }
  6627. var nameSpan = $('#' + videoSpanId + '>span.displayname');
  6628. var defaultLocalDisplayName = APP.translation.generateTranslatonHTML(
  6629. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  6630. // If we already have a display name for this video.
  6631. if (nameSpan.length > 0) {
  6632. var nameSpanElement = nameSpan.get(0);
  6633. if (nameSpanElement.id === 'localDisplayName' &&
  6634. $('#localDisplayName').text() !== displayName) {
  6635. if (displayName && displayName.length > 0)
  6636. {
  6637. var meHTML = APP.translation.generateTranslatonHTML("me");
  6638. $('#localDisplayName').html(displayName + ' (' + meHTML + ')');
  6639. }
  6640. else
  6641. $('#localDisplayName').html(defaultLocalDisplayName);
  6642. } else {
  6643. if (displayName && displayName.length > 0)
  6644. {
  6645. $('#' + videoSpanId + '_name').html(displayName);
  6646. }
  6647. else if (key && key.length > 0)
  6648. {
  6649. var nameHtml = APP.translation.generateTranslatonHTML(key);
  6650. $('#' + videoSpanId + '_name').html(nameHtml);
  6651. }
  6652. else
  6653. $('#' + videoSpanId + '_name').text(
  6654. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  6655. }
  6656. } else {
  6657. var editButton = null;
  6658. nameSpan = document.createElement('span');
  6659. nameSpan.className = 'displayname';
  6660. $('#' + videoSpanId)[0].appendChild(nameSpan);
  6661. if (videoSpanId === 'localVideoContainer') {
  6662. editButton = createEditDisplayNameButton();
  6663. if (displayName && displayName.length > 0) {
  6664. var meHTML = APP.translation.generateTranslatonHTML("me");
  6665. nameSpan.innerHTML = displayName + meHTML;
  6666. }
  6667. else
  6668. nameSpan.innerHTML = defaultLocalDisplayName;
  6669. }
  6670. else {
  6671. if (displayName && displayName.length > 0) {
  6672. nameSpan.innerText = displayName;
  6673. }
  6674. else
  6675. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  6676. }
  6677. if (!editButton) {
  6678. nameSpan.id = videoSpanId + '_name';
  6679. } else {
  6680. nameSpan.id = 'localDisplayName';
  6681. $('#' + videoSpanId)[0].appendChild(editButton);
  6682. //translates popover of edit button
  6683. APP.translation.translateElement($("a.displayname"));
  6684. var editableText = document.createElement('input');
  6685. editableText.className = 'displayname';
  6686. editableText.type = 'text';
  6687. editableText.id = 'editDisplayName';
  6688. if (displayName && displayName.length) {
  6689. editableText.value
  6690. = displayName;
  6691. }
  6692. var defaultNickname = APP.translation.translateString(
  6693. "defaultNickname", {name: "Jane Pink"});
  6694. editableText.setAttribute('style', 'display:none;');
  6695. editableText.setAttribute('data-18n',
  6696. '[placeholder]defaultNickname');
  6697. editableText.setAttribute("data-i18n-options",
  6698. JSON.stringify({name: "Jane Pink"}));
  6699. editableText.setAttribute("placeholder", defaultNickname);
  6700. $('#' + videoSpanId)[0].appendChild(editableText);
  6701. $('#localVideoContainer .displayname')
  6702. .bind("click", function (e) {
  6703. e.preventDefault();
  6704. e.stopPropagation();
  6705. $('#localDisplayName').hide();
  6706. $('#editDisplayName').show();
  6707. $('#editDisplayName').focus();
  6708. $('#editDisplayName').select();
  6709. $('#editDisplayName').one("focusout", function (e) {
  6710. VideoLayout.inputDisplayNameHandler(this.value);
  6711. });
  6712. $('#editDisplayName').on('keydown', function (e) {
  6713. if (e.keyCode === 13) {
  6714. e.preventDefault();
  6715. VideoLayout.inputDisplayNameHandler(this.value);
  6716. }
  6717. });
  6718. });
  6719. }
  6720. }
  6721. }
  6722. /**
  6723. * Gets the selector of video thumbnail container for the user identified by
  6724. * given <tt>userJid</tt>
  6725. * @param resourceJid user's Jid for whom we want to get the video container.
  6726. */
  6727. function getParticipantContainer(resourceJid)
  6728. {
  6729. if (!resourceJid)
  6730. return null;
  6731. if (resourceJid === APP.xmpp.myResource())
  6732. return $("#localVideoContainer");
  6733. else
  6734. return $("#participant_" + resourceJid);
  6735. }
  6736. /**
  6737. * Sets the size and position of the given video element.
  6738. *
  6739. * @param video the video element to position
  6740. * @param width the desired video width
  6741. * @param height the desired video height
  6742. * @param horizontalIndent the left and right indent
  6743. * @param verticalIndent the top and bottom indent
  6744. */
  6745. function positionVideo(video,
  6746. width,
  6747. height,
  6748. horizontalIndent,
  6749. verticalIndent) {
  6750. video.width(width);
  6751. video.height(height);
  6752. video.css({ top: verticalIndent + 'px',
  6753. bottom: verticalIndent + 'px',
  6754. left: horizontalIndent + 'px',
  6755. right: horizontalIndent + 'px'});
  6756. }
  6757. /**
  6758. * Adds the remote video menu element for the given <tt>jid</tt> in the
  6759. * given <tt>parentElement</tt>.
  6760. *
  6761. * @param jid the jid indicating the video for which we're adding a menu.
  6762. * @param parentElement the parent element where this menu will be added
  6763. */
  6764. function addRemoteVideoMenu(jid, parentElement) {
  6765. var spanElement = document.createElement('span');
  6766. spanElement.className = 'remotevideomenu';
  6767. parentElement.appendChild(spanElement);
  6768. var menuElement = document.createElement('i');
  6769. menuElement.className = 'fa fa-angle-down';
  6770. menuElement.title = 'Remote user controls';
  6771. spanElement.appendChild(menuElement);
  6772. // <ul class="popupmenu">
  6773. // <li><a href="#">Mute</a></li>
  6774. // <li><a href="#">Eject</a></li>
  6775. // </ul>
  6776. var popupmenuElement = document.createElement('ul');
  6777. popupmenuElement.className = 'popupmenu';
  6778. popupmenuElement.id
  6779. = 'remote_popupmenu_' + Strophe.getResourceFromJid(jid);
  6780. spanElement.appendChild(popupmenuElement);
  6781. var muteMenuItem = document.createElement('li');
  6782. var muteLinkItem = document.createElement('a');
  6783. var mutedIndicator = "<i style='float:left;' class='icon-mic-disabled'></i>";
  6784. if (!mutedAudios[jid]) {
  6785. muteLinkItem.innerHTML = mutedIndicator +
  6786. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  6787. muteLinkItem.className = 'mutelink';
  6788. }
  6789. else {
  6790. muteLinkItem.innerHTML = mutedIndicator +
  6791. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  6792. muteLinkItem.className = 'mutelink disabled';
  6793. }
  6794. muteLinkItem.onclick = function(){
  6795. if ($(this).attr('disabled') != undefined) {
  6796. event.preventDefault();
  6797. }
  6798. var isMute = mutedAudios[jid] == true;
  6799. APP.xmpp.setMute(jid, !isMute);
  6800. popupmenuElement.setAttribute('style', 'display:none;');
  6801. if (isMute) {
  6802. this.innerHTML = mutedIndicator +
  6803. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  6804. this.className = 'mutelink disabled';
  6805. }
  6806. else {
  6807. this.innerHTML = mutedIndicator +
  6808. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  6809. this.className = 'mutelink';
  6810. }
  6811. };
  6812. muteMenuItem.appendChild(muteLinkItem);
  6813. popupmenuElement.appendChild(muteMenuItem);
  6814. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  6815. var ejectMenuItem = document.createElement('li');
  6816. var ejectLinkItem = document.createElement('a');
  6817. var ejectText = "<div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.kick'>&nbsp;</div>";
  6818. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  6819. ejectLinkItem.onclick = function(){
  6820. APP.xmpp.eject(jid);
  6821. popupmenuElement.setAttribute('style', 'display:none;');
  6822. };
  6823. ejectMenuItem.appendChild(ejectLinkItem);
  6824. popupmenuElement.appendChild(ejectMenuItem);
  6825. var paddingSpan = document.createElement('span');
  6826. paddingSpan.className = 'popupmenuPadding';
  6827. popupmenuElement.appendChild(paddingSpan);
  6828. APP.translation.translateElement($("#" + popupmenuElement.id + " > li > a > div"));
  6829. }
  6830. /**
  6831. * Removes remote video menu element from video element identified by
  6832. * given <tt>videoElementId</tt>.
  6833. *
  6834. * @param videoElementId the id of local or remote video element.
  6835. */
  6836. function removeRemoteVideoMenu(videoElementId) {
  6837. var menuSpan = $('#' + videoElementId + '>span.remotevideomenu');
  6838. if (menuSpan.length) {
  6839. menuSpan.remove();
  6840. }
  6841. }
  6842. /**
  6843. * Updates the data for the indicator
  6844. * @param id the id of the indicator
  6845. * @param percent the percent for connection quality
  6846. * @param object the data
  6847. */
  6848. function updateStatsIndicator(id, percent, object) {
  6849. if(VideoLayout.connectionIndicators[id])
  6850. VideoLayout.connectionIndicators[id].updateConnectionQuality(percent, object);
  6851. }
  6852. /**
  6853. * Returns an array of the video dimensions, so that it keeps it's aspect
  6854. * ratio and fits available area with it's larger dimension. This method
  6855. * ensures that whole video will be visible and can leave empty areas.
  6856. *
  6857. * @return an array with 2 elements, the video width and the video height
  6858. */
  6859. function getDesktopVideoSize(videoWidth,
  6860. videoHeight,
  6861. videoSpaceWidth,
  6862. videoSpaceHeight) {
  6863. if (!videoWidth)
  6864. videoWidth = currentVideoWidth;
  6865. if (!videoHeight)
  6866. videoHeight = currentVideoHeight;
  6867. var aspectRatio = videoWidth / videoHeight;
  6868. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  6869. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  6870. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  6871. if (availableWidth / aspectRatio >= videoSpaceHeight)
  6872. {
  6873. availableHeight = videoSpaceHeight;
  6874. availableWidth = availableHeight * aspectRatio;
  6875. }
  6876. if (availableHeight * aspectRatio >= videoSpaceWidth)
  6877. {
  6878. availableWidth = videoSpaceWidth;
  6879. availableHeight = availableWidth / aspectRatio;
  6880. }
  6881. return [availableWidth, availableHeight];
  6882. }
  6883. /**
  6884. * Creates the edit display name button.
  6885. *
  6886. * @returns the edit button
  6887. */
  6888. function createEditDisplayNameButton() {
  6889. var editButton = document.createElement('a');
  6890. editButton.className = 'displayname';
  6891. UIUtil.setTooltip(editButton,
  6892. "videothumbnail.editnickname",
  6893. "top");
  6894. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  6895. return editButton;
  6896. }
  6897. /**
  6898. * Creates the element indicating the moderator(owner) of the conference.
  6899. *
  6900. * @param parentElement the parent element where the owner indicator will
  6901. * be added
  6902. */
  6903. function createModeratorIndicatorElement(parentElement) {
  6904. var moderatorIndicator = document.createElement('i');
  6905. moderatorIndicator.className = 'fa fa-star';
  6906. parentElement.appendChild(moderatorIndicator);
  6907. UIUtil.setTooltip(parentElement,
  6908. "videothumbnail.moderator",
  6909. "top");
  6910. }
  6911. var VideoLayout = (function (my) {
  6912. my.connectionIndicators = {};
  6913. // By default we use camera
  6914. my.getVideoSize = getCameraVideoSize;
  6915. my.getVideoPosition = getCameraVideoPosition;
  6916. my.init = function (emitter) {
  6917. // Listen for large video size updates
  6918. document.getElementById('largeVideo')
  6919. .addEventListener('loadedmetadata', function (e) {
  6920. currentVideoWidth = this.videoWidth;
  6921. currentVideoHeight = this.videoHeight;
  6922. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  6923. });
  6924. eventEmitter = emitter;
  6925. };
  6926. my.isInLastN = function(resource) {
  6927. return lastNCount < 0 // lastN is disabled, return true
  6928. || (lastNCount > 0 && lastNEndpointsCache.length == 0) // lastNEndpoints cache not built yet, return true
  6929. || (lastNEndpointsCache && lastNEndpointsCache.indexOf(resource) !== -1);
  6930. };
  6931. my.changeLocalStream = function (stream, isMuted) {
  6932. VideoLayout.changeLocalVideo(stream, isMuted);
  6933. };
  6934. my.changeLocalAudio = function(stream, isMuted) {
  6935. if(isMuted)
  6936. APP.UI.setAudioMuted(true, true);
  6937. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  6938. document.getElementById('localAudio').autoplay = true;
  6939. document.getElementById('localAudio').volume = 0;
  6940. };
  6941. my.changeLocalVideo = function(stream, isMuted) {
  6942. // Set default display name.
  6943. setDisplayName('localVideoContainer');
  6944. if(!VideoLayout.connectionIndicators["localVideoContainer"]) {
  6945. VideoLayout.connectionIndicators["localVideoContainer"]
  6946. = new ConnectionIndicator($("#localVideoContainer")[0], null, VideoLayout);
  6947. }
  6948. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  6949. var localVideo = null;
  6950. function localVideoClick(event) {
  6951. event.stopPropagation();
  6952. VideoLayout.handleVideoThumbClicked(
  6953. APP.RTC.getVideoSrc(localVideo),
  6954. false,
  6955. APP.xmpp.myResource());
  6956. }
  6957. $('#localVideoContainer').click(localVideoClick);
  6958. // Add hover handler
  6959. $('#localVideoContainer').hover(
  6960. function() {
  6961. VideoLayout.showDisplayName('localVideoContainer', true);
  6962. },
  6963. function() {
  6964. if (!VideoLayout.isLargeVideoVisible()
  6965. || APP.RTC.getVideoSrc(localVideo) !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  6966. VideoLayout.showDisplayName('localVideoContainer', false);
  6967. }
  6968. );
  6969. if(isMuted)
  6970. {
  6971. APP.UI.setVideoMute(true);
  6972. return;
  6973. }
  6974. var flipX = true;
  6975. if(stream.videoType == "screen")
  6976. flipX = false;
  6977. var localVideo = document.createElement('video');
  6978. localVideo.id = 'localVideo_' +
  6979. APP.RTC.getStreamID(stream.getOriginalStream());
  6980. localVideo.autoplay = true;
  6981. localVideo.volume = 0; // is it required if audio is separated ?
  6982. localVideo.oncontextmenu = function () { return false; };
  6983. var localVideoContainer = document.getElementById('localVideoWrapper');
  6984. localVideoContainer.appendChild(localVideo);
  6985. var localVideoSelector = $('#' + localVideo.id);
  6986. // Add click handler to both video and video wrapper elements in case
  6987. // there's no video.
  6988. localVideoSelector.click(localVideoClick);
  6989. // Flip video x axis if needed
  6990. flipXLocalVideo = flipX;
  6991. if (flipX) {
  6992. localVideoSelector.addClass("flipVideoX");
  6993. }
  6994. // Attach WebRTC stream
  6995. APP.RTC.attachMediaStream(localVideoSelector, stream.getOriginalStream());
  6996. // Add stream ended handler
  6997. stream.getOriginalStream().onended = function () {
  6998. localVideoContainer.removeChild(localVideo);
  6999. VideoLayout.updateRemovedVideo(APP.RTC.getVideoSrc(localVideo));
  7000. };
  7001. localVideoSrc = APP.RTC.getVideoSrc(localVideo);
  7002. var myResourceJid = APP.xmpp.myResource();
  7003. VideoLayout.updateLargeVideo(localVideoSrc, 0, myResourceJid);
  7004. };
  7005. my.mucJoined = function () {
  7006. var myResourceJid = APP.xmpp.myResource();
  7007. if (!largeVideoState.userResourceJid)
  7008. VideoLayout.updateLargeVideo(localVideoSrc, 0, myResourceJid, true);
  7009. };
  7010. /**
  7011. * Adds or removes icons for not available camera and microphone.
  7012. * @param resourceJid the jid of user
  7013. * @param devices available devices
  7014. */
  7015. my.setDeviceAvailabilityIcons = function (resourceJid, devices) {
  7016. if(!devices)
  7017. return;
  7018. var container = null
  7019. if(!resourceJid)
  7020. {
  7021. container = $("#localVideoContainer")[0];
  7022. }
  7023. else
  7024. {
  7025. container = $("#participant_" + resourceJid)[0];
  7026. }
  7027. if(!container)
  7028. return;
  7029. $("#" + container.id + " > .noMic").remove();
  7030. $("#" + container.id + " > .noVideo").remove();
  7031. if(!devices.audio)
  7032. {
  7033. container.appendChild(document.createElement("div")).setAttribute("class","noMic");
  7034. }
  7035. if(!devices.video)
  7036. {
  7037. container.appendChild(document.createElement("div")).setAttribute("class","noVideo");
  7038. }
  7039. if(!devices.audio && !devices.video)
  7040. {
  7041. $("#" + container.id + " > .noMic").css("background-position", "75%");
  7042. $("#" + container.id + " > .noVideo").css("background-position", "25%");
  7043. $("#" + container.id + " > .noVideo").css("background-color", "transparent");
  7044. }
  7045. }
  7046. /**
  7047. * Checks if removed video is currently displayed and tries to display
  7048. * another one instead.
  7049. * @param removedVideoSrc src stream identifier of the video.
  7050. */
  7051. my.updateRemovedVideo = function(removedVideoSrc) {
  7052. if (removedVideoSrc === APP.RTC.getVideoSrc($('#largeVideo')[0])) {
  7053. // this is currently displayed as large
  7054. // pick the last visible video in the row
  7055. // if nobody else is left, this picks the local video
  7056. var pick
  7057. = $('#remoteVideos>span[id!="mixedstream"]:visible:last>video')
  7058. .get(0);
  7059. if (!pick) {
  7060. console.info("Last visible video no longer exists");
  7061. pick = $('#remoteVideos>span[id!="mixedstream"]>video').get(0);
  7062. if (!pick || !APP.RTC.getVideoSrc(pick)) {
  7063. // Try local video
  7064. console.info("Fallback to local video...");
  7065. pick = $('#remoteVideos>span>span>video').get(0);
  7066. }
  7067. }
  7068. var src = null, volume = null;
  7069. // mute if localvideo
  7070. if (pick) {
  7071. var container = pick.parentNode;
  7072. src = APP.RTC.getVideoSrc(pick);
  7073. volume = pick.volume;
  7074. } else {
  7075. console.warn("Failed to elect large video");
  7076. container = $('#remoteVideos>span[id!="mixedstream"]:visible:last').get(0);
  7077. }
  7078. var jid = null;
  7079. if(container)
  7080. {
  7081. if(container.id == "localVideoWrapper")
  7082. {
  7083. jid = APP.xmpp.myResource();
  7084. }
  7085. else
  7086. {
  7087. jid = VideoLayout.getPeerContainerResourceJid(container);
  7088. }
  7089. }
  7090. else
  7091. return;
  7092. VideoLayout.updateLargeVideo(src, volume, jid);
  7093. }
  7094. };
  7095. my.onRemoteStreamAdded = function (stream) {
  7096. var container;
  7097. var remotes = document.getElementById('remoteVideos');
  7098. if (stream.peerjid) {
  7099. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  7100. container = document.getElementById(
  7101. 'participant_' + Strophe.getResourceFromJid(stream.peerjid));
  7102. } else {
  7103. var id = stream.getOriginalStream().id;
  7104. if (id !== 'mixedmslabel'
  7105. // FIXME: default stream is added always with new focus
  7106. // (to be investigated)
  7107. && id !== 'default') {
  7108. console.error('can not associate stream',
  7109. id,
  7110. 'with a participant');
  7111. // We don't want to add it here since it will cause troubles
  7112. return;
  7113. }
  7114. // FIXME: for the mixed ms we dont need a video -- currently
  7115. container = document.createElement('span');
  7116. container.id = 'mixedstream';
  7117. container.className = 'videocontainer';
  7118. remotes.appendChild(container);
  7119. }
  7120. if (container) {
  7121. VideoLayout.addRemoteStreamElement( container,
  7122. stream.sid,
  7123. stream.getOriginalStream(),
  7124. stream.peerjid,
  7125. stream.ssrc);
  7126. }
  7127. }
  7128. my.getLargeVideoState = function () {
  7129. return largeVideoState;
  7130. };
  7131. /**
  7132. * Updates the large video with the given new video source.
  7133. */
  7134. my.updateLargeVideo = function(newSrc, vol, resourceJid, forceUpdate) {
  7135. console.log('hover in', newSrc, resourceJid);
  7136. if (APP.RTC.getVideoSrc($('#largeVideo')[0]) !== newSrc || forceUpdate) {
  7137. $('#activeSpeaker').css('visibility', 'hidden');
  7138. // Due to the simulcast the localVideoSrc may have changed when the
  7139. // fadeOut event triggers. In that case the getJidFromVideoSrc and
  7140. // isVideoSrcDesktop methods will not function correctly.
  7141. //
  7142. // Also, again due to the simulcast, the updateLargeVideo method can
  7143. // be called multiple times almost simultaneously. Therefore, we
  7144. // store the state here and update only once.
  7145. largeVideoState.newSrc = newSrc;
  7146. largeVideoState.isVisible = $('#largeVideo').is(':visible');
  7147. largeVideoState.isDesktop = APP.RTC.isVideoSrcDesktop(
  7148. APP.xmpp.findJidFromResource(resourceJid));
  7149. if(largeVideoState.userResourceJid) {
  7150. largeVideoState.oldResourceJid = largeVideoState.userResourceJid;
  7151. } else {
  7152. largeVideoState.oldResourceJid = null;
  7153. }
  7154. largeVideoState.userResourceJid = resourceJid;
  7155. // Screen stream is already rotated
  7156. largeVideoState.flipX = (newSrc === localVideoSrc) && flipXLocalVideo;
  7157. if (largeVideoState.oldResourceJid !== largeVideoState.userResourceJid) {
  7158. // we want the notification to trigger even if userJid is undefined,
  7159. // or null.
  7160. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT,
  7161. largeVideoState.userResourceJid);
  7162. }
  7163. $('#largeVideo').fadeOut(300, function () {
  7164. Avatar.updateActiveSpeakerAvatarSrc(
  7165. APP.xmpp.findJidFromResource(
  7166. largeVideoState.userResourceJid));
  7167. APP.RTC.setVideoSrc($('#largeVideo')[0], largeVideoState.newSrc);
  7168. var videoTransform = document.getElementById('largeVideo')
  7169. .style.webkitTransform;
  7170. if (largeVideoState.flipX && videoTransform !== 'scaleX(-1)') {
  7171. document.getElementById('largeVideo').style.webkitTransform
  7172. = "scaleX(-1)";
  7173. }
  7174. else if (!largeVideoState.flipX && videoTransform === 'scaleX(-1)') {
  7175. document.getElementById('largeVideo').style.webkitTransform
  7176. = "none";
  7177. }
  7178. // Change the way we'll be measuring and positioning large video
  7179. VideoLayout.getVideoSize = largeVideoState.isDesktop
  7180. ? getDesktopVideoSize
  7181. : getCameraVideoSize;
  7182. VideoLayout.getVideoPosition = largeVideoState.isDesktop
  7183. ? getDesktopVideoPosition
  7184. : getCameraVideoPosition;
  7185. // Only if the large video is currently visible.
  7186. // Disable previous dominant speaker video.
  7187. if (largeVideoState.oldResourceJid) {
  7188. VideoLayout.enableDominantSpeaker(
  7189. largeVideoState.oldResourceJid,
  7190. false);
  7191. }
  7192. // Enable new dominant speaker in the remote videos section.
  7193. if (largeVideoState.userResourceJid) {
  7194. VideoLayout.enableDominantSpeaker(
  7195. largeVideoState.userResourceJid,
  7196. true);
  7197. }
  7198. if (largeVideoState.isVisible) {
  7199. // using "this" should be ok because we're called
  7200. // from within the fadeOut event.
  7201. $(this).fadeIn(300);
  7202. }
  7203. Avatar.showUserAvatar(
  7204. APP.xmpp.findJidFromResource(
  7205. largeVideoState.oldResourceJid));
  7206. });
  7207. } else {
  7208. Avatar.showUserAvatar(
  7209. APP.xmpp.findJidFromResource(
  7210. largeVideoState.userResourceJid));
  7211. }
  7212. };
  7213. my.handleVideoThumbClicked = function(videoSrc,
  7214. noPinnedEndpointChangedEvent,
  7215. resourceJid) {
  7216. // Restore style for previously focused video
  7217. var oldContainer = null;
  7218. if(focusedVideoInfo) {
  7219. var focusResourceJid = focusedVideoInfo.resourceJid;
  7220. oldContainer = getParticipantContainer(focusResourceJid);
  7221. }
  7222. if (oldContainer) {
  7223. oldContainer.removeClass("videoContainerFocused");
  7224. }
  7225. // Unlock current focused.
  7226. if (focusedVideoInfo && focusedVideoInfo.src === videoSrc)
  7227. {
  7228. focusedVideoInfo = null;
  7229. var dominantSpeakerVideo = null;
  7230. // Enable the currently set dominant speaker.
  7231. if (currentDominantSpeaker) {
  7232. dominantSpeakerVideo
  7233. = $('#participant_' + currentDominantSpeaker + '>video')
  7234. .get(0);
  7235. if (dominantSpeakerVideo) {
  7236. VideoLayout.updateLargeVideo(
  7237. APP.RTC.getVideoSrc(dominantSpeakerVideo),
  7238. 1,
  7239. currentDominantSpeaker);
  7240. }
  7241. }
  7242. if (!noPinnedEndpointChangedEvent) {
  7243. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  7244. }
  7245. return;
  7246. }
  7247. // Lock new video
  7248. focusedVideoInfo = {
  7249. src: videoSrc,
  7250. resourceJid: resourceJid
  7251. };
  7252. // Update focused/pinned interface.
  7253. if (resourceJid)
  7254. {
  7255. var container = getParticipantContainer(resourceJid);
  7256. container.addClass("videoContainerFocused");
  7257. if (!noPinnedEndpointChangedEvent) {
  7258. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  7259. }
  7260. }
  7261. if ($('#largeVideo').attr('src') === videoSrc &&
  7262. VideoLayout.isLargeVideoOnTop()) {
  7263. return;
  7264. }
  7265. // Triggers a "video.selected" event. The "false" parameter indicates
  7266. // this isn't a prezi.
  7267. $(document).trigger("video.selected", [false]);
  7268. VideoLayout.updateLargeVideo(videoSrc, 1, resourceJid);
  7269. $('audio').each(function (idx, el) {
  7270. if (el.id.indexOf('mixedmslabel') !== -1) {
  7271. el.volume = 0;
  7272. el.volume = 1;
  7273. }
  7274. });
  7275. };
  7276. /**
  7277. * Positions the large video.
  7278. *
  7279. * @param videoWidth the stream video width
  7280. * @param videoHeight the stream video height
  7281. */
  7282. my.positionLarge = function (videoWidth, videoHeight) {
  7283. var videoSpaceWidth = $('#videospace').width();
  7284. var videoSpaceHeight = window.innerHeight;
  7285. var videoSize = VideoLayout.getVideoSize(videoWidth,
  7286. videoHeight,
  7287. videoSpaceWidth,
  7288. videoSpaceHeight);
  7289. var largeVideoWidth = videoSize[0];
  7290. var largeVideoHeight = videoSize[1];
  7291. var videoPosition = VideoLayout.getVideoPosition(largeVideoWidth,
  7292. largeVideoHeight,
  7293. videoSpaceWidth,
  7294. videoSpaceHeight);
  7295. var horizontalIndent = videoPosition[0];
  7296. var verticalIndent = videoPosition[1];
  7297. positionVideo($('#largeVideo'),
  7298. largeVideoWidth,
  7299. largeVideoHeight,
  7300. horizontalIndent, verticalIndent);
  7301. };
  7302. /**
  7303. * Shows/hides the large video.
  7304. */
  7305. my.setLargeVideoVisible = function(isVisible) {
  7306. var resourceJid = largeVideoState.userResourceJid;
  7307. if (isVisible) {
  7308. $('#largeVideo').css({visibility: 'visible'});
  7309. $('.watermark').css({visibility: 'visible'});
  7310. VideoLayout.enableDominantSpeaker(resourceJid, true);
  7311. }
  7312. else {
  7313. $('#largeVideo').css({visibility: 'hidden'});
  7314. $('#activeSpeaker').css('visibility', 'hidden');
  7315. $('.watermark').css({visibility: 'hidden'});
  7316. VideoLayout.enableDominantSpeaker(resourceJid, false);
  7317. if(focusedVideoInfo) {
  7318. var focusResourceJid = focusedVideoInfo.resourceJid;
  7319. var oldContainer = getParticipantContainer(focusResourceJid);
  7320. if (oldContainer && oldContainer.length > 0) {
  7321. oldContainer.removeClass("videoContainerFocused");
  7322. }
  7323. focusedVideoInfo = null;
  7324. if(focusResourceJid) {
  7325. Avatar.showUserAvatar(
  7326. APP.xmpp.findJidFromResource(focusResourceJid));
  7327. }
  7328. }
  7329. }
  7330. };
  7331. /**
  7332. * Indicates if the large video is currently visible.
  7333. *
  7334. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  7335. */
  7336. my.isLargeVideoVisible = function() {
  7337. return $('#largeVideo').is(':visible');
  7338. };
  7339. my.isLargeVideoOnTop = function () {
  7340. var Etherpad = require("../etherpad/Etherpad");
  7341. var Prezi = require("../prezi/Prezi");
  7342. return !Prezi.isPresentationVisible() && !Etherpad.isVisible();
  7343. };
  7344. /**
  7345. * Checks if container for participant identified by given peerJid exists
  7346. * in the document and creates it eventually.
  7347. *
  7348. * @param peerJid peer Jid to check.
  7349. * @param userId user email or id for setting the avatar
  7350. *
  7351. * @return Returns <tt>true</tt> if the peer container exists,
  7352. * <tt>false</tt> - otherwise
  7353. */
  7354. my.ensurePeerContainerExists = function(peerJid, userId) {
  7355. ContactList.ensureAddContact(peerJid, userId);
  7356. var resourceJid = Strophe.getResourceFromJid(peerJid);
  7357. var videoSpanId = 'participant_' + resourceJid;
  7358. if (!$('#' + videoSpanId).length) {
  7359. var container =
  7360. VideoLayout.addRemoteVideoContainer(peerJid, videoSpanId, userId);
  7361. Avatar.setUserAvatar(peerJid, userId);
  7362. // Set default display name.
  7363. setDisplayName(videoSpanId);
  7364. VideoLayout.connectionIndicators[videoSpanId] =
  7365. new ConnectionIndicator(container, peerJid, VideoLayout);
  7366. var nickfield = document.createElement('span');
  7367. nickfield.className = "nick";
  7368. nickfield.appendChild(document.createTextNode(resourceJid));
  7369. container.appendChild(nickfield);
  7370. // In case this is not currently in the last n we don't show it.
  7371. if (localLastNCount
  7372. && localLastNCount > 0
  7373. && $('#remoteVideos>span').length >= localLastNCount + 2) {
  7374. showPeerContainer(resourceJid, 'hide');
  7375. }
  7376. else
  7377. VideoLayout.resizeThumbnails();
  7378. }
  7379. };
  7380. my.addRemoteVideoContainer = function(peerJid, spanId) {
  7381. var container = document.createElement('span');
  7382. container.id = spanId;
  7383. container.className = 'videocontainer';
  7384. var remotes = document.getElementById('remoteVideos');
  7385. remotes.appendChild(container);
  7386. // If the peerJid is null then this video span couldn't be directly
  7387. // associated with a participant (this could happen in the case of prezi).
  7388. if (APP.xmpp.isModerator() && peerJid !== null)
  7389. addRemoteVideoMenu(peerJid, container);
  7390. AudioLevels.updateAudioLevelCanvas(peerJid, VideoLayout);
  7391. return container;
  7392. };
  7393. /**
  7394. * Creates an audio or video stream element.
  7395. */
  7396. my.createStreamElement = function (sid, stream) {
  7397. var isVideo = stream.getVideoTracks().length > 0;
  7398. var element = isVideo
  7399. ? document.createElement('video')
  7400. : document.createElement('audio');
  7401. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_')
  7402. + sid + '_' + APP.RTC.getStreamID(stream);
  7403. element.id = id;
  7404. element.autoplay = true;
  7405. element.oncontextmenu = function () { return false; };
  7406. return element;
  7407. };
  7408. my.addRemoteStreamElement
  7409. = function (container, sid, stream, peerJid, thessrc) {
  7410. var newElementId = null;
  7411. var isVideo = stream.getVideoTracks().length > 0;
  7412. if (container) {
  7413. var streamElement = VideoLayout.createStreamElement(sid, stream);
  7414. newElementId = streamElement.id;
  7415. container.appendChild(streamElement);
  7416. var sel = $('#' + newElementId);
  7417. sel.hide();
  7418. // If the container is currently visible we attach the stream.
  7419. if (!isVideo
  7420. || (container.offsetParent !== null && isVideo)) {
  7421. APP.RTC.attachMediaStream(sel, stream);
  7422. if (isVideo)
  7423. waitForRemoteVideo(sel, thessrc, stream, peerJid);
  7424. }
  7425. stream.onended = function () {
  7426. console.log('stream ended', this);
  7427. VideoLayout.removeRemoteStreamElement(
  7428. stream, isVideo, container, newElementId);
  7429. // NOTE(gp) it seems that under certain circumstances, the
  7430. // onended event is not fired and thus the contact list is not
  7431. // updated.
  7432. //
  7433. // The onended event of a stream should be fired when the SSRCs
  7434. // corresponding to that stream are removed from the SDP; but
  7435. // this doesn't seem to always be the case, resulting in ghost
  7436. // contacts.
  7437. //
  7438. // In an attempt to fix the ghost contacts problem, I'm moving
  7439. // the removeContact() method call in app.js, inside the
  7440. // 'muc.left' event handler.
  7441. //if (peerJid)
  7442. // ContactList.removeContact(peerJid);
  7443. };
  7444. // Add click handler.
  7445. container.onclick = function (event) {
  7446. /*
  7447. * FIXME It turns out that videoThumb may not exist (if there is
  7448. * no actual video).
  7449. */
  7450. var videoThumb = $('#' + container.id + '>video').get(0);
  7451. if (videoThumb) {
  7452. VideoLayout.handleVideoThumbClicked(
  7453. APP.RTC.getVideoSrc(videoThumb),
  7454. false,
  7455. Strophe.getResourceFromJid(peerJid));
  7456. }
  7457. event.stopPropagation();
  7458. event.preventDefault();
  7459. return false;
  7460. };
  7461. // Add hover handler
  7462. $(container).hover(
  7463. function() {
  7464. VideoLayout.showDisplayName(container.id, true);
  7465. },
  7466. function() {
  7467. var videoSrc = null;
  7468. if ($('#' + container.id + '>video')
  7469. && $('#' + container.id + '>video').length > 0) {
  7470. videoSrc = APP.RTC.getVideoSrc($('#' + container.id + '>video').get(0));
  7471. }
  7472. // If the video has been "pinned" by the user we want to
  7473. // keep the display name on place.
  7474. if (!VideoLayout.isLargeVideoVisible()
  7475. || videoSrc !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  7476. VideoLayout.showDisplayName(container.id, false);
  7477. }
  7478. );
  7479. }
  7480. return newElementId;
  7481. };
  7482. /**
  7483. * Removes the remote stream element corresponding to the given stream and
  7484. * parent container.
  7485. *
  7486. * @param stream the stream
  7487. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  7488. * @param container
  7489. */
  7490. my.removeRemoteStreamElement = function (stream, isVideo, container, id) {
  7491. if (!container)
  7492. return;
  7493. var select = null;
  7494. var removedVideoSrc = null;
  7495. if (isVideo) {
  7496. select = $('#' + id);
  7497. removedVideoSrc = APP.RTC.getVideoSrc(select.get(0));
  7498. }
  7499. else
  7500. select = $('#' + container.id + '>audio');
  7501. // Mark video as removed to cancel waiting loop(if video is removed
  7502. // before has started)
  7503. select.removed = true;
  7504. select.remove();
  7505. var audioCount = $('#' + container.id + '>audio').length;
  7506. var videoCount = $('#' + container.id + '>video').length;
  7507. if (!audioCount && !videoCount) {
  7508. console.log("Remove whole user", container.id);
  7509. if(VideoLayout.connectionIndicators[container.id])
  7510. VideoLayout.connectionIndicators[container.id].remove();
  7511. // Remove whole container
  7512. container.remove();
  7513. VideoLayout.resizeThumbnails();
  7514. }
  7515. if (removedVideoSrc)
  7516. VideoLayout.updateRemovedVideo(removedVideoSrc);
  7517. };
  7518. /**
  7519. * Show/hide peer container for the given resourceJid.
  7520. */
  7521. function showPeerContainer(resourceJid, state) {
  7522. var peerContainer = $('#participant_' + resourceJid);
  7523. if (!peerContainer)
  7524. return;
  7525. var isHide = state === 'hide';
  7526. var resizeThumbnails = false;
  7527. if (!isHide) {
  7528. if (!peerContainer.is(':visible')) {
  7529. resizeThumbnails = true;
  7530. peerContainer.show();
  7531. }
  7532. var jid = APP.xmpp.findJidFromResource(resourceJid);
  7533. if (state == 'show')
  7534. {
  7535. // peerContainer.css('-webkit-filter', '');
  7536. Avatar.showUserAvatar(jid, false);
  7537. }
  7538. else // if (state == 'avatar')
  7539. {
  7540. // peerContainer.css('-webkit-filter', 'grayscale(100%)');
  7541. Avatar.showUserAvatar(jid, true);
  7542. }
  7543. }
  7544. else if (peerContainer.is(':visible') && isHide)
  7545. {
  7546. resizeThumbnails = true;
  7547. peerContainer.hide();
  7548. if(VideoLayout.connectionIndicators['participant_' + resourceJid])
  7549. VideoLayout.connectionIndicators['participant_' + resourceJid].hide();
  7550. }
  7551. if (resizeThumbnails) {
  7552. VideoLayout.resizeThumbnails();
  7553. }
  7554. // We want to be able to pin a participant from the contact list, even
  7555. // if he's not in the lastN set!
  7556. // ContactList.setClickable(resourceJid, !isHide);
  7557. };
  7558. my.inputDisplayNameHandler = function (name) {
  7559. NicknameHandler.setNickname(name);
  7560. if (!$('#localDisplayName').is(":visible")) {
  7561. if (NicknameHandler.getNickname())
  7562. {
  7563. var meHTML = APP.translation.generateTranslatonHTML("me");
  7564. $('#localDisplayName').html(NicknameHandler.getNickname() + " (" + meHTML + ")");
  7565. }
  7566. else
  7567. {
  7568. var defaultHTML = APP.translation.generateTranslatonHTML(
  7569. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  7570. $('#localDisplayName')
  7571. .html(defaultHTML);
  7572. }
  7573. $('#localDisplayName').show();
  7574. }
  7575. $('#editDisplayName').hide();
  7576. };
  7577. /**
  7578. * Shows/hides the display name on the remote video.
  7579. * @param videoSpanId the identifier of the video span element
  7580. * @param isShow indicates if the display name should be shown or hidden
  7581. */
  7582. my.showDisplayName = function(videoSpanId, isShow) {
  7583. var nameSpan = $('#' + videoSpanId + '>span.displayname').get(0);
  7584. if (isShow) {
  7585. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  7586. nameSpan.setAttribute("style", "display:inline-block;");
  7587. }
  7588. else {
  7589. if (nameSpan)
  7590. nameSpan.setAttribute("style", "display:none;");
  7591. }
  7592. };
  7593. /**
  7594. * Shows the presence status message for the given video.
  7595. */
  7596. my.setPresenceStatus = function (videoSpanId, statusMsg) {
  7597. if (!$('#' + videoSpanId).length) {
  7598. // No container
  7599. return;
  7600. }
  7601. var statusSpan = $('#' + videoSpanId + '>span.status');
  7602. if (!statusSpan.length) {
  7603. //Add status span
  7604. statusSpan = document.createElement('span');
  7605. statusSpan.className = 'status';
  7606. statusSpan.id = videoSpanId + '_status';
  7607. $('#' + videoSpanId)[0].appendChild(statusSpan);
  7608. statusSpan = $('#' + videoSpanId + '>span.status');
  7609. }
  7610. // Display status
  7611. if (statusMsg && statusMsg.length) {
  7612. $('#' + videoSpanId + '_status').text(statusMsg);
  7613. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  7614. }
  7615. else {
  7616. // Hide
  7617. statusSpan.get(0).setAttribute("style", "display:none;");
  7618. }
  7619. };
  7620. /**
  7621. * Shows a visual indicator for the moderator of the conference.
  7622. */
  7623. my.showModeratorIndicator = function () {
  7624. var isModerator = APP.xmpp.isModerator();
  7625. if (isModerator) {
  7626. var indicatorSpan = $('#localVideoContainer .focusindicator');
  7627. if (indicatorSpan.children().length === 0)
  7628. {
  7629. createModeratorIndicatorElement(indicatorSpan[0]);
  7630. //translates text in focus indicator
  7631. APP.translation.translateElement($('#localVideoContainer .focusindicator'));
  7632. }
  7633. }
  7634. var members = APP.xmpp.getMembers();
  7635. Object.keys(members).forEach(function (jid) {
  7636. if (Strophe.getResourceFromJid(jid) === 'focus') {
  7637. // Skip server side focus
  7638. return;
  7639. }
  7640. var resourceJid = Strophe.getResourceFromJid(jid);
  7641. var videoSpanId = 'participant_' + resourceJid;
  7642. var videoContainer = document.getElementById(videoSpanId);
  7643. if (!videoContainer) {
  7644. console.error("No video container for " + jid);
  7645. return;
  7646. }
  7647. var member = members[jid];
  7648. if (member.role === 'moderator') {
  7649. // Remove menu if peer is moderator
  7650. var menuSpan = $('#' + videoSpanId + '>span.remotevideomenu');
  7651. if (menuSpan.length) {
  7652. removeRemoteVideoMenu(videoSpanId);
  7653. }
  7654. // Show moderator indicator
  7655. var indicatorSpan
  7656. = $('#' + videoSpanId + ' .focusindicator');
  7657. if (!indicatorSpan || indicatorSpan.length === 0) {
  7658. indicatorSpan = document.createElement('span');
  7659. indicatorSpan.className = 'focusindicator';
  7660. videoContainer.appendChild(indicatorSpan);
  7661. createModeratorIndicatorElement(indicatorSpan);
  7662. //translates text in focus indicators
  7663. APP.translation.translateElement($('#' + videoSpanId + ' .focusindicator'));
  7664. }
  7665. } else if (isModerator) {
  7666. // We are moderator, but user is not - add menu
  7667. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  7668. addRemoteVideoMenu(
  7669. jid,
  7670. document.getElementById('participant_' + resourceJid));
  7671. }
  7672. }
  7673. });
  7674. };
  7675. /**
  7676. * Shows video muted indicator over small videos.
  7677. */
  7678. my.showVideoIndicator = function(videoSpanId, isMuted) {
  7679. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  7680. if (isMuted === 'false') {
  7681. if (videoMutedSpan.length > 0) {
  7682. videoMutedSpan.remove();
  7683. }
  7684. }
  7685. else {
  7686. if(videoMutedSpan.length == 0) {
  7687. videoMutedSpan = document.createElement('span');
  7688. videoMutedSpan.className = 'videoMuted';
  7689. $('#' + videoSpanId)[0].appendChild(videoMutedSpan);
  7690. var mutedIndicator = document.createElement('i');
  7691. mutedIndicator.className = 'icon-camera-disabled';
  7692. UIUtil.setTooltip(mutedIndicator,
  7693. "videothumbnail.videomute",
  7694. "top");
  7695. videoMutedSpan.appendChild(mutedIndicator);
  7696. //translate texts for muted indicator
  7697. APP.translation.translateElement($('#' + videoSpanId + " > span > i"));
  7698. }
  7699. VideoLayout.updateMutePosition(videoSpanId);
  7700. }
  7701. };
  7702. my.updateMutePosition = function (videoSpanId) {
  7703. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  7704. var connectionIndicator = $('#' + videoSpanId + '>div.connectionindicator');
  7705. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  7706. if(connectionIndicator.length > 0
  7707. && connectionIndicator[0].style.display != "none") {
  7708. audioMutedSpan.css({right: "23px"});
  7709. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  7710. }
  7711. else
  7712. {
  7713. audioMutedSpan.css({right: "0px"});
  7714. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  7715. }
  7716. }
  7717. /**
  7718. * Shows audio muted indicator over small videos.
  7719. * @param {string} isMuted
  7720. */
  7721. my.showAudioIndicator = function(videoSpanId, isMuted) {
  7722. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  7723. if (isMuted === 'false') {
  7724. if (audioMutedSpan.length > 0) {
  7725. audioMutedSpan.popover('hide');
  7726. audioMutedSpan.remove();
  7727. }
  7728. }
  7729. else {
  7730. if(audioMutedSpan.length == 0 ) {
  7731. audioMutedSpan = document.createElement('span');
  7732. audioMutedSpan.className = 'audioMuted';
  7733. UIUtil.setTooltip(audioMutedSpan,
  7734. "videothumbnail.mute",
  7735. "top");
  7736. $('#' + videoSpanId)[0].appendChild(audioMutedSpan);
  7737. APP.translation.translateElement($('#' + videoSpanId + " > span"));
  7738. var mutedIndicator = document.createElement('i');
  7739. mutedIndicator.className = 'icon-mic-disabled';
  7740. audioMutedSpan.appendChild(mutedIndicator);
  7741. }
  7742. VideoLayout.updateMutePosition(videoSpanId);
  7743. }
  7744. };
  7745. /*
  7746. * Shows or hides the audio muted indicator over the local thumbnail video.
  7747. * @param {boolean} isMuted
  7748. */
  7749. my.showLocalAudioIndicator = function(isMuted) {
  7750. VideoLayout.showAudioIndicator('localVideoContainer', isMuted.toString());
  7751. };
  7752. /**
  7753. * Resizes the large video container.
  7754. */
  7755. my.resizeLargeVideoContainer = function () {
  7756. Chat.resizeChat();
  7757. var availableHeight = window.innerHeight;
  7758. var availableWidth = UIUtil.getAvailableVideoWidth();
  7759. if (availableWidth < 0 || availableHeight < 0) return;
  7760. $('#videospace').width(availableWidth);
  7761. $('#videospace').height(availableHeight);
  7762. $('#largeVideoContainer').width(availableWidth);
  7763. $('#largeVideoContainer').height(availableHeight);
  7764. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  7765. var top = availableHeight / 2 - avatarSize / 4 * 3;
  7766. $('#activeSpeaker').css('top', top);
  7767. VideoLayout.resizeThumbnails();
  7768. };
  7769. /**
  7770. * Resizes thumbnails.
  7771. */
  7772. my.resizeThumbnails = function() {
  7773. var videoSpaceWidth = $('#remoteVideos').width();
  7774. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  7775. var width = thumbnailSize[0];
  7776. var height = thumbnailSize[1];
  7777. // size videos so that while keeping AR and max height, we have a
  7778. // nice fit
  7779. $('#remoteVideos').height(height);
  7780. $('#remoteVideos>span').width(width);
  7781. $('#remoteVideos>span').height(height);
  7782. $('.userAvatar').css('left', (width - height) / 2);
  7783. $(document).trigger("remotevideo.resized", [width, height]);
  7784. };
  7785. /**
  7786. * Enables the dominant speaker UI.
  7787. *
  7788. * @param resourceJid the jid indicating the video element to
  7789. * activate/deactivate
  7790. * @param isEnable indicates if the dominant speaker should be enabled or
  7791. * disabled
  7792. */
  7793. my.enableDominantSpeaker = function(resourceJid, isEnable) {
  7794. var videoSpanId = null;
  7795. var videoContainerId = null;
  7796. if (resourceJid
  7797. === APP.xmpp.myResource()) {
  7798. videoSpanId = 'localVideoWrapper';
  7799. videoContainerId = 'localVideoContainer';
  7800. }
  7801. else {
  7802. videoSpanId = 'participant_' + resourceJid;
  7803. videoContainerId = videoSpanId;
  7804. }
  7805. var displayName = resourceJid;
  7806. var nameSpan = $('#' + videoContainerId + '>span.displayname');
  7807. if (nameSpan.length > 0)
  7808. displayName = nameSpan.html();
  7809. console.log("UI enable dominant speaker",
  7810. displayName,
  7811. resourceJid,
  7812. isEnable);
  7813. videoSpan = document.getElementById(videoContainerId);
  7814. if (!videoSpan) {
  7815. return;
  7816. }
  7817. var video = $('#' + videoSpanId + '>video');
  7818. if (video && video.length > 0) {
  7819. if (isEnable) {
  7820. var isLargeVideoVisible = VideoLayout.isLargeVideoOnTop();
  7821. VideoLayout.showDisplayName(videoContainerId, isLargeVideoVisible);
  7822. if (!videoSpan.classList.contains("dominantspeaker"))
  7823. videoSpan.classList.add("dominantspeaker");
  7824. }
  7825. else {
  7826. VideoLayout.showDisplayName(videoContainerId, false);
  7827. if (videoSpan.classList.contains("dominantspeaker"))
  7828. videoSpan.classList.remove("dominantspeaker");
  7829. }
  7830. }
  7831. Avatar.showUserAvatar(
  7832. APP.xmpp.findJidFromResource(resourceJid));
  7833. };
  7834. /**
  7835. * Calculates the thumbnail size.
  7836. *
  7837. * @param videoSpaceWidth the width of the video space
  7838. */
  7839. my.calculateThumbnailSize = function (videoSpaceWidth) {
  7840. // Calculate the available height, which is the inner window height minus
  7841. // 39px for the header minus 2px for the delimiter lines on the top and
  7842. // bottom of the large video, minus the 36px space inside the remoteVideos
  7843. // container used for highlighting shadow.
  7844. var availableHeight = 100;
  7845. var numvids = $('#remoteVideos>span:visible').length;
  7846. if (localLastNCount && localLastNCount > 0) {
  7847. numvids = Math.min(localLastNCount + 1, numvids);
  7848. }
  7849. // Remove the 3px borders arround videos and border around the remote
  7850. // videos area and the 4 pixels between the local video and the others
  7851. //TODO: Find out where the 4 pixels come from and remove them
  7852. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  7853. var availableWidth = availableWinWidth / numvids;
  7854. var aspectRatio = 16.0 / 9.0;
  7855. var maxHeight = Math.min(160, availableHeight);
  7856. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  7857. if (availableHeight < availableWidth / aspectRatio) {
  7858. availableWidth = Math.floor(availableHeight * aspectRatio);
  7859. }
  7860. return [availableWidth, availableHeight];
  7861. };
  7862. /**
  7863. * Updates the remote video menu.
  7864. *
  7865. * @param jid the jid indicating the video for which we're adding a menu.
  7866. * @param isMuted indicates the current mute state
  7867. */
  7868. my.updateRemoteVideoMenu = function(jid, isMuted) {
  7869. var muteMenuItem
  7870. = $('#remote_popupmenu_'
  7871. + Strophe.getResourceFromJid(jid)
  7872. + '>li>a.mutelink');
  7873. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  7874. if (muteMenuItem.length) {
  7875. var muteLink = muteMenuItem.get(0);
  7876. if (isMuted === 'true') {
  7877. muteLink.innerHTML = mutedIndicator + ' Muted';
  7878. muteLink.className = 'mutelink disabled';
  7879. }
  7880. else {
  7881. muteLink.innerHTML = mutedIndicator + ' Mute';
  7882. muteLink.className = 'mutelink';
  7883. }
  7884. }
  7885. };
  7886. /**
  7887. * Returns the current dominant speaker resource jid.
  7888. */
  7889. my.getDominantSpeakerResourceJid = function () {
  7890. return currentDominantSpeaker;
  7891. };
  7892. /**
  7893. * Returns the corresponding resource jid to the given peer container
  7894. * DOM element.
  7895. *
  7896. * @return the corresponding resource jid to the given peer container
  7897. * DOM element
  7898. */
  7899. my.getPeerContainerResourceJid = function (containerElement) {
  7900. var i = containerElement.id.indexOf('participant_');
  7901. if (i >= 0)
  7902. return containerElement.id.substring(i + 12);
  7903. };
  7904. /**
  7905. * On contact list item clicked.
  7906. */
  7907. $(ContactList).bind('contactclicked', function(event, jid) {
  7908. if (!jid) {
  7909. return;
  7910. }
  7911. var resource = Strophe.getResourceFromJid(jid);
  7912. var videoContainer = $("#participant_" + resource);
  7913. if (videoContainer.length > 0) {
  7914. var videoThumb = $('video', videoContainer).get(0);
  7915. // It is not always the case that a videoThumb exists (if there is
  7916. // no actual video).
  7917. if (videoThumb) {
  7918. if (videoThumb.src && videoThumb.src != '') {
  7919. // We have a video src, great! Let's update the large video
  7920. // now.
  7921. VideoLayout.handleVideoThumbClicked(
  7922. videoThumb.src,
  7923. false,
  7924. Strophe.getResourceFromJid(jid));
  7925. } else {
  7926. // If we don't have a video src for jid, there's absolutely
  7927. // no point in calling handleVideoThumbClicked; Quite
  7928. // simply, it won't work because it needs an src to attach
  7929. // to the large video.
  7930. //
  7931. // Instead, we trigger the pinned endpoint changed event to
  7932. // let the bridge adjust its lastN set for myjid and store
  7933. // the pinned user in the lastNPickupJid variable to be
  7934. // picked up later by the lastN changed event handler.
  7935. lastNPickupJid = jid;
  7936. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  7937. Strophe.getResourceFromJid(jid));
  7938. }
  7939. } else if (jid == APP.xmpp.myJid()) {
  7940. $("#localVideoContainer").click();
  7941. }
  7942. }
  7943. });
  7944. /**
  7945. * On audio muted event.
  7946. */
  7947. $(document).bind('audiomuted.muc', function (event, jid, isMuted) {
  7948. /*
  7949. // FIXME: but focus can not mute in this case ? - check
  7950. if (jid === xmpp.myJid()) {
  7951. // The local mute indicator is controlled locally
  7952. return;
  7953. }*/
  7954. var videoSpanId = null;
  7955. if (jid === APP.xmpp.myJid()) {
  7956. videoSpanId = 'localVideoContainer';
  7957. } else {
  7958. VideoLayout.ensurePeerContainerExists(jid);
  7959. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  7960. }
  7961. mutedAudios[jid] = isMuted;
  7962. if (APP.xmpp.isModerator()) {
  7963. VideoLayout.updateRemoteVideoMenu(jid, isMuted);
  7964. }
  7965. if (videoSpanId)
  7966. VideoLayout.showAudioIndicator(videoSpanId, isMuted);
  7967. });
  7968. /**
  7969. * On video muted event.
  7970. */
  7971. $(document).bind('videomuted.muc', function (event, jid, value) {
  7972. var isMuted = (value === "true");
  7973. if(jid !== APP.xmpp.myJid() && !APP.RTC.muteRemoteVideoStream(jid, isMuted))
  7974. return;
  7975. Avatar.showUserAvatar(jid, isMuted);
  7976. var videoSpanId = null;
  7977. if (jid === APP.xmpp.myJid()) {
  7978. videoSpanId = 'localVideoContainer';
  7979. } else {
  7980. VideoLayout.ensurePeerContainerExists(jid);
  7981. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  7982. }
  7983. if (videoSpanId)
  7984. VideoLayout.showVideoIndicator(videoSpanId, value);
  7985. });
  7986. /**
  7987. * Display name changed.
  7988. */
  7989. my.onDisplayNameChanged =
  7990. function (jid, displayName, status) {
  7991. if (jid === 'localVideoContainer'
  7992. || jid === APP.xmpp.myJid()) {
  7993. setDisplayName('localVideoContainer',
  7994. displayName);
  7995. } else {
  7996. VideoLayout.ensurePeerContainerExists(jid);
  7997. setDisplayName(
  7998. 'participant_' + Strophe.getResourceFromJid(jid),
  7999. displayName,
  8000. status);
  8001. }
  8002. };
  8003. /**
  8004. * On dominant speaker changed event.
  8005. */
  8006. my.onDominantSpeakerChanged = function (resourceJid) {
  8007. // We ignore local user events.
  8008. if (resourceJid === APP.xmpp.myResource())
  8009. return;
  8010. var members = APP.xmpp.getMembers();
  8011. // Update the current dominant speaker.
  8012. if (resourceJid !== currentDominantSpeaker) {
  8013. var oldSpeakerVideoSpanId = "participant_" + currentDominantSpeaker,
  8014. newSpeakerVideoSpanId = "participant_" + resourceJid;
  8015. var currentJID = APP.xmpp.findJidFromResource(currentDominantSpeaker);
  8016. var newJID = APP.xmpp.findJidFromResource(resourceJid);
  8017. if(currentDominantSpeaker && (!members || !members[currentJID] ||
  8018. !members[currentJID].displayName)) {
  8019. setDisplayName(oldSpeakerVideoSpanId, null);
  8020. }
  8021. if(resourceJid && (!members || !members[newJID] ||
  8022. !members[newJID].displayName)) {
  8023. setDisplayName(newSpeakerVideoSpanId, null,
  8024. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  8025. }
  8026. currentDominantSpeaker = resourceJid;
  8027. } else {
  8028. return;
  8029. }
  8030. // Obtain container for new dominant speaker.
  8031. var container = document.getElementById(
  8032. 'participant_' + resourceJid);
  8033. // Local video will not have container found, but that's ok
  8034. // since we don't want to switch to local video.
  8035. if (container && !focusedVideoInfo)
  8036. {
  8037. var video = container.getElementsByTagName("video");
  8038. // Update the large video if the video source is already available,
  8039. // otherwise wait for the "videoactive.jingle" event.
  8040. if (video.length && video[0].currentTime > 0) {
  8041. VideoLayout.updateLargeVideo(
  8042. APP.RTC.getVideoSrc(video[0]), 1, resourceJid);
  8043. }
  8044. }
  8045. };
  8046. /**
  8047. * On last N change event.
  8048. *
  8049. * @param lastNEndpoints the list of last N endpoints
  8050. * @param endpointsEnteringLastN the list currently entering last N
  8051. * endpoints
  8052. */
  8053. my.onLastNEndpointsChanged = function ( lastNEndpoints,
  8054. endpointsEnteringLastN,
  8055. stream) {
  8056. if (lastNCount !== lastNEndpoints.length)
  8057. lastNCount = lastNEndpoints.length;
  8058. lastNEndpointsCache = lastNEndpoints;
  8059. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  8060. //
  8061. // If LastN drops to, say, 2, because of adaptivity, then E should see
  8062. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  8063. // so E sees them. C is only in E's local LastN set.
  8064. //
  8065. // If F starts talking and LastN = 3, then E should see thumbnails for
  8066. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  8067. // enters E's local LastN ejecting C.
  8068. // Increase the local LastN set size, if necessary.
  8069. if (lastNCount > localLastNCount) {
  8070. localLastNCount = lastNCount;
  8071. }
  8072. // Update the local LastN set preserving the order in which the
  8073. // endpoints appeared in the LastN/local LastN set.
  8074. var nextLocalLastNSet = lastNEndpoints.slice(0);
  8075. for (var i = 0; i < localLastNSet.length; i++) {
  8076. if (nextLocalLastNSet.length >= localLastNCount) {
  8077. break;
  8078. }
  8079. var resourceJid = localLastNSet[i];
  8080. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  8081. nextLocalLastNSet.push(resourceJid);
  8082. }
  8083. }
  8084. localLastNSet = nextLocalLastNSet;
  8085. var updateLargeVideo = false;
  8086. // Handle LastN/local LastN changes.
  8087. $('#remoteVideos>span').each(function( index, element ) {
  8088. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  8089. var isReceived = true;
  8090. if (resourceJid
  8091. && lastNEndpoints.indexOf(resourceJid) < 0
  8092. && localLastNSet.indexOf(resourceJid) < 0) {
  8093. console.log("Remove from last N", resourceJid);
  8094. showPeerContainer(resourceJid, 'hide');
  8095. isReceived = false;
  8096. } else if (resourceJid
  8097. && $('#participant_' + resourceJid).is(':visible')
  8098. && lastNEndpoints.indexOf(resourceJid) < 0
  8099. && localLastNSet.indexOf(resourceJid) >= 0) {
  8100. showPeerContainer(resourceJid, 'avatar');
  8101. isReceived = false;
  8102. }
  8103. if (!isReceived) {
  8104. // resourceJid has dropped out of the server side lastN set, so
  8105. // it is no longer being received. If resourceJid was being
  8106. // displayed in the large video we have to switch to another
  8107. // user.
  8108. var largeVideoResource = largeVideoState.userResourceJid;
  8109. if (!updateLargeVideo && resourceJid === largeVideoResource) {
  8110. updateLargeVideo = true;
  8111. }
  8112. }
  8113. });
  8114. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  8115. endpointsEnteringLastN = lastNEndpoints;
  8116. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  8117. endpointsEnteringLastN.forEach(function (resourceJid) {
  8118. var isVisible = $('#participant_' + resourceJid).is(':visible');
  8119. showPeerContainer(resourceJid, 'show');
  8120. if (!isVisible) {
  8121. console.log("Add to last N", resourceJid);
  8122. var jid = APP.xmpp.findJidFromResource(resourceJid);
  8123. var mediaStream = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  8124. var sel = $('#participant_' + resourceJid + '>video');
  8125. APP.RTC.attachMediaStream(sel, mediaStream.stream);
  8126. if (lastNPickupJid == mediaStream.peerjid) {
  8127. // Clean up the lastN pickup jid.
  8128. lastNPickupJid = null;
  8129. // Don't fire the events again, they've already
  8130. // been fired in the contact list click handler.
  8131. VideoLayout.handleVideoThumbClicked(
  8132. $(sel).attr('src'),
  8133. false,
  8134. Strophe.getResourceFromJid(mediaStream.peerjid));
  8135. updateLargeVideo = false;
  8136. }
  8137. waitForRemoteVideo(sel, mediaStream.ssrc, mediaStream.stream, resourceJid);
  8138. }
  8139. })
  8140. }
  8141. // The endpoint that was being shown in the large video has dropped out
  8142. // of the lastN set and there was no lastN pickup jid. We need to update
  8143. // the large video now.
  8144. if (updateLargeVideo) {
  8145. var resource, container, src;
  8146. var myResource
  8147. = APP.xmpp.myResource();
  8148. // Find out which endpoint to show in the large video.
  8149. for (var i = 0; i < lastNEndpoints.length; i++) {
  8150. resource = lastNEndpoints[i];
  8151. if (!resource || resource === myResource)
  8152. continue;
  8153. container = $("#participant_" + resource);
  8154. if (container.length == 0)
  8155. continue;
  8156. src = $('video', container).attr('src');
  8157. if (!src)
  8158. continue;
  8159. // videoSrcToSsrc needs to be update for this call to succeed.
  8160. VideoLayout.updateLargeVideo(src, 1, resource);
  8161. break;
  8162. }
  8163. }
  8164. };
  8165. /**
  8166. * Updates local stats
  8167. * @param percent
  8168. * @param object
  8169. */
  8170. my.updateLocalConnectionStats = function (percent, object) {
  8171. var resolution = null;
  8172. if(object.resolution !== null)
  8173. {
  8174. resolution = object.resolution;
  8175. object.resolution = resolution[APP.xmpp.myJid()];
  8176. delete resolution[APP.xmpp.myJid()];
  8177. }
  8178. updateStatsIndicator("localVideoContainer", percent, object);
  8179. for(var jid in resolution)
  8180. {
  8181. if(resolution[jid] === null)
  8182. continue;
  8183. var id = 'participant_' + Strophe.getResourceFromJid(jid);
  8184. if(VideoLayout.connectionIndicators[id])
  8185. {
  8186. VideoLayout.connectionIndicators[id].updateResolution(resolution[jid]);
  8187. }
  8188. }
  8189. };
  8190. /**
  8191. * Updates remote stats.
  8192. * @param jid the jid associated with the stats
  8193. * @param percent the connection quality percent
  8194. * @param object the stats data
  8195. */
  8196. my.updateConnectionStats = function (jid, percent, object) {
  8197. var resourceJid = Strophe.getResourceFromJid(jid);
  8198. var videoSpanId = 'participant_' + resourceJid;
  8199. updateStatsIndicator(videoSpanId, percent, object);
  8200. };
  8201. /**
  8202. * Removes the connection
  8203. * @param jid
  8204. */
  8205. my.removeConnectionIndicator = function (jid) {
  8206. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  8207. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].remove();
  8208. };
  8209. /**
  8210. * Hides the connection indicator
  8211. * @param jid
  8212. */
  8213. my.hideConnectionIndicator = function (jid) {
  8214. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  8215. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].hide();
  8216. };
  8217. /**
  8218. * Hides all the indicators
  8219. */
  8220. my.onStatsStop = function () {
  8221. for(var indicator in VideoLayout.connectionIndicators)
  8222. {
  8223. VideoLayout.connectionIndicators[indicator].hideIndicator();
  8224. }
  8225. };
  8226. my.participantLeft = function (jid) {
  8227. // Unlock large video
  8228. var resourceJid = Strophe.getResourceFromJid(jid);
  8229. if (focusedVideoInfo && focusedVideoInfo.resourceJid === resourceJid)
  8230. {
  8231. console.info("Focused video owner has left the conference");
  8232. focusedVideoInfo = null;
  8233. }
  8234. }
  8235. my.onVideoTypeChanged = function (jid) {
  8236. if(jid &&
  8237. Strophe.getResourceFromJid(jid) === largeVideoState.userResourceJid)
  8238. {
  8239. largeVideoState.isDesktop = APP.RTC.isVideoSrcDesktop(jid);
  8240. VideoLayout.getVideoSize = largeVideoState.isDesktop
  8241. ? getDesktopVideoSize
  8242. : getCameraVideoSize;
  8243. VideoLayout.getVideoPosition = largeVideoState.isDesktop
  8244. ? getDesktopVideoPosition
  8245. : getCameraVideoPosition;
  8246. VideoLayout.positionLarge(null, null);
  8247. }
  8248. }
  8249. return my;
  8250. }(VideoLayout || {}));
  8251. module.exports = VideoLayout;
  8252. },{"../../../service/RTC/MediaStreamTypes":101,"../../../service/UI/UIEvents":106,"../audio_levels/AudioLevels":10,"../avatar/Avatar":14,"../etherpad/Etherpad":15,"../prezi/Prezi":16,"../side_pannels/chat/Chat":19,"../side_pannels/contactlist/ContactList":23,"../util/NicknameHandler":30,"../util/UIUtil":31,"./ConnectionIndicator":32}],34:[function(require,module,exports){
  8253. /*
  8254. * Copyright @ 2015 Atlassian Pty Ltd
  8255. *
  8256. * Licensed under the Apache License, Version 2.0 (the "License");
  8257. * you may not use this file except in compliance with the License.
  8258. * You may obtain a copy of the License at
  8259. *
  8260. * http://www.apache.org/licenses/LICENSE-2.0
  8261. *
  8262. * Unless required by applicable law or agreed to in writing, software
  8263. * distributed under the License is distributed on an "AS IS" BASIS,
  8264. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8265. * See the License for the specific language governing permissions and
  8266. * limitations under the License.
  8267. */
  8268. //var nouns = [
  8269. //];
  8270. var pluralNouns = [
  8271. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  8272. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  8273. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  8274. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  8275. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  8276. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  8277. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  8278. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  8279. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  8280. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  8281. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  8282. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  8283. ];
  8284. //var places = [
  8285. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  8286. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  8287. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  8288. // "Bridge"
  8289. //];
  8290. var verbs = [
  8291. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  8292. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  8293. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  8294. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  8295. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  8296. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  8297. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  8298. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  8299. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  8300. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  8301. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  8302. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  8303. ];
  8304. var adverbs = [
  8305. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  8306. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  8307. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  8308. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  8309. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  8310. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  8311. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  8312. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  8313. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  8314. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  8315. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  8316. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  8317. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  8318. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  8319. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly", "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  8320. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  8321. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  8322. ];
  8323. var adjectives = [
  8324. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  8325. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  8326. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  8327. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  8328. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  8329. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  8330. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  8331. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  8332. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  8333. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  8334. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  8335. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  8336. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  8337. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  8338. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  8339. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  8340. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  8341. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  8342. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  8343. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  8344. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  8345. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  8346. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  8347. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  8348. "Zealous"
  8349. ];
  8350. //var pronouns = [
  8351. //];
  8352. //var conjunctions = [
  8353. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  8354. //];
  8355. /*
  8356. * Maps a string (category name) to the array of words from that category.
  8357. */
  8358. var CATEGORIES =
  8359. {
  8360. //"_NOUN_": nouns,
  8361. "_PLURALNOUN_": pluralNouns,
  8362. //"_PLACE_": places,
  8363. "_VERB_": verbs,
  8364. "_ADVERB_": adverbs,
  8365. "_ADJECTIVE_": adjectives
  8366. //"_PRONOUN_": pronouns,
  8367. //"_CONJUNCTION_": conjunctions,
  8368. };
  8369. var PATTERNS = [
  8370. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  8371. // BeautifulFungiOrSpaghetti
  8372. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  8373. // AmazinglyScaryToy
  8374. //"_ADVERB__ADJECTIVE__NOUN_",
  8375. // NeitherTrashNorRifle
  8376. //"Neither_NOUN_Nor_NOUN_",
  8377. //"Either_NOUN_Or_NOUN_",
  8378. // EitherCopulateOrInvestigate
  8379. //"Either_VERB_Or_VERB_",
  8380. //"Neither_VERB_Nor_VERB_",
  8381. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  8382. //"The_ADVERB__ADJECTIVE__NOUN_",
  8383. //"The_ADVERB__ADJECTIVE__NOUN_s",
  8384. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  8385. // WolvesComputeBadly
  8386. //"_PLURALNOUN__VERB__ADVERB_",
  8387. // UniteFacilitateAndMerge
  8388. //"_VERB__VERB_And_VERB_",
  8389. //NastyWitchesAtThePub
  8390. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  8391. ];
  8392. /*
  8393. * Returns a random element from the array 'arr'
  8394. */
  8395. function randomElement(arr)
  8396. {
  8397. return arr[Math.floor(Math.random() * arr.length)];
  8398. }
  8399. /*
  8400. * Returns true if the string 's' contains one of the
  8401. * template strings.
  8402. */
  8403. function hasTemplate(s)
  8404. {
  8405. for (var template in CATEGORIES){
  8406. if (s.indexOf(template) >= 0){
  8407. return true;
  8408. }
  8409. }
  8410. }
  8411. /**
  8412. * Generates new room name.
  8413. */
  8414. var RoomNameGenerator = {
  8415. generateRoomWithoutSeparator: function()
  8416. {
  8417. // Note that if more than one pattern is available, the choice of 'name' won't be random (names from patterns
  8418. // with fewer options will have higher probability of being chosen that names from patterns with more options).
  8419. var name = randomElement(PATTERNS);
  8420. var word;
  8421. while (hasTemplate(name)){
  8422. for (var template in CATEGORIES){
  8423. word = randomElement(CATEGORIES[template]);
  8424. name = name.replace(template, word);
  8425. }
  8426. }
  8427. return name;
  8428. }
  8429. }
  8430. module.exports = RoomNameGenerator;
  8431. },{}],35:[function(require,module,exports){
  8432. /*
  8433. * Copyright @ 2015 Atlassian Pty Ltd
  8434. *
  8435. * Licensed under the Apache License, Version 2.0 (the "License");
  8436. * you may not use this file except in compliance with the License.
  8437. * You may obtain a copy of the License at
  8438. *
  8439. * http://www.apache.org/licenses/LICENSE-2.0
  8440. *
  8441. * Unless required by applicable law or agreed to in writing, software
  8442. * distributed under the License is distributed on an "AS IS" BASIS,
  8443. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8444. * See the License for the specific language governing permissions and
  8445. * limitations under the License.
  8446. */
  8447. var animateTimeout, updateTimeout;
  8448. var RoomNameGenerator = require("./RoomnameGenerator");
  8449. function enter_room()
  8450. {
  8451. var val = $("#enter_room_field").val();
  8452. if(!val) {
  8453. val = $("#enter_room_field").attr("room_name");
  8454. }
  8455. if (val) {
  8456. window.location.pathname = "/" + val;
  8457. }
  8458. }
  8459. function animate(word) {
  8460. var currentVal = $("#enter_room_field").attr("placeholder");
  8461. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  8462. animateTimeout = setTimeout(function() {
  8463. animate(word.substring(1, word.length))
  8464. }, 70);
  8465. }
  8466. function update_roomname()
  8467. {
  8468. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  8469. $("#enter_room_field").attr("room_name", word);
  8470. $("#enter_room_field").attr("placeholder", "");
  8471. clearTimeout(animateTimeout);
  8472. animate(word);
  8473. updateTimeout = setTimeout(update_roomname, 10000);
  8474. }
  8475. function setupWelcomePage()
  8476. {
  8477. $("#videoconference_page").hide();
  8478. $("#domain_name").text(
  8479. window.location.protocol + "//" + window.location.host + "/");
  8480. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  8481. var leftWatermarkDiv
  8482. = $("#welcome_page_header div[class='watermark leftwatermark']");
  8483. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  8484. {
  8485. leftWatermarkDiv.css({display: 'block'});
  8486. leftWatermarkDiv.parent().get(0).href
  8487. = interfaceConfig.JITSI_WATERMARK_LINK;
  8488. }
  8489. }
  8490. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  8491. var rightWatermarkDiv
  8492. = $("#welcome_page_header div[class='watermark rightwatermark']");
  8493. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  8494. rightWatermarkDiv.css({display: 'block'});
  8495. rightWatermarkDiv.parent().get(0).href
  8496. = interfaceConfig.BRAND_WATERMARK_LINK;
  8497. rightWatermarkDiv.get(0).style.backgroundImage
  8498. = "url(images/rightwatermark.png)";
  8499. }
  8500. }
  8501. if (interfaceConfig.SHOW_POWERED_BY) {
  8502. $("#welcome_page_header>a[class='poweredby']")
  8503. .css({display: 'block'});
  8504. }
  8505. $("#enter_room_button").click(function()
  8506. {
  8507. enter_room();
  8508. });
  8509. $("#enter_room_field").keydown(function (event) {
  8510. if (event.keyCode === 13 /* enter */) {
  8511. enter_room();
  8512. }
  8513. });
  8514. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  8515. var updateTimeout;
  8516. var animateTimeout;
  8517. $("#reload_roomname").click(function () {
  8518. clearTimeout(updateTimeout);
  8519. clearTimeout(animateTimeout);
  8520. update_roomname();
  8521. });
  8522. $("#reload_roomname").show();
  8523. update_roomname();
  8524. }
  8525. $("#disable_welcome").click(function () {
  8526. window.localStorage.welcomePageDisabled
  8527. = $("#disable_welcome").is(":checked");
  8528. });
  8529. }
  8530. module.exports = setupWelcomePage;
  8531. },{"./RoomnameGenerator":34}],36:[function(require,module,exports){
  8532. /*
  8533. * Copyright @ 2015 Atlassian Pty Ltd
  8534. *
  8535. * Licensed under the Apache License, Version 2.0 (the "License");
  8536. * you may not use this file except in compliance with the License.
  8537. * You may obtain a copy of the License at
  8538. *
  8539. * http://www.apache.org/licenses/LICENSE-2.0
  8540. *
  8541. * Unless required by applicable law or agreed to in writing, software
  8542. * distributed under the License is distributed on an "AS IS" BASIS,
  8543. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8544. * See the License for the specific language governing permissions and
  8545. * limitations under the License.
  8546. */
  8547. var params = {};
  8548. function getConfigParamsFromUrl() {
  8549. if(!location.hash)
  8550. return {};
  8551. var hash = location.hash.substr(1);
  8552. var result = {};
  8553. hash.split("&").forEach(function(part) {
  8554. var item = part.split("=");
  8555. result[item[0]] = JSON.parse(
  8556. decodeURIComponent(item[1]).replace(/\\&/, "&"));
  8557. });
  8558. return result;
  8559. }
  8560. params = getConfigParamsFromUrl();
  8561. var URLProcessor = {
  8562. setConfigParametersFromUrl: function () {
  8563. for(var k in params)
  8564. {
  8565. if(typeof k !== "string" || k.indexOf("config.") === -1)
  8566. continue;
  8567. var v = params[k];
  8568. var confKey = k.substr(7);
  8569. if(config[confKey] && typeof config[confKey] !== typeof v)
  8570. {
  8571. console.warn("The type of " + k +
  8572. " is wrong. That parameter won't be updated in config.js.");
  8573. continue;
  8574. }
  8575. config[confKey] = v;
  8576. }
  8577. }
  8578. };
  8579. module.exports = URLProcessor;
  8580. },{}],37:[function(require,module,exports){
  8581. /*
  8582. * Copyright @ 2015 Atlassian Pty Ltd
  8583. *
  8584. * Licensed under the Apache License, Version 2.0 (the "License");
  8585. * you may not use this file except in compliance with the License.
  8586. * You may obtain a copy of the License at
  8587. *
  8588. * http://www.apache.org/licenses/LICENSE-2.0
  8589. *
  8590. * Unless required by applicable law or agreed to in writing, software
  8591. * distributed under the License is distributed on an "AS IS" BASIS,
  8592. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8593. * See the License for the specific language governing permissions and
  8594. * limitations under the License.
  8595. */
  8596. var EventEmitter = require("events");
  8597. var eventEmitter = new EventEmitter();
  8598. var CQEvents = require("../../service/connectionquality/CQEvents");
  8599. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8600. /**
  8601. * local stats
  8602. * @type {{}}
  8603. */
  8604. var stats = {};
  8605. /**
  8606. * remote stats
  8607. * @type {{}}
  8608. */
  8609. var remoteStats = {};
  8610. /**
  8611. * Interval for sending statistics to other participants
  8612. * @type {null}
  8613. */
  8614. var sendIntervalId = null;
  8615. /**
  8616. * Start statistics sending.
  8617. */
  8618. function startSendingStats() {
  8619. sendStats();
  8620. sendIntervalId = setInterval(sendStats, 10000);
  8621. }
  8622. /**
  8623. * Sends statistics to other participants
  8624. */
  8625. function sendStats() {
  8626. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  8627. }
  8628. /**
  8629. * Converts statistics to format for sending through XMPP
  8630. * @param stats the statistics
  8631. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  8632. */
  8633. function convertToMUCStats(stats) {
  8634. return {
  8635. "bitrate_download": stats.bitrate.download,
  8636. "bitrate_upload": stats.bitrate.upload,
  8637. "packetLoss_total": stats.packetLoss.total,
  8638. "packetLoss_download": stats.packetLoss.download,
  8639. "packetLoss_upload": stats.packetLoss.upload
  8640. };
  8641. }
  8642. /**
  8643. * Converts statitistics to format used by VideoLayout
  8644. * @param stats
  8645. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  8646. */
  8647. function parseMUCStats(stats) {
  8648. return {
  8649. bitrate: {
  8650. download: stats.bitrate_download,
  8651. upload: stats.bitrate_upload
  8652. },
  8653. packetLoss: {
  8654. total: stats.packetLoss_total,
  8655. download: stats.packetLoss_download,
  8656. upload: stats.packetLoss_upload
  8657. }
  8658. };
  8659. }
  8660. var ConnectionQuality = {
  8661. init: function () {
  8662. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  8663. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  8664. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  8665. },
  8666. /**
  8667. * Updates the local statistics
  8668. * @param data new statistics
  8669. */
  8670. updateLocalStats: function (data) {
  8671. stats = data;
  8672. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  8673. if (sendIntervalId == null) {
  8674. startSendingStats();
  8675. }
  8676. },
  8677. /**
  8678. * Updates remote statistics
  8679. * @param jid the jid associated with the statistics
  8680. * @param data the statistics
  8681. */
  8682. updateRemoteStats: function (jid, data) {
  8683. if (data == null || data.packetLoss_total == null) {
  8684. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  8685. return;
  8686. }
  8687. remoteStats[jid] = parseMUCStats(data);
  8688. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  8689. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  8690. },
  8691. /**
  8692. * Stops statistics sending.
  8693. */
  8694. stopSendingStats: function () {
  8695. clearInterval(sendIntervalId);
  8696. sendIntervalId = null;
  8697. //notify UI about stopping statistics gathering
  8698. eventEmitter.emit(CQEvents.STOP);
  8699. },
  8700. /**
  8701. * Returns the local statistics.
  8702. */
  8703. getStats: function () {
  8704. return stats;
  8705. },
  8706. addListener: function (type, listener) {
  8707. eventEmitter.on(type, listener);
  8708. }
  8709. };
  8710. module.exports = ConnectionQuality;
  8711. },{"../../service/connectionquality/CQEvents":108,"../../service/xmpp/XMPPEvents":112,"events":62}],38:[function(require,module,exports){
  8712. /*
  8713. * Copyright @ 2015 Atlassian Pty Ltd
  8714. *
  8715. * Licensed under the Apache License, Version 2.0 (the "License");
  8716. * you may not use this file except in compliance with the License.
  8717. * You may obtain a copy of the License at
  8718. *
  8719. * http://www.apache.org/licenses/LICENSE-2.0
  8720. *
  8721. * Unless required by applicable law or agreed to in writing, software
  8722. * distributed under the License is distributed on an "AS IS" BASIS,
  8723. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8724. * See the License for the specific language governing permissions and
  8725. * limitations under the License.
  8726. */
  8727. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  8728. getUserMediaWithConstraints */
  8729. /**
  8730. * Indicates that desktop stream is currently in use(for toggle purpose).
  8731. * @type {boolean}
  8732. */
  8733. var isUsingScreenStream = false;
  8734. /**
  8735. * Indicates that switch stream operation is in progress and prevent from
  8736. * triggering new events.
  8737. * @type {boolean}
  8738. */
  8739. var switchInProgress = false;
  8740. /**
  8741. * Method used to get screen sharing stream.
  8742. *
  8743. * @type {function (stream_callback, failure_callback}
  8744. */
  8745. var obtainDesktopStream = null;
  8746. /**
  8747. * Indicates whether desktop sharing extension is installed.
  8748. * @type {boolean}
  8749. */
  8750. var extInstalled = false;
  8751. /**
  8752. * Indicates whether update of desktop sharing extension is required.
  8753. * @type {boolean}
  8754. */
  8755. var extUpdateRequired = false;
  8756. /**
  8757. * Flag used to cache desktop sharing enabled state. Do not use directly as
  8758. * it can be <tt>null</tt>.
  8759. *
  8760. * @type {null|boolean}
  8761. */
  8762. var _desktopSharingEnabled = null;
  8763. var EventEmitter = require("events");
  8764. var eventEmitter = new EventEmitter();
  8765. var DesktopSharingEventTypes
  8766. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  8767. /**
  8768. * Method obtains desktop stream from WebRTC 'screen' source.
  8769. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  8770. */
  8771. function obtainWebRTCScreen(streamCallback, failCallback) {
  8772. APP.RTC.getUserMediaWithConstraints(
  8773. ['screen'],
  8774. streamCallback,
  8775. failCallback
  8776. );
  8777. }
  8778. /**
  8779. * Constructs inline install URL for Chrome desktop streaming extension.
  8780. * The 'chromeExtensionId' must be defined in config.js.
  8781. * @returns {string}
  8782. */
  8783. function getWebStoreInstallUrl()
  8784. {
  8785. return "https://chrome.google.com/webstore/detail/" +
  8786. config.chromeExtensionId;
  8787. }
  8788. /**
  8789. * Checks whether extension update is required.
  8790. * @param minVersion minimal required version
  8791. * @param extVersion current extension version
  8792. * @returns {boolean}
  8793. */
  8794. function isUpdateRequired(minVersion, extVersion)
  8795. {
  8796. try
  8797. {
  8798. var s1 = minVersion.split('.');
  8799. var s2 = extVersion.split('.');
  8800. var len = Math.max(s1.length, s2.length);
  8801. for (var i = 0; i < len; i++)
  8802. {
  8803. var n1 = 0,
  8804. n2 = 0;
  8805. if (i < s1.length)
  8806. n1 = parseInt(s1[i]);
  8807. if (i < s2.length)
  8808. n2 = parseInt(s2[i]);
  8809. if (isNaN(n1) || isNaN(n2))
  8810. {
  8811. return true;
  8812. }
  8813. else if (n1 !== n2)
  8814. {
  8815. return n1 > n2;
  8816. }
  8817. }
  8818. // will happen if boths version has identical numbers in
  8819. // their components (even if one of them is longer, has more components)
  8820. return false;
  8821. }
  8822. catch (e)
  8823. {
  8824. console.error("Failed to parse extension version", e);
  8825. APP.UI.messageHandler.showError("dialog.error",
  8826. "dialog.detectext");
  8827. return true;
  8828. }
  8829. }
  8830. function checkExtInstalled(callback) {
  8831. if (!chrome.runtime) {
  8832. // No API, so no extension for sure
  8833. callback(false, false);
  8834. return;
  8835. }
  8836. chrome.runtime.sendMessage(
  8837. config.chromeExtensionId,
  8838. { getVersion: true },
  8839. function (response) {
  8840. if (!response || !response.version) {
  8841. // Communication failure - assume that no endpoint exists
  8842. console.warn(
  8843. "Extension not installed?: ", chrome.runtime.lastError);
  8844. callback(false, false);
  8845. return;
  8846. }
  8847. // Check installed extension version
  8848. var extVersion = response.version;
  8849. console.log('Extension version is: ' + extVersion);
  8850. var updateRequired
  8851. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  8852. callback(!updateRequired, updateRequired);
  8853. }
  8854. );
  8855. }
  8856. function doGetStreamFromExtension(streamCallback, failCallback) {
  8857. // Sends 'getStream' msg to the extension.
  8858. // Extension id must be defined in the config.
  8859. chrome.runtime.sendMessage(
  8860. config.chromeExtensionId,
  8861. { getStream: true, sources: config.desktopSharingSources },
  8862. function (response) {
  8863. if (!response) {
  8864. failCallback(chrome.runtime.lastError);
  8865. return;
  8866. }
  8867. console.log("Response from extension: " + response);
  8868. if (response.streamId) {
  8869. APP.RTC.getUserMediaWithConstraints(
  8870. ['desktop'],
  8871. function (stream) {
  8872. streamCallback(stream);
  8873. },
  8874. failCallback,
  8875. null, null, null,
  8876. response.streamId);
  8877. } else {
  8878. failCallback("Extension failed to get the stream");
  8879. }
  8880. }
  8881. );
  8882. }
  8883. /**
  8884. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  8885. * stream for returned stream token.
  8886. */
  8887. function obtainScreenFromExtension(streamCallback, failCallback) {
  8888. if (extInstalled) {
  8889. doGetStreamFromExtension(streamCallback, failCallback);
  8890. } else {
  8891. if (extUpdateRequired) {
  8892. alert(
  8893. 'Jitsi Desktop Streamer requires update. ' +
  8894. 'Changes will take effect after next Chrome restart.');
  8895. }
  8896. chrome.webstore.install(
  8897. getWebStoreInstallUrl(),
  8898. function (arg) {
  8899. console.log("Extension installed successfully", arg);
  8900. extInstalled = true;
  8901. // We need to give a moment for the endpoint to become available
  8902. window.setTimeout(function () {
  8903. doGetStreamFromExtension(streamCallback, failCallback);
  8904. }, 500);
  8905. },
  8906. function (arg) {
  8907. console.log("Failed to install the extension", arg);
  8908. failCallback(arg);
  8909. APP.UI.messageHandler.showError("dialog.error",
  8910. "dialog.failtoinstall");
  8911. }
  8912. );
  8913. }
  8914. }
  8915. /**
  8916. * Call this method to toggle desktop sharing feature.
  8917. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  8918. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  8919. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  8920. * enabled), pass any other string or nothing in order to disable this
  8921. * feature completely.
  8922. */
  8923. function setDesktopSharing(method) {
  8924. // Check if we are running chrome
  8925. if (!navigator.webkitGetUserMedia) {
  8926. obtainDesktopStream = null;
  8927. console.info("Desktop sharing disabled");
  8928. } else if (method == "ext") {
  8929. obtainDesktopStream = obtainScreenFromExtension;
  8930. console.info("Using Chrome extension for desktop sharing");
  8931. } else if (method == "webrtc") {
  8932. obtainDesktopStream = obtainWebRTCScreen;
  8933. console.info("Using Chrome WebRTC for desktop sharing");
  8934. }
  8935. // Reset enabled cache
  8936. _desktopSharingEnabled = null;
  8937. }
  8938. /**
  8939. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  8940. * config.js to support inline installs. Host site must be selected as main
  8941. * website of published extension.
  8942. */
  8943. function initInlineInstalls()
  8944. {
  8945. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  8946. }
  8947. function getVideoStreamFailed(error) {
  8948. console.error("Failed to obtain the stream to switch to", error);
  8949. switchInProgress = false;
  8950. isUsingScreenStream = false;
  8951. newStreamCreated(null);
  8952. }
  8953. function getDesktopStreamFailed(error) {
  8954. console.error("Failed to obtain the stream to switch to", error);
  8955. switchInProgress = false;
  8956. }
  8957. function streamSwitchDone() {
  8958. switchInProgress = false;
  8959. eventEmitter.emit(
  8960. DesktopSharingEventTypes.SWITCHING_DONE,
  8961. isUsingScreenStream);
  8962. }
  8963. function newStreamCreated(stream)
  8964. {
  8965. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  8966. stream, isUsingScreenStream, streamSwitchDone);
  8967. }
  8968. module.exports = {
  8969. isUsingScreenStream: function () {
  8970. return isUsingScreenStream;
  8971. },
  8972. /**
  8973. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  8974. * and enabled.
  8975. */
  8976. isDesktopSharingEnabled: function () {
  8977. if (_desktopSharingEnabled === null) {
  8978. if (obtainDesktopStream === obtainScreenFromExtension) {
  8979. // Parse chrome version
  8980. var userAgent = navigator.userAgent.toLowerCase();
  8981. // We can assume that user agent is chrome, because it's
  8982. // enforced when 'ext' streaming method is set
  8983. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  8984. console.log("Chrome version" + userAgent, ver);
  8985. _desktopSharingEnabled = ver >= 34;
  8986. } else {
  8987. _desktopSharingEnabled =
  8988. obtainDesktopStream === obtainWebRTCScreen;
  8989. }
  8990. }
  8991. return _desktopSharingEnabled;
  8992. },
  8993. init: function () {
  8994. setDesktopSharing(config.desktopSharing);
  8995. // Initialize Chrome extension inline installs
  8996. if (config.chromeExtensionId) {
  8997. initInlineInstalls();
  8998. // Check if extension is installed
  8999. checkExtInstalled(function (installed, updateRequired) {
  9000. extInstalled = installed;
  9001. extUpdateRequired = updateRequired;
  9002. console.info(
  9003. "Chrome extension installed: " + extInstalled +
  9004. " updateRequired: " + extUpdateRequired);
  9005. });
  9006. }
  9007. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  9008. },
  9009. addListener: function (listener, type)
  9010. {
  9011. eventEmitter.on(type, listener);
  9012. },
  9013. removeListener: function (listener, type) {
  9014. eventEmitter.removeListener(type, listener);
  9015. },
  9016. /*
  9017. * Toggles screen sharing.
  9018. */
  9019. toggleScreenSharing: function () {
  9020. if (switchInProgress || !obtainDesktopStream) {
  9021. console.warn("Switch in progress or no method defined");
  9022. return;
  9023. }
  9024. switchInProgress = true;
  9025. if (!isUsingScreenStream)
  9026. {
  9027. // Switch to desktop stream
  9028. obtainDesktopStream(
  9029. function (stream) {
  9030. // We now use screen stream
  9031. isUsingScreenStream = true;
  9032. // Hook 'ended' event to restore camera
  9033. // when screen stream stops
  9034. stream.addEventListener('ended',
  9035. function (e) {
  9036. if (!switchInProgress && isUsingScreenStream) {
  9037. APP.desktopsharing.toggleScreenSharing();
  9038. }
  9039. }
  9040. );
  9041. newStreamCreated(stream);
  9042. },
  9043. getDesktopStreamFailed);
  9044. } else {
  9045. // Disable screen stream
  9046. APP.RTC.getUserMediaWithConstraints(
  9047. ['video'],
  9048. function (stream) {
  9049. // We are now using camera stream
  9050. isUsingScreenStream = false;
  9051. newStreamCreated(stream);
  9052. },
  9053. getVideoStreamFailed, config.resolution || '360'
  9054. );
  9055. }
  9056. }
  9057. };
  9058. },{"../../service/desktopsharing/DesktopSharingEventTypes":109,"events":62}],39:[function(require,module,exports){
  9059. /*
  9060. * Copyright @ 2015 Atlassian Pty Ltd
  9061. *
  9062. * Licensed under the Apache License, Version 2.0 (the "License");
  9063. * you may not use this file except in compliance with the License.
  9064. * You may obtain a copy of the License at
  9065. *
  9066. * http://www.apache.org/licenses/LICENSE-2.0
  9067. *
  9068. * Unless required by applicable law or agreed to in writing, software
  9069. * distributed under the License is distributed on an "AS IS" BASIS,
  9070. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9071. * See the License for the specific language governing permissions and
  9072. * limitations under the License.
  9073. */
  9074. //maps keycode to character, id of popover for given function and function
  9075. var shortcuts = {
  9076. 67: {
  9077. character: "C",
  9078. id: "toggleChatPopover",
  9079. function: APP.UI.toggleChat
  9080. },
  9081. 70: {
  9082. character: "F",
  9083. id: "filmstripPopover",
  9084. function: APP.UI.toggleFilmStrip
  9085. },
  9086. 77: {
  9087. character: "M",
  9088. id: "mutePopover",
  9089. function: APP.UI.toggleAudio
  9090. },
  9091. 84: {
  9092. character: "T",
  9093. function: function() {
  9094. if(!APP.RTC.localAudio.isMuted()) {
  9095. APP.UI.toggleAudio();
  9096. }
  9097. }
  9098. },
  9099. 86: {
  9100. character: "V",
  9101. id: "toggleVideoPopover",
  9102. function: APP.UI.toggleVideo
  9103. }
  9104. };
  9105. var KeyboardShortcut = {
  9106. init: function () {
  9107. window.onkeyup = function(e) {
  9108. var keycode = e.which;
  9109. if(!($(":focus").is("input[type=text]") ||
  9110. $(":focus").is("input[type=password]") ||
  9111. $(":focus").is("textarea"))) {
  9112. if (typeof shortcuts[keycode] === "object") {
  9113. shortcuts[keycode].function();
  9114. }
  9115. else if (keycode >= "0".charCodeAt(0) &&
  9116. keycode <= "9".charCodeAt(0)) {
  9117. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  9118. }
  9119. //esc while the smileys are visible hides them
  9120. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  9121. APP.UI.toggleSmileys();
  9122. }
  9123. };
  9124. window.onkeydown = function(e) {
  9125. if(!($(":focus").is("input[type=text]") ||
  9126. $(":focus").is("input[type=password]") ||
  9127. $(":focus").is("textarea"))) {
  9128. if(e.which === "T".charCodeAt(0)) {
  9129. if(APP.RTC.localAudio.isMuted()) {
  9130. APP.UI.toggleAudio();
  9131. }
  9132. }
  9133. }
  9134. };
  9135. var self = this;
  9136. $('body').popover({ selector: '[data-toggle=popover]',
  9137. trigger: 'click hover',
  9138. content: function() {
  9139. return this.getAttribute("content") +
  9140. self.getShortcut(this.getAttribute("shortcut"));
  9141. }
  9142. });
  9143. },
  9144. /**
  9145. *
  9146. * @param id indicates the popover associated with the shortcut
  9147. * @returns {string} the keyboard shortcut used for the id given
  9148. */
  9149. getShortcut: function (id) {
  9150. for (var keycode in shortcuts) {
  9151. if (shortcuts.hasOwnProperty(keycode)) {
  9152. if (shortcuts[keycode].id === id) {
  9153. return " (" + shortcuts[keycode].character + ")";
  9154. }
  9155. }
  9156. }
  9157. return "";
  9158. }
  9159. };
  9160. module.exports = KeyboardShortcut;
  9161. },{}],40:[function(require,module,exports){
  9162. /*
  9163. * Copyright @ 2015 Atlassian Pty Ltd
  9164. *
  9165. * Licensed under the Apache License, Version 2.0 (the "License");
  9166. * you may not use this file except in compliance with the License.
  9167. * You may obtain a copy of the License at
  9168. *
  9169. * http://www.apache.org/licenses/LICENSE-2.0
  9170. *
  9171. * Unless required by applicable law or agreed to in writing, software
  9172. * distributed under the License is distributed on an "AS IS" BASIS,
  9173. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9174. * See the License for the specific language governing permissions and
  9175. * limitations under the License.
  9176. */
  9177. /* global APP */
  9178. /**
  9179. * This module is meant to (eventually) contain and manage all information
  9180. * about members/participants of the conference, so that other modules don't
  9181. * have to do it on their own, and so that other modules can access members'
  9182. * information from a single place.
  9183. *
  9184. * Currently this module only manages information about the support of jingle
  9185. * DTMF of the members. Other fields, as well as accessor methods are meant to
  9186. * be added as needed.
  9187. */
  9188. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9189. var Events = require("../../service/members/Events");
  9190. var EventEmitter = require("events");
  9191. var eventEmitter = new EventEmitter();
  9192. /**
  9193. * The actual container.
  9194. */
  9195. var members = {};
  9196. /**
  9197. * There is at least one member that supports DTMF (i.e. is jigasi).
  9198. */
  9199. var atLeastOneDtmf = false;
  9200. function registerListeners() {
  9201. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  9202. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  9203. }
  9204. /**
  9205. * Handles a new member joining the MUC.
  9206. */
  9207. function onMucMemberJoined(jid, id, displayName) {
  9208. var member = {
  9209. displayName: displayName
  9210. };
  9211. APP.xmpp.getConnection().disco.info(
  9212. jid, "" /* node */, function(iq) { onDiscoInfoReceived(jid, iq); });
  9213. members[jid] = member;
  9214. }
  9215. /**
  9216. * Handles a member leaving the MUC.
  9217. */
  9218. function onMucMemberLeft(jid) {
  9219. delete members[jid];
  9220. updateAtLeastOneDtmf();
  9221. }
  9222. /**
  9223. * Handles the reception of a disco#info packet from a particular JID.
  9224. * @param jid the JID sending the packet.
  9225. * @param iq the packet.
  9226. */
  9227. function onDiscoInfoReceived(jid, iq) {
  9228. if (!members[jid])
  9229. return;
  9230. var supportsDtmf
  9231. = $(iq).find('>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  9232. updateDtmf(jid, supportsDtmf);
  9233. }
  9234. /**
  9235. * Updates the 'supportsDtmf' field for a member.
  9236. * @param jid the jid of the member.
  9237. * @param newValue the new value for the 'supportsDtmf' field.
  9238. */
  9239. function updateDtmf(jid, newValue) {
  9240. var oldValue = members[jid].supportsDtmf;
  9241. members[jid].supportsDtmf = newValue;
  9242. if (newValue != oldValue) {
  9243. updateAtLeastOneDtmf();
  9244. }
  9245. }
  9246. /**
  9247. * Checks each member's 'supportsDtmf' field and updates
  9248. * 'atLastOneSupportsDtmf'.
  9249. */
  9250. function updateAtLeastOneDtmf(){
  9251. var newAtLeastOneDtmf = false;
  9252. for (var key in members) {
  9253. if (typeof members[key].supportsDtmf !== 'undefined'
  9254. && members[key].supportsDtmf) {
  9255. newAtLeastOneDtmf= true;
  9256. break;
  9257. }
  9258. }
  9259. if (atLeastOneDtmf != newAtLeastOneDtmf) {
  9260. atLeastOneDtmf = newAtLeastOneDtmf;
  9261. eventEmitter.emit(Events.DTMF_SUPPORT_CHANGED, atLeastOneDtmf);
  9262. }
  9263. }
  9264. /**
  9265. * Exported interface.
  9266. */
  9267. var Members = {
  9268. start: function(){
  9269. registerListeners();
  9270. },
  9271. addListener: function(type, listener)
  9272. {
  9273. eventEmitter.on(type, listener);
  9274. },
  9275. removeListener: function (type, listener) {
  9276. eventEmitter.removeListener(type, listener);
  9277. },
  9278. size: function () {
  9279. return Object.keys(members).length;
  9280. },
  9281. getMembers: function () {
  9282. return members;
  9283. }
  9284. };
  9285. module.exports = Members;
  9286. },{"../../service/members/Events":110,"../../service/xmpp/XMPPEvents":112,"events":62}],41:[function(require,module,exports){
  9287. /*
  9288. * Copyright @ 2015 Atlassian Pty Ltd
  9289. *
  9290. * Licensed under the Apache License, Version 2.0 (the "License");
  9291. * you may not use this file except in compliance with the License.
  9292. * You may obtain a copy of the License at
  9293. *
  9294. * http://www.apache.org/licenses/LICENSE-2.0
  9295. *
  9296. * Unless required by applicable law or agreed to in writing, software
  9297. * distributed under the License is distributed on an "AS IS" BASIS,
  9298. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9299. * See the License for the specific language governing permissions and
  9300. * limitations under the License.
  9301. */
  9302. var email = '';
  9303. var displayName = '';
  9304. var userId;
  9305. var language = null;
  9306. function supportsLocalStorage() {
  9307. try {
  9308. return 'localStorage' in window && window.localStorage !== null;
  9309. } catch (e) {
  9310. console.log("localstorage is not supported");
  9311. return false;
  9312. }
  9313. }
  9314. function generateUniqueId() {
  9315. function _p8() {
  9316. return (Math.random().toString(16) + "000000000").substr(2, 8);
  9317. }
  9318. return _p8() + _p8() + _p8() + _p8();
  9319. }
  9320. if (supportsLocalStorage()) {
  9321. if (!window.localStorage.jitsiMeetId) {
  9322. window.localStorage.jitsiMeetId = generateUniqueId();
  9323. console.log("generated id", window.localStorage.jitsiMeetId);
  9324. }
  9325. userId = window.localStorage.jitsiMeetId || '';
  9326. email = window.localStorage.email || '';
  9327. displayName = window.localStorage.displayname || '';
  9328. language = window.localStorage.language;
  9329. } else {
  9330. console.log("local storage is not supported");
  9331. userId = generateUniqueId();
  9332. }
  9333. var Settings =
  9334. {
  9335. setDisplayName: function (newDisplayName) {
  9336. displayName = newDisplayName;
  9337. window.localStorage.displayname = displayName;
  9338. return displayName;
  9339. },
  9340. setEmail: function (newEmail)
  9341. {
  9342. email = newEmail;
  9343. window.localStorage.email = newEmail;
  9344. return email;
  9345. },
  9346. getSettings: function () {
  9347. return {
  9348. email: email,
  9349. displayName: displayName,
  9350. uid: userId,
  9351. language: language
  9352. };
  9353. },
  9354. setLanguage: function (lang) {
  9355. language = lang;
  9356. window.localStorage.language = lang;
  9357. }
  9358. };
  9359. module.exports = Settings;
  9360. },{}],42:[function(require,module,exports){
  9361. /*
  9362. * Copyright @ 2015 Atlassian Pty Ltd
  9363. *
  9364. * Licensed under the Apache License, Version 2.0 (the "License");
  9365. * you may not use this file except in compliance with the License.
  9366. * You may obtain a copy of the License at
  9367. *
  9368. * http://www.apache.org/licenses/LICENSE-2.0
  9369. *
  9370. * Unless required by applicable law or agreed to in writing, software
  9371. * distributed under the License is distributed on an "AS IS" BASIS,
  9372. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9373. * See the License for the specific language governing permissions and
  9374. * limitations under the License.
  9375. */
  9376. /**
  9377. * Provides statistics for the local stream.
  9378. */
  9379. /**
  9380. * Size of the webaudio analizer buffer.
  9381. * @type {number}
  9382. */
  9383. var WEBAUDIO_ANALIZER_FFT_SIZE = 2048;
  9384. /**
  9385. * Value of the webaudio analizer smoothing time parameter.
  9386. * @type {number}
  9387. */
  9388. var WEBAUDIO_ANALIZER_SMOOTING_TIME = 0.8;
  9389. /**
  9390. * Converts time domain data array to audio level.
  9391. * @param array the time domain data array.
  9392. * @returns {number} the audio level
  9393. */
  9394. function timeDomainDataToAudioLevel(samples) {
  9395. var maxVolume = 0;
  9396. var length = samples.length;
  9397. for (var i = 0; i < length; i++) {
  9398. if (maxVolume < samples[i])
  9399. maxVolume = samples[i];
  9400. }
  9401. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  9402. };
  9403. /**
  9404. * Animates audio level change
  9405. * @param newLevel the new audio level
  9406. * @param lastLevel the last audio level
  9407. * @returns {Number} the audio level to be set
  9408. */
  9409. function animateLevel(newLevel, lastLevel)
  9410. {
  9411. var value = 0;
  9412. var diff = lastLevel - newLevel;
  9413. if(diff > 0.2)
  9414. {
  9415. value = lastLevel - 0.2;
  9416. }
  9417. else if(diff < -0.4)
  9418. {
  9419. value = lastLevel + 0.4;
  9420. }
  9421. else
  9422. {
  9423. value = newLevel;
  9424. }
  9425. return parseFloat(value.toFixed(3));
  9426. }
  9427. /**
  9428. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  9429. *
  9430. * @param stream the local stream
  9431. * @param interval stats refresh interval given in ms.
  9432. * @param {function(LocalStatsCollector)} updateCallback the callback called on stats
  9433. * update.
  9434. * @constructor
  9435. */
  9436. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  9437. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  9438. this.stream = stream;
  9439. this.intervalId = null;
  9440. this.intervalMilis = interval;
  9441. this.eventEmitter = eventEmitter;
  9442. this.audioLevel = 0;
  9443. this.statisticsService = statisticsService;
  9444. }
  9445. /**
  9446. * Starts the collecting the statistics.
  9447. */
  9448. LocalStatsCollector.prototype.start = function () {
  9449. if (config.disableAudioLevels || !window.AudioContext)
  9450. return;
  9451. var context = new AudioContext();
  9452. var analyser = context.createAnalyser();
  9453. analyser.smoothingTimeConstant = WEBAUDIO_ANALIZER_SMOOTING_TIME;
  9454. analyser.fftSize = WEBAUDIO_ANALIZER_FFT_SIZE;
  9455. var source = context.createMediaStreamSource(this.stream);
  9456. source.connect(analyser);
  9457. var self = this;
  9458. this.intervalId = setInterval(
  9459. function () {
  9460. var array = new Uint8Array(analyser.frequencyBinCount);
  9461. analyser.getByteTimeDomainData(array);
  9462. var audioLevel = timeDomainDataToAudioLevel(array);
  9463. if(audioLevel != self.audioLevel) {
  9464. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  9465. self.eventEmitter.emit(
  9466. "statistics.audioLevel",
  9467. self.statisticsService.LOCAL_JID,
  9468. self.audioLevel);
  9469. }
  9470. },
  9471. this.intervalMilis
  9472. );
  9473. };
  9474. /**
  9475. * Stops collecting the statistics.
  9476. */
  9477. LocalStatsCollector.prototype.stop = function () {
  9478. if (this.intervalId) {
  9479. clearInterval(this.intervalId);
  9480. this.intervalId = null;
  9481. }
  9482. };
  9483. module.exports = LocalStatsCollector;
  9484. },{}],43:[function(require,module,exports){
  9485. /*
  9486. * Copyright @ 2015 Atlassian Pty Ltd
  9487. *
  9488. * Licensed under the Apache License, Version 2.0 (the "License");
  9489. * you may not use this file except in compliance with the License.
  9490. * You may obtain a copy of the License at
  9491. *
  9492. * http://www.apache.org/licenses/LICENSE-2.0
  9493. *
  9494. * Unless required by applicable law or agreed to in writing, software
  9495. * distributed under the License is distributed on an "AS IS" BASIS,
  9496. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9497. * See the License for the specific language governing permissions and
  9498. * limitations under the License.
  9499. */
  9500. /* global ssrc2jid */
  9501. /* jshint -W117 */
  9502. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  9503. /**
  9504. * Calculates packet lost percent using the number of lost packets and the
  9505. * number of all packet.
  9506. * @param lostPackets the number of lost packets
  9507. * @param totalPackets the number of all packets.
  9508. * @returns {number} packet loss percent
  9509. */
  9510. function calculatePacketLoss(lostPackets, totalPackets) {
  9511. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  9512. return 0;
  9513. return Math.round((lostPackets/totalPackets)*100);
  9514. }
  9515. function getStatValue(item, name) {
  9516. if(!keyMap[APP.RTC.getBrowserType()][name])
  9517. throw "The property isn't supported!";
  9518. var key = keyMap[APP.RTC.getBrowserType()][name];
  9519. return APP.RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_CHROME? item.stat(key) : item[key];
  9520. }
  9521. /**
  9522. * Peer statistics data holder.
  9523. * @constructor
  9524. */
  9525. function PeerStats()
  9526. {
  9527. this.ssrc2Loss = {};
  9528. this.ssrc2AudioLevel = {};
  9529. this.ssrc2bitrate = {};
  9530. this.ssrc2resolution = {};
  9531. }
  9532. /**
  9533. * The bandwidth
  9534. * @type {{}}
  9535. */
  9536. PeerStats.bandwidth = {};
  9537. /**
  9538. * The bit rate
  9539. * @type {{}}
  9540. */
  9541. PeerStats.bitrate = {};
  9542. /**
  9543. * The packet loss rate
  9544. * @type {{}}
  9545. */
  9546. PeerStats.packetLoss = null;
  9547. /**
  9548. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  9549. * represented by this instance.
  9550. * @param ssrc audio or video RTP stream SSRC.
  9551. * @param lossRate new packet loss rate value to be set.
  9552. */
  9553. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  9554. {
  9555. this.ssrc2Loss[ssrc] = lossRate;
  9556. };
  9557. /**
  9558. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  9559. * represented by this instance.
  9560. * @param ssrc audio or video RTP stream SSRC.
  9561. * @param resolution new resolution value to be set.
  9562. */
  9563. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  9564. {
  9565. if(resolution === null && this.ssrc2resolution[ssrc])
  9566. {
  9567. delete this.ssrc2resolution[ssrc];
  9568. }
  9569. else if(resolution !== null)
  9570. this.ssrc2resolution[ssrc] = resolution;
  9571. };
  9572. /**
  9573. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  9574. * represented by this instance.
  9575. * @param ssrc audio or video RTP stream SSRC.
  9576. * @param bitrate new bitrate value to be set.
  9577. */
  9578. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  9579. {
  9580. if(this.ssrc2bitrate[ssrc])
  9581. {
  9582. this.ssrc2bitrate[ssrc].download += bitrate.download;
  9583. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  9584. }
  9585. else {
  9586. this.ssrc2bitrate[ssrc] = bitrate;
  9587. }
  9588. };
  9589. /**
  9590. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  9591. * the stream which belongs to the peer represented by this instance.
  9592. * @param ssrc RTP stream SSRC for which current audio level value will be
  9593. * updated.
  9594. * @param audioLevel the new audio level value to be set. Value is truncated to
  9595. * fit the range from 0 to 1.
  9596. */
  9597. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  9598. {
  9599. // Range limit 0 - 1
  9600. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  9601. };
  9602. function formatAudioLevel(audioLevel) {
  9603. return Math.min(Math.max(audioLevel, 0), 1);
  9604. }
  9605. /**
  9606. * Array with the transport information.
  9607. * @type {Array}
  9608. */
  9609. PeerStats.transport = [];
  9610. /**
  9611. * <tt>StatsCollector</tt> registers for stats updates of given
  9612. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  9613. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  9614. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  9615. * instance as an event source.
  9616. *
  9617. * @param peerconnection webRTC peer connection object.
  9618. * @param interval stats refresh interval given in ms.
  9619. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  9620. * called on stats update.
  9621. * @constructor
  9622. */
  9623. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  9624. {
  9625. this.peerconnection = peerconnection;
  9626. this.baselineAudioLevelsReport = null;
  9627. this.currentAudioLevelsReport = null;
  9628. this.currentStatsReport = null;
  9629. this.baselineStatsReport = null;
  9630. this.audioLevelsIntervalId = null;
  9631. this.eventEmitter = eventEmitter;
  9632. /**
  9633. * Gather PeerConnection stats once every this many milliseconds.
  9634. */
  9635. this.GATHER_INTERVAL = 15000;
  9636. /**
  9637. * Log stats via the focus once every this many milliseconds.
  9638. */
  9639. this.LOG_INTERVAL = 60000;
  9640. /**
  9641. * Gather stats and store them in this.statsToBeLogged.
  9642. */
  9643. this.gatherStatsIntervalId = null;
  9644. /**
  9645. * Send the stats already saved in this.statsToBeLogged to be logged via
  9646. * the focus.
  9647. */
  9648. this.logStatsIntervalId = null;
  9649. /**
  9650. * Stores the statistics which will be send to the focus to be logged.
  9651. */
  9652. this.statsToBeLogged =
  9653. {
  9654. timestamps: [],
  9655. stats: {}
  9656. };
  9657. // Updates stats interval
  9658. this.audioLevelsIntervalMilis = audioLevelsInterval;
  9659. this.statsIntervalId = null;
  9660. this.statsIntervalMilis = statsInterval;
  9661. // Map of jids to PeerStats
  9662. this.jid2stats = {};
  9663. }
  9664. module.exports = StatsCollector;
  9665. /**
  9666. * Stops stats updates.
  9667. */
  9668. StatsCollector.prototype.stop = function () {
  9669. if (this.audioLevelsIntervalId) {
  9670. clearInterval(this.audioLevelsIntervalId);
  9671. this.audioLevelsIntervalId = null;
  9672. }
  9673. if (this.statsIntervalId)
  9674. {
  9675. clearInterval(this.statsIntervalId);
  9676. this.statsIntervalId = null;
  9677. }
  9678. if(this.logStatsIntervalId)
  9679. {
  9680. clearInterval(this.logStatsIntervalId);
  9681. this.logStatsIntervalId = null;
  9682. }
  9683. if(this.gatherStatsIntervalId)
  9684. {
  9685. clearInterval(this.gatherStatsIntervalId);
  9686. this.gatherStatsIntervalId = null;
  9687. }
  9688. };
  9689. /**
  9690. * Callback passed to <tt>getStats</tt> method.
  9691. * @param error an error that occurred on <tt>getStats</tt> call.
  9692. */
  9693. StatsCollector.prototype.errorCallback = function (error)
  9694. {
  9695. console.error("Get stats error", error);
  9696. this.stop();
  9697. };
  9698. /**
  9699. * Starts stats updates.
  9700. */
  9701. StatsCollector.prototype.start = function ()
  9702. {
  9703. var self = this;
  9704. if(!config.disableAudioLevels) {
  9705. this.audioLevelsIntervalId = setInterval(
  9706. function () {
  9707. // Interval updates
  9708. self.peerconnection.getStats(
  9709. function (report) {
  9710. var results = null;
  9711. if (!report || !report.result ||
  9712. typeof report.result != 'function') {
  9713. results = report;
  9714. }
  9715. else {
  9716. results = report.result();
  9717. }
  9718. //console.error("Got interval report", results);
  9719. self.currentAudioLevelsReport = results;
  9720. self.processAudioLevelReport();
  9721. self.baselineAudioLevelsReport =
  9722. self.currentAudioLevelsReport;
  9723. },
  9724. self.errorCallback
  9725. );
  9726. },
  9727. self.audioLevelsIntervalMilis
  9728. );
  9729. }
  9730. if(!config.disableStats && !navigator.mozGetUserMedia) {
  9731. this.statsIntervalId = setInterval(
  9732. function () {
  9733. // Interval updates
  9734. self.peerconnection.getStats(
  9735. function (report) {
  9736. var results = null;
  9737. if (!report || !report.result ||
  9738. typeof report.result != 'function') {
  9739. //firefox
  9740. results = report;
  9741. }
  9742. else {
  9743. //chrome
  9744. results = report.result();
  9745. }
  9746. //console.error("Got interval report", results);
  9747. self.currentStatsReport = results;
  9748. try {
  9749. self.processStatsReport();
  9750. }
  9751. catch (e) {
  9752. console.error("Unsupported key:" + e, e);
  9753. }
  9754. self.baselineStatsReport = self.currentStatsReport;
  9755. },
  9756. self.errorCallback
  9757. );
  9758. },
  9759. self.statsIntervalMilis
  9760. );
  9761. }
  9762. if (config.logStats && !navigator.mozGetUserMedia) {
  9763. this.gatherStatsIntervalId = setInterval(
  9764. function () {
  9765. self.peerconnection.getStats(
  9766. function (report) {
  9767. self.addStatsToBeLogged(report.result());
  9768. },
  9769. function () {
  9770. }
  9771. );
  9772. },
  9773. this.GATHER_INTERVAL
  9774. );
  9775. this.logStatsIntervalId = setInterval(
  9776. function() { self.logStats(); },
  9777. this.LOG_INTERVAL);
  9778. }
  9779. };
  9780. /**
  9781. * Checks whether a certain record should be included in the logged statistics.
  9782. */
  9783. function acceptStat(reportId, reportType, statName) {
  9784. if (reportType == "googCandidatePair" && statName == "googChannelId")
  9785. return false;
  9786. if (reportType == "ssrc") {
  9787. if (statName == "googTrackId" ||
  9788. statName == "transportId" ||
  9789. statName == "ssrc")
  9790. return false;
  9791. }
  9792. return true;
  9793. }
  9794. /**
  9795. * Checks whether a certain record should be included in the logged statistics.
  9796. */
  9797. function acceptReport(id, type) {
  9798. if (id.substring(0, 15) == "googCertificate" ||
  9799. id.substring(0, 9) == "googTrack" ||
  9800. id.substring(0, 20) == "googLibjingleSession")
  9801. return false;
  9802. if (type == "googComponent")
  9803. return false;
  9804. return true;
  9805. }
  9806. /**
  9807. * Converts the stats to the format used for logging, and saves the data in
  9808. * this.statsToBeLogged.
  9809. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  9810. */
  9811. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  9812. var self = this;
  9813. var num_records = this.statsToBeLogged.timestamps.length;
  9814. this.statsToBeLogged.timestamps.push(new Date().getTime());
  9815. reports.map(function (report) {
  9816. if (!acceptReport(report.id, report.type))
  9817. return;
  9818. var stat = self.statsToBeLogged.stats[report.id];
  9819. if (!stat) {
  9820. stat = self.statsToBeLogged.stats[report.id] = {};
  9821. }
  9822. stat.type = report.type;
  9823. report.names().map(function (name) {
  9824. if (!acceptStat(report.id, report.type, name))
  9825. return;
  9826. var values = stat[name];
  9827. if (!values) {
  9828. values = stat[name] = [];
  9829. }
  9830. while (values.length < num_records) {
  9831. values.push(null);
  9832. }
  9833. values.push(report.stat(name));
  9834. });
  9835. });
  9836. };
  9837. StatsCollector.prototype.logStats = function () {
  9838. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  9839. return;
  9840. // Reset the stats
  9841. this.statsToBeLogged.stats = {};
  9842. this.statsToBeLogged.timestamps = [];
  9843. };
  9844. var keyMap = {};
  9845. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  9846. "ssrc": "ssrc",
  9847. "packetsReceived": "packetsReceived",
  9848. "packetsLost": "packetsLost",
  9849. "packetsSent": "packetsSent",
  9850. "bytesReceived": "bytesReceived",
  9851. "bytesSent": "bytesSent"
  9852. };
  9853. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  9854. "receiveBandwidth": "googAvailableReceiveBandwidth",
  9855. "sendBandwidth": "googAvailableSendBandwidth",
  9856. "remoteAddress": "googRemoteAddress",
  9857. "transportType": "googTransportType",
  9858. "localAddress": "googLocalAddress",
  9859. "activeConnection": "googActiveConnection",
  9860. "ssrc": "ssrc",
  9861. "packetsReceived": "packetsReceived",
  9862. "packetsSent": "packetsSent",
  9863. "packetsLost": "packetsLost",
  9864. "bytesReceived": "bytesReceived",
  9865. "bytesSent": "bytesSent",
  9866. "googFrameHeightReceived": "googFrameHeightReceived",
  9867. "googFrameWidthReceived": "googFrameWidthReceived",
  9868. "googFrameHeightSent": "googFrameHeightSent",
  9869. "googFrameWidthSent": "googFrameWidthSent",
  9870. "audioInputLevel": "audioInputLevel",
  9871. "audioOutputLevel": "audioOutputLevel"
  9872. };
  9873. /**
  9874. * Stats processing logic.
  9875. */
  9876. StatsCollector.prototype.processStatsReport = function () {
  9877. if (!this.baselineStatsReport) {
  9878. return;
  9879. }
  9880. for (var idx in this.currentStatsReport) {
  9881. var now = this.currentStatsReport[idx];
  9882. try {
  9883. if (getStatValue(now, 'receiveBandwidth') ||
  9884. getStatValue(now, 'sendBandwidth')) {
  9885. PeerStats.bandwidth = {
  9886. "download": Math.round(
  9887. (getStatValue(now, 'receiveBandwidth')) / 1000),
  9888. "upload": Math.round(
  9889. (getStatValue(now, 'sendBandwidth')) / 1000)
  9890. };
  9891. }
  9892. }
  9893. catch(e){/*not supported*/}
  9894. if(now.type == 'googCandidatePair')
  9895. {
  9896. var ip, type, localIP, active;
  9897. try {
  9898. ip = getStatValue(now, 'remoteAddress');
  9899. type = getStatValue(now, "transportType");
  9900. localIP = getStatValue(now, "localAddress");
  9901. active = getStatValue(now, "activeConnection");
  9902. }
  9903. catch(e){/*not supported*/}
  9904. if(!ip || !type || !localIP || active != "true")
  9905. continue;
  9906. var addressSaved = false;
  9907. for(var i = 0; i < PeerStats.transport.length; i++)
  9908. {
  9909. if(PeerStats.transport[i].ip == ip &&
  9910. PeerStats.transport[i].type == type &&
  9911. PeerStats.transport[i].localip == localIP)
  9912. {
  9913. addressSaved = true;
  9914. }
  9915. }
  9916. if(addressSaved)
  9917. continue;
  9918. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  9919. continue;
  9920. }
  9921. if(now.type == "candidatepair")
  9922. {
  9923. if(now.state == "succeeded")
  9924. continue;
  9925. var local = this.currentStatsReport[now.localCandidateId];
  9926. var remote = this.currentStatsReport[now.remoteCandidateId];
  9927. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  9928. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  9929. }
  9930. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  9931. now.type != "inboundrtp") {
  9932. continue;
  9933. }
  9934. var before = this.baselineStatsReport[idx];
  9935. if (!before) {
  9936. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  9937. continue;
  9938. }
  9939. var ssrc = getStatValue(now, 'ssrc');
  9940. if(!ssrc)
  9941. continue;
  9942. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  9943. if (!jid && (Date.now() - now.timestamp) < 3000) {
  9944. console.warn("No jid for ssrc: " + ssrc);
  9945. continue;
  9946. }
  9947. var jidStats = this.jid2stats[jid];
  9948. if (!jidStats) {
  9949. jidStats = new PeerStats();
  9950. this.jid2stats[jid] = jidStats;
  9951. }
  9952. var isDownloadStream = true;
  9953. var key = 'packetsReceived';
  9954. if (!getStatValue(now, key))
  9955. {
  9956. isDownloadStream = false;
  9957. key = 'packetsSent';
  9958. if (!getStatValue(now, key))
  9959. {
  9960. console.warn("No packetsReceived nor packetSent stat found");
  9961. continue;
  9962. }
  9963. }
  9964. var packetsNow = getStatValue(now, key);
  9965. if(!packetsNow || packetsNow < 0)
  9966. packetsNow = 0;
  9967. var packetsBefore = getStatValue(before, key);
  9968. if(!packetsBefore || packetsBefore < 0)
  9969. packetsBefore = 0;
  9970. var packetRate = packetsNow - packetsBefore;
  9971. if(!packetRate || packetRate < 0)
  9972. packetRate = 0;
  9973. var currentLoss = getStatValue(now, 'packetsLost');
  9974. if(!currentLoss || currentLoss < 0)
  9975. currentLoss = 0;
  9976. var previousLoss = getStatValue(before, 'packetsLost');
  9977. if(!previousLoss || previousLoss < 0)
  9978. previousLoss = 0;
  9979. var lossRate = currentLoss - previousLoss;
  9980. if(!lossRate || lossRate < 0)
  9981. lossRate = 0;
  9982. var packetsTotal = (packetRate + lossRate);
  9983. jidStats.setSsrcLoss(ssrc,
  9984. {"packetsTotal": packetsTotal,
  9985. "packetsLost": lossRate,
  9986. "isDownloadStream": isDownloadStream});
  9987. var bytesReceived = 0, bytesSent = 0;
  9988. if(getStatValue(now, "bytesReceived"))
  9989. {
  9990. bytesReceived = getStatValue(now, "bytesReceived") -
  9991. getStatValue(before, "bytesReceived");
  9992. }
  9993. if(getStatValue(now, "bytesSent"))
  9994. {
  9995. bytesSent = getStatValue(now, "bytesSent") -
  9996. getStatValue(before, "bytesSent");
  9997. }
  9998. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  9999. if(bytesReceived <= 0 || time <= 0)
  10000. {
  10001. bytesReceived = 0;
  10002. }
  10003. else
  10004. {
  10005. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  10006. }
  10007. if(bytesSent <= 0 || time <= 0)
  10008. {
  10009. bytesSent = 0;
  10010. }
  10011. else
  10012. {
  10013. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  10014. }
  10015. jidStats.setSsrcBitrate(ssrc, {
  10016. "download": bytesReceived,
  10017. "upload": bytesSent});
  10018. var resolution = {height: null, width: null};
  10019. try {
  10020. if (getStatValue(now, "googFrameHeightReceived") &&
  10021. getStatValue(now, "googFrameWidthReceived")) {
  10022. resolution.height = getStatValue(now, "googFrameHeightReceived");
  10023. resolution.width = getStatValue(now, "googFrameWidthReceived");
  10024. }
  10025. else if (getStatValue(now, "googFrameHeightSent") &&
  10026. getStatValue(now, "googFrameWidthSent")) {
  10027. resolution.height = getStatValue(now, "googFrameHeightSent");
  10028. resolution.width = getStatValue(now, "googFrameWidthSent");
  10029. }
  10030. }
  10031. catch(e){/*not supported*/}
  10032. if(resolution.height && resolution.width)
  10033. {
  10034. jidStats.setSsrcResolution(ssrc, resolution);
  10035. }
  10036. else
  10037. {
  10038. jidStats.setSsrcResolution(ssrc, null);
  10039. }
  10040. }
  10041. var self = this;
  10042. // Jid stats
  10043. var totalPackets = {download: 0, upload: 0};
  10044. var lostPackets = {download: 0, upload: 0};
  10045. var bitrateDownload = 0;
  10046. var bitrateUpload = 0;
  10047. var resolutions = {};
  10048. Object.keys(this.jid2stats).forEach(
  10049. function (jid)
  10050. {
  10051. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  10052. function (ssrc)
  10053. {
  10054. var type = "upload";
  10055. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  10056. type = "download";
  10057. totalPackets[type] +=
  10058. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  10059. lostPackets[type] +=
  10060. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  10061. }
  10062. );
  10063. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  10064. function (ssrc) {
  10065. bitrateDownload +=
  10066. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  10067. bitrateUpload +=
  10068. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  10069. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  10070. }
  10071. );
  10072. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  10073. }
  10074. );
  10075. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  10076. PeerStats.packetLoss = {
  10077. total:
  10078. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  10079. totalPackets.download + totalPackets.upload),
  10080. download:
  10081. calculatePacketLoss(lostPackets.download, totalPackets.download),
  10082. upload:
  10083. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  10084. };
  10085. this.eventEmitter.emit("statistics.connectionstats",
  10086. {
  10087. "bitrate": PeerStats.bitrate,
  10088. "packetLoss": PeerStats.packetLoss,
  10089. "bandwidth": PeerStats.bandwidth,
  10090. "resolution": resolutions,
  10091. "transport": PeerStats.transport
  10092. });
  10093. PeerStats.transport = [];
  10094. };
  10095. /**
  10096. * Stats processing logic.
  10097. */
  10098. StatsCollector.prototype.processAudioLevelReport = function ()
  10099. {
  10100. if (!this.baselineAudioLevelsReport)
  10101. {
  10102. return;
  10103. }
  10104. for (var idx in this.currentAudioLevelsReport)
  10105. {
  10106. var now = this.currentAudioLevelsReport[idx];
  10107. if (now.type != 'ssrc')
  10108. {
  10109. continue;
  10110. }
  10111. var before = this.baselineAudioLevelsReport[idx];
  10112. if (!before)
  10113. {
  10114. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  10115. continue;
  10116. }
  10117. var ssrc = getStatValue(now, 'ssrc');
  10118. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  10119. if (!jid)
  10120. {
  10121. if((Date.now() - now.timestamp) < 3000)
  10122. console.warn("No jid for ssrc: " + ssrc);
  10123. continue;
  10124. }
  10125. var jidStats = this.jid2stats[jid];
  10126. if (!jidStats)
  10127. {
  10128. jidStats = new PeerStats();
  10129. this.jid2stats[jid] = jidStats;
  10130. }
  10131. // Audio level
  10132. var audioLevel = null;
  10133. try {
  10134. audioLevel = getStatValue(now, 'audioInputLevel');
  10135. if (!audioLevel)
  10136. audioLevel = getStatValue(now, 'audioOutputLevel');
  10137. }
  10138. catch(e) {/*not supported*/
  10139. console.warn("Audio Levels are not available in the statistics.");
  10140. clearInterval(this.audioLevelsIntervalId);
  10141. return;
  10142. }
  10143. if (audioLevel)
  10144. {
  10145. // TODO: can't find specs about what this value really is,
  10146. // but it seems to vary between 0 and around 32k.
  10147. audioLevel = audioLevel / 32767;
  10148. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  10149. if(jid != APP.xmpp.myJid())
  10150. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  10151. }
  10152. }
  10153. };
  10154. },{"../../service/RTC/RTCBrowserType":102}],44:[function(require,module,exports){
  10155. /*
  10156. * Copyright @ 2015 Atlassian Pty Ltd
  10157. *
  10158. * Licensed under the Apache License, Version 2.0 (the "License");
  10159. * you may not use this file except in compliance with the License.
  10160. * You may obtain a copy of the License at
  10161. *
  10162. * http://www.apache.org/licenses/LICENSE-2.0
  10163. *
  10164. * Unless required by applicable law or agreed to in writing, software
  10165. * distributed under the License is distributed on an "AS IS" BASIS,
  10166. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10167. * See the License for the specific language governing permissions and
  10168. * limitations under the License.
  10169. *
  10170. * Created by hristo on 8/4/14.
  10171. */
  10172. var LocalStats = require("./LocalStatsCollector.js");
  10173. var RTPStats = require("./RTPStatsCollector.js");
  10174. var EventEmitter = require("events");
  10175. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  10176. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10177. var eventEmitter = new EventEmitter();
  10178. var localStats = null;
  10179. var rtpStats = null;
  10180. function stopLocal()
  10181. {
  10182. if(localStats)
  10183. {
  10184. localStats.stop();
  10185. localStats = null;
  10186. }
  10187. }
  10188. function stopRemote()
  10189. {
  10190. if(rtpStats)
  10191. {
  10192. rtpStats.stop();
  10193. eventEmitter.emit("statistics.stop");
  10194. rtpStats = null;
  10195. }
  10196. }
  10197. function startRemoteStats (peerconnection) {
  10198. if(rtpStats)
  10199. {
  10200. rtpStats.stop();
  10201. rtpStats = null;
  10202. }
  10203. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  10204. rtpStats.start();
  10205. }
  10206. function onStreamCreated(stream)
  10207. {
  10208. if(stream.getOriginalStream().getAudioTracks().length === 0)
  10209. return;
  10210. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  10211. eventEmitter);
  10212. localStats.start();
  10213. }
  10214. function onDisposeConference(onUnload) {
  10215. stopRemote();
  10216. if(onUnload) {
  10217. stopLocal();
  10218. eventEmitter.removeAllListeners();
  10219. }
  10220. }
  10221. var statistics =
  10222. {
  10223. /**
  10224. * Indicates that this audio level is for local jid.
  10225. * @type {string}
  10226. */
  10227. LOCAL_JID: 'local',
  10228. addAudioLevelListener: function(listener)
  10229. {
  10230. eventEmitter.on("statistics.audioLevel", listener);
  10231. },
  10232. removeAudioLevelListener: function(listener)
  10233. {
  10234. eventEmitter.removeListener("statistics.audioLevel", listener);
  10235. },
  10236. addConnectionStatsListener: function(listener)
  10237. {
  10238. eventEmitter.on("statistics.connectionstats", listener);
  10239. },
  10240. removeConnectionStatsListener: function(listener)
  10241. {
  10242. eventEmitter.removeListener("statistics.connectionstats", listener);
  10243. },
  10244. addRemoteStatsStopListener: function(listener)
  10245. {
  10246. eventEmitter.on("statistics.stop", listener);
  10247. },
  10248. removeRemoteStatsStopListener: function(listener)
  10249. {
  10250. eventEmitter.removeListener("statistics.stop", listener);
  10251. },
  10252. stop: function () {
  10253. stopLocal();
  10254. stopRemote();
  10255. if(eventEmitter)
  10256. {
  10257. eventEmitter.removeAllListeners();
  10258. }
  10259. },
  10260. stopRemoteStatistics: function()
  10261. {
  10262. stopRemote();
  10263. },
  10264. start: function () {
  10265. APP.RTC.addStreamListener(onStreamCreated,
  10266. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  10267. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  10268. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  10269. startRemoteStats(event.peerconnection);
  10270. });
  10271. }
  10272. };
  10273. module.exports = statistics;
  10274. },{"../../service/RTC/StreamEventTypes.js":105,"../../service/xmpp/XMPPEvents":112,"./LocalStatsCollector.js":42,"./RTPStatsCollector.js":43,"events":62}],45:[function(require,module,exports){
  10275. /*
  10276. * Copyright @ 2015 Atlassian Pty Ltd
  10277. *
  10278. * Licensed under the Apache License, Version 2.0 (the "License");
  10279. * you may not use this file except in compliance with the License.
  10280. * You may obtain a copy of the License at
  10281. *
  10282. * http://www.apache.org/licenses/LICENSE-2.0
  10283. *
  10284. * Unless required by applicable law or agreed to in writing, software
  10285. * distributed under the License is distributed on an "AS IS" BASIS,
  10286. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10287. * See the License for the specific language governing permissions and
  10288. * limitations under the License.
  10289. */
  10290. var i18n = require("i18next-client");
  10291. var languages = require("../../service/translation/languages");
  10292. var Settings = require("../settings/Settings");
  10293. var DEFAULT_LANG = languages.EN;
  10294. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  10295. return value.replace("__app__", interfaceConfig.APP_NAME);
  10296. });
  10297. var defaultOptions = {
  10298. detectLngQS: "lang",
  10299. useCookie: false,
  10300. fallbackLng: DEFAULT_LANG,
  10301. load: "unspecific",
  10302. resGetPath: 'lang/__ns__-__lng__.json',
  10303. ns: {
  10304. namespaces: ['main', 'languages'],
  10305. defaultNs: 'main'
  10306. },
  10307. lngWhitelist : languages.getLanguages(),
  10308. fallbackOnNull: true,
  10309. fallbackOnEmpty: true,
  10310. useDataAttrOptions: true,
  10311. defaultValueFromContent: false,
  10312. app: interfaceConfig.APP_NAME,
  10313. getAsync: false,
  10314. defaultValueFromContent: false,
  10315. customLoad: function(lng, ns, options, done) {
  10316. var resPath = "lang/__ns__-__lng__.json";
  10317. if(lng === languages.EN)
  10318. resPath = "lang/__ns__.json";
  10319. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  10320. i18n.functions.ajax({
  10321. url: url,
  10322. success: function(data, status, xhr) {
  10323. i18n.functions.log('loaded: ' + url);
  10324. done(null, data);
  10325. },
  10326. error : function(xhr, status, error) {
  10327. if ((status && status == 200) ||
  10328. (xhr && xhr.status && xhr.status == 200)) {
  10329. // file loaded but invalid json, stop waste time !
  10330. i18n.functions.error('There is a typo in: ' + url);
  10331. } else if ((status && status == 404) ||
  10332. (xhr && xhr.status && xhr.status == 404)) {
  10333. i18n.functions.log('Does not exist: ' + url);
  10334. } else {
  10335. var theStatus = status ? status :
  10336. ((xhr && xhr.status) ? xhr.status : null);
  10337. i18n.functions.log(theStatus + ' when loading ' + url);
  10338. }
  10339. done(error, {});
  10340. },
  10341. dataType: "json",
  10342. async : options.getAsync
  10343. });
  10344. }
  10345. // options for caching
  10346. // useLocalStorage: true,
  10347. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  10348. };
  10349. function initCompleted(t)
  10350. {
  10351. $("[data-i18n]").i18n();
  10352. }
  10353. function checkForParameter() {
  10354. var query = window.location.search.substring(1);
  10355. var vars = query.split("&");
  10356. for (var i=0;i<vars.length;i++) {
  10357. var pair = vars[i].split("=");
  10358. if(pair[0] == "lang")
  10359. {
  10360. return pair[1];
  10361. }
  10362. }
  10363. return null;
  10364. }
  10365. module.exports = {
  10366. init: function (lang) {
  10367. var options = defaultOptions;
  10368. if(!lang)
  10369. {
  10370. lang = checkForParameter();
  10371. if(!lang)
  10372. {
  10373. var settings = Settings.getSettings();
  10374. if(settings)
  10375. lang = settings.language;
  10376. if(!lang && config.defaultLanguage)
  10377. {
  10378. lang = config.defaultLanguage;
  10379. }
  10380. }
  10381. }
  10382. if(lang) {
  10383. options.lng = lang;
  10384. }
  10385. i18n.init(options, initCompleted);
  10386. },
  10387. translateString: function (key, options) {
  10388. return i18n.t(key, options);
  10389. },
  10390. setLanguage: function (lang) {
  10391. if(!lang)
  10392. lang = DEFAULT_LANG;
  10393. i18n.setLng(lang, defaultOptions, initCompleted);
  10394. },
  10395. getCurrentLanguage: function () {
  10396. return i18n.lng();
  10397. },
  10398. translateElement: function (selector) {
  10399. selector.i18n();
  10400. },
  10401. generateTranslatonHTML: function (key, options) {
  10402. var str = "<span data-i18n=\"" + key + "\"";
  10403. if(options)
  10404. {
  10405. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  10406. }
  10407. str += ">";
  10408. str += this.translateString(key, options);
  10409. str += "</span>";
  10410. return str;
  10411. }
  10412. };
  10413. },{"../../service/translation/languages":111,"../settings/Settings":41,"i18next-client":63}],46:[function(require,module,exports){
  10414. /*
  10415. * Copyright @ 2015 Atlassian Pty Ltd
  10416. *
  10417. * Licensed under the Apache License, Version 2.0 (the "License");
  10418. * you may not use this file except in compliance with the License.
  10419. * You may obtain a copy of the License at
  10420. *
  10421. * http://www.apache.org/licenses/LICENSE-2.0
  10422. *
  10423. * Unless required by applicable law or agreed to in writing, software
  10424. * distributed under the License is distributed on an "AS IS" BASIS,
  10425. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10426. * See the License for the specific language governing permissions and
  10427. * limitations under the License.
  10428. */
  10429. /* jshint -W117 */
  10430. var TraceablePeerConnection = require("./TraceablePeerConnection");
  10431. var SDPDiffer = require("./SDPDiffer");
  10432. var SDPUtil = require("./SDPUtil");
  10433. var SDP = require("./SDP");
  10434. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  10435. var async = require("async");
  10436. var transform = require("sdp-transform");
  10437. // Jingle stuff
  10438. function JingleSession(me, sid, connection, service) {
  10439. this.me = me;
  10440. this.sid = sid;
  10441. this.connection = connection;
  10442. this.initiator = null;
  10443. this.responder = null;
  10444. this.isInitiator = null;
  10445. this.peerjid = null;
  10446. this.state = null;
  10447. this.localSDP = null;
  10448. this.remoteSDP = null;
  10449. this.relayedStreams = [];
  10450. this.startTime = null;
  10451. this.stopTime = null;
  10452. this.media_constraints = null;
  10453. this.pc_constraints = null;
  10454. this.ice_config = {};
  10455. this.drip_container = [];
  10456. this.service = service;
  10457. this.usetrickle = true;
  10458. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  10459. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  10460. this.hadstuncandidate = false;
  10461. this.hadturncandidate = false;
  10462. this.lasticecandidate = false;
  10463. this.statsinterval = null;
  10464. this.reason = null;
  10465. this.addssrc = [];
  10466. this.removessrc = [];
  10467. this.pendingop = null;
  10468. this.switchstreams = false;
  10469. this.wait = true;
  10470. this.localStreamsSSRC = null;
  10471. /**
  10472. * The indicator which determines whether the (local) video has been muted
  10473. * in response to a user command in contrast to an automatic decision made
  10474. * by the application logic.
  10475. */
  10476. this.videoMuteByUser = false;
  10477. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  10478. // We start with the queue paused. We resume it when the signaling state is
  10479. // stable and the ice connection state is connected.
  10480. this.modifySourcesQueue.pause();
  10481. }
  10482. JingleSession.prototype.updateModifySourcesQueue = function() {
  10483. var signalingState = this.peerconnection.signalingState;
  10484. var iceConnectionState = this.peerconnection.iceConnectionState;
  10485. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  10486. this.modifySourcesQueue.resume();
  10487. } else {
  10488. this.modifySourcesQueue.pause();
  10489. }
  10490. };
  10491. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  10492. var self = this;
  10493. if (this.state !== null) {
  10494. console.error('attempt to initiate on session ' + this.sid +
  10495. 'in state ' + this.state);
  10496. return;
  10497. }
  10498. this.isInitiator = isInitiator;
  10499. this.state = 'pending';
  10500. this.initiator = isInitiator ? this.me : peerjid;
  10501. this.responder = !isInitiator ? this.me : peerjid;
  10502. this.peerjid = peerjid;
  10503. this.hadstuncandidate = false;
  10504. this.hadturncandidate = false;
  10505. this.lasticecandidate = false;
  10506. this.peerconnection
  10507. = new TraceablePeerConnection(
  10508. this.connection.jingle.ice_config,
  10509. this.connection.jingle.pc_constraints );
  10510. this.peerconnection.onicecandidate = function (event) {
  10511. self.sendIceCandidate(event.candidate);
  10512. };
  10513. this.peerconnection.onaddstream = function (event) {
  10514. if (event.stream.id !== 'default') {
  10515. console.log("REMOTE STREAM ADDED: " + event.stream + " - " + event.stream.id);
  10516. self.remoteStreamAdded(event);
  10517. } else {
  10518. // This is a recvonly stream. Clients that implement Unified Plan,
  10519. // such as Firefox use recvonly "streams/channels/tracks" for
  10520. // receiving remote stream/tracks, as opposed to Plan B where there
  10521. // are only 3 channels: audio, video and data.
  10522. console.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  10523. }
  10524. };
  10525. this.peerconnection.onremovestream = function (event) {
  10526. // Remove the stream from remoteStreams
  10527. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  10528. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  10529. };
  10530. this.peerconnection.onsignalingstatechange = function (event) {
  10531. if (!(self && self.peerconnection)) return;
  10532. self.updateModifySourcesQueue();
  10533. };
  10534. this.peerconnection.oniceconnectionstatechange = function (event) {
  10535. if (!(self && self.peerconnection)) return;
  10536. self.updateModifySourcesQueue();
  10537. switch (self.peerconnection.iceConnectionState) {
  10538. case 'connected':
  10539. this.startTime = new Date();
  10540. break;
  10541. case 'disconnected':
  10542. this.stopTime = new Date();
  10543. break;
  10544. }
  10545. onIceConnectionStateChange(self.sid, self);
  10546. };
  10547. // add any local and relayed stream
  10548. APP.RTC.localStreams.forEach(function(stream) {
  10549. self.peerconnection.addStream(stream.getOriginalStream());
  10550. });
  10551. this.relayedStreams.forEach(function(stream) {
  10552. self.peerconnection.addStream(stream);
  10553. });
  10554. };
  10555. function onIceConnectionStateChange(sid, session) {
  10556. switch (session.peerconnection.iceConnectionState) {
  10557. case 'checking':
  10558. session.timeChecking = (new Date()).getTime();
  10559. session.firstconnect = true;
  10560. break;
  10561. case 'completed': // on caller side
  10562. case 'connected':
  10563. if (session.firstconnect) {
  10564. session.firstconnect = false;
  10565. var metadata = {};
  10566. metadata.setupTime
  10567. = (new Date()).getTime() - session.timeChecking;
  10568. session.peerconnection.getStats(function (res) {
  10569. if(res && res.result) {
  10570. res.result().forEach(function (report) {
  10571. if (report.type == 'googCandidatePair' &&
  10572. report.stat('googActiveConnection') == 'true') {
  10573. metadata.localCandidateType
  10574. = report.stat('googLocalCandidateType');
  10575. metadata.remoteCandidateType
  10576. = report.stat('googRemoteCandidateType');
  10577. // log pair as well so we can get nice pie
  10578. // charts
  10579. metadata.candidatePair
  10580. = report.stat('googLocalCandidateType') +
  10581. ';' +
  10582. report.stat('googRemoteCandidateType');
  10583. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  10584. {
  10585. metadata.ipv6 = true;
  10586. }
  10587. }
  10588. });
  10589. }
  10590. });
  10591. }
  10592. break;
  10593. }
  10594. }
  10595. JingleSession.prototype.accept = function () {
  10596. var self = this;
  10597. this.state = 'active';
  10598. var pranswer = this.peerconnection.localDescription;
  10599. if (!pranswer || pranswer.type != 'pranswer') {
  10600. return;
  10601. }
  10602. console.log('going from pranswer to answer');
  10603. if (this.usetrickle) {
  10604. // remove candidates already sent from session-accept
  10605. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  10606. for (var i = 0; i < lines.length; i++) {
  10607. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  10608. }
  10609. }
  10610. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  10611. // FIXME: change any inactive to sendrecv or whatever they were originally
  10612. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  10613. }
  10614. var prsdp = new SDP(pranswer.sdp);
  10615. var accept = $iq({to: this.peerjid,
  10616. type: 'set'})
  10617. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10618. action: 'session-accept',
  10619. initiator: this.initiator,
  10620. responder: this.responder,
  10621. sid: this.sid });
  10622. prsdp.toJingle(accept, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10623. var sdp = this.peerconnection.localDescription.sdp;
  10624. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  10625. // FIXME: change any inactive to sendrecv or whatever they were originally
  10626. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  10627. }
  10628. var self = this;
  10629. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  10630. function () {
  10631. //console.log('setLocalDescription success');
  10632. self.setLocalDescription();
  10633. self.connection.sendIQ(accept,
  10634. function () {
  10635. var ack = {};
  10636. ack.source = 'answer';
  10637. $(document).trigger('ack.jingle', [self.sid, ack]);
  10638. },
  10639. function (stanza) {
  10640. var error = ($(stanza).find('error').length) ? {
  10641. code: $(stanza).find('error').attr('code'),
  10642. reason: $(stanza).find('error :first')[0].tagName
  10643. }:{};
  10644. error.source = 'answer';
  10645. JingleSession.onJingleError(self.sid, error);
  10646. },
  10647. 10000);
  10648. },
  10649. function (e) {
  10650. console.error('setLocalDescription failed', e);
  10651. }
  10652. );
  10653. };
  10654. JingleSession.prototype.terminate = function (reason) {
  10655. this.state = 'ended';
  10656. this.reason = reason;
  10657. this.peerconnection.close();
  10658. if (this.statsinterval !== null) {
  10659. window.clearInterval(this.statsinterval);
  10660. this.statsinterval = null;
  10661. }
  10662. };
  10663. JingleSession.prototype.active = function () {
  10664. return this.state == 'active';
  10665. };
  10666. JingleSession.prototype.sendIceCandidate = function (candidate) {
  10667. var self = this;
  10668. if (candidate && !this.lasticecandidate) {
  10669. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  10670. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  10671. if (!(ice && jcand)) {
  10672. console.error('failed to get ice && jcand');
  10673. return;
  10674. }
  10675. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10676. if (jcand.type === 'srflx') {
  10677. this.hadstuncandidate = true;
  10678. } else if (jcand.type === 'relay') {
  10679. this.hadturncandidate = true;
  10680. }
  10681. if (this.usetrickle) {
  10682. if (this.usedrip) {
  10683. if (this.drip_container.length === 0) {
  10684. // start 20ms callout
  10685. window.setTimeout(function () {
  10686. if (self.drip_container.length === 0) return;
  10687. self.sendIceCandidates(self.drip_container);
  10688. self.drip_container = [];
  10689. }, 20);
  10690. }
  10691. this.drip_container.push(candidate);
  10692. return;
  10693. } else {
  10694. self.sendIceCandidate([candidate]);
  10695. }
  10696. }
  10697. } else {
  10698. //console.log('sendIceCandidate: last candidate.');
  10699. if (!this.usetrickle) {
  10700. //console.log('should send full offer now...');
  10701. var init = $iq({to: this.peerjid,
  10702. type: 'set'})
  10703. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10704. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  10705. initiator: this.initiator,
  10706. sid: this.sid});
  10707. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  10708. var self = this;
  10709. var sendJingle = function (ssrc) {
  10710. if(!ssrc)
  10711. ssrc = {};
  10712. self.localSDP.toJingle(init, self.initiator == self.me ? 'initiator' : 'responder', ssrc);
  10713. self.connection.sendIQ(init,
  10714. function () {
  10715. //console.log('session initiate ack');
  10716. var ack = {};
  10717. ack.source = 'offer';
  10718. $(document).trigger('ack.jingle', [self.sid, ack]);
  10719. },
  10720. function (stanza) {
  10721. self.state = 'error';
  10722. self.peerconnection.close();
  10723. var error = ($(stanza).find('error').length) ? {
  10724. code: $(stanza).find('error').attr('code'),
  10725. reason: $(stanza).find('error :first')[0].tagName,
  10726. }:{};
  10727. error.source = 'offer';
  10728. JingleSession.onJingleError(self.sid, error);
  10729. },
  10730. 10000);
  10731. }
  10732. sendJingle();
  10733. }
  10734. this.lasticecandidate = true;
  10735. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  10736. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  10737. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  10738. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  10739. }
  10740. }
  10741. };
  10742. JingleSession.prototype.sendIceCandidates = function (candidates) {
  10743. console.log('sendIceCandidates', candidates);
  10744. var cand = $iq({to: this.peerjid, type: 'set'})
  10745. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10746. action: 'transport-info',
  10747. initiator: this.initiator,
  10748. sid: this.sid});
  10749. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  10750. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  10751. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  10752. if (cands.length > 0) {
  10753. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  10754. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10755. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  10756. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  10757. }).c('transport', ice);
  10758. for (var i = 0; i < cands.length; i++) {
  10759. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  10760. }
  10761. // add fingerprint
  10762. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  10763. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  10764. tmp.required = true;
  10765. cand.c(
  10766. 'fingerprint',
  10767. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  10768. .t(tmp.fingerprint);
  10769. delete tmp.fingerprint;
  10770. cand.attrs(tmp);
  10771. cand.up();
  10772. }
  10773. cand.up(); // transport
  10774. cand.up(); // content
  10775. }
  10776. }
  10777. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  10778. //console.log('was this the last candidate', this.lasticecandidate);
  10779. this.connection.sendIQ(cand,
  10780. function () {
  10781. var ack = {};
  10782. ack.source = 'transportinfo';
  10783. $(document).trigger('ack.jingle', [this.sid, ack]);
  10784. },
  10785. function (stanza) {
  10786. var error = ($(stanza).find('error').length) ? {
  10787. code: $(stanza).find('error').attr('code'),
  10788. reason: $(stanza).find('error :first')[0].tagName,
  10789. }:{};
  10790. error.source = 'transportinfo';
  10791. JingleSession.onJingleError(this.sid, error);
  10792. },
  10793. 10000);
  10794. };
  10795. JingleSession.prototype.sendOffer = function () {
  10796. //console.log('sendOffer...');
  10797. var self = this;
  10798. this.peerconnection.createOffer(function (sdp) {
  10799. self.createdOffer(sdp);
  10800. },
  10801. function (e) {
  10802. console.error('createOffer failed', e);
  10803. },
  10804. this.media_constraints
  10805. );
  10806. };
  10807. JingleSession.prototype.createdOffer = function (sdp) {
  10808. //console.log('createdOffer', sdp);
  10809. var self = this;
  10810. this.localSDP = new SDP(sdp.sdp);
  10811. //this.localSDP.mangle();
  10812. var sendJingle = function () {
  10813. var init = $iq({to: this.peerjid,
  10814. type: 'set'})
  10815. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10816. action: 'session-initiate',
  10817. initiator: this.initiator,
  10818. sid: this.sid});
  10819. self.localSDP.toJingle(init, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10820. self.connection.sendIQ(init,
  10821. function () {
  10822. var ack = {};
  10823. ack.source = 'offer';
  10824. $(document).trigger('ack.jingle', [self.sid, ack]);
  10825. },
  10826. function (stanza) {
  10827. self.state = 'error';
  10828. self.peerconnection.close();
  10829. var error = ($(stanza).find('error').length) ? {
  10830. code: $(stanza).find('error').attr('code'),
  10831. reason: $(stanza).find('error :first')[0].tagName,
  10832. }:{};
  10833. error.source = 'offer';
  10834. JingleSession.onJingleError(self.sid, error);
  10835. },
  10836. 10000);
  10837. }
  10838. sdp.sdp = this.localSDP.raw;
  10839. this.peerconnection.setLocalDescription(sdp,
  10840. function () {
  10841. if(self.usetrickle)
  10842. {
  10843. sendJingle();
  10844. }
  10845. self.setLocalDescription();
  10846. //console.log('setLocalDescription success');
  10847. },
  10848. function (e) {
  10849. console.error('setLocalDescription failed', e);
  10850. }
  10851. );
  10852. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  10853. for (var i = 0; i < cands.length; i++) {
  10854. var cand = SDPUtil.parse_icecandidate(cands[i]);
  10855. if (cand.type == 'srflx') {
  10856. this.hadstuncandidate = true;
  10857. } else if (cand.type == 'relay') {
  10858. this.hadturncandidate = true;
  10859. }
  10860. }
  10861. };
  10862. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  10863. //console.log('setting remote description... ', desctype);
  10864. this.remoteSDP = new SDP('');
  10865. this.remoteSDP.fromJingle(elem);
  10866. if (this.peerconnection.remoteDescription !== null) {
  10867. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  10868. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  10869. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  10870. for (var i = 0; i < pranswer.media.length; i++) {
  10871. // make sure we have ice ufrag and pwd
  10872. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  10873. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  10874. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  10875. } else {
  10876. console.warn('no ice ufrag?');
  10877. }
  10878. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  10879. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  10880. } else {
  10881. console.warn('no ice pwd?');
  10882. }
  10883. }
  10884. // copy over candidates
  10885. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  10886. for (var j = 0; j < lines.length; j++) {
  10887. this.remoteSDP.media[i] += lines[j] + '\r\n';
  10888. }
  10889. }
  10890. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  10891. }
  10892. }
  10893. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  10894. this.peerconnection.setRemoteDescription(remotedesc,
  10895. function () {
  10896. //console.log('setRemoteDescription success');
  10897. },
  10898. function (e) {
  10899. console.error('setRemoteDescription error', e);
  10900. JingleSession.onJingleFatalError(self, e);
  10901. }
  10902. );
  10903. };
  10904. JingleSession.prototype.addIceCandidate = function (elem) {
  10905. var self = this;
  10906. if (this.peerconnection.signalingState == 'closed') {
  10907. return;
  10908. }
  10909. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  10910. console.log('trickle ice candidate arriving before session accept...');
  10911. // create a PRANSWER for setRemoteDescription
  10912. if (!this.remoteSDP) {
  10913. var cobbled = 'v=0\r\n' +
  10914. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  10915. 's=-\r\n' +
  10916. 't=0 0\r\n';
  10917. // first, take some things from the local description
  10918. for (var i = 0; i < this.localSDP.media.length; i++) {
  10919. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  10920. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  10921. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  10922. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  10923. }
  10924. cobbled += 'a=inactive\r\n';
  10925. }
  10926. this.remoteSDP = new SDP(cobbled);
  10927. }
  10928. // then add things like ice and dtls from remote candidate
  10929. elem.each(function () {
  10930. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  10931. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10932. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10933. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  10934. var tmp = $(this).find('transport');
  10935. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  10936. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  10937. tmp = $(this).find('transport>fingerprint');
  10938. if (tmp.length) {
  10939. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  10940. } else {
  10941. console.log('no dtls fingerprint (webrtc issue #1718?)');
  10942. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  10943. }
  10944. break;
  10945. }
  10946. }
  10947. }
  10948. });
  10949. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  10950. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  10951. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  10952. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  10953. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  10954. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  10955. }).length == this.remoteSDP.media.length;
  10956. if (iscomplete) {
  10957. console.log('setting pranswer');
  10958. try {
  10959. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  10960. function() {
  10961. },
  10962. function(e) {
  10963. console.log('setRemoteDescription pranswer failed', e.toString());
  10964. });
  10965. } catch (e) {
  10966. console.error('setting pranswer failed', e);
  10967. }
  10968. } else {
  10969. //console.log('not yet setting pranswer');
  10970. }
  10971. }
  10972. // operate on each content element
  10973. elem.each(function () {
  10974. // would love to deactivate this, but firefox still requires it
  10975. var idx = -1;
  10976. var i;
  10977. for (i = 0; i < self.remoteSDP.media.length; i++) {
  10978. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10979. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10980. idx = i;
  10981. break;
  10982. }
  10983. }
  10984. if (idx == -1) { // fall back to localdescription
  10985. for (i = 0; i < self.localSDP.media.length; i++) {
  10986. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10987. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10988. idx = i;
  10989. break;
  10990. }
  10991. }
  10992. }
  10993. var name = $(this).attr('name');
  10994. // TODO: check ice-pwd and ice-ufrag?
  10995. $(this).find('transport>candidate').each(function () {
  10996. var line, candidate;
  10997. line = SDPUtil.candidateFromJingle(this);
  10998. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  10999. sdpMid: name,
  11000. candidate: line});
  11001. try {
  11002. self.peerconnection.addIceCandidate(candidate);
  11003. } catch (e) {
  11004. console.error('addIceCandidate failed', e.toString(), line);
  11005. }
  11006. });
  11007. });
  11008. };
  11009. JingleSession.prototype.sendAnswer = function (provisional) {
  11010. //console.log('createAnswer', provisional);
  11011. var self = this;
  11012. this.peerconnection.createAnswer(
  11013. function (sdp) {
  11014. self.createdAnswer(sdp, provisional);
  11015. },
  11016. function (e) {
  11017. console.error('createAnswer failed', e);
  11018. },
  11019. this.media_constraints
  11020. );
  11021. };
  11022. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  11023. //console.log('createAnswer callback');
  11024. var self = this;
  11025. this.localSDP = new SDP(sdp.sdp);
  11026. //this.localSDP.mangle();
  11027. this.usepranswer = provisional === true;
  11028. if (this.usetrickle) {
  11029. if (this.usepranswer) {
  11030. sdp.type = 'pranswer';
  11031. for (var i = 0; i < this.localSDP.media.length; i++) {
  11032. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  11033. }
  11034. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  11035. }
  11036. }
  11037. var self = this;
  11038. var sendJingle = function (ssrcs) {
  11039. var accept = $iq({to: self.peerjid,
  11040. type: 'set'})
  11041. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11042. action: 'session-accept',
  11043. initiator: self.initiator,
  11044. responder: self.responder,
  11045. sid: self.sid });
  11046. self.localSDP.toJingle(accept, self.initiator == self.me ? 'initiator' : 'responder', ssrcs);
  11047. self.connection.sendIQ(accept,
  11048. function () {
  11049. var ack = {};
  11050. ack.source = 'answer';
  11051. $(document).trigger('ack.jingle', [self.sid, ack]);
  11052. },
  11053. function (stanza) {
  11054. var error = ($(stanza).find('error').length) ? {
  11055. code: $(stanza).find('error').attr('code'),
  11056. reason: $(stanza).find('error :first')[0].tagName,
  11057. }:{};
  11058. error.source = 'answer';
  11059. JingleSession.onJingleError(self.sid, error);
  11060. },
  11061. 10000);
  11062. }
  11063. sdp.sdp = this.localSDP.raw;
  11064. this.peerconnection.setLocalDescription(sdp,
  11065. function () {
  11066. //console.log('setLocalDescription success');
  11067. if (self.usetrickle && !self.usepranswer) {
  11068. sendJingle();
  11069. }
  11070. self.setLocalDescription();
  11071. },
  11072. function (e) {
  11073. console.error('setLocalDescription failed', e);
  11074. }
  11075. );
  11076. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  11077. for (var j = 0; j < cands.length; j++) {
  11078. var cand = SDPUtil.parse_icecandidate(cands[j]);
  11079. if (cand.type == 'srflx') {
  11080. this.hadstuncandidate = true;
  11081. } else if (cand.type == 'relay') {
  11082. this.hadturncandidate = true;
  11083. }
  11084. }
  11085. };
  11086. JingleSession.prototype.sendTerminate = function (reason, text) {
  11087. var self = this,
  11088. term = $iq({to: this.peerjid,
  11089. type: 'set'})
  11090. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11091. action: 'session-terminate',
  11092. initiator: this.initiator,
  11093. sid: this.sid})
  11094. .c('reason')
  11095. .c(reason || 'success');
  11096. if (text) {
  11097. term.up().c('text').t(text);
  11098. }
  11099. this.connection.sendIQ(term,
  11100. function () {
  11101. self.peerconnection.close();
  11102. self.peerconnection = null;
  11103. self.terminate();
  11104. var ack = {};
  11105. ack.source = 'terminate';
  11106. $(document).trigger('ack.jingle', [self.sid, ack]);
  11107. },
  11108. function (stanza) {
  11109. var error = ($(stanza).find('error').length) ? {
  11110. code: $(stanza).find('error').attr('code'),
  11111. reason: $(stanza).find('error :first')[0].tagName,
  11112. }:{};
  11113. $(document).trigger('ack.jingle', [self.sid, error]);
  11114. },
  11115. 10000);
  11116. if (this.statsinterval !== null) {
  11117. window.clearInterval(this.statsinterval);
  11118. this.statsinterval = null;
  11119. }
  11120. };
  11121. JingleSession.prototype.addSource = function (elem, fromJid) {
  11122. var self = this;
  11123. // FIXME: dirty waiting
  11124. if (!this.peerconnection.localDescription)
  11125. {
  11126. console.warn("addSource - localDescription not ready yet")
  11127. setTimeout(function()
  11128. {
  11129. self.addSource(elem, fromJid);
  11130. },
  11131. 200
  11132. );
  11133. return;
  11134. }
  11135. console.log('addssrc', new Date().getTime());
  11136. console.log('ice', this.peerconnection.iceConnectionState);
  11137. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11138. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  11139. $(elem).each(function (idx, content) {
  11140. var name = $(content).attr('name');
  11141. var lines = '';
  11142. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  11143. var semantics = this.getAttribute('semantics');
  11144. var ssrcs = $(this).find('>source').map(function () {
  11145. return this.getAttribute('ssrc');
  11146. }).get();
  11147. if (ssrcs.length != 0) {
  11148. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  11149. }
  11150. });
  11151. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  11152. tmp.each(function () {
  11153. var ssrc = $(this).attr('ssrc');
  11154. if(mySdp.containsSSRC(ssrc)){
  11155. /**
  11156. * This happens when multiple participants change their streams at the same time and
  11157. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  11158. * addssrc are scheduled for update IQ. See
  11159. */
  11160. console.warn("Got add stream request for my own ssrc: "+ssrc);
  11161. return;
  11162. }
  11163. $(this).find('>parameter').each(function () {
  11164. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  11165. if ($(this).attr('value') && $(this).attr('value').length)
  11166. lines += ':' + $(this).attr('value');
  11167. lines += '\r\n';
  11168. });
  11169. });
  11170. sdp.media.forEach(function(media, idx) {
  11171. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  11172. return;
  11173. sdp.media[idx] += lines;
  11174. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  11175. self.addssrc[idx] += lines;
  11176. });
  11177. sdp.raw = sdp.session + sdp.media.join('');
  11178. });
  11179. this.modifySourcesQueue.push(function() {
  11180. // When a source is added and if this is FF, a new channel is allocated
  11181. // for receiving the added source. We need to diffuse the SSRC of this
  11182. // new recvonly channel to the rest of the peers.
  11183. console.log('modify sources done');
  11184. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  11185. console.log("SDPs", mySdp, newSdp);
  11186. self.notifyMySSRCUpdate(mySdp, newSdp);
  11187. });
  11188. };
  11189. JingleSession.prototype.removeSource = function (elem, fromJid) {
  11190. var self = this;
  11191. // FIXME: dirty waiting
  11192. if (!this.peerconnection.localDescription)
  11193. {
  11194. console.warn("removeSource - localDescription not ready yet")
  11195. setTimeout(function()
  11196. {
  11197. self.removeSource(elem, fromJid);
  11198. },
  11199. 200
  11200. );
  11201. return;
  11202. }
  11203. console.log('removessrc', new Date().getTime());
  11204. console.log('ice', this.peerconnection.iceConnectionState);
  11205. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11206. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  11207. $(elem).each(function (idx, content) {
  11208. var name = $(content).attr('name');
  11209. var lines = '';
  11210. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  11211. var semantics = this.getAttribute('semantics');
  11212. var ssrcs = $(this).find('>source').map(function () {
  11213. return this.getAttribute('ssrc');
  11214. }).get();
  11215. if (ssrcs.length != 0) {
  11216. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  11217. }
  11218. });
  11219. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  11220. tmp.each(function () {
  11221. var ssrc = $(this).attr('ssrc');
  11222. // This should never happen, but can be useful for bug detection
  11223. if(mySdp.containsSSRC(ssrc)){
  11224. console.error("Got remove stream request for my own ssrc: "+ssrc);
  11225. return;
  11226. }
  11227. $(this).find('>parameter').each(function () {
  11228. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  11229. if ($(this).attr('value') && $(this).attr('value').length)
  11230. lines += ':' + $(this).attr('value');
  11231. lines += '\r\n';
  11232. });
  11233. });
  11234. sdp.media.forEach(function(media, idx) {
  11235. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  11236. return;
  11237. sdp.media[idx] += lines;
  11238. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  11239. self.removessrc[idx] += lines;
  11240. });
  11241. sdp.raw = sdp.session + sdp.media.join('');
  11242. });
  11243. this.modifySourcesQueue.push(function() {
  11244. // When a source is removed and if this is FF, the recvonly channel that
  11245. // receives the remote stream is deactivated . We need to diffuse the
  11246. // recvonly SSRC removal to the rest of the peers.
  11247. console.log('modify sources done');
  11248. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  11249. console.log("SDPs", mySdp, newSdp);
  11250. self.notifyMySSRCUpdate(mySdp, newSdp);
  11251. });
  11252. };
  11253. JingleSession.prototype._modifySources = function (successCallback, queueCallback) {
  11254. var self = this;
  11255. if (this.peerconnection.signalingState == 'closed') return;
  11256. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  11257. // There is nothing to do since scheduled job might have been executed by another succeeding call
  11258. this.setLocalDescription();
  11259. if(successCallback){
  11260. successCallback();
  11261. }
  11262. queueCallback();
  11263. return;
  11264. }
  11265. // Reset switch streams flag
  11266. this.switchstreams = false;
  11267. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11268. // add sources
  11269. this.addssrc.forEach(function(lines, idx) {
  11270. sdp.media[idx] += lines;
  11271. });
  11272. this.addssrc = [];
  11273. // remove sources
  11274. this.removessrc.forEach(function(lines, idx) {
  11275. lines = lines.split('\r\n');
  11276. lines.pop(); // remove empty last element;
  11277. lines.forEach(function(line) {
  11278. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  11279. });
  11280. });
  11281. this.removessrc = [];
  11282. // FIXME:
  11283. // this was a hack for the situation when only one peer exists
  11284. // in the conference.
  11285. // check if still required and remove
  11286. if (sdp.media[0])
  11287. sdp.media[0] = sdp.media[0].replace('a=recvonly', 'a=sendrecv');
  11288. if (sdp.media[1])
  11289. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11290. sdp.raw = sdp.session + sdp.media.join('');
  11291. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  11292. function() {
  11293. if(self.signalingState == 'closed') {
  11294. console.error("createAnswer attempt on closed state");
  11295. queueCallback("createAnswer attempt on closed state");
  11296. return;
  11297. }
  11298. self.peerconnection.createAnswer(
  11299. function(modifiedAnswer) {
  11300. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  11301. if (self.pendingop !== null) {
  11302. var sdp = new SDP(modifiedAnswer.sdp);
  11303. if (sdp.media.length > 1) {
  11304. switch(self.pendingop) {
  11305. case 'mute':
  11306. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  11307. break;
  11308. case 'unmute':
  11309. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11310. break;
  11311. }
  11312. sdp.raw = sdp.session + sdp.media.join('');
  11313. modifiedAnswer.sdp = sdp.raw;
  11314. }
  11315. self.pendingop = null;
  11316. }
  11317. // FIXME: pushing down an answer while ice connection state
  11318. // is still checking is bad...
  11319. //console.log(self.peerconnection.iceConnectionState);
  11320. // trying to work around another chrome bug
  11321. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  11322. self.peerconnection.setLocalDescription(modifiedAnswer,
  11323. function() {
  11324. //console.log('modified setLocalDescription ok');
  11325. self.setLocalDescription();
  11326. if(successCallback){
  11327. successCallback();
  11328. }
  11329. queueCallback();
  11330. },
  11331. function(error) {
  11332. console.error('modified setLocalDescription failed', error);
  11333. queueCallback(error);
  11334. }
  11335. );
  11336. },
  11337. function(error) {
  11338. console.error('modified answer failed', error);
  11339. queueCallback(error);
  11340. }
  11341. );
  11342. },
  11343. function(error) {
  11344. console.error('modify failed', error);
  11345. queueCallback(error);
  11346. }
  11347. );
  11348. };
  11349. /**
  11350. * Switches video streams.
  11351. * @param new_stream new stream that will be used as video of this session.
  11352. * @param oldStream old video stream of this session.
  11353. * @param success_callback callback executed after successful stream switch.
  11354. */
  11355. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback, isAudio) {
  11356. var self = this;
  11357. // Remember SDP to figure out added/removed SSRCs
  11358. var oldSdp = null;
  11359. if(self.peerconnection) {
  11360. if(self.peerconnection.localDescription) {
  11361. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  11362. }
  11363. self.peerconnection.removeStream(oldStream, true);
  11364. if(new_stream)
  11365. self.peerconnection.addStream(new_stream);
  11366. }
  11367. if(!isAudio)
  11368. APP.RTC.switchVideoStreams(new_stream, oldStream);
  11369. // Conference is not active
  11370. if(!oldSdp || !self.peerconnection) {
  11371. success_callback();
  11372. return;
  11373. }
  11374. self.switchstreams = true;
  11375. self.modifySourcesQueue.push(function() {
  11376. console.log('modify sources done');
  11377. success_callback();
  11378. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  11379. console.log("SDPs", oldSdp, newSdp);
  11380. self.notifyMySSRCUpdate(oldSdp, newSdp);
  11381. });
  11382. };
  11383. /**
  11384. * Figures out added/removed ssrcs and send update IQs.
  11385. * @param old_sdp SDP object for old description.
  11386. * @param new_sdp SDP object for new description.
  11387. */
  11388. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  11389. if (!(this.peerconnection.signalingState == 'stable' &&
  11390. this.peerconnection.iceConnectionState == 'connected')){
  11391. console.log("Too early to send updates");
  11392. return;
  11393. }
  11394. // send source-remove IQ.
  11395. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  11396. var remove = $iq({to: this.peerjid, type: 'set'})
  11397. .c('jingle', {
  11398. xmlns: 'urn:xmpp:jingle:1',
  11399. action: 'source-remove',
  11400. initiator: this.initiator,
  11401. sid: this.sid
  11402. }
  11403. );
  11404. var removed = sdpDiffer.toJingle(remove);
  11405. if (removed) {
  11406. this.connection.sendIQ(remove,
  11407. function (res) {
  11408. console.info('got remove result', res);
  11409. },
  11410. function (err) {
  11411. console.error('got remove error', err);
  11412. }
  11413. );
  11414. } else {
  11415. console.log('removal not necessary');
  11416. }
  11417. // send source-add IQ.
  11418. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  11419. var add = $iq({to: this.peerjid, type: 'set'})
  11420. .c('jingle', {
  11421. xmlns: 'urn:xmpp:jingle:1',
  11422. action: 'source-add',
  11423. initiator: this.initiator,
  11424. sid: this.sid
  11425. }
  11426. );
  11427. var added = sdpDiffer.toJingle(add);
  11428. if (added) {
  11429. this.connection.sendIQ(add,
  11430. function (res) {
  11431. console.info('got add result', res);
  11432. },
  11433. function (err) {
  11434. console.error('got add error', err);
  11435. }
  11436. );
  11437. } else {
  11438. console.log('addition not necessary');
  11439. }
  11440. };
  11441. /**
  11442. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  11443. *
  11444. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  11445. * tracks; otherwise, <tt>false</tt>
  11446. * @param callback a function to be invoked with <tt>mute</tt> after all video
  11447. * tracks have been enabled/disabled. The function may, optionally, return
  11448. * another function which is to be invoked after the whole mute/unmute operation
  11449. * has completed successfully.
  11450. * @param options an object which specifies optional arguments such as the
  11451. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  11452. * specifies whether the method was initiated in response to a user command (in
  11453. * contrast to an automatic decision made by the application logic)
  11454. */
  11455. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  11456. var byUser;
  11457. if (options) {
  11458. byUser = options.byUser;
  11459. if (typeof byUser === 'undefined') {
  11460. byUser = true;
  11461. }
  11462. } else {
  11463. byUser = true;
  11464. }
  11465. // The user's command to mute the (local) video takes precedence over any
  11466. // automatic decision made by the application logic.
  11467. if (byUser) {
  11468. this.videoMuteByUser = mute;
  11469. } else if (this.videoMuteByUser) {
  11470. return;
  11471. }
  11472. this.hardMuteVideo(mute);
  11473. var self = this;
  11474. var oldSdp = null;
  11475. if(self.peerconnection) {
  11476. if(self.peerconnection.localDescription) {
  11477. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  11478. }
  11479. }
  11480. this.modifySourcesQueue.push(function() {
  11481. console.log('modify sources done');
  11482. callback(mute);
  11483. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  11484. console.log("SDPs", oldSdp, newSdp);
  11485. self.notifyMySSRCUpdate(oldSdp, newSdp);
  11486. });
  11487. };
  11488. JingleSession.prototype.hardMuteVideo = function (muted) {
  11489. this.pendingop = muted ? 'mute' : 'unmute';
  11490. };
  11491. JingleSession.prototype.sendMute = function (muted, content) {
  11492. var info = $iq({to: this.peerjid,
  11493. type: 'set'})
  11494. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11495. action: 'session-info',
  11496. initiator: this.initiator,
  11497. sid: this.sid });
  11498. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11499. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  11500. if (content) {
  11501. info.attrs({'name': content});
  11502. }
  11503. this.connection.send(info);
  11504. };
  11505. JingleSession.prototype.sendRinging = function () {
  11506. var info = $iq({to: this.peerjid,
  11507. type: 'set'})
  11508. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11509. action: 'session-info',
  11510. initiator: this.initiator,
  11511. sid: this.sid });
  11512. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11513. this.connection.send(info);
  11514. };
  11515. JingleSession.prototype.getStats = function (interval) {
  11516. var self = this;
  11517. var recv = {audio: 0, video: 0};
  11518. var lost = {audio: 0, video: 0};
  11519. var lastrecv = {audio: 0, video: 0};
  11520. var lastlost = {audio: 0, video: 0};
  11521. var loss = {audio: 0, video: 0};
  11522. var delta = {audio: 0, video: 0};
  11523. this.statsinterval = window.setInterval(function () {
  11524. if (self && self.peerconnection && self.peerconnection.getStats) {
  11525. self.peerconnection.getStats(function (stats) {
  11526. var results = stats.result();
  11527. // TODO: there are so much statistics you can get from this..
  11528. for (var i = 0; i < results.length; ++i) {
  11529. if (results[i].type == 'ssrc') {
  11530. var packetsrecv = results[i].stat('packetsReceived');
  11531. var packetslost = results[i].stat('packetsLost');
  11532. if (packetsrecv && packetslost) {
  11533. packetsrecv = parseInt(packetsrecv, 10);
  11534. packetslost = parseInt(packetslost, 10);
  11535. if (results[i].stat('googFrameRateReceived')) {
  11536. lastlost.video = lost.video;
  11537. lastrecv.video = recv.video;
  11538. recv.video = packetsrecv;
  11539. lost.video = packetslost;
  11540. } else {
  11541. lastlost.audio = lost.audio;
  11542. lastrecv.audio = recv.audio;
  11543. recv.audio = packetsrecv;
  11544. lost.audio = packetslost;
  11545. }
  11546. }
  11547. }
  11548. }
  11549. delta.audio = recv.audio - lastrecv.audio;
  11550. delta.video = recv.video - lastrecv.video;
  11551. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  11552. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  11553. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  11554. });
  11555. }
  11556. }, interval || 3000);
  11557. return this.statsinterval;
  11558. };
  11559. JingleSession.onJingleError = function (session, error)
  11560. {
  11561. console.error("Jingle error", error);
  11562. }
  11563. JingleSession.onJingleFatalError = function (session, error)
  11564. {
  11565. this.service.sessionTerminated = true;
  11566. this.connection.emuc.doLeave();
  11567. APP.UI.messageHandler.showError("dialog.sorry",
  11568. "dialog.internalError");
  11569. }
  11570. JingleSession.prototype.setLocalDescription = function () {
  11571. // put our ssrcs into presence so other clients can identify our stream
  11572. var newssrcs = [];
  11573. var session = transform.parse(this.peerconnection.localDescription.sdp);
  11574. session.media.forEach(function (media) {
  11575. if (media.ssrcs != null && media.ssrcs.length > 0) {
  11576. // TODO(gp) maybe exclude FID streams?
  11577. media.ssrcs.forEach(function (ssrc) {
  11578. if (ssrc.attribute !== 'cname') {
  11579. return;
  11580. }
  11581. newssrcs.push({
  11582. 'ssrc': ssrc.id,
  11583. 'type': media.type,
  11584. 'direction': media.direction
  11585. });
  11586. });
  11587. }
  11588. else if(this.localStreamsSSRC && this.localStreamsSSRC[media.type])
  11589. {
  11590. newssrcs.push({
  11591. 'ssrc': this.localStreamsSSRC[media.type],
  11592. 'type': media.type,
  11593. 'direction': media.direction
  11594. });
  11595. }
  11596. });
  11597. console.log('new ssrcs', newssrcs);
  11598. // Have to clear presence map to get rid of removed streams
  11599. this.connection.emuc.clearPresenceMedia();
  11600. if (newssrcs.length > 0) {
  11601. for (var i = 1; i <= newssrcs.length; i ++) {
  11602. // Change video type to screen
  11603. if (newssrcs[i-1].type === 'video' && APP.desktopsharing.isUsingScreenStream()) {
  11604. newssrcs[i-1].type = 'screen';
  11605. }
  11606. this.connection.emuc.addMediaToPresence(i,
  11607. newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
  11608. }
  11609. this.connection.emuc.sendPresence();
  11610. }
  11611. }
  11612. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11613. function sendKeyframe(pc) {
  11614. console.log('sendkeyframe', pc.iceConnectionState);
  11615. if (pc.iceConnectionState !== 'connected') return; // safe...
  11616. pc.setRemoteDescription(
  11617. pc.remoteDescription,
  11618. function () {
  11619. pc.createAnswer(
  11620. function (modifiedAnswer) {
  11621. pc.setLocalDescription(
  11622. modifiedAnswer,
  11623. function () {
  11624. // noop
  11625. },
  11626. function (error) {
  11627. console.log('triggerKeyframe setLocalDescription failed', error);
  11628. APP.UI.messageHandler.showError();
  11629. }
  11630. );
  11631. },
  11632. function (error) {
  11633. console.log('triggerKeyframe createAnswer failed', error);
  11634. APP.UI.messageHandler.showError();
  11635. }
  11636. );
  11637. },
  11638. function (error) {
  11639. console.log('triggerKeyframe setRemoteDescription failed', error);
  11640. APP.UI.messageHandler.showError();
  11641. }
  11642. );
  11643. }
  11644. JingleSession.prototype.remoteStreamAdded = function (data, times) {
  11645. var self = this;
  11646. var thessrc;
  11647. var ssrc2jid = this.connection.emuc.ssrc2jid;
  11648. // look up an associated JID for a stream id
  11649. if (data.stream.id && data.stream.id.indexOf('mixedmslabel') === -1) {
  11650. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  11651. var ssrclines
  11652. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  11653. ssrclines = ssrclines.filter(function (line) {
  11654. // NOTE(gp) previously we filtered on the mslabel, but that property
  11655. // is not always present.
  11656. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  11657. return ((line.indexOf('msid:' + data.stream.id) !== -1));
  11658. });
  11659. if (ssrclines.length) {
  11660. thessrc = ssrclines[0].substring(7).split(' ')[0];
  11661. // We signal our streams (through Jingle to the focus) before we set
  11662. // our presence (through which peers associate remote streams to
  11663. // jids). So, it might arrive that a remote stream is added but
  11664. // ssrc2jid is not yet updated and thus data.peerjid cannot be
  11665. // successfully set. Here we wait for up to a second for the
  11666. // presence to arrive.
  11667. if (!ssrc2jid[thessrc]) {
  11668. if (typeof times === 'undefined')
  11669. {
  11670. times = 0;
  11671. }
  11672. if (times > 10)
  11673. {
  11674. console.warning('Waiting for jid timed out', thessrc);
  11675. }
  11676. else
  11677. {
  11678. setTimeout(function(d) {
  11679. return function() {
  11680. self.remoteStreamAdded(d, times++);
  11681. }
  11682. }(data), 250);
  11683. }
  11684. return;
  11685. }
  11686. // ok to overwrite the one from focus? might save work in colibri.js
  11687. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  11688. if (ssrc2jid[thessrc]) {
  11689. data.peerjid = ssrc2jid[thessrc];
  11690. }
  11691. }
  11692. }
  11693. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  11694. var isVideo = data.stream.getVideoTracks().length > 0;
  11695. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11696. if (isVideo &&
  11697. data.peerjid && this.peerjid === data.peerjid &&
  11698. data.stream.getVideoTracks().length === 0 &&
  11699. APP.RTC.localVideo.getTracks().length > 0) {
  11700. window.setTimeout(function () {
  11701. sendKeyframe(self.peerconnection);
  11702. }, 3000);
  11703. }
  11704. }
  11705. module.exports = JingleSession;
  11706. },{"../../service/RTC/RTCBrowserType":102,"./SDP":47,"./SDPDiffer":48,"./SDPUtil":49,"./TraceablePeerConnection":50,"async":60,"sdp-transform":98}],47:[function(require,module,exports){
  11707. /*
  11708. * Copyright @ 2015 Atlassian Pty Ltd
  11709. *
  11710. * Licensed under the Apache License, Version 2.0 (the "License");
  11711. * you may not use this file except in compliance with the License.
  11712. * You may obtain a copy of the License at
  11713. *
  11714. * http://www.apache.org/licenses/LICENSE-2.0
  11715. *
  11716. * Unless required by applicable law or agreed to in writing, software
  11717. * distributed under the License is distributed on an "AS IS" BASIS,
  11718. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11719. * See the License for the specific language governing permissions and
  11720. * limitations under the License.
  11721. */
  11722. /* jshint -W117 */
  11723. var SDPUtil = require("./SDPUtil");
  11724. // SDP STUFF
  11725. function SDP(sdp) {
  11726. this.media = sdp.split('\r\nm=');
  11727. for (var i = 1; i < this.media.length; i++) {
  11728. this.media[i] = 'm=' + this.media[i];
  11729. if (i != this.media.length - 1) {
  11730. this.media[i] += '\r\n';
  11731. }
  11732. }
  11733. this.session = this.media.shift() + '\r\n';
  11734. this.raw = this.session + this.media.join('');
  11735. }
  11736. /**
  11737. * Returns map of MediaChannel mapped per channel idx.
  11738. */
  11739. SDP.prototype.getMediaSsrcMap = function() {
  11740. var self = this;
  11741. var media_ssrcs = {};
  11742. var tmp;
  11743. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  11744. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  11745. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  11746. var media = {
  11747. mediaindex: mediaindex,
  11748. mid: mid,
  11749. ssrcs: {},
  11750. ssrcGroups: []
  11751. };
  11752. media_ssrcs[mediaindex] = media;
  11753. tmp.forEach(function (line) {
  11754. var linessrc = line.substring(7).split(' ')[0];
  11755. // allocate new ChannelSsrc
  11756. if(!media.ssrcs[linessrc]) {
  11757. media.ssrcs[linessrc] = {
  11758. ssrc: linessrc,
  11759. lines: []
  11760. };
  11761. }
  11762. media.ssrcs[linessrc].lines.push(line);
  11763. });
  11764. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  11765. tmp.forEach(function(line){
  11766. var semantics = line.substr(0, idx).substr(13);
  11767. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11768. if (ssrcs.length != 0) {
  11769. media.ssrcGroups.push({
  11770. semantics: semantics,
  11771. ssrcs: ssrcs
  11772. });
  11773. }
  11774. });
  11775. }
  11776. return media_ssrcs;
  11777. };
  11778. /**
  11779. * Returns <tt>true</tt> if this SDP contains given SSRC.
  11780. * @param ssrc the ssrc to check.
  11781. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  11782. */
  11783. SDP.prototype.containsSSRC = function(ssrc) {
  11784. var medias = this.getMediaSsrcMap();
  11785. var contains = false;
  11786. Object.keys(medias).forEach(function(mediaindex){
  11787. var media = medias[mediaindex];
  11788. //console.log("Check", channel, ssrc);
  11789. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  11790. contains = true;
  11791. }
  11792. });
  11793. return contains;
  11794. };
  11795. // remove iSAC and CN from SDP
  11796. SDP.prototype.mangle = function () {
  11797. var i, j, mline, lines, rtpmap, newdesc;
  11798. for (i = 0; i < this.media.length; i++) {
  11799. lines = this.media[i].split('\r\n');
  11800. lines.pop(); // remove empty last element
  11801. mline = SDPUtil.parse_mline(lines.shift());
  11802. if (mline.media != 'audio')
  11803. continue;
  11804. newdesc = '';
  11805. mline.fmt.length = 0;
  11806. for (j = 0; j < lines.length; j++) {
  11807. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  11808. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  11809. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  11810. continue;
  11811. mline.fmt.push(rtpmap.id);
  11812. newdesc += lines[j] + '\r\n';
  11813. } else {
  11814. newdesc += lines[j] + '\r\n';
  11815. }
  11816. }
  11817. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  11818. this.media[i] += newdesc;
  11819. }
  11820. this.raw = this.session + this.media.join('');
  11821. };
  11822. // remove lines matching prefix from session section
  11823. SDP.prototype.removeSessionLines = function(prefix) {
  11824. var self = this;
  11825. var lines = SDPUtil.find_lines(this.session, prefix);
  11826. lines.forEach(function(line) {
  11827. self.session = self.session.replace(line + '\r\n', '');
  11828. });
  11829. this.raw = this.session + this.media.join('');
  11830. return lines;
  11831. }
  11832. // remove lines matching prefix from a media section specified by mediaindex
  11833. // TODO: non-numeric mediaindex could match mid
  11834. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  11835. var self = this;
  11836. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  11837. lines.forEach(function(line) {
  11838. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  11839. });
  11840. this.raw = this.session + this.media.join('');
  11841. return lines;
  11842. }
  11843. // add content's to a jingle element
  11844. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  11845. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  11846. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  11847. var self = this;
  11848. // new bundle plan
  11849. if (SDPUtil.find_line(this.session, 'a=group:')) {
  11850. lines = SDPUtil.find_lines(this.session, 'a=group:');
  11851. for (i = 0; i < lines.length; i++) {
  11852. tmp = lines[i].split(' ');
  11853. var semantics = tmp.shift().substr(8);
  11854. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  11855. for (j = 0; j < tmp.length; j++) {
  11856. elem.c('content', {name: tmp[j]}).up();
  11857. }
  11858. elem.up();
  11859. }
  11860. }
  11861. for (i = 0; i < this.media.length; i++) {
  11862. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  11863. if (!(mline.media === 'audio' ||
  11864. mline.media === 'video' ||
  11865. mline.media === 'application'))
  11866. {
  11867. continue;
  11868. }
  11869. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  11870. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  11871. } else {
  11872. if(ssrcs && ssrcs[mline.media])
  11873. {
  11874. ssrc = ssrcs[mline.media];
  11875. }
  11876. else
  11877. ssrc = false;
  11878. }
  11879. elem.c('content', {creator: thecreator, name: mline.media});
  11880. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  11881. // prefer identifier from a=mid if present
  11882. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  11883. elem.attrs({ name: mid });
  11884. }
  11885. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  11886. {
  11887. elem.c('description',
  11888. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  11889. media: mline.media });
  11890. if (ssrc) {
  11891. elem.attrs({ssrc: ssrc});
  11892. }
  11893. for (j = 0; j < mline.fmt.length; j++) {
  11894. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  11895. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  11896. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  11897. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  11898. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  11899. for (k = 0; k < tmp.length; k++) {
  11900. elem.c('parameter', tmp[k]).up();
  11901. }
  11902. }
  11903. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  11904. elem.up();
  11905. }
  11906. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  11907. elem.c('encryption', {required: 1});
  11908. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  11909. crypto.forEach(function(line) {
  11910. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  11911. });
  11912. elem.up(); // end of encryption
  11913. }
  11914. if (ssrc) {
  11915. // new style mapping
  11916. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11917. // FIXME: group by ssrc and support multiple different ssrcs
  11918. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  11919. if(ssrclines.length > 0) {
  11920. ssrclines.forEach(function (line) {
  11921. idx = line.indexOf(' ');
  11922. var linessrc = line.substr(0, idx).substr(7);
  11923. if (linessrc != ssrc) {
  11924. elem.up();
  11925. ssrc = linessrc;
  11926. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11927. }
  11928. var kv = line.substr(idx + 1);
  11929. elem.c('parameter');
  11930. if (kv.indexOf(':') == -1) {
  11931. elem.attrs({ name: kv });
  11932. } else {
  11933. elem.attrs({ name: kv.split(':', 2)[0] });
  11934. elem.attrs({ value: kv.split(':', 2)[1] });
  11935. }
  11936. elem.up();
  11937. });
  11938. elem.up();
  11939. }
  11940. else
  11941. {
  11942. elem.up();
  11943. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11944. elem.c('parameter');
  11945. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  11946. elem.up();
  11947. var msid = null;
  11948. if(mline.media == "audio")
  11949. {
  11950. msid = APP.RTC.localAudio.getId();
  11951. }
  11952. else
  11953. {
  11954. msid = APP.RTC.localVideo.getId();
  11955. }
  11956. if(msid != null)
  11957. {
  11958. msid = msid.replace(/[\{,\}]/g,"");
  11959. elem.c('parameter');
  11960. elem.attrs({name: "msid", value:msid});
  11961. elem.up();
  11962. elem.c('parameter');
  11963. elem.attrs({name: "mslabel", value:msid});
  11964. elem.up();
  11965. elem.c('parameter');
  11966. elem.attrs({name: "label", value:msid});
  11967. elem.up();
  11968. elem.up();
  11969. }
  11970. }
  11971. // XEP-0339 handle ssrc-group attributes
  11972. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  11973. ssrc_group_lines.forEach(function(line) {
  11974. idx = line.indexOf(' ');
  11975. var semantics = line.substr(0, idx).substr(13);
  11976. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11977. if (ssrcs.length != 0) {
  11978. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11979. ssrcs.forEach(function(ssrc) {
  11980. elem.c('source', { ssrc: ssrc })
  11981. .up();
  11982. });
  11983. elem.up();
  11984. }
  11985. });
  11986. }
  11987. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  11988. elem.c('rtcp-mux').up();
  11989. }
  11990. // XEP-0293 -- map a=rtcp-fb:*
  11991. this.RtcpFbToJingle(i, elem, '*');
  11992. // XEP-0294
  11993. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  11994. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  11995. for (j = 0; j < lines.length; j++) {
  11996. tmp = SDPUtil.parse_extmap(lines[j]);
  11997. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  11998. uri: tmp.uri,
  11999. id: tmp.value });
  12000. if (tmp.hasOwnProperty('direction')) {
  12001. switch (tmp.direction) {
  12002. case 'sendonly':
  12003. elem.attrs({senders: 'responder'});
  12004. break;
  12005. case 'recvonly':
  12006. elem.attrs({senders: 'initiator'});
  12007. break;
  12008. case 'sendrecv':
  12009. elem.attrs({senders: 'both'});
  12010. break;
  12011. case 'inactive':
  12012. elem.attrs({senders: 'none'});
  12013. break;
  12014. }
  12015. }
  12016. // TODO: handle params
  12017. elem.up();
  12018. }
  12019. }
  12020. elem.up(); // end of description
  12021. }
  12022. // map ice-ufrag/pwd, dtls fingerprint, candidates
  12023. this.TransportToJingle(i, elem);
  12024. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  12025. elem.attrs({senders: 'both'});
  12026. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  12027. elem.attrs({senders: 'initiator'});
  12028. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  12029. elem.attrs({senders: 'responder'});
  12030. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  12031. elem.attrs({senders: 'none'});
  12032. }
  12033. if (mline.port == '0') {
  12034. // estos hack to reject an m-line
  12035. elem.attrs({senders: 'rejected'});
  12036. }
  12037. elem.up(); // end of content
  12038. }
  12039. elem.up();
  12040. return elem;
  12041. };
  12042. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  12043. var i = mediaindex;
  12044. var tmp;
  12045. var self = this;
  12046. elem.c('transport');
  12047. // XEP-0343 DTLS/SCTP
  12048. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  12049. {
  12050. var sctpmap = SDPUtil.find_line(
  12051. this.media[i], 'a=sctpmap:', self.session);
  12052. if (sctpmap)
  12053. {
  12054. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  12055. elem.c('sctpmap',
  12056. {
  12057. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  12058. number: sctpAttrs[0], /* SCTP port */
  12059. protocol: sctpAttrs[1], /* protocol */
  12060. });
  12061. // Optional stream count attribute
  12062. if (sctpAttrs.length > 2)
  12063. elem.attrs({ streams: sctpAttrs[2]});
  12064. elem.up();
  12065. }
  12066. }
  12067. // XEP-0320
  12068. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  12069. fingerprints.forEach(function(line) {
  12070. tmp = SDPUtil.parse_fingerprint(line);
  12071. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  12072. elem.c('fingerprint').t(tmp.fingerprint);
  12073. delete tmp.fingerprint;
  12074. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  12075. if (line) {
  12076. tmp.setup = line.substr(8);
  12077. }
  12078. elem.attrs(tmp);
  12079. elem.up(); // end of fingerprint
  12080. });
  12081. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  12082. if (tmp) {
  12083. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  12084. elem.attrs(tmp);
  12085. // XEP-0176
  12086. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  12087. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  12088. lines.forEach(function (line) {
  12089. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  12090. });
  12091. }
  12092. }
  12093. elem.up(); // end of transport
  12094. }
  12095. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  12096. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  12097. lines.forEach(function (line) {
  12098. var tmp = SDPUtil.parse_rtcpfb(line);
  12099. if (tmp.type == 'trr-int') {
  12100. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  12101. elem.up();
  12102. } else {
  12103. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  12104. if (tmp.params.length > 0) {
  12105. elem.attrs({'subtype': tmp.params[0]});
  12106. }
  12107. elem.up();
  12108. }
  12109. });
  12110. };
  12111. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  12112. var media = '';
  12113. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  12114. if (tmp.length) {
  12115. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  12116. if (tmp.attr('value')) {
  12117. media += tmp.attr('value');
  12118. } else {
  12119. media += '0';
  12120. }
  12121. media += '\r\n';
  12122. }
  12123. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  12124. tmp.each(function () {
  12125. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  12126. if ($(this).attr('subtype')) {
  12127. media += ' ' + $(this).attr('subtype');
  12128. }
  12129. media += '\r\n';
  12130. });
  12131. return media;
  12132. };
  12133. // construct an SDP from a jingle stanza
  12134. SDP.prototype.fromJingle = function (jingle) {
  12135. var self = this;
  12136. this.raw = 'v=0\r\n' +
  12137. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  12138. 's=-\r\n' +
  12139. 't=0 0\r\n';
  12140. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  12141. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  12142. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  12143. var contents = $(group).find('>content').map(function (idx, content) {
  12144. return content.getAttribute('name');
  12145. }).get();
  12146. if (contents.length > 0) {
  12147. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  12148. }
  12149. });
  12150. }
  12151. this.session = this.raw;
  12152. jingle.find('>content').each(function () {
  12153. var m = self.jingle2media($(this));
  12154. self.media.push(m);
  12155. });
  12156. // reconstruct msid-semantic -- apparently not necessary
  12157. /*
  12158. var msid = SDPUtil.parse_ssrc(this.raw);
  12159. if (msid.hasOwnProperty('mslabel')) {
  12160. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  12161. }
  12162. */
  12163. this.raw = this.session + this.media.join('');
  12164. };
  12165. // translate a jingle content element into an an SDP media part
  12166. SDP.prototype.jingle2media = function (content) {
  12167. var media = '',
  12168. desc = content.find('description'),
  12169. ssrc = desc.attr('ssrc'),
  12170. self = this,
  12171. tmp;
  12172. var sctp = content.find(
  12173. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  12174. tmp = { media: desc.attr('media') };
  12175. tmp.port = '1';
  12176. if (content.attr('senders') == 'rejected') {
  12177. // estos hack to reject an m-line.
  12178. tmp.port = '0';
  12179. }
  12180. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  12181. if (sctp.length)
  12182. tmp.proto = 'DTLS/SCTP';
  12183. else
  12184. tmp.proto = 'RTP/SAVPF';
  12185. } else {
  12186. tmp.proto = 'RTP/AVPF';
  12187. }
  12188. if (!sctp.length)
  12189. {
  12190. tmp.fmt = desc.find('payload-type').map(
  12191. function () { return this.getAttribute('id'); }).get();
  12192. media += SDPUtil.build_mline(tmp) + '\r\n';
  12193. }
  12194. else
  12195. {
  12196. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  12197. media += 'a=sctpmap:' + sctp.attr('number') +
  12198. ' ' + sctp.attr('protocol');
  12199. var streamCount = sctp.attr('streams');
  12200. if (streamCount)
  12201. media += ' ' + streamCount + '\r\n';
  12202. else
  12203. media += '\r\n';
  12204. }
  12205. media += 'c=IN IP4 0.0.0.0\r\n';
  12206. if (!sctp.length)
  12207. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  12208. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  12209. if (tmp.length) {
  12210. if (tmp.attr('ufrag')) {
  12211. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  12212. }
  12213. if (tmp.attr('pwd')) {
  12214. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  12215. }
  12216. tmp.find('>fingerprint').each(function () {
  12217. // FIXME: check namespace at some point
  12218. media += 'a=fingerprint:' + this.getAttribute('hash');
  12219. media += ' ' + $(this).text();
  12220. media += '\r\n';
  12221. if (this.getAttribute('setup')) {
  12222. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  12223. }
  12224. });
  12225. }
  12226. switch (content.attr('senders')) {
  12227. case 'initiator':
  12228. media += 'a=sendonly\r\n';
  12229. break;
  12230. case 'responder':
  12231. media += 'a=recvonly\r\n';
  12232. break;
  12233. case 'none':
  12234. media += 'a=inactive\r\n';
  12235. break;
  12236. case 'both':
  12237. media += 'a=sendrecv\r\n';
  12238. break;
  12239. }
  12240. media += 'a=mid:' + content.attr('name') + '\r\n';
  12241. // <description><rtcp-mux/></description>
  12242. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  12243. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  12244. if (desc.find('rtcp-mux').length) {
  12245. media += 'a=rtcp-mux\r\n';
  12246. }
  12247. if (desc.find('encryption').length) {
  12248. desc.find('encryption>crypto').each(function () {
  12249. media += 'a=crypto:' + this.getAttribute('tag');
  12250. media += ' ' + this.getAttribute('crypto-suite');
  12251. media += ' ' + this.getAttribute('key-params');
  12252. if (this.getAttribute('session-params')) {
  12253. media += ' ' + this.getAttribute('session-params');
  12254. }
  12255. media += '\r\n';
  12256. });
  12257. }
  12258. desc.find('payload-type').each(function () {
  12259. media += SDPUtil.build_rtpmap(this) + '\r\n';
  12260. if ($(this).find('>parameter').length) {
  12261. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  12262. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  12263. media += '\r\n';
  12264. }
  12265. // xep-0293
  12266. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  12267. });
  12268. // xep-0293
  12269. media += self.RtcpFbFromJingle(desc, '*');
  12270. // xep-0294
  12271. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  12272. tmp.each(function () {
  12273. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  12274. });
  12275. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  12276. media += SDPUtil.candidateFromJingle(this);
  12277. });
  12278. // XEP-0339 handle ssrc-group attributes
  12279. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12280. var semantics = this.getAttribute('semantics');
  12281. var ssrcs = $(this).find('>source').map(function() {
  12282. return this.getAttribute('ssrc');
  12283. }).get();
  12284. if (ssrcs.length != 0) {
  12285. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12286. }
  12287. });
  12288. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  12289. tmp.each(function () {
  12290. var ssrc = this.getAttribute('ssrc');
  12291. $(this).find('>parameter').each(function () {
  12292. media += 'a=ssrc:' + ssrc + ' ' + this.getAttribute('name');
  12293. if (this.getAttribute('value') && this.getAttribute('value').length)
  12294. media += ':' + this.getAttribute('value');
  12295. media += '\r\n';
  12296. });
  12297. });
  12298. return media;
  12299. };
  12300. module.exports = SDP;
  12301. },{"./SDPUtil":49}],48:[function(require,module,exports){
  12302. /*
  12303. * Copyright @ 2015 Atlassian Pty Ltd
  12304. *
  12305. * Licensed under the Apache License, Version 2.0 (the "License");
  12306. * you may not use this file except in compliance with the License.
  12307. * You may obtain a copy of the License at
  12308. *
  12309. * http://www.apache.org/licenses/LICENSE-2.0
  12310. *
  12311. * Unless required by applicable law or agreed to in writing, software
  12312. * distributed under the License is distributed on an "AS IS" BASIS,
  12313. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12314. * See the License for the specific language governing permissions and
  12315. * limitations under the License.
  12316. */
  12317. function SDPDiffer(mySDP, otherSDP) {
  12318. this.mySDP = mySDP;
  12319. this.otherSDP = otherSDP;
  12320. }
  12321. /**
  12322. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  12323. * @param otherSdp the other SDP to check ssrc with.
  12324. */
  12325. SDPDiffer.prototype.getNewMedia = function() {
  12326. // this could be useful in Array.prototype.
  12327. function arrayEquals(array) {
  12328. // if the other array is a falsy value, return
  12329. if (!array)
  12330. return false;
  12331. // compare lengths - can save a lot of time
  12332. if (this.length != array.length)
  12333. return false;
  12334. for (var i = 0, l=this.length; i < l; i++) {
  12335. // Check if we have nested arrays
  12336. if (this[i] instanceof Array && array[i] instanceof Array) {
  12337. // recurse into the nested arrays
  12338. if (!this[i].equals(array[i]))
  12339. return false;
  12340. }
  12341. else if (this[i] != array[i]) {
  12342. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  12343. return false;
  12344. }
  12345. }
  12346. return true;
  12347. }
  12348. var myMedias = this.mySDP.getMediaSsrcMap();
  12349. var othersMedias = this.otherSDP.getMediaSsrcMap();
  12350. var newMedia = {};
  12351. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  12352. var myMedia = myMedias[othersMediaIdx];
  12353. var othersMedia = othersMedias[othersMediaIdx];
  12354. if(!myMedia && othersMedia) {
  12355. // Add whole channel
  12356. newMedia[othersMediaIdx] = othersMedia;
  12357. return;
  12358. }
  12359. // Look for new ssrcs accross the channel
  12360. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  12361. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  12362. // Allocate channel if we've found ssrc that doesn't exist in our channel
  12363. if(!newMedia[othersMediaIdx]){
  12364. newMedia[othersMediaIdx] = {
  12365. mediaindex: othersMedia.mediaindex,
  12366. mid: othersMedia.mid,
  12367. ssrcs: {},
  12368. ssrcGroups: []
  12369. };
  12370. }
  12371. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  12372. }
  12373. });
  12374. // Look for new ssrc groups across the channels
  12375. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  12376. // try to match the other ssrc-group with an ssrc-group of ours
  12377. var matched = false;
  12378. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  12379. var mySsrcGroup = myMedia.ssrcGroups[i];
  12380. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  12381. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  12382. matched = true;
  12383. break;
  12384. }
  12385. }
  12386. if (!matched) {
  12387. // Allocate channel if we've found an ssrc-group that doesn't
  12388. // exist in our channel
  12389. if(!newMedia[othersMediaIdx]){
  12390. newMedia[othersMediaIdx] = {
  12391. mediaindex: othersMedia.mediaindex,
  12392. mid: othersMedia.mid,
  12393. ssrcs: {},
  12394. ssrcGroups: []
  12395. };
  12396. }
  12397. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  12398. }
  12399. });
  12400. });
  12401. return newMedia;
  12402. };
  12403. /**
  12404. * Sends SSRC update IQ.
  12405. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  12406. * @param sid session identifier that will be put into the IQ.
  12407. * @param initiator initiator identifier.
  12408. * @param toJid destination Jid
  12409. * @param isAdd indicates if this is remove or add operation.
  12410. */
  12411. SDPDiffer.prototype.toJingle = function(modify) {
  12412. var sdpMediaSsrcs = this.getNewMedia();
  12413. var self = this;
  12414. // FIXME: only announce video ssrcs since we mix audio and dont need
  12415. // the audio ssrcs therefore
  12416. var modified = false;
  12417. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  12418. modified = true;
  12419. var media = sdpMediaSsrcs[mediaindex];
  12420. modify.c('content', {name: media.mid});
  12421. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  12422. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  12423. // generate sources from lines
  12424. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  12425. var mediaSsrc = media.ssrcs[ssrcNum];
  12426. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12427. modify.attrs({ssrc: mediaSsrc.ssrc});
  12428. // iterate over ssrc lines
  12429. mediaSsrc.lines.forEach(function (line) {
  12430. var idx = line.indexOf(' ');
  12431. var kv = line.substr(idx + 1);
  12432. modify.c('parameter');
  12433. if (kv.indexOf(':') == -1) {
  12434. modify.attrs({ name: kv });
  12435. } else {
  12436. modify.attrs({ name: kv.split(':', 2)[0] });
  12437. modify.attrs({ value: kv.split(':', 2)[1] });
  12438. }
  12439. modify.up(); // end of parameter
  12440. });
  12441. modify.up(); // end of source
  12442. });
  12443. // generate source groups from lines
  12444. media.ssrcGroups.forEach(function(ssrcGroup) {
  12445. if (ssrcGroup.ssrcs.length != 0) {
  12446. modify.c('ssrc-group', {
  12447. semantics: ssrcGroup.semantics,
  12448. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  12449. });
  12450. ssrcGroup.ssrcs.forEach(function (ssrc) {
  12451. modify.c('source', { ssrc: ssrc })
  12452. .up(); // end of source
  12453. });
  12454. modify.up(); // end of ssrc-group
  12455. }
  12456. });
  12457. modify.up(); // end of description
  12458. modify.up(); // end of content
  12459. });
  12460. return modified;
  12461. };
  12462. module.exports = SDPDiffer;
  12463. },{}],49:[function(require,module,exports){
  12464. /*
  12465. * Copyright @ 2015 Atlassian Pty Ltd
  12466. *
  12467. * Licensed under the Apache License, Version 2.0 (the "License");
  12468. * you may not use this file except in compliance with the License.
  12469. * You may obtain a copy of the License at
  12470. *
  12471. * http://www.apache.org/licenses/LICENSE-2.0
  12472. *
  12473. * Unless required by applicable law or agreed to in writing, software
  12474. * distributed under the License is distributed on an "AS IS" BASIS,
  12475. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12476. * See the License for the specific language governing permissions and
  12477. * limitations under the License.
  12478. */
  12479. SDPUtil = {
  12480. iceparams: function (mediadesc, sessiondesc) {
  12481. var data = null;
  12482. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  12483. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  12484. data = {
  12485. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  12486. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  12487. };
  12488. }
  12489. return data;
  12490. },
  12491. parse_iceufrag: function (line) {
  12492. return line.substring(12);
  12493. },
  12494. build_iceufrag: function (frag) {
  12495. return 'a=ice-ufrag:' + frag;
  12496. },
  12497. parse_icepwd: function (line) {
  12498. return line.substring(10);
  12499. },
  12500. build_icepwd: function (pwd) {
  12501. return 'a=ice-pwd:' + pwd;
  12502. },
  12503. parse_mid: function (line) {
  12504. return line.substring(6);
  12505. },
  12506. parse_mline: function (line) {
  12507. var parts = line.substring(2).split(' '),
  12508. data = {};
  12509. data.media = parts.shift();
  12510. data.port = parts.shift();
  12511. data.proto = parts.shift();
  12512. if (parts[parts.length - 1] === '') { // trailing whitespace
  12513. parts.pop();
  12514. }
  12515. data.fmt = parts;
  12516. return data;
  12517. },
  12518. build_mline: function (mline) {
  12519. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  12520. },
  12521. parse_rtpmap: function (line) {
  12522. var parts = line.substring(9).split(' '),
  12523. data = {};
  12524. data.id = parts.shift();
  12525. parts = parts[0].split('/');
  12526. data.name = parts.shift();
  12527. data.clockrate = parts.shift();
  12528. data.channels = parts.length ? parts.shift() : '1';
  12529. return data;
  12530. },
  12531. /**
  12532. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  12533. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  12534. * @returns [SCTP port number, protocol, streams]
  12535. */
  12536. parse_sctpmap: function (line)
  12537. {
  12538. var parts = line.substring(10).split(' ');
  12539. var sctpPort = parts[0];
  12540. var protocol = parts[1];
  12541. // Stream count is optional
  12542. var streamCount = parts.length > 2 ? parts[2] : null;
  12543. return [sctpPort, protocol, streamCount];// SCTP port
  12544. },
  12545. build_rtpmap: function (el) {
  12546. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  12547. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  12548. line += '/' + el.getAttribute('channels');
  12549. }
  12550. return line;
  12551. },
  12552. parse_crypto: function (line) {
  12553. var parts = line.substring(9).split(' '),
  12554. data = {};
  12555. data.tag = parts.shift();
  12556. data['crypto-suite'] = parts.shift();
  12557. data['key-params'] = parts.shift();
  12558. if (parts.length) {
  12559. data['session-params'] = parts.join(' ');
  12560. }
  12561. return data;
  12562. },
  12563. parse_fingerprint: function (line) { // RFC 4572
  12564. var parts = line.substring(14).split(' '),
  12565. data = {};
  12566. data.hash = parts.shift();
  12567. data.fingerprint = parts.shift();
  12568. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  12569. return data;
  12570. },
  12571. parse_fmtp: function (line) {
  12572. var parts = line.split(' '),
  12573. i, key, value,
  12574. data = [];
  12575. parts.shift();
  12576. parts = parts.join(' ').split(';');
  12577. for (i = 0; i < parts.length; i++) {
  12578. key = parts[i].split('=')[0];
  12579. while (key.length && key[0] == ' ') {
  12580. key = key.substring(1);
  12581. }
  12582. value = parts[i].split('=')[1];
  12583. if (key && value) {
  12584. data.push({name: key, value: value});
  12585. } else if (key) {
  12586. // rfc 4733 (DTMF) style stuff
  12587. data.push({name: '', value: key});
  12588. }
  12589. }
  12590. return data;
  12591. },
  12592. parse_icecandidate: function (line) {
  12593. var candidate = {},
  12594. elems = line.split(' ');
  12595. candidate.foundation = elems[0].substring(12);
  12596. candidate.component = elems[1];
  12597. candidate.protocol = elems[2].toLowerCase();
  12598. candidate.priority = elems[3];
  12599. candidate.ip = elems[4];
  12600. candidate.port = elems[5];
  12601. // elems[6] => "typ"
  12602. candidate.type = elems[7];
  12603. candidate.generation = 0; // default value, may be overwritten below
  12604. for (var i = 8; i < elems.length; i += 2) {
  12605. switch (elems[i]) {
  12606. case 'raddr':
  12607. candidate['rel-addr'] = elems[i + 1];
  12608. break;
  12609. case 'rport':
  12610. candidate['rel-port'] = elems[i + 1];
  12611. break;
  12612. case 'generation':
  12613. candidate.generation = elems[i + 1];
  12614. break;
  12615. case 'tcptype':
  12616. candidate.tcptype = elems[i + 1];
  12617. break;
  12618. default: // TODO
  12619. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12620. }
  12621. }
  12622. candidate.network = '1';
  12623. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12624. return candidate;
  12625. },
  12626. build_icecandidate: function (cand) {
  12627. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  12628. line += ' ';
  12629. switch (cand.type) {
  12630. case 'srflx':
  12631. case 'prflx':
  12632. case 'relay':
  12633. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  12634. line += 'raddr';
  12635. line += ' ';
  12636. line += cand['rel-addr'];
  12637. line += ' ';
  12638. line += 'rport';
  12639. line += ' ';
  12640. line += cand['rel-port'];
  12641. line += ' ';
  12642. }
  12643. break;
  12644. }
  12645. if (cand.hasOwnAttribute('tcptype')) {
  12646. line += 'tcptype';
  12647. line += ' ';
  12648. line += cand.tcptype;
  12649. line += ' ';
  12650. }
  12651. line += 'generation';
  12652. line += ' ';
  12653. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  12654. return line;
  12655. },
  12656. parse_ssrc: function (desc) {
  12657. // proprietary mapping of a=ssrc lines
  12658. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  12659. // and parse according to that
  12660. var lines = desc.split('\r\n'),
  12661. data = {};
  12662. for (var i = 0; i < lines.length; i++) {
  12663. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  12664. var idx = lines[i].indexOf(' ');
  12665. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  12666. }
  12667. }
  12668. return data;
  12669. },
  12670. parse_rtcpfb: function (line) {
  12671. var parts = line.substr(10).split(' ');
  12672. var data = {};
  12673. data.pt = parts.shift();
  12674. data.type = parts.shift();
  12675. data.params = parts;
  12676. return data;
  12677. },
  12678. parse_extmap: function (line) {
  12679. var parts = line.substr(9).split(' ');
  12680. var data = {};
  12681. data.value = parts.shift();
  12682. if (data.value.indexOf('/') != -1) {
  12683. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  12684. data.value = data.value.substr(0, data.value.indexOf('/'));
  12685. } else {
  12686. data.direction = 'both';
  12687. }
  12688. data.uri = parts.shift();
  12689. data.params = parts;
  12690. return data;
  12691. },
  12692. find_line: function (haystack, needle, sessionpart) {
  12693. var lines = haystack.split('\r\n');
  12694. for (var i = 0; i < lines.length; i++) {
  12695. if (lines[i].substring(0, needle.length) == needle) {
  12696. return lines[i];
  12697. }
  12698. }
  12699. if (!sessionpart) {
  12700. return false;
  12701. }
  12702. // search session part
  12703. lines = sessionpart.split('\r\n');
  12704. for (var j = 0; j < lines.length; j++) {
  12705. if (lines[j].substring(0, needle.length) == needle) {
  12706. return lines[j];
  12707. }
  12708. }
  12709. return false;
  12710. },
  12711. find_lines: function (haystack, needle, sessionpart) {
  12712. var lines = haystack.split('\r\n'),
  12713. needles = [];
  12714. for (var i = 0; i < lines.length; i++) {
  12715. if (lines[i].substring(0, needle.length) == needle)
  12716. needles.push(lines[i]);
  12717. }
  12718. if (needles.length || !sessionpart) {
  12719. return needles;
  12720. }
  12721. // search session part
  12722. lines = sessionpart.split('\r\n');
  12723. for (var j = 0; j < lines.length; j++) {
  12724. if (lines[j].substring(0, needle.length) == needle) {
  12725. needles.push(lines[j]);
  12726. }
  12727. }
  12728. return needles;
  12729. },
  12730. candidateToJingle: function (line) {
  12731. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  12732. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  12733. if (line.indexOf('candidate:') === 0) {
  12734. line = 'a=' + line;
  12735. } else if (line.substring(0, 12) != 'a=candidate:') {
  12736. console.log('parseCandidate called with a line that is not a candidate line');
  12737. console.log(line);
  12738. return null;
  12739. }
  12740. if (line.substring(line.length - 2) == '\r\n') // chomp it
  12741. line = line.substring(0, line.length - 2);
  12742. var candidate = {},
  12743. elems = line.split(' '),
  12744. i;
  12745. if (elems[6] != 'typ') {
  12746. console.log('did not find typ in the right place');
  12747. console.log(line);
  12748. return null;
  12749. }
  12750. candidate.foundation = elems[0].substring(12);
  12751. candidate.component = elems[1];
  12752. candidate.protocol = elems[2].toLowerCase();
  12753. candidate.priority = elems[3];
  12754. candidate.ip = elems[4];
  12755. candidate.port = elems[5];
  12756. // elems[6] => "typ"
  12757. candidate.type = elems[7];
  12758. candidate.generation = '0'; // default, may be overwritten below
  12759. for (i = 8; i < elems.length; i += 2) {
  12760. switch (elems[i]) {
  12761. case 'raddr':
  12762. candidate['rel-addr'] = elems[i + 1];
  12763. break;
  12764. case 'rport':
  12765. candidate['rel-port'] = elems[i + 1];
  12766. break;
  12767. case 'generation':
  12768. candidate.generation = elems[i + 1];
  12769. break;
  12770. case 'tcptype':
  12771. candidate.tcptype = elems[i + 1];
  12772. break;
  12773. default: // TODO
  12774. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12775. }
  12776. }
  12777. candidate.network = '1';
  12778. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12779. return candidate;
  12780. },
  12781. candidateFromJingle: function (cand) {
  12782. var line = 'a=candidate:';
  12783. line += cand.getAttribute('foundation');
  12784. line += ' ';
  12785. line += cand.getAttribute('component');
  12786. line += ' ';
  12787. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  12788. line += ' ';
  12789. line += cand.getAttribute('priority');
  12790. line += ' ';
  12791. line += cand.getAttribute('ip');
  12792. line += ' ';
  12793. line += cand.getAttribute('port');
  12794. line += ' ';
  12795. line += 'typ';
  12796. line += ' ' + cand.getAttribute('type');
  12797. line += ' ';
  12798. switch (cand.getAttribute('type')) {
  12799. case 'srflx':
  12800. case 'prflx':
  12801. case 'relay':
  12802. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  12803. line += 'raddr';
  12804. line += ' ';
  12805. line += cand.getAttribute('rel-addr');
  12806. line += ' ';
  12807. line += 'rport';
  12808. line += ' ';
  12809. line += cand.getAttribute('rel-port');
  12810. line += ' ';
  12811. }
  12812. break;
  12813. }
  12814. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  12815. line += 'tcptype';
  12816. line += ' ';
  12817. line += cand.getAttribute('tcptype');
  12818. line += ' ';
  12819. }
  12820. line += 'generation';
  12821. line += ' ';
  12822. line += cand.getAttribute('generation') || '0';
  12823. return line + '\r\n';
  12824. }
  12825. };
  12826. module.exports = SDPUtil;
  12827. },{}],50:[function(require,module,exports){
  12828. /*
  12829. * Copyright @ 2015 Atlassian Pty Ltd
  12830. *
  12831. * Licensed under the Apache License, Version 2.0 (the "License");
  12832. * you may not use this file except in compliance with the License.
  12833. * You may obtain a copy of the License at
  12834. *
  12835. * http://www.apache.org/licenses/LICENSE-2.0
  12836. *
  12837. * Unless required by applicable law or agreed to in writing, software
  12838. * distributed under the License is distributed on an "AS IS" BASIS,
  12839. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12840. * See the License for the specific language governing permissions and
  12841. * limitations under the License.
  12842. */
  12843. function TraceablePeerConnection(ice_config, constraints) {
  12844. var self = this;
  12845. var RTCPeerconnection = navigator.mozGetUserMedia ? mozRTCPeerConnection : webkitRTCPeerConnection;
  12846. this.peerconnection = new RTCPeerconnection(ice_config, constraints);
  12847. this.updateLog = [];
  12848. this.stats = {};
  12849. this.statsinterval = null;
  12850. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  12851. var Interop = require('sdp-interop').Interop;
  12852. this.interop = new Interop();
  12853. var Simulcast = require('sdp-simulcast');
  12854. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  12855. // override as desired
  12856. this.trace = function (what, info) {
  12857. //console.warn('WTRACE', what, info);
  12858. self.updateLog.push({
  12859. time: new Date(),
  12860. type: what,
  12861. value: info || ""
  12862. });
  12863. };
  12864. this.onicecandidate = null;
  12865. this.peerconnection.onicecandidate = function (event) {
  12866. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  12867. if (self.onicecandidate !== null) {
  12868. self.onicecandidate(event);
  12869. }
  12870. };
  12871. this.onaddstream = null;
  12872. this.peerconnection.onaddstream = function (event) {
  12873. self.trace('onaddstream', event.stream.id);
  12874. if (self.onaddstream !== null) {
  12875. self.onaddstream(event);
  12876. }
  12877. };
  12878. this.onremovestream = null;
  12879. this.peerconnection.onremovestream = function (event) {
  12880. self.trace('onremovestream', event.stream.id);
  12881. if (self.onremovestream !== null) {
  12882. self.onremovestream(event);
  12883. }
  12884. };
  12885. this.onsignalingstatechange = null;
  12886. this.peerconnection.onsignalingstatechange = function (event) {
  12887. self.trace('onsignalingstatechange', self.signalingState);
  12888. if (self.onsignalingstatechange !== null) {
  12889. self.onsignalingstatechange(event);
  12890. }
  12891. };
  12892. this.oniceconnectionstatechange = null;
  12893. this.peerconnection.oniceconnectionstatechange = function (event) {
  12894. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  12895. if (self.oniceconnectionstatechange !== null) {
  12896. self.oniceconnectionstatechange(event);
  12897. }
  12898. };
  12899. this.onnegotiationneeded = null;
  12900. this.peerconnection.onnegotiationneeded = function (event) {
  12901. self.trace('onnegotiationneeded');
  12902. if (self.onnegotiationneeded !== null) {
  12903. self.onnegotiationneeded(event);
  12904. }
  12905. };
  12906. self.ondatachannel = null;
  12907. this.peerconnection.ondatachannel = function (event) {
  12908. self.trace('ondatachannel', event);
  12909. if (self.ondatachannel !== null) {
  12910. self.ondatachannel(event);
  12911. }
  12912. };
  12913. if (!navigator.mozGetUserMedia && this.maxstats) {
  12914. this.statsinterval = window.setInterval(function() {
  12915. self.peerconnection.getStats(function(stats) {
  12916. var results = stats.result();
  12917. for (var i = 0; i < results.length; ++i) {
  12918. //console.log(results[i].type, results[i].id, results[i].names())
  12919. var now = new Date();
  12920. results[i].names().forEach(function (name) {
  12921. var id = results[i].id + '-' + name;
  12922. if (!self.stats[id]) {
  12923. self.stats[id] = {
  12924. startTime: now,
  12925. endTime: now,
  12926. values: [],
  12927. times: []
  12928. };
  12929. }
  12930. self.stats[id].values.push(results[i].stat(name));
  12931. self.stats[id].times.push(now.getTime());
  12932. if (self.stats[id].values.length > self.maxstats) {
  12933. self.stats[id].values.shift();
  12934. self.stats[id].times.shift();
  12935. }
  12936. self.stats[id].endTime = now;
  12937. });
  12938. }
  12939. });
  12940. }, 1000);
  12941. }
  12942. };
  12943. dumpSDP = function(description) {
  12944. if (typeof description === 'undefined' || description == null) {
  12945. return '';
  12946. }
  12947. return 'type: ' + description.type + '\r\n' + description.sdp;
  12948. };
  12949. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  12950. TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
  12951. TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
  12952. TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() {
  12953. var desc = this.peerconnection.localDescription;
  12954. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  12955. // if we're running on FF, transform to Plan B first.
  12956. if (navigator.mozGetUserMedia) {
  12957. desc = this.interop.toPlanB(desc);
  12958. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  12959. }
  12960. return desc;
  12961. });
  12962. TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() {
  12963. var desc = this.peerconnection.remoteDescription;
  12964. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  12965. // if we're running on FF, transform to Plan B first.
  12966. if (navigator.mozGetUserMedia) {
  12967. desc = this.interop.toPlanB(desc);
  12968. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  12969. }
  12970. return desc;
  12971. });
  12972. }
  12973. TraceablePeerConnection.prototype.addStream = function (stream) {
  12974. this.trace('addStream', stream.id);
  12975. try
  12976. {
  12977. this.peerconnection.addStream(stream);
  12978. }
  12979. catch (e)
  12980. {
  12981. console.error(e);
  12982. return;
  12983. }
  12984. };
  12985. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  12986. this.trace('removeStream', stream.id);
  12987. if(stopStreams) {
  12988. stream.getAudioTracks().forEach(function (track) {
  12989. track.stop();
  12990. });
  12991. stream.getVideoTracks().forEach(function (track) {
  12992. track.stop();
  12993. });
  12994. }
  12995. try {
  12996. // FF doesn't support this yet.
  12997. this.peerconnection.removeStream(stream);
  12998. } catch (e) {
  12999. console.error(e);
  13000. }
  13001. };
  13002. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  13003. this.trace('createDataChannel', label, opts);
  13004. return this.peerconnection.createDataChannel(label, opts);
  13005. };
  13006. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  13007. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  13008. // if we're running on FF, transform to Plan A first.
  13009. if (navigator.mozGetUserMedia) {
  13010. description = this.interop.toUnifiedPlan(description);
  13011. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  13012. }
  13013. var self = this;
  13014. this.peerconnection.setLocalDescription(description,
  13015. function () {
  13016. self.trace('setLocalDescriptionOnSuccess');
  13017. successCallback();
  13018. },
  13019. function (err) {
  13020. self.trace('setLocalDescriptionOnFailure', err);
  13021. failureCallback(err);
  13022. }
  13023. );
  13024. /*
  13025. if (this.statsinterval === null && this.maxstats > 0) {
  13026. // start gathering stats
  13027. }
  13028. */
  13029. };
  13030. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  13031. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  13032. // TODO the focus should squeze or explode the remote simulcast
  13033. description = this.simulcast.mungeRemoteDescription(description);
  13034. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  13035. // if we're running on FF, transform to Plan A first.
  13036. if (navigator.mozGetUserMedia) {
  13037. description = this.interop.toUnifiedPlan(description);
  13038. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  13039. }
  13040. var self = this;
  13041. this.peerconnection.setRemoteDescription(description,
  13042. function () {
  13043. self.trace('setRemoteDescriptionOnSuccess');
  13044. successCallback();
  13045. },
  13046. function (err) {
  13047. self.trace('setRemoteDescriptionOnFailure', err);
  13048. failureCallback(err);
  13049. }
  13050. );
  13051. /*
  13052. if (this.statsinterval === null && this.maxstats > 0) {
  13053. // start gathering stats
  13054. }
  13055. */
  13056. };
  13057. TraceablePeerConnection.prototype.close = function () {
  13058. this.trace('stop');
  13059. if (this.statsinterval !== null) {
  13060. window.clearInterval(this.statsinterval);
  13061. this.statsinterval = null;
  13062. }
  13063. this.peerconnection.close();
  13064. };
  13065. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  13066. var self = this;
  13067. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  13068. this.peerconnection.createOffer(
  13069. function (offer) {
  13070. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  13071. // if we're running on FF, transform to Plan B first.
  13072. // NOTE this is not tested because in meet the focus generates the
  13073. // offer.
  13074. if (navigator.mozGetUserMedia) {
  13075. offer = self.interop.toPlanB(offer);
  13076. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  13077. }
  13078. if (config.enableSimulcast && self.simulcast.isSupported()) {
  13079. offer = self.simulcast.mungeLocalDescription(offer);
  13080. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  13081. }
  13082. successCallback(offer);
  13083. },
  13084. function(err) {
  13085. self.trace('createOfferOnFailure', err);
  13086. failureCallback(err);
  13087. },
  13088. constraints
  13089. );
  13090. };
  13091. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  13092. var self = this;
  13093. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  13094. this.peerconnection.createAnswer(
  13095. function (answer) {
  13096. self.trace('createAnswerOnSuccess::preTransfom', dumpSDP(answer));
  13097. // if we're running on FF, transform to Plan A first.
  13098. if (navigator.mozGetUserMedia) {
  13099. answer = self.interop.toPlanB(answer);
  13100. self.trace('createAnswerOnSuccess::postTransfom (Plan B)', dumpSDP(answer));
  13101. }
  13102. if (config.enableSimulcast && self.simulcast.isSupported()) {
  13103. answer = self.simulcast.mungeLocalDescription(answer);
  13104. self.trace('createAnswerOnSuccess::postTransfom (simulcast)', dumpSDP(answer));
  13105. }
  13106. successCallback(answer);
  13107. },
  13108. function(err) {
  13109. self.trace('createAnswerOnFailure', err);
  13110. failureCallback(err);
  13111. },
  13112. constraints
  13113. );
  13114. };
  13115. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  13116. var self = this;
  13117. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  13118. this.peerconnection.addIceCandidate(candidate);
  13119. /* maybe later
  13120. this.peerconnection.addIceCandidate(candidate,
  13121. function () {
  13122. self.trace('addIceCandidateOnSuccess');
  13123. successCallback();
  13124. },
  13125. function (err) {
  13126. self.trace('addIceCandidateOnFailure', err);
  13127. failureCallback(err);
  13128. }
  13129. );
  13130. */
  13131. };
  13132. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  13133. if (navigator.mozGetUserMedia) {
  13134. // ignore for now...
  13135. if(!errback)
  13136. errback = function () {
  13137. }
  13138. this.peerconnection.getStats(null,callback,errback);
  13139. } else {
  13140. this.peerconnection.getStats(callback);
  13141. }
  13142. };
  13143. module.exports = TraceablePeerConnection;
  13144. },{"sdp-interop":84,"sdp-simulcast":91}],51:[function(require,module,exports){
  13145. /*
  13146. * Copyright @ 2015 Atlassian Pty Ltd
  13147. *
  13148. * Licensed under the Apache License, Version 2.0 (the "License");
  13149. * you may not use this file except in compliance with the License.
  13150. * You may obtain a copy of the License at
  13151. *
  13152. * http://www.apache.org/licenses/LICENSE-2.0
  13153. *
  13154. * Unless required by applicable law or agreed to in writing, software
  13155. * distributed under the License is distributed on an "AS IS" BASIS,
  13156. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13157. * See the License for the specific language governing permissions and
  13158. * limitations under the License.
  13159. */
  13160. /* global $, $iq, APP, config, connection, UI, messageHandler,
  13161. roomName, sessionTerminated, Strophe, Util */
  13162. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13163. var Settings = require("../settings/Settings");
  13164. var AuthenticationEvents
  13165. = require("../../service/authentication/AuthenticationEvents");
  13166. /**
  13167. * Contains logic responsible for enabling/disabling functionality available
  13168. * only to moderator users.
  13169. */
  13170. var connection = null;
  13171. var focusUserJid;
  13172. function createExpBackoffTimer(step) {
  13173. var count = 1;
  13174. return function (reset) {
  13175. // Reset call
  13176. if (reset) {
  13177. count = 1;
  13178. return;
  13179. }
  13180. // Calculate next timeout
  13181. var timeout = Math.pow(2, count - 1);
  13182. count += 1;
  13183. return timeout * step;
  13184. };
  13185. }
  13186. var getNextTimeout = createExpBackoffTimer(1000);
  13187. var getNextErrorTimeout = createExpBackoffTimer(1000);
  13188. // External authentication stuff
  13189. var externalAuthEnabled = false;
  13190. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  13191. // it will be enabled automatically if focus detects the component through
  13192. // service discovery.
  13193. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  13194. var eventEmitter = null;
  13195. var Moderator = {
  13196. isModerator: function () {
  13197. return connection && connection.emuc.isModerator();
  13198. },
  13199. isPeerModerator: function (peerJid) {
  13200. return connection &&
  13201. connection.emuc.getMemberRole(peerJid) === 'moderator';
  13202. },
  13203. isExternalAuthEnabled: function () {
  13204. return externalAuthEnabled;
  13205. },
  13206. isSipGatewayEnabled: function () {
  13207. return sipGatewayEnabled;
  13208. },
  13209. setConnection: function (con) {
  13210. connection = con;
  13211. },
  13212. init: function (xmpp, emitter) {
  13213. this.xmppService = xmpp;
  13214. eventEmitter = emitter;
  13215. // Message listener that talks to POPUP window
  13216. function listener(event) {
  13217. if (event.data && event.data.sessionId) {
  13218. if (event.origin !== window.location.origin) {
  13219. console.warn(
  13220. "Ignoring sessionId from different origin: " + event.origin);
  13221. return;
  13222. }
  13223. localStorage.setItem('sessionId', event.data.sessionId);
  13224. // After popup is closed we will authenticate
  13225. }
  13226. }
  13227. // Register
  13228. if (window.addEventListener) {
  13229. window.addEventListener("message", listener, false);
  13230. } else {
  13231. window.attachEvent("onmessage", listener);
  13232. }
  13233. },
  13234. onMucMemberLeft: function (jid) {
  13235. console.info("Someone left is it focus ? " + jid);
  13236. var resource = Strophe.getResourceFromJid(jid);
  13237. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  13238. console.info(
  13239. "Focus has left the room - leaving conference");
  13240. //hangUp();
  13241. // We'd rather reload to have everything re-initialized
  13242. // FIXME: show some message before reload
  13243. location.reload();
  13244. }
  13245. },
  13246. setFocusUserJid: function (focusJid) {
  13247. if (!focusUserJid) {
  13248. focusUserJid = focusJid;
  13249. console.info("Focus jid set to: " + focusUserJid);
  13250. }
  13251. },
  13252. getFocusUserJid: function () {
  13253. return focusUserJid;
  13254. },
  13255. getFocusComponent: function () {
  13256. // Get focus component address
  13257. var focusComponent = config.hosts.focus;
  13258. // If not specified use default: 'focus.domain'
  13259. if (!focusComponent) {
  13260. focusComponent = 'focus.' + config.hosts.domain;
  13261. }
  13262. return focusComponent;
  13263. },
  13264. createConferenceIq: function (roomName) {
  13265. // Generate create conference IQ
  13266. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  13267. // Session Id used for authentication
  13268. var sessionId = localStorage.getItem('sessionId');
  13269. var machineUID = Settings.getSettings().uid;
  13270. console.info(
  13271. "Session ID: " + sessionId + " machine UID: " + machineUID);
  13272. elem.c('conference', {
  13273. xmlns: 'http://jitsi.org/protocol/focus',
  13274. room: roomName,
  13275. 'machine-uid': machineUID
  13276. });
  13277. if (sessionId) {
  13278. elem.attrs({ 'session-id': sessionId});
  13279. }
  13280. if (config.hosts.bridge !== undefined) {
  13281. elem.c(
  13282. 'property',
  13283. { name: 'bridge', value: config.hosts.bridge})
  13284. .up();
  13285. }
  13286. // Tell the focus we have Jigasi configured
  13287. if (config.hosts.call_control !== undefined) {
  13288. elem.c(
  13289. 'property',
  13290. { name: 'call_control', value: config.hosts.call_control})
  13291. .up();
  13292. }
  13293. if (config.channelLastN !== undefined) {
  13294. elem.c(
  13295. 'property',
  13296. { name: 'channelLastN', value: config.channelLastN})
  13297. .up();
  13298. }
  13299. if (config.adaptiveLastN !== undefined) {
  13300. elem.c(
  13301. 'property',
  13302. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  13303. .up();
  13304. }
  13305. if (config.adaptiveSimulcast !== undefined) {
  13306. elem.c(
  13307. 'property',
  13308. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  13309. .up();
  13310. }
  13311. if (config.openSctp !== undefined) {
  13312. elem.c(
  13313. 'property',
  13314. { name: 'openSctp', value: config.openSctp})
  13315. .up();
  13316. }
  13317. if(config.startAudioMuted !== undefined)
  13318. {
  13319. elem.c(
  13320. 'property',
  13321. { name: 'startAudioMuted', value: config.startAudioMuted})
  13322. .up();
  13323. }
  13324. if(config.startVideoMuted !== undefined)
  13325. {
  13326. elem.c(
  13327. 'property',
  13328. { name: 'startVideoMuted', value: config.startVideoMuted})
  13329. .up();
  13330. }
  13331. elem.c(
  13332. 'property',
  13333. { name: 'simulcastMode', value: 'rewriting'})
  13334. .up();
  13335. elem.up();
  13336. return elem;
  13337. },
  13338. parseSessionId: function (resultIq) {
  13339. var sessionId = $(resultIq).find('conference').attr('session-id');
  13340. if (sessionId) {
  13341. console.info('Received sessionId: ' + sessionId);
  13342. localStorage.setItem('sessionId', sessionId);
  13343. }
  13344. },
  13345. parseConfigOptions: function (resultIq) {
  13346. Moderator.setFocusUserJid(
  13347. $(resultIq).find('conference').attr('focusjid'));
  13348. var authenticationEnabled
  13349. = $(resultIq).find(
  13350. '>conference>property' +
  13351. '[name=\'authentication\'][value=\'true\']').length > 0;
  13352. console.info("Authentication enabled: " + authenticationEnabled);
  13353. externalAuthEnabled
  13354. = $(resultIq).find(
  13355. '>conference>property' +
  13356. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  13357. console.info('External authentication enabled: ' + externalAuthEnabled);
  13358. if (!externalAuthEnabled) {
  13359. // We expect to receive sessionId in 'internal' authentication mode
  13360. Moderator.parseSessionId(resultIq);
  13361. }
  13362. var authIdentity = $(resultIq).find('>conference').attr('identity');
  13363. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  13364. authenticationEnabled, authIdentity);
  13365. // Check if focus has auto-detected Jigasi component(this will be also
  13366. // included if we have passed our host from the config)
  13367. if ($(resultIq).find(
  13368. '>conference>property' +
  13369. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  13370. sipGatewayEnabled = true;
  13371. }
  13372. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  13373. },
  13374. // FIXME: we need to show the fact that we're waiting for the focus
  13375. // to the user(or that focus is not available)
  13376. allocateConferenceFocus: function (roomName, callback) {
  13377. // Try to use focus user JID from the config
  13378. Moderator.setFocusUserJid(config.focusUserJid);
  13379. // Send create conference IQ
  13380. var iq = Moderator.createConferenceIq(roomName);
  13381. var self = this;
  13382. connection.sendIQ(
  13383. iq,
  13384. function (result) {
  13385. // Setup config options
  13386. Moderator.parseConfigOptions(result);
  13387. if ('true' === $(result).find('conference').attr('ready')) {
  13388. // Reset both timers
  13389. getNextTimeout(true);
  13390. getNextErrorTimeout(true);
  13391. // Exec callback
  13392. callback();
  13393. } else {
  13394. var waitMs = getNextTimeout();
  13395. console.info("Waiting for the focus... " + waitMs);
  13396. // Reset error timeout
  13397. getNextErrorTimeout(true);
  13398. window.setTimeout(
  13399. function () {
  13400. Moderator.allocateConferenceFocus(
  13401. roomName, callback);
  13402. }, waitMs);
  13403. }
  13404. },
  13405. function (error) {
  13406. // Invalid session ? remove and try again
  13407. // without session ID to get a new one
  13408. var invalidSession
  13409. = $(error).find('>error>session-invalid').length;
  13410. if (invalidSession) {
  13411. console.info("Session expired! - removing");
  13412. localStorage.removeItem("sessionId");
  13413. }
  13414. if ($(error).find('>error>graceful-shutdown').length) {
  13415. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  13416. return;
  13417. }
  13418. // Check for error returned by the reservation system
  13419. var reservationErr = $(error).find('>error>reservation-error');
  13420. if (reservationErr.length) {
  13421. // Trigger error event
  13422. var errorCode = reservationErr.attr('error-code');
  13423. var errorMsg;
  13424. if ($(error).find('>error>text')) {
  13425. errorMsg = $(error).find('>error>text').text();
  13426. }
  13427. eventEmitter.emit(
  13428. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  13429. return;
  13430. }
  13431. // Not authorized to create new room
  13432. if ($(error).find('>error>not-authorized').length) {
  13433. console.warn("Unauthorized to start the conference", error);
  13434. var toDomain
  13435. = Strophe.getDomainFromJid(error.getAttribute('to'));
  13436. if (toDomain !== config.hosts.anonymousdomain) {
  13437. // FIXME: "is external" should come either from
  13438. // the focus or config.js
  13439. externalAuthEnabled = true;
  13440. }
  13441. eventEmitter.emit(
  13442. XMPPEvents.AUTHENTICATION_REQUIRED,
  13443. function () {
  13444. Moderator.allocateConferenceFocus(
  13445. roomName, callback);
  13446. });
  13447. return;
  13448. }
  13449. var waitMs = getNextErrorTimeout();
  13450. console.error("Focus error, retry after " + waitMs, error);
  13451. // Show message
  13452. var focusComponent = Moderator.getFocusComponent();
  13453. var retrySec = waitMs / 1000;
  13454. // FIXME: message is duplicated ?
  13455. // Do not show in case of session invalid
  13456. // which means just a retry
  13457. if (!invalidSession) {
  13458. APP.UI.messageHandler.notify(
  13459. null, "notify.focus",
  13460. 'disconnected', "notify.focusFail",
  13461. {component: focusComponent, ms: retrySec});
  13462. }
  13463. // Reset response timeout
  13464. getNextTimeout(true);
  13465. window.setTimeout(
  13466. function () {
  13467. Moderator.allocateConferenceFocus(roomName, callback);
  13468. }, waitMs);
  13469. }
  13470. );
  13471. },
  13472. getLoginUrl: function (roomName, urlCallback) {
  13473. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13474. iq.c('login-url', {
  13475. xmlns: 'http://jitsi.org/protocol/focus',
  13476. room: roomName,
  13477. 'machine-uid': Settings.getSettings().uid
  13478. });
  13479. connection.sendIQ(
  13480. iq,
  13481. function (result) {
  13482. var url = $(result).find('login-url').attr('url');
  13483. url = url = decodeURIComponent(url);
  13484. if (url) {
  13485. console.info("Got auth url: " + url);
  13486. urlCallback(url);
  13487. } else {
  13488. console.error(
  13489. "Failed to get auth url from the focus", result);
  13490. }
  13491. },
  13492. function (error) {
  13493. console.error("Get auth url error", error);
  13494. }
  13495. );
  13496. },
  13497. getPopupLoginUrl: function (roomName, urlCallback) {
  13498. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13499. iq.c('login-url', {
  13500. xmlns: 'http://jitsi.org/protocol/focus',
  13501. room: roomName,
  13502. 'machine-uid': Settings.getSettings().uid,
  13503. popup: true
  13504. });
  13505. connection.sendIQ(
  13506. iq,
  13507. function (result) {
  13508. var url = $(result).find('login-url').attr('url');
  13509. url = url = decodeURIComponent(url);
  13510. if (url) {
  13511. console.info("Got POPUP auth url: " + url);
  13512. urlCallback(url);
  13513. } else {
  13514. console.error(
  13515. "Failed to get POPUP auth url from the focus", result);
  13516. }
  13517. },
  13518. function (error) {
  13519. console.error('Get POPUP auth url error', error);
  13520. }
  13521. );
  13522. },
  13523. logout: function (callback) {
  13524. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  13525. var sessionId = localStorage.getItem('sessionId');
  13526. if (!sessionId) {
  13527. callback();
  13528. return;
  13529. }
  13530. iq.c('logout', {
  13531. xmlns: 'http://jitsi.org/protocol/focus',
  13532. 'session-id': sessionId
  13533. });
  13534. connection.sendIQ(
  13535. iq,
  13536. function (result) {
  13537. var logoutUrl = $(result).find('logout').attr('logout-url');
  13538. if (logoutUrl) {
  13539. logoutUrl = decodeURIComponent(logoutUrl);
  13540. }
  13541. console.info("Log out OK, url: " + logoutUrl, result);
  13542. localStorage.removeItem('sessionId');
  13543. callback(logoutUrl);
  13544. },
  13545. function (error) {
  13546. console.error("Logout error", error);
  13547. }
  13548. );
  13549. }
  13550. };
  13551. module.exports = Moderator;
  13552. },{"../../service/authentication/AuthenticationEvents":107,"../../service/xmpp/XMPPEvents":112,"../settings/Settings":41}],52:[function(require,module,exports){
  13553. /*
  13554. * Copyright @ 2015 Atlassian Pty Ltd
  13555. *
  13556. * Licensed under the Apache License, Version 2.0 (the "License");
  13557. * you may not use this file except in compliance with the License.
  13558. * You may obtain a copy of the License at
  13559. *
  13560. * http://www.apache.org/licenses/LICENSE-2.0
  13561. *
  13562. * Unless required by applicable law or agreed to in writing, software
  13563. * distributed under the License is distributed on an "AS IS" BASIS,
  13564. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13565. * See the License for the specific language governing permissions and
  13566. * limitations under the License.
  13567. */
  13568. /* global $, $iq, config, connection, focusMucJid, messageHandler, Moderator,
  13569. Toolbar, Util */
  13570. var Moderator = require("./moderator");
  13571. var recordingToken = null;
  13572. var recordingEnabled;
  13573. /**
  13574. * Whether to use a jirecon component for recording, or use the videobridge
  13575. * through COLIBRI.
  13576. */
  13577. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  13578. /**
  13579. * The ID of the jirecon recording session. Jirecon generates it when we
  13580. * initially start recording, and it needs to be used in subsequent requests
  13581. * to jirecon.
  13582. */
  13583. var jireconRid = null;
  13584. function setRecordingToken(token) {
  13585. recordingToken = token;
  13586. }
  13587. function setRecording(state, token, callback, connection) {
  13588. if (useJirecon){
  13589. setRecordingJirecon(state, token, callback, connection);
  13590. } else {
  13591. setRecordingColibri(state, token, callback, connection);
  13592. }
  13593. }
  13594. function setRecordingJirecon(state, token, callback, connection) {
  13595. if (state == recordingEnabled){
  13596. return;
  13597. }
  13598. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  13599. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  13600. action: state ? 'start' : 'stop',
  13601. mucjid: connection.emuc.roomjid});
  13602. if (!state){
  13603. iq.attrs({rid: jireconRid});
  13604. }
  13605. console.log('Start recording');
  13606. connection.sendIQ(
  13607. iq,
  13608. function (result) {
  13609. // TODO wait for an IQ with the real status, since this is
  13610. // provisional?
  13611. jireconRid = $(result).find('recording').attr('rid');
  13612. console.log('Recording ' + (state ? 'started' : 'stopped') +
  13613. '(jirecon)' + result);
  13614. recordingEnabled = state;
  13615. if (!state){
  13616. jireconRid = null;
  13617. }
  13618. callback(state);
  13619. },
  13620. function (error) {
  13621. console.log('Failed to start recording, error: ', error);
  13622. callback(recordingEnabled);
  13623. });
  13624. }
  13625. // Sends a COLIBRI message which enables or disables (according to 'state')
  13626. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  13627. // with the new recording state, according to the IQ.
  13628. function setRecordingColibri(state, token, callback, connection) {
  13629. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  13630. elem.c('conference', {
  13631. xmlns: 'http://jitsi.org/protocol/colibri'
  13632. });
  13633. elem.c('recording', {state: state, token: token});
  13634. connection.sendIQ(elem,
  13635. function (result) {
  13636. console.log('Set recording "', state, '". Result:', result);
  13637. var recordingElem = $(result).find('>conference>recording');
  13638. var newState = ('true' === recordingElem.attr('state'));
  13639. recordingEnabled = newState;
  13640. callback(newState);
  13641. },
  13642. function (error) {
  13643. console.warn(error);
  13644. callback(recordingEnabled);
  13645. }
  13646. );
  13647. }
  13648. var Recording = {
  13649. toggleRecording: function (tokenEmptyCallback,
  13650. startingCallback, startedCallback, connection) {
  13651. if (!Moderator.isModerator()) {
  13652. console.log(
  13653. 'non-focus, or conference not yet organized:' +
  13654. ' not enabling recording');
  13655. return;
  13656. }
  13657. var self = this;
  13658. // Jirecon does not (currently) support a token.
  13659. if (!recordingToken && !useJirecon) {
  13660. tokenEmptyCallback(function (value) {
  13661. setRecordingToken(value);
  13662. self.toggleRecording(tokenEmptyCallback,
  13663. startingCallback, startedCallback, connection);
  13664. });
  13665. return;
  13666. }
  13667. var oldState = recordingEnabled;
  13668. startingCallback(!oldState);
  13669. setRecording(!oldState,
  13670. recordingToken,
  13671. function (state) {
  13672. console.log("New recording state: ", state);
  13673. if (state === oldState) {
  13674. // FIXME: new focus:
  13675. // this will not work when moderator changes
  13676. // during active session. Then it will assume that
  13677. // recording status has changed to true, but it might have
  13678. // been already true(and we only received actual status from
  13679. // the focus).
  13680. //
  13681. // SO we start with status null, so that it is initialized
  13682. // here and will fail only after second click, so if invalid
  13683. // token was used we have to press the button twice before
  13684. // current status will be fetched and token will be reset.
  13685. //
  13686. // Reliable way would be to return authentication error.
  13687. // Or status update when moderator connects.
  13688. // Or we have to stop recording session when current
  13689. // moderator leaves the room.
  13690. // Failed to change, reset the token because it might
  13691. // have been wrong
  13692. setRecordingToken(null);
  13693. }
  13694. startedCallback(state);
  13695. },
  13696. connection
  13697. );
  13698. }
  13699. }
  13700. module.exports = Recording;
  13701. },{"./moderator":51}],53:[function(require,module,exports){
  13702. /*
  13703. * Copyright @ 2015 Atlassian Pty Ltd
  13704. *
  13705. * Licensed under the Apache License, Version 2.0 (the "License");
  13706. * you may not use this file except in compliance with the License.
  13707. * You may obtain a copy of the License at
  13708. *
  13709. * http://www.apache.org/licenses/LICENSE-2.0
  13710. *
  13711. * Unless required by applicable law or agreed to in writing, software
  13712. * distributed under the License is distributed on an "AS IS" BASIS,
  13713. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13714. * See the License for the specific language governing permissions and
  13715. * limitations under the License.
  13716. */
  13717. /* jshint -W117 */
  13718. /* a simple MUC connection plugin
  13719. * can only handle a single MUC room
  13720. */
  13721. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13722. var Moderator = require("./moderator");
  13723. var JingleSession = require("./JingleSession");
  13724. var bridgeIsDown = false;
  13725. module.exports = function(XMPP, eventEmitter) {
  13726. Strophe.addConnectionPlugin('emuc', {
  13727. connection: null,
  13728. roomjid: null,
  13729. myroomjid: null,
  13730. members: {},
  13731. list_members: [], // so we can elect a new focus
  13732. presMap: {},
  13733. preziMap: {},
  13734. joined: false,
  13735. isOwner: false,
  13736. role: null,
  13737. focusMucJid: null,
  13738. ssrc2jid: {},
  13739. init: function (conn) {
  13740. this.connection = conn;
  13741. },
  13742. initPresenceMap: function (myroomjid) {
  13743. this.presMap['to'] = myroomjid;
  13744. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  13745. if(APP.RTC.localAudio.isMuted())
  13746. {
  13747. this.addAudioInfoToPresence(true);
  13748. }
  13749. if(APP.RTC.localVideo.isMuted())
  13750. {
  13751. this.addVideoInfoToPresence(true);
  13752. }
  13753. },
  13754. doJoin: function (jid, password) {
  13755. this.myroomjid = jid;
  13756. console.info("Joined MUC as " + this.myroomjid);
  13757. this.initPresenceMap(this.myroomjid);
  13758. if (!this.roomjid) {
  13759. this.roomjid = Strophe.getBareJidFromJid(jid);
  13760. // add handlers (just once)
  13761. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  13762. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  13763. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  13764. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  13765. }
  13766. if (password !== undefined) {
  13767. this.presMap['password'] = password;
  13768. }
  13769. this.sendPresence();
  13770. },
  13771. doLeave: function () {
  13772. console.log("do leave", this.myroomjid);
  13773. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  13774. this.presMap.length = 0;
  13775. this.connection.send(pres);
  13776. },
  13777. createNonAnonymousRoom: function () {
  13778. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  13779. var getForm = $iq({type: 'get', to: this.roomjid})
  13780. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  13781. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13782. var self = this;
  13783. this.connection.sendIQ(getForm, function (form) {
  13784. if (!$(form).find(
  13785. '>query>x[xmlns="jabber:x:data"]' +
  13786. '>field[var="muc#roomconfig_whois"]').length) {
  13787. console.error('non-anonymous rooms not supported');
  13788. return;
  13789. }
  13790. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  13791. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  13792. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13793. formSubmit.c('field', {'var': 'FORM_TYPE'})
  13794. .c('value')
  13795. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  13796. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  13797. .c('value').t('anyone').up().up();
  13798. self.connection.sendIQ(formSubmit);
  13799. }, function (error) {
  13800. console.error("Error getting room configuration form");
  13801. });
  13802. },
  13803. onPresence: function (pres) {
  13804. var from = pres.getAttribute('from');
  13805. // What is this for? A workaround for something?
  13806. if (pres.getAttribute('type')) {
  13807. return true;
  13808. }
  13809. // Parse etherpad tag.
  13810. var etherpad = $(pres).find('>etherpad');
  13811. if (etherpad.length) {
  13812. if (config.etherpad_base) {
  13813. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  13814. }
  13815. }
  13816. // Parse prezi tag.
  13817. var presentation = $(pres).find('>prezi');
  13818. if (presentation.length) {
  13819. var url = presentation.attr('url');
  13820. var current = presentation.find('>current').text();
  13821. console.log('presentation info received from', from, url);
  13822. if (this.preziMap[from] == null) {
  13823. this.preziMap[from] = url;
  13824. $(document).trigger('presentationadded.muc', [from, url, current]);
  13825. }
  13826. else {
  13827. $(document).trigger('gotoslide.muc', [from, url, current]);
  13828. }
  13829. }
  13830. else if (this.preziMap[from] != null) {
  13831. var url = this.preziMap[from];
  13832. delete this.preziMap[from];
  13833. $(document).trigger('presentationremoved.muc', [from, url]);
  13834. }
  13835. // Parse audio info tag.
  13836. var audioMuted = $(pres).find('>audiomuted');
  13837. if (audioMuted.length) {
  13838. $(document).trigger('audiomuted.muc', [from, audioMuted.text()]);
  13839. }
  13840. // Parse video info tag.
  13841. var videoMuted = $(pres).find('>videomuted');
  13842. if (videoMuted.length) {
  13843. $(document).trigger('videomuted.muc', [from, videoMuted.text()]);
  13844. }
  13845. var startMuted = $(pres).find('>startmuted');
  13846. if (startMuted.length)
  13847. {
  13848. eventEmitter.emit(XMPPEvents.START_MUTED,
  13849. startMuted.attr("audio") === "true", startMuted.attr("video") === "true");
  13850. }
  13851. var devices = $(pres).find('>devices');
  13852. if(devices.length)
  13853. {
  13854. var audio = devices.find('>audio');
  13855. var video = devices.find('>video');
  13856. var devicesValues = {audio: false, video: false};
  13857. if(audio.length && audio.text() === "true")
  13858. {
  13859. devicesValues.audio = true;
  13860. }
  13861. if(video.length && video.text() === "true")
  13862. {
  13863. devicesValues.video = true;
  13864. }
  13865. eventEmitter.emit(XMPPEvents.DEVICE_AVAILABLE,
  13866. Strophe.getResourceFromJid(from), devicesValues);
  13867. }
  13868. var stats = $(pres).find('>stats');
  13869. if (stats.length) {
  13870. var statsObj = {};
  13871. Strophe.forEachChild(stats[0], "stat", function (el) {
  13872. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  13873. });
  13874. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  13875. }
  13876. // Parse status.
  13877. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  13878. this.isOwner = true;
  13879. this.createNonAnonymousRoom();
  13880. }
  13881. // Parse roles.
  13882. var member = {};
  13883. member.show = $(pres).find('>show').text();
  13884. member.status = $(pres).find('>status').text();
  13885. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  13886. member.affiliation = tmp.attr('affiliation');
  13887. member.role = tmp.attr('role');
  13888. // Focus recognition
  13889. member.jid = tmp.attr('jid');
  13890. member.isFocus = false;
  13891. if (member.jid
  13892. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  13893. member.isFocus = true;
  13894. }
  13895. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  13896. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  13897. if (from == this.myroomjid) {
  13898. if (member.affiliation == 'owner') this.isOwner = true;
  13899. if (this.role !== member.role) {
  13900. this.role = member.role;
  13901. eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  13902. from, member, pres, Moderator.isModerator());
  13903. }
  13904. if (!this.joined) {
  13905. this.joined = true;
  13906. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  13907. this.list_members.push(from);
  13908. }
  13909. } else if (this.members[from] === undefined) {
  13910. // new participant
  13911. this.members[from] = member;
  13912. this.list_members.push(from);
  13913. console.log('entered', from, member);
  13914. if (member.isFocus) {
  13915. this.focusMucJid = from;
  13916. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  13917. }
  13918. else {
  13919. var id = $(pres).find('>userId').text();
  13920. var email = $(pres).find('>email');
  13921. if (email.length > 0) {
  13922. id = email.text();
  13923. }
  13924. eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, id, member.displayName);
  13925. }
  13926. } else {
  13927. // Presence update for existing participant
  13928. // Watch role change:
  13929. if (this.members[from].role != member.role) {
  13930. this.members[from].role = member.role;
  13931. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  13932. member.role, member.displayName);
  13933. }
  13934. }
  13935. // Always trigger presence to update bindings
  13936. this.parsePresence(from, member, pres);
  13937. // Trigger status message update
  13938. if (member.status) {
  13939. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  13940. }
  13941. return true;
  13942. },
  13943. onPresenceUnavailable: function (pres) {
  13944. var from = pres.getAttribute('from');
  13945. // room destroyed ?
  13946. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  13947. '>destroy').length) {
  13948. var reason;
  13949. var reasonSelect = $(pres).find(
  13950. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  13951. '>destroy>reason');
  13952. if (reasonSelect.length) {
  13953. reason = reasonSelect.text();
  13954. }
  13955. XMPP.disposeConference(false);
  13956. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  13957. return true;
  13958. }
  13959. var self = this;
  13960. // Remove old ssrcs coming from the jid
  13961. Object.keys(this.ssrc2jid).forEach(function (ssrc) {
  13962. if (self.ssrc2jid[ssrc] == from) {
  13963. delete self.ssrc2jid[ssrc];
  13964. }
  13965. });
  13966. // Status code 110 indicates that this notification is "self-presence".
  13967. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  13968. delete this.members[from];
  13969. this.list_members.splice(this.list_members.indexOf(from), 1);
  13970. this.onParticipantLeft(from);
  13971. }
  13972. // If the status code is 110 this means we're leaving and we would like
  13973. // to remove everyone else from our view, so we trigger the event.
  13974. else if (this.list_members.length > 1) {
  13975. for (var i = 0; i < this.list_members.length; i++) {
  13976. var member = this.list_members[i];
  13977. delete this.members[i];
  13978. this.list_members.splice(i, 1);
  13979. this.onParticipantLeft(member);
  13980. }
  13981. }
  13982. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  13983. $(document).trigger('kicked.muc', [from]);
  13984. if (this.myroomjid === from) {
  13985. XMPP.disposeConference(false);
  13986. eventEmitter.emit(XMPPEvents.KICKED);
  13987. }
  13988. }
  13989. return true;
  13990. },
  13991. onPresenceError: function (pres) {
  13992. var from = pres.getAttribute('from');
  13993. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13994. console.log('on password required', from);
  13995. var self = this;
  13996. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  13997. self.doJoin(from, value);
  13998. });
  13999. } else if ($(pres).find(
  14000. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  14001. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  14002. if (toDomain === config.hosts.anonymousdomain) {
  14003. // enter the room by replying with 'not-authorized'. This would
  14004. // result in reconnection from authorized domain.
  14005. // We're either missing Jicofo/Prosody config for anonymous
  14006. // domains or something is wrong.
  14007. // XMPP.promptLogin();
  14008. APP.UI.messageHandler.openReportDialog(null,
  14009. "dialog.joinError", pres);
  14010. } else {
  14011. console.warn('onPresError ', pres);
  14012. APP.UI.messageHandler.openReportDialog(null,
  14013. "dialog.connectError",
  14014. pres);
  14015. }
  14016. } else {
  14017. console.warn('onPresError ', pres);
  14018. APP.UI.messageHandler.openReportDialog(null,
  14019. "dialog.connectError",
  14020. pres);
  14021. }
  14022. return true;
  14023. },
  14024. sendMessage: function (body, nickname) {
  14025. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  14026. msg.c('body', body).up();
  14027. if (nickname) {
  14028. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  14029. }
  14030. this.connection.send(msg);
  14031. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  14032. },
  14033. setSubject: function (subject) {
  14034. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  14035. msg.c('subject', subject);
  14036. this.connection.send(msg);
  14037. console.log("topic changed to " + subject);
  14038. },
  14039. onMessage: function (msg) {
  14040. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  14041. var from = msg.getAttribute('from');
  14042. var nick =
  14043. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  14044. .text() ||
  14045. Strophe.getResourceFromJid(from);
  14046. var txt = $(msg).find('>body').text();
  14047. var type = msg.getAttribute("type");
  14048. if (type == "error") {
  14049. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  14050. $(msg).find('>text').text(), txt);
  14051. return true;
  14052. }
  14053. var subject = $(msg).find('>subject');
  14054. if (subject.length) {
  14055. var subjectText = subject.text();
  14056. if (subjectText || subjectText == "") {
  14057. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  14058. console.log("Subject is changed to " + subjectText);
  14059. }
  14060. }
  14061. if (txt) {
  14062. console.log('chat', nick, txt);
  14063. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  14064. from, nick, txt, this.myroomjid);
  14065. }
  14066. return true;
  14067. },
  14068. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  14069. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  14070. var ob = this;
  14071. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  14072. function (res) {
  14073. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  14074. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  14075. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  14076. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  14077. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  14078. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  14079. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  14080. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  14081. ob.connection.sendIQ(formsubmit,
  14082. onSuccess,
  14083. onError);
  14084. } else {
  14085. onNotSupported();
  14086. }
  14087. }, onError);
  14088. },
  14089. kick: function (jid) {
  14090. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  14091. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  14092. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  14093. .c('reason').t('You have been kicked.').up().up().up();
  14094. this.connection.sendIQ(
  14095. kickIQ,
  14096. function (result) {
  14097. console.log('Kick participant with jid: ', jid, result);
  14098. },
  14099. function (error) {
  14100. console.log('Kick participant error: ', error);
  14101. });
  14102. },
  14103. sendPresence: function () {
  14104. if (!this.presMap['to']) {
  14105. // Too early to send presence - not initialized
  14106. return;
  14107. }
  14108. var pres = $pres({to: this.presMap['to'] });
  14109. pres.c('x', {xmlns: this.presMap['xns']});
  14110. if (this.presMap['password']) {
  14111. pres.c('password').t(this.presMap['password']).up();
  14112. }
  14113. pres.up();
  14114. // Send XEP-0115 'c' stanza that contains our capabilities info
  14115. if (this.connection.caps) {
  14116. this.connection.caps.node = config.clientNode;
  14117. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  14118. }
  14119. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  14120. .t(navigator.userAgent).up();
  14121. if (this.presMap['bridgeIsDown']) {
  14122. pres.c('bridgeIsDown').up();
  14123. }
  14124. if (this.presMap['email']) {
  14125. pres.c('email').t(this.presMap['email']).up();
  14126. }
  14127. if (this.presMap['userId']) {
  14128. pres.c('userId').t(this.presMap['userId']).up();
  14129. }
  14130. if (this.presMap['displayName']) {
  14131. // XEP-0172
  14132. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  14133. .t(this.presMap['displayName']).up();
  14134. }
  14135. if(this.presMap["devices"])
  14136. {
  14137. pres.c('devices').c('audio').t(this.presMap['devices'].audio).up()
  14138. .c('video').t(this.presMap['devices'].video).up().up();
  14139. }
  14140. if (this.presMap['audions']) {
  14141. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  14142. .t(this.presMap['audiomuted']).up();
  14143. }
  14144. if (this.presMap['videons']) {
  14145. pres.c('videomuted', {xmlns: this.presMap['videons']})
  14146. .t(this.presMap['videomuted']).up();
  14147. }
  14148. if (this.presMap['statsns']) {
  14149. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  14150. for (var stat in this.presMap["stats"])
  14151. if (this.presMap["stats"][stat] != null)
  14152. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  14153. pres.up();
  14154. }
  14155. if (this.presMap['prezins']) {
  14156. pres.c('prezi',
  14157. {xmlns: this.presMap['prezins'],
  14158. 'url': this.presMap['preziurl']})
  14159. .c('current').t(this.presMap['prezicurrent']).up().up();
  14160. }
  14161. if (this.presMap['medians']) {
  14162. pres.c('media', {xmlns: this.presMap['medians']});
  14163. var sourceNumber = 0;
  14164. Object.keys(this.presMap).forEach(function (key) {
  14165. if (key.indexOf('source') >= 0) {
  14166. sourceNumber++;
  14167. }
  14168. });
  14169. if (sourceNumber > 0)
  14170. for (var i = 1; i <= sourceNumber / 3; i++) {
  14171. pres.c('source',
  14172. {type: this.presMap['source' + i + '_type'],
  14173. ssrc: this.presMap['source' + i + '_ssrc'],
  14174. direction: this.presMap['source' + i + '_direction']
  14175. || 'sendrecv' }
  14176. ).up();
  14177. }
  14178. pres.up();
  14179. }
  14180. if(this.presMap["startMuted"] !== undefined)
  14181. {
  14182. pres.c("startmuted", {audio: this.presMap["startMuted"].audio,
  14183. video: this.presMap["startMuted"].video,
  14184. xmlns: "http://jitsi.org/jitmeet/start-muted"});
  14185. delete this.presMap["startMuted"];
  14186. }
  14187. pres.up();
  14188. this.connection.send(pres);
  14189. },
  14190. addDisplayNameToPresence: function (displayName) {
  14191. this.presMap['displayName'] = displayName;
  14192. },
  14193. addMediaToPresence: function (sourceNumber, mtype, ssrcs, direction) {
  14194. if (!this.presMap['medians'])
  14195. this.presMap['medians'] = 'http://estos.de/ns/mjs';
  14196. this.presMap['source' + sourceNumber + '_type'] = mtype;
  14197. this.presMap['source' + sourceNumber + '_ssrc'] = ssrcs;
  14198. this.presMap['source' + sourceNumber + '_direction'] = direction;
  14199. },
  14200. addDevicesToPresence: function (devices) {
  14201. this.presMap['devices'] = devices;
  14202. },
  14203. clearPresenceMedia: function () {
  14204. var self = this;
  14205. Object.keys(this.presMap).forEach(function (key) {
  14206. if (key.indexOf('source') != -1) {
  14207. delete self.presMap[key];
  14208. }
  14209. });
  14210. },
  14211. addPreziToPresence: function (url, currentSlide) {
  14212. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  14213. this.presMap['preziurl'] = url;
  14214. this.presMap['prezicurrent'] = currentSlide;
  14215. },
  14216. removePreziFromPresence: function () {
  14217. delete this.presMap['prezins'];
  14218. delete this.presMap['preziurl'];
  14219. delete this.presMap['prezicurrent'];
  14220. },
  14221. addCurrentSlideToPresence: function (currentSlide) {
  14222. this.presMap['prezicurrent'] = currentSlide;
  14223. },
  14224. getPrezi: function (roomjid) {
  14225. return this.preziMap[roomjid];
  14226. },
  14227. addAudioInfoToPresence: function (isMuted) {
  14228. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  14229. this.presMap['audiomuted'] = isMuted.toString();
  14230. },
  14231. addVideoInfoToPresence: function (isMuted) {
  14232. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  14233. this.presMap['videomuted'] = isMuted.toString();
  14234. },
  14235. addConnectionInfoToPresence: function (stats) {
  14236. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  14237. this.presMap['stats'] = stats;
  14238. },
  14239. findJidFromResource: function (resourceJid) {
  14240. if (resourceJid &&
  14241. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  14242. return this.myroomjid;
  14243. }
  14244. var peerJid = null;
  14245. Object.keys(this.members).some(function (jid) {
  14246. peerJid = jid;
  14247. return Strophe.getResourceFromJid(jid) === resourceJid;
  14248. });
  14249. return peerJid;
  14250. },
  14251. addBridgeIsDownToPresence: function () {
  14252. this.presMap['bridgeIsDown'] = true;
  14253. },
  14254. addEmailToPresence: function (email) {
  14255. this.presMap['email'] = email;
  14256. },
  14257. addUserIdToPresence: function (userId) {
  14258. this.presMap['userId'] = userId;
  14259. },
  14260. addStartMutedToPresence: function (audio, video) {
  14261. this.presMap["startMuted"] = {audio: audio, video: video};
  14262. },
  14263. isModerator: function () {
  14264. return this.role === 'moderator';
  14265. },
  14266. getMemberRole: function (peerJid) {
  14267. if (this.members[peerJid]) {
  14268. return this.members[peerJid].role;
  14269. }
  14270. return null;
  14271. },
  14272. onParticipantLeft: function (jid) {
  14273. eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  14274. this.connection.jingle.terminateByJid(jid);
  14275. if (this.getPrezi(jid)) {
  14276. $(document).trigger('presentationremoved.muc',
  14277. [jid, this.getPrezi(jid)]);
  14278. }
  14279. Moderator.onMucMemberLeft(jid);
  14280. },
  14281. parsePresence: function (from, memeber, pres) {
  14282. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  14283. bridgeIsDown = true;
  14284. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  14285. }
  14286. if(memeber.isFocus)
  14287. return;
  14288. var self = this;
  14289. // Remove old ssrcs coming from the jid
  14290. Object.keys(this.ssrc2jid).forEach(function (ssrc) {
  14291. if (self.ssrc2jid[ssrc] == from) {
  14292. delete self.ssrc2jid[ssrc];
  14293. }
  14294. });
  14295. var changedStreams = [];
  14296. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  14297. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  14298. var ssrcV = ssrc.getAttribute('ssrc');
  14299. self.ssrc2jid[ssrcV] = from;
  14300. var type = ssrc.getAttribute('type');
  14301. var direction = ssrc.getAttribute('direction');
  14302. changedStreams.push({type: type, direction: direction});
  14303. });
  14304. eventEmitter.emit(XMPPEvents.STREAMS_CHANGED, from, changedStreams);
  14305. var displayName = !config.displayJids
  14306. ? memeber.displayName : Strophe.getResourceFromJid(from);
  14307. if (displayName && displayName.length > 0)
  14308. {
  14309. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  14310. }
  14311. var id = $(pres).find('>userID').text();
  14312. var email = $(pres).find('>email');
  14313. if(email.length > 0) {
  14314. id = email.text();
  14315. }
  14316. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  14317. }
  14318. });
  14319. };
  14320. },{"../../service/xmpp/XMPPEvents":112,"./JingleSession":46,"./moderator":51}],54:[function(require,module,exports){
  14321. /*
  14322. * Copyright @ 2015 Atlassian Pty Ltd
  14323. *
  14324. * Licensed under the Apache License, Version 2.0 (the "License");
  14325. * you may not use this file except in compliance with the License.
  14326. * You may obtain a copy of the License at
  14327. *
  14328. * http://www.apache.org/licenses/LICENSE-2.0
  14329. *
  14330. * Unless required by applicable law or agreed to in writing, software
  14331. * distributed under the License is distributed on an "AS IS" BASIS,
  14332. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14333. * See the License for the specific language governing permissions and
  14334. * limitations under the License.
  14335. */
  14336. /* jshint -W117 */
  14337. var JingleSession = require("./JingleSession");
  14338. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14339. module.exports = function(XMPP, eventEmitter)
  14340. {
  14341. function CallIncomingJingle(sid, connection) {
  14342. var sess = connection.jingle.sessions[sid];
  14343. // TODO: do we check activecall == null?
  14344. connection.jingle.activecall = sess;
  14345. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  14346. // TODO: check affiliation and/or role
  14347. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  14348. sess.usedrip = true; // not-so-naive trickle ice
  14349. sess.sendAnswer();
  14350. sess.accept();
  14351. };
  14352. Strophe.addConnectionPlugin('jingle', {
  14353. connection: null,
  14354. sessions: {},
  14355. jid2session: {},
  14356. ice_config: {iceServers: []},
  14357. pc_constraints: {},
  14358. activecall: null,
  14359. media_constraints: {
  14360. mandatory: {
  14361. 'OfferToReceiveAudio': true,
  14362. 'OfferToReceiveVideo': true
  14363. }
  14364. // MozDontOfferDataChannel: true when this is firefox
  14365. },
  14366. init: function (conn) {
  14367. this.connection = conn;
  14368. if (this.connection.disco) {
  14369. // http://xmpp.org/extensions/xep-0167.html#support
  14370. // http://xmpp.org/extensions/xep-0176.html#support
  14371. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  14372. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  14373. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  14374. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  14375. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  14376. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  14377. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  14378. // this is dealt with by SDP O/A so we don't need to annouce this
  14379. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  14380. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  14381. if (config.useRtcpMux) {
  14382. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  14383. }
  14384. if (config.useBundle) {
  14385. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  14386. }
  14387. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  14388. }
  14389. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  14390. },
  14391. onJingle: function (iq) {
  14392. var sid = $(iq).find('jingle').attr('sid');
  14393. var action = $(iq).find('jingle').attr('action');
  14394. var fromJid = iq.getAttribute('from');
  14395. // send ack first
  14396. var ack = $iq({type: 'result',
  14397. to: fromJid,
  14398. id: iq.getAttribute('id')
  14399. });
  14400. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  14401. var sess = this.sessions[sid];
  14402. if ('session-initiate' != action) {
  14403. if (sess === null) {
  14404. ack.type = 'error';
  14405. ack.c('error', {type: 'cancel'})
  14406. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  14407. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  14408. this.connection.send(ack);
  14409. return true;
  14410. }
  14411. // compare from to sess.peerjid (bare jid comparison for later compat with message-mode)
  14412. // local jid is not checked
  14413. if (Strophe.getBareJidFromJid(fromJid) != Strophe.getBareJidFromJid(sess.peerjid)) {
  14414. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  14415. ack.type = 'error';
  14416. ack.c('error', {type: 'cancel'})
  14417. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  14418. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  14419. this.connection.send(ack);
  14420. return true;
  14421. }
  14422. } else if (sess !== undefined) {
  14423. // existing session with same session id
  14424. // this might be out-of-order if the sess.peerjid is the same as from
  14425. ack.type = 'error';
  14426. ack.c('error', {type: 'cancel'})
  14427. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  14428. console.warn('duplicate session id', sid);
  14429. this.connection.send(ack);
  14430. return true;
  14431. }
  14432. // FIXME: check for a defined action
  14433. this.connection.send(ack);
  14434. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  14435. switch (action) {
  14436. case 'session-initiate':
  14437. var startMuted = $(iq).find('jingle>startmuted');
  14438. if(startMuted && startMuted.length > 0)
  14439. {
  14440. var audioMuted = startMuted.attr("audio");
  14441. var videoMuted = startMuted.attr("video");
  14442. APP.UI.setInitialMuteFromFocus((audioMuted === "true"),
  14443. (videoMuted === "true"));
  14444. }
  14445. sess = new JingleSession(
  14446. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  14447. this.connection, XMPP);
  14448. // configure session
  14449. sess.media_constraints = this.media_constraints;
  14450. sess.pc_constraints = this.pc_constraints;
  14451. sess.ice_config = this.ice_config;
  14452. sess.initiate(fromJid, false);
  14453. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  14454. sess.setRemoteDescription($(iq).find('>jingle'), 'offer');
  14455. this.sessions[sess.sid] = sess;
  14456. this.jid2session[sess.peerjid] = sess;
  14457. // the callback should either
  14458. // .sendAnswer and .accept
  14459. // or .sendTerminate -- not necessarily synchronus
  14460. CallIncomingJingle(sess.sid, this.connection);
  14461. break;
  14462. case 'session-accept':
  14463. sess.setRemoteDescription($(iq).find('>jingle'), 'answer');
  14464. sess.accept();
  14465. $(document).trigger('callaccepted.jingle', [sess.sid]);
  14466. break;
  14467. case 'session-terminate':
  14468. // If this is not the focus sending the terminate, we have
  14469. // nothing more to do here.
  14470. if (Object.keys(this.sessions).length < 1
  14471. || !(this.sessions[Object.keys(this.sessions)[0]]
  14472. instanceof JingleSession))
  14473. {
  14474. break;
  14475. }
  14476. console.log('terminating...', sess.sid);
  14477. sess.terminate();
  14478. this.terminate(sess.sid);
  14479. if ($(iq).find('>jingle>reason').length) {
  14480. $(document).trigger('callterminated.jingle', [
  14481. sess.sid,
  14482. sess.peerjid,
  14483. $(iq).find('>jingle>reason>:first')[0].tagName,
  14484. $(iq).find('>jingle>reason>text').text()
  14485. ]);
  14486. } else {
  14487. $(document).trigger('callterminated.jingle',
  14488. [sess.sid, sess.peerjid]);
  14489. }
  14490. break;
  14491. case 'transport-info':
  14492. sess.addIceCandidate($(iq).find('>jingle>content'));
  14493. break;
  14494. case 'session-info':
  14495. var affected;
  14496. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14497. $(document).trigger('ringing.jingle', [sess.sid]);
  14498. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14499. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14500. $(document).trigger('mute.jingle', [sess.sid, affected]);
  14501. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14502. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14503. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  14504. }
  14505. break;
  14506. case 'addsource': // FIXME: proprietary, un-jingleish
  14507. case 'source-add': // FIXME: proprietary
  14508. sess.addSource($(iq).find('>jingle>content'), fromJid);
  14509. break;
  14510. case 'removesource': // FIXME: proprietary, un-jingleish
  14511. case 'source-remove': // FIXME: proprietary
  14512. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  14513. break;
  14514. default:
  14515. console.warn('jingle action not implemented', action);
  14516. break;
  14517. }
  14518. return true;
  14519. },
  14520. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  14521. var sess = new JingleSession(myjid || this.connection.jid,
  14522. Math.random().toString(36).substr(2, 12), // random string
  14523. this.connection, XMPP);
  14524. // configure session
  14525. sess.media_constraints = this.media_constraints;
  14526. sess.pc_constraints = this.pc_constraints;
  14527. sess.ice_config = this.ice_config;
  14528. sess.initiate(peerjid, true);
  14529. this.sessions[sess.sid] = sess;
  14530. this.jid2session[sess.peerjid] = sess;
  14531. sess.sendOffer();
  14532. return sess;
  14533. },
  14534. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  14535. if (sid === null || sid === undefined) {
  14536. for (sid in this.sessions) {
  14537. if (this.sessions[sid].state != 'ended') {
  14538. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14539. this.sessions[sid].terminate();
  14540. }
  14541. delete this.jid2session[this.sessions[sid].peerjid];
  14542. delete this.sessions[sid];
  14543. }
  14544. } else if (this.sessions.hasOwnProperty(sid)) {
  14545. if (this.sessions[sid].state != 'ended') {
  14546. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14547. this.sessions[sid].terminate();
  14548. }
  14549. delete this.jid2session[this.sessions[sid].peerjid];
  14550. delete this.sessions[sid];
  14551. }
  14552. },
  14553. // Used to terminate a session when an unavailable presence is received.
  14554. terminateByJid: function (jid) {
  14555. if (this.jid2session.hasOwnProperty(jid)) {
  14556. var sess = this.jid2session[jid];
  14557. if (sess) {
  14558. sess.terminate();
  14559. console.log('peer went away silently', jid);
  14560. delete this.sessions[sess.sid];
  14561. delete this.jid2session[jid];
  14562. $(document).trigger('callterminated.jingle',
  14563. [sess.sid, jid], 'gone');
  14564. }
  14565. }
  14566. },
  14567. terminateRemoteByJid: function (jid, reason) {
  14568. if (this.jid2session.hasOwnProperty(jid)) {
  14569. var sess = this.jid2session[jid];
  14570. if (sess) {
  14571. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  14572. sess.terminate();
  14573. console.log('terminate peer with jid', sess.sid, jid);
  14574. delete this.sessions[sess.sid];
  14575. delete this.jid2session[jid];
  14576. $(document).trigger('callterminated.jingle',
  14577. [sess.sid, jid, 'kicked']);
  14578. }
  14579. }
  14580. },
  14581. getStunAndTurnCredentials: function () {
  14582. // get stun and turn configuration from server via xep-0215
  14583. // uses time-limited credentials as described in
  14584. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  14585. //
  14586. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  14587. // for a prosody module which implements this
  14588. //
  14589. // currently, this doesn't work with updateIce and therefore credentials with a long
  14590. // validity have to be fetched before creating the peerconnection
  14591. // TODO: implement refresh via updateIce as described in
  14592. // https://code.google.com/p/webrtc/issues/detail?id=1650
  14593. var self = this;
  14594. this.connection.sendIQ(
  14595. $iq({type: 'get', to: this.connection.domain})
  14596. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  14597. function (res) {
  14598. var iceservers = [];
  14599. $(res).find('>services>service').each(function (idx, el) {
  14600. el = $(el);
  14601. var dict = {};
  14602. var type = el.attr('type');
  14603. switch (type) {
  14604. case 'stun':
  14605. dict.url = 'stun:' + el.attr('host');
  14606. if (el.attr('port')) {
  14607. dict.url += ':' + el.attr('port');
  14608. }
  14609. iceservers.push(dict);
  14610. break;
  14611. case 'turn':
  14612. case 'turns':
  14613. dict.url = type + ':';
  14614. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  14615. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  14616. dict.url += el.attr('username') + '@';
  14617. } else {
  14618. dict.username = el.attr('username'); // only works in M28
  14619. }
  14620. }
  14621. dict.url += el.attr('host');
  14622. if (el.attr('port') && el.attr('port') != '3478') {
  14623. dict.url += ':' + el.attr('port');
  14624. }
  14625. if (el.attr('transport') && el.attr('transport') != 'udp') {
  14626. dict.url += '?transport=' + el.attr('transport');
  14627. }
  14628. if (el.attr('password')) {
  14629. dict.credential = el.attr('password');
  14630. }
  14631. iceservers.push(dict);
  14632. break;
  14633. }
  14634. });
  14635. self.ice_config.iceServers = iceservers;
  14636. },
  14637. function (err) {
  14638. console.warn('getting turn credentials failed', err);
  14639. console.warn('is mod_turncredentials or similar installed?');
  14640. }
  14641. );
  14642. // implement push?
  14643. },
  14644. /**
  14645. * Populates the log data
  14646. */
  14647. populateData: function () {
  14648. var data = {};
  14649. var self = this;
  14650. Object.keys(this.sessions).forEach(function (sid) {
  14651. var session = self.sessions[sid];
  14652. if (session.peerconnection && session.peerconnection.updateLog) {
  14653. // FIXME: should probably be a .dump call
  14654. data["jingle_" + session.sid] = {
  14655. updateLog: session.peerconnection.updateLog,
  14656. stats: session.peerconnection.stats,
  14657. url: window.location.href
  14658. };
  14659. }
  14660. });
  14661. return data;
  14662. }
  14663. });
  14664. };
  14665. },{"../../service/xmpp/XMPPEvents":112,"./JingleSession":46}],55:[function(require,module,exports){
  14666. /*
  14667. * Copyright @ 2015 Atlassian Pty Ltd
  14668. *
  14669. * Licensed under the Apache License, Version 2.0 (the "License");
  14670. * you may not use this file except in compliance with the License.
  14671. * You may obtain a copy of the License at
  14672. *
  14673. * http://www.apache.org/licenses/LICENSE-2.0
  14674. *
  14675. * Unless required by applicable law or agreed to in writing, software
  14676. * distributed under the License is distributed on an "AS IS" BASIS,
  14677. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14678. * See the License for the specific language governing permissions and
  14679. * limitations under the License.
  14680. */
  14681. /* global Strophe */
  14682. module.exports = function () {
  14683. Strophe.addConnectionPlugin('logger', {
  14684. // logs raw stanzas and makes them available for download as JSON
  14685. connection: null,
  14686. log: [],
  14687. init: function (conn) {
  14688. this.connection = conn;
  14689. this.connection.rawInput = this.log_incoming.bind(this);
  14690. this.connection.rawOutput = this.log_outgoing.bind(this);
  14691. },
  14692. log_incoming: function (stanza) {
  14693. this.log.push([new Date().getTime(), 'incoming', stanza]);
  14694. },
  14695. log_outgoing: function (stanza) {
  14696. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  14697. }
  14698. });
  14699. };
  14700. },{}],56:[function(require,module,exports){
  14701. /*
  14702. * Copyright @ 2015 Atlassian Pty Ltd
  14703. *
  14704. * Licensed under the Apache License, Version 2.0 (the "License");
  14705. * you may not use this file except in compliance with the License.
  14706. * You may obtain a copy of the License at
  14707. *
  14708. * http://www.apache.org/licenses/LICENSE-2.0
  14709. *
  14710. * Unless required by applicable law or agreed to in writing, software
  14711. * distributed under the License is distributed on an "AS IS" BASIS,
  14712. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14713. * See the License for the specific language governing permissions and
  14714. * limitations under the License.
  14715. */
  14716. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  14717. setAudioMuted, Strophe */
  14718. /**
  14719. * Moderate connection plugin.
  14720. */
  14721. module.exports = function (XMPP) {
  14722. Strophe.addConnectionPlugin('moderate', {
  14723. connection: null,
  14724. init: function (conn) {
  14725. this.connection = conn;
  14726. this.connection.addHandler(this.onMute.bind(this),
  14727. 'http://jitsi.org/jitmeet/audio',
  14728. 'iq',
  14729. 'set',
  14730. null,
  14731. null);
  14732. },
  14733. setMute: function (jid, mute) {
  14734. console.info("set mute", mute);
  14735. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  14736. .c('mute', {
  14737. xmlns: 'http://jitsi.org/jitmeet/audio',
  14738. jid: jid
  14739. })
  14740. .t(mute.toString())
  14741. .up();
  14742. this.connection.sendIQ(
  14743. iqToFocus,
  14744. function (result) {
  14745. console.log('set mute', result);
  14746. },
  14747. function (error) {
  14748. console.log('set mute error', error);
  14749. });
  14750. },
  14751. onMute: function (iq) {
  14752. var from = iq.getAttribute('from');
  14753. if (from !== this.connection.emuc.focusMucJid) {
  14754. console.warn("Ignored mute from non focus peer");
  14755. return false;
  14756. }
  14757. var mute = $(iq).find('mute');
  14758. if (mute.length) {
  14759. var doMuteAudio = mute.text() === "true";
  14760. APP.UI.setAudioMuted(doMuteAudio);
  14761. XMPP.forceMuted = doMuteAudio;
  14762. }
  14763. return true;
  14764. },
  14765. eject: function (jid) {
  14766. // We're not the focus, so can't terminate
  14767. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  14768. this.connection.emuc.kick(jid);
  14769. }
  14770. });
  14771. }
  14772. },{}],57:[function(require,module,exports){
  14773. /*
  14774. * Copyright @ 2015 Atlassian Pty Ltd
  14775. *
  14776. * Licensed under the Apache License, Version 2.0 (the "License");
  14777. * you may not use this file except in compliance with the License.
  14778. * You may obtain a copy of the License at
  14779. *
  14780. * http://www.apache.org/licenses/LICENSE-2.0
  14781. *
  14782. * Unless required by applicable law or agreed to in writing, software
  14783. * distributed under the License is distributed on an "AS IS" BASIS,
  14784. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14785. * See the License for the specific language governing permissions and
  14786. * limitations under the License.
  14787. */
  14788. /* jshint -W117 */
  14789. module.exports = function() {
  14790. Strophe.addConnectionPlugin('rayo',
  14791. {
  14792. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  14793. connection: null,
  14794. init: function (conn) {
  14795. this.connection = conn;
  14796. if (this.connection.disco) {
  14797. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  14798. }
  14799. this.connection.addHandler(
  14800. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  14801. },
  14802. onRayo: function (iq) {
  14803. console.info("Rayo IQ", iq);
  14804. },
  14805. dial: function (to, from, roomName, roomPass) {
  14806. var self = this;
  14807. var req = $iq(
  14808. {
  14809. type: 'set',
  14810. to: this.connection.emuc.focusMucJid
  14811. }
  14812. );
  14813. req.c('dial',
  14814. {
  14815. xmlns: this.RAYO_XMLNS,
  14816. to: to,
  14817. from: from
  14818. });
  14819. req.c('header',
  14820. {
  14821. name: 'JvbRoomName',
  14822. value: roomName
  14823. }).up();
  14824. if (roomPass !== null && roomPass.length) {
  14825. req.c('header',
  14826. {
  14827. name: 'JvbRoomPassword',
  14828. value: roomPass
  14829. }).up();
  14830. }
  14831. this.connection.sendIQ(
  14832. req,
  14833. function (result) {
  14834. console.info('Dial result ', result);
  14835. var resource = $(result).find('ref').attr('uri');
  14836. this.call_resource = resource.substr('xmpp:'.length);
  14837. console.info(
  14838. "Received call resource: " + this.call_resource);
  14839. },
  14840. function (error) {
  14841. console.info('Dial error ', error);
  14842. }
  14843. );
  14844. },
  14845. hang_up: function () {
  14846. if (!this.call_resource) {
  14847. console.warn("No call in progress");
  14848. return;
  14849. }
  14850. var self = this;
  14851. var req = $iq(
  14852. {
  14853. type: 'set',
  14854. to: this.call_resource
  14855. }
  14856. );
  14857. req.c('hangup',
  14858. {
  14859. xmlns: this.RAYO_XMLNS
  14860. });
  14861. this.connection.sendIQ(
  14862. req,
  14863. function (result) {
  14864. console.info('Hangup result ', result);
  14865. self.call_resource = null;
  14866. },
  14867. function (error) {
  14868. console.info('Hangup error ', error);
  14869. self.call_resource = null;
  14870. }
  14871. );
  14872. }
  14873. }
  14874. );
  14875. };
  14876. },{}],58:[function(require,module,exports){
  14877. /*
  14878. * Copyright @ 2015 Atlassian Pty Ltd
  14879. *
  14880. * Licensed under the Apache License, Version 2.0 (the "License");
  14881. * you may not use this file except in compliance with the License.
  14882. * You may obtain a copy of the License at
  14883. *
  14884. * http://www.apache.org/licenses/LICENSE-2.0
  14885. *
  14886. * Unless required by applicable law or agreed to in writing, software
  14887. * distributed under the License is distributed on an "AS IS" BASIS,
  14888. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14889. * See the License for the specific language governing permissions and
  14890. * limitations under the License.
  14891. */
  14892. /**
  14893. * Strophe logger implementation. Logs from level WARN and above.
  14894. */
  14895. module.exports = function () {
  14896. Strophe.log = function (level, msg) {
  14897. switch (level) {
  14898. case Strophe.LogLevel.WARN:
  14899. console.warn("Strophe: " + msg);
  14900. break;
  14901. case Strophe.LogLevel.ERROR:
  14902. case Strophe.LogLevel.FATAL:
  14903. console.error("Strophe: " + msg);
  14904. break;
  14905. }
  14906. };
  14907. Strophe.getStatusString = function (status) {
  14908. switch (status) {
  14909. case Strophe.Status.ERROR:
  14910. return "ERROR";
  14911. case Strophe.Status.CONNECTING:
  14912. return "CONNECTING";
  14913. case Strophe.Status.CONNFAIL:
  14914. return "CONNFAIL";
  14915. case Strophe.Status.AUTHENTICATING:
  14916. return "AUTHENTICATING";
  14917. case Strophe.Status.AUTHFAIL:
  14918. return "AUTHFAIL";
  14919. case Strophe.Status.CONNECTED:
  14920. return "CONNECTED";
  14921. case Strophe.Status.DISCONNECTED:
  14922. return "DISCONNECTED";
  14923. case Strophe.Status.DISCONNECTING:
  14924. return "DISCONNECTING";
  14925. case Strophe.Status.ATTACHED:
  14926. return "ATTACHED";
  14927. default:
  14928. return "unknown";
  14929. }
  14930. };
  14931. };
  14932. },{}],59:[function(require,module,exports){
  14933. /*
  14934. * Copyright @ 2015 Atlassian Pty Ltd
  14935. *
  14936. * Licensed under the Apache License, Version 2.0 (the "License");
  14937. * you may not use this file except in compliance with the License.
  14938. * You may obtain a copy of the License at
  14939. *
  14940. * http://www.apache.org/licenses/LICENSE-2.0
  14941. *
  14942. * Unless required by applicable law or agreed to in writing, software
  14943. * distributed under the License is distributed on an "AS IS" BASIS,
  14944. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14945. * See the License for the specific language governing permissions and
  14946. * limitations under the License.
  14947. */
  14948. /* global $, APP, config, Strophe*/
  14949. var Moderator = require("./moderator");
  14950. var EventEmitter = require("events");
  14951. var Recording = require("./recording");
  14952. var SDP = require("./SDP");
  14953. var Settings = require("../settings/Settings");
  14954. var Pako = require("pako");
  14955. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  14956. var RTCEvents = require("../../service/RTC/RTCEvents");
  14957. var UIEvents = require("../../service/UI/UIEvents");
  14958. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14959. var retry = require('retry');
  14960. var eventEmitter = new EventEmitter();
  14961. var connection = null;
  14962. var authenticatedUser = false;
  14963. function connect(jid, password) {
  14964. var faultTolerantConnect = retry.operation({
  14965. retries: 3
  14966. });
  14967. // fault tolerant connect
  14968. faultTolerantConnect.attempt(function () {
  14969. connection = XMPP.createConnection();
  14970. Moderator.setConnection(connection);
  14971. if (connection.disco) {
  14972. // for chrome, add multistream cap
  14973. }
  14974. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  14975. if (config.useIPv6) {
  14976. // https://code.google.com/p/webrtc/issues/detail?id=2828
  14977. if (!connection.jingle.pc_constraints.optional)
  14978. connection.jingle.pc_constraints.optional = [];
  14979. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  14980. }
  14981. // Include user info in MUC presence
  14982. var settings = Settings.getSettings();
  14983. if (settings.email) {
  14984. connection.emuc.addEmailToPresence(settings.email);
  14985. }
  14986. if (settings.uid) {
  14987. connection.emuc.addUserIdToPresence(settings.uid);
  14988. }
  14989. if (settings.displayName) {
  14990. connection.emuc.addDisplayNameToPresence(settings.displayName);
  14991. }
  14992. // connection.connect() starts the connection process.
  14993. //
  14994. // As the connection process proceeds, the user supplied callback will
  14995. // be triggered multiple times with status updates. The callback should
  14996. // take two arguments - the status code and the error condition.
  14997. //
  14998. // The status code will be one of the values in the Strophe.Status
  14999. // constants. The error condition will be one of the conditions defined
  15000. // in RFC 3920 or the condition ‘strophe-parsererror’.
  15001. //
  15002. // The Parameters wait, hold and route are optional and only relevant
  15003. // for BOSH connections. Please see XEP 124 for a more detailed
  15004. // explanation of the optional parameters.
  15005. //
  15006. // Connection status constants for use by the connection handler
  15007. // callback.
  15008. //
  15009. // Status.ERROR - An error has occurred (websockets specific)
  15010. // Status.CONNECTING - The connection is currently being made
  15011. // Status.CONNFAIL - The connection attempt failed
  15012. // Status.AUTHENTICATING - The connection is authenticating
  15013. // Status.AUTHFAIL - The authentication attempt failed
  15014. // Status.CONNECTED - The connection has succeeded
  15015. // Status.DISCONNECTED - The connection has been terminated
  15016. // Status.DISCONNECTING - The connection is currently being terminated
  15017. // Status.ATTACHED - The connection has been attached
  15018. var anonymousConnectionFailed = false;
  15019. var connectionFailed = false;
  15020. var lastErrorMsg;
  15021. connection.connect(jid, password, function (status, msg) {
  15022. console.log('Strophe status changed to',
  15023. Strophe.getStatusString(status), msg);
  15024. if (status === Strophe.Status.CONNECTED) {
  15025. if (config.useStunTurn) {
  15026. connection.jingle.getStunAndTurnCredentials();
  15027. }
  15028. console.info("My Jabber ID: " + connection.jid);
  15029. if (password)
  15030. authenticatedUser = true;
  15031. maybeDoJoin();
  15032. } else if (status === Strophe.Status.CONNFAIL) {
  15033. if (msg === 'x-strophe-bad-non-anon-jid') {
  15034. anonymousConnectionFailed = true;
  15035. } else {
  15036. connectionFailed = true;
  15037. }
  15038. lastErrorMsg = msg;
  15039. } else if (status === Strophe.Status.DISCONNECTED) {
  15040. if (anonymousConnectionFailed) {
  15041. // prompt user for username and password
  15042. XMPP.promptLogin();
  15043. } else {
  15044. // Strophe already has built-in HTTP/BOSH error handling and
  15045. // request retry logic. Requests are resent automatically
  15046. // until their error count reaches 5. Strophe.js disconnects
  15047. // if the error count is > 5. We are not replicating this
  15048. // here.
  15049. //
  15050. // The "problem" is that failed HTTP/BOSH requests don't
  15051. // trigger a callback with a status update, so when a
  15052. // callback with status Strophe.Status.DISCONNECTED arrives,
  15053. // we can't be sure if it's a graceful disconnect or if it's
  15054. // triggered by some HTTP/BOSH error.
  15055. //
  15056. // But that's a minor issue in Jitsi Meet as we never
  15057. // disconnect anyway, not even when the user closes the
  15058. // browser window (which is kind of wrong, but the point is
  15059. // that we should never ever get disconnected).
  15060. //
  15061. // On the other hand, failed connections due to XMPP layer
  15062. // errors, trigger a callback with status Strophe.Status.CONNFAIL.
  15063. //
  15064. // Here we implement retry logic for failed connections due
  15065. // to XMPP layer errors and we display an error to the user
  15066. // if we get disconnected from the XMPP server permanently.
  15067. // If the connection failed, retry.
  15068. if (connectionFailed
  15069. && faultTolerantConnect.retry("connection-failed")) {
  15070. return;
  15071. }
  15072. // If we failed to connect to the XMPP server, fire an event
  15073. // to let all the interested module now about it.
  15074. eventEmitter.emit(XMPPEvents.CONNECTION_FAILED,
  15075. msg ? msg : lastErrorMsg);
  15076. }
  15077. } else if (status === Strophe.Status.AUTHFAIL) {
  15078. // wrong password or username, prompt user
  15079. XMPP.promptLogin();
  15080. }
  15081. });
  15082. });
  15083. }
  15084. function maybeDoJoin() {
  15085. if (connection && connection.connected &&
  15086. Strophe.getResourceFromJid(connection.jid)
  15087. && (APP.RTC.localAudio || APP.RTC.localVideo)) {
  15088. // .connected is true while connecting?
  15089. doJoin();
  15090. }
  15091. }
  15092. function doJoin() {
  15093. var roomName = APP.UI.generateRoomName();
  15094. Moderator.allocateConferenceFocus(
  15095. roomName, APP.UI.checkForNicknameAndJoin);
  15096. }
  15097. function initStrophePlugins()
  15098. {
  15099. require("./strophe.emuc")(XMPP, eventEmitter);
  15100. require("./strophe.jingle")(XMPP, eventEmitter);
  15101. require("./strophe.moderate")(XMPP);
  15102. require("./strophe.util")();
  15103. require("./strophe.rayo")();
  15104. require("./strophe.logger")();
  15105. }
  15106. function registerListeners() {
  15107. APP.RTC.addStreamListener(maybeDoJoin,
  15108. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  15109. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  15110. XMPP.addToPresence("devices", devices);
  15111. })
  15112. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  15113. XMPP.addToPresence("displayName", nickname);
  15114. });
  15115. }
  15116. var unload = (function () {
  15117. var unloaded = false;
  15118. return function () {
  15119. if (unloaded) { return; }
  15120. unloaded = true;
  15121. if (connection && connection.connected) {
  15122. // ensure signout
  15123. $.ajax({
  15124. type: 'POST',
  15125. url: config.bosh,
  15126. async: false,
  15127. cache: false,
  15128. contentType: 'application/xml',
  15129. data: "<body rid='" + (connection.rid || connection._proto.rid) +
  15130. "' xmlns='http://jabber.org/protocol/httpbind' sid='" +
  15131. (connection.sid || connection._proto.sid) +
  15132. "' type='terminate'>" +
  15133. "<presence xmlns='jabber:client' type='unavailable'/>" +
  15134. "</body>",
  15135. success: function (data) {
  15136. console.log('signed out');
  15137. console.log(data);
  15138. },
  15139. error: function (XMLHttpRequest, textStatus, errorThrown) {
  15140. console.log('signout error',
  15141. textStatus + ' (' + errorThrown + ')');
  15142. }
  15143. });
  15144. }
  15145. XMPP.disposeConference(true);
  15146. };
  15147. })();
  15148. function setupEvents() {
  15149. // In recent versions of FF the 'beforeunload' event is not fired when the
  15150. // window or the tab is closed. It is only fired when we leave the page
  15151. // (change URL). If this participant doesn't unload properly, then it
  15152. // becomes a ghost for the rest of the participants that stay in the
  15153. // conference. Thankfully handling the 'unload' event in addition to the
  15154. // 'beforeunload' event seems to garante the execution of the 'unload'
  15155. // method at least once.
  15156. //
  15157. // The 'unload' method can safely be run multiple times, it will actually do
  15158. // something only the first time that it's run, so we're don't have to worry
  15159. // about browsers that fire both events.
  15160. $(window).bind('beforeunload', unload);
  15161. $(window).bind('unload', unload);
  15162. }
  15163. var XMPP = {
  15164. getConnection: function(){ return connection; },
  15165. sessionTerminated: false,
  15166. /**
  15167. * XMPP connection status
  15168. */
  15169. Status: Strophe.Status,
  15170. /**
  15171. * Remembers if we were muted by the focus.
  15172. * @type {boolean}
  15173. */
  15174. forceMuted: false,
  15175. start: function () {
  15176. setupEvents();
  15177. initStrophePlugins();
  15178. registerListeners();
  15179. Moderator.init(this, eventEmitter);
  15180. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  15181. // Force authenticated domain if room is appended with '?login=true'
  15182. if (config.hosts.anonymousdomain &&
  15183. window.location.search.indexOf("login=true") !== -1) {
  15184. configDomain = config.hosts.domain;
  15185. }
  15186. var jid = configDomain || window.location.hostname;
  15187. connect(jid, null);
  15188. },
  15189. createConnection: function () {
  15190. var bosh = config.bosh || '/http-bind';
  15191. return new Strophe.Connection(bosh);
  15192. },
  15193. getStatusString: function (status) {
  15194. return Strophe.getStatusString(status);
  15195. },
  15196. promptLogin: function () {
  15197. // FIXME: re-use LoginDialog which supports retries
  15198. APP.UI.showLoginPopup(connect);
  15199. },
  15200. joinRoom: function(roomName, useNicks, nick)
  15201. {
  15202. var roomjid;
  15203. roomjid = roomName;
  15204. if (useNicks) {
  15205. if (nick) {
  15206. roomjid += '/' + nick;
  15207. } else {
  15208. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  15209. }
  15210. } else {
  15211. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  15212. if(!authenticatedUser)
  15213. tmpJid = tmpJid.substr(0, 8);
  15214. roomjid += '/' + tmpJid;
  15215. }
  15216. connection.emuc.doJoin(roomjid);
  15217. },
  15218. myJid: function () {
  15219. if(!connection)
  15220. return null;
  15221. return connection.emuc.myroomjid;
  15222. },
  15223. myResource: function () {
  15224. if(!connection || ! connection.emuc.myroomjid)
  15225. return null;
  15226. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  15227. },
  15228. disposeConference: function (onUnload) {
  15229. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  15230. var handler = connection.jingle.activecall;
  15231. if (handler && handler.peerconnection) {
  15232. // FIXME: probably removing streams is not required and close() should
  15233. // be enough
  15234. if (APP.RTC.localAudio) {
  15235. handler.peerconnection.removeStream(
  15236. APP.RTC.localAudio.getOriginalStream(), onUnload);
  15237. }
  15238. if (APP.RTC.localVideo) {
  15239. handler.peerconnection.removeStream(
  15240. APP.RTC.localVideo.getOriginalStream(), onUnload);
  15241. }
  15242. handler.peerconnection.close();
  15243. }
  15244. connection.jingle.activecall = null;
  15245. if(!onUnload)
  15246. {
  15247. this.sessionTerminated = true;
  15248. connection.emuc.doLeave();
  15249. }
  15250. },
  15251. addListener: function(type, listener)
  15252. {
  15253. eventEmitter.on(type, listener);
  15254. },
  15255. removeListener: function (type, listener) {
  15256. eventEmitter.removeListener(type, listener);
  15257. },
  15258. allocateConferenceFocus: function(roomName, callback) {
  15259. Moderator.allocateConferenceFocus(roomName, callback);
  15260. },
  15261. getLoginUrl: function (roomName, callback) {
  15262. Moderator.getLoginUrl(roomName, callback);
  15263. },
  15264. getPopupLoginUrl: function (roomName, callback) {
  15265. Moderator.getPopupLoginUrl(roomName, callback);
  15266. },
  15267. isModerator: function () {
  15268. return Moderator.isModerator();
  15269. },
  15270. isSipGatewayEnabled: function () {
  15271. return Moderator.isSipGatewayEnabled();
  15272. },
  15273. isExternalAuthEnabled: function () {
  15274. return Moderator.isExternalAuthEnabled();
  15275. },
  15276. switchStreams: function (stream, oldStream, callback, isAudio) {
  15277. if (connection && connection.jingle.activecall) {
  15278. // FIXME: will block switchInProgress on true value in case of exception
  15279. connection.jingle.activecall.switchStreams(stream, oldStream, callback, isAudio);
  15280. } else {
  15281. // We are done immediately
  15282. console.warn("No conference handler or conference not started yet");
  15283. callback();
  15284. }
  15285. },
  15286. sendVideoInfoPresence: function (mute) {
  15287. if(!connection)
  15288. return;
  15289. connection.emuc.addVideoInfoToPresence(mute);
  15290. connection.emuc.sendPresence();
  15291. },
  15292. setVideoMute: function (mute, callback, options) {
  15293. if(!connection)
  15294. return;
  15295. var self = this;
  15296. var localCallback = function (mute) {
  15297. self.sendVideoInfoPresence(mute);
  15298. return callback(mute);
  15299. };
  15300. if(connection.jingle.activecall)
  15301. {
  15302. connection.jingle.activecall.setVideoMute(
  15303. mute, localCallback, options);
  15304. }
  15305. else {
  15306. localCallback(mute);
  15307. }
  15308. },
  15309. setAudioMute: function (mute, callback) {
  15310. if (!(connection && APP.RTC.localAudio)) {
  15311. return false;
  15312. }
  15313. if (this.forceMuted && !mute) {
  15314. console.info("Asking focus for unmute");
  15315. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  15316. // FIXME: wait for result before resetting muted status
  15317. this.forceMuted = false;
  15318. }
  15319. if (mute == APP.RTC.localAudio.isMuted()) {
  15320. // Nothing to do
  15321. return true;
  15322. }
  15323. // It is not clear what is the right way to handle multiple tracks.
  15324. // So at least make sure that they are all muted or all unmuted and
  15325. // that we send presence just once.
  15326. APP.RTC.localAudio.setMute(!mute);
  15327. // isMuted is the opposite of audioEnabled
  15328. this.sendAudioInfoPresence(mute, callback);
  15329. return true;
  15330. },
  15331. sendAudioInfoPresence: function(mute, callback)
  15332. {
  15333. if(connection) {
  15334. connection.emuc.addAudioInfoToPresence(mute);
  15335. connection.emuc.sendPresence();
  15336. }
  15337. callback();
  15338. return true;
  15339. },
  15340. // Really mute video, i.e. dont even send black frames
  15341. muteVideo: function (pc, unmute) {
  15342. // FIXME: this probably needs another of those lovely state safeguards...
  15343. // which checks for iceconn == connected and sigstate == stable
  15344. pc.setRemoteDescription(pc.remoteDescription,
  15345. function () {
  15346. pc.createAnswer(
  15347. function (answer) {
  15348. var sdp = new SDP(answer.sdp);
  15349. if (sdp.media.length > 1) {
  15350. if (unmute)
  15351. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  15352. else
  15353. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  15354. sdp.raw = sdp.session + sdp.media.join('');
  15355. answer.sdp = sdp.raw;
  15356. }
  15357. pc.setLocalDescription(answer,
  15358. function () {
  15359. console.log('mute SLD ok');
  15360. },
  15361. function (error) {
  15362. console.log('mute SLD error');
  15363. APP.UI.messageHandler.showError("dialog.error",
  15364. "dialog.SLDFailure");
  15365. }
  15366. );
  15367. },
  15368. function (error) {
  15369. console.log(error);
  15370. APP.UI.messageHandler.showError();
  15371. }
  15372. );
  15373. },
  15374. function (error) {
  15375. console.log('muteVideo SRD error');
  15376. APP.UI.messageHandler.showError("dialog.error",
  15377. "dialog.SRDFailure");
  15378. }
  15379. );
  15380. },
  15381. toggleRecording: function (tokenEmptyCallback,
  15382. startingCallback, startedCallback) {
  15383. Recording.toggleRecording(tokenEmptyCallback,
  15384. startingCallback, startedCallback, connection);
  15385. },
  15386. addToPresence: function (name, value, dontSend) {
  15387. switch (name)
  15388. {
  15389. case "displayName":
  15390. connection.emuc.addDisplayNameToPresence(value);
  15391. break;
  15392. case "prezi":
  15393. connection.emuc.addPreziToPresence(value, 0);
  15394. break;
  15395. case "preziSlide":
  15396. connection.emuc.addCurrentSlideToPresence(value);
  15397. break;
  15398. case "connectionQuality":
  15399. connection.emuc.addConnectionInfoToPresence(value);
  15400. break;
  15401. case "email":
  15402. connection.emuc.addEmailToPresence(value);
  15403. break;
  15404. case "devices":
  15405. connection.emuc.addDevicesToPresence(value);
  15406. break;
  15407. case "startMuted":
  15408. if(!Moderator.isModerator())
  15409. return;
  15410. connection.emuc.addStartMutedToPresence(value[0],
  15411. value[1]);
  15412. break;
  15413. default :
  15414. console.log("Unknown tag for presence: " + name);
  15415. return;
  15416. }
  15417. if (!dontSend)
  15418. connection.emuc.sendPresence();
  15419. },
  15420. /**
  15421. * Sends 'data' as a log message to the focus. Returns true iff a message
  15422. * was sent.
  15423. * @param data
  15424. * @returns {boolean} true iff a message was sent.
  15425. */
  15426. sendLogs: function (data) {
  15427. if(!connection.emuc.focusMucJid)
  15428. return false;
  15429. var deflate = true;
  15430. var content = JSON.stringify(data);
  15431. if (deflate) {
  15432. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  15433. }
  15434. content = Base64.encode(content);
  15435. // XEP-0337-ish
  15436. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  15437. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  15438. id: 'PeerConnectionStats'});
  15439. message.c('message').t(content).up();
  15440. if (deflate) {
  15441. message.c('tag', {name: "deflated", value: "true"}).up();
  15442. }
  15443. message.up();
  15444. connection.send(message);
  15445. return true;
  15446. },
  15447. populateData: function () {
  15448. var data = {};
  15449. if (connection.jingle) {
  15450. data = connection.jingle.populateData();
  15451. }
  15452. return data;
  15453. },
  15454. getLogger: function () {
  15455. if(connection.logger)
  15456. return connection.logger.log;
  15457. return null;
  15458. },
  15459. getPrezi: function () {
  15460. return connection.emuc.getPrezi(this.myJid());
  15461. },
  15462. removePreziFromPresence: function () {
  15463. connection.emuc.removePreziFromPresence();
  15464. connection.emuc.sendPresence();
  15465. },
  15466. sendChatMessage: function (message, nickname) {
  15467. connection.emuc.sendMessage(message, nickname);
  15468. },
  15469. setSubject: function (topic) {
  15470. connection.emuc.setSubject(topic);
  15471. },
  15472. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  15473. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  15474. },
  15475. dial: function (to, from, roomName,roomPass) {
  15476. connection.rayo.dial(to, from, roomName,roomPass);
  15477. },
  15478. setMute: function (jid, mute) {
  15479. connection.moderate.setMute(jid, mute);
  15480. },
  15481. eject: function (jid) {
  15482. connection.moderate.eject(jid);
  15483. },
  15484. logout: function (callback) {
  15485. Moderator.logout(callback);
  15486. },
  15487. findJidFromResource: function (resource) {
  15488. return connection.emuc.findJidFromResource(resource);
  15489. },
  15490. getMembers: function () {
  15491. return connection.emuc.members;
  15492. },
  15493. getJidFromSSRC: function (ssrc) {
  15494. if(!connection)
  15495. return null;
  15496. return connection.emuc.ssrc2jid[ssrc];
  15497. },
  15498. getMUCJoined: function () {
  15499. return connection.emuc.joined;
  15500. },
  15501. getSessions: function () {
  15502. return connection.jingle.sessions;
  15503. },
  15504. removeStream: function (stream) {
  15505. if(!connection || !connection.jingle.activecall ||
  15506. !connection.jingle.activecall.peerconnection)
  15507. return;
  15508. connection.jingle.activecall.peerconnection.removeStream(stream);
  15509. }
  15510. };
  15511. module.exports = XMPP;
  15512. },{"../../service/RTC/RTCEvents":103,"../../service/RTC/StreamEventTypes":105,"../../service/UI/UIEvents":106,"../../service/xmpp/XMPPEvents":112,"../settings/Settings":41,"./SDP":47,"./moderator":51,"./recording":52,"./strophe.emuc":53,"./strophe.jingle":54,"./strophe.logger":55,"./strophe.moderate":56,"./strophe.rayo":57,"./strophe.util":58,"events":62,"pako":64,"retry":80}],60:[function(require,module,exports){
  15513. (function (process){
  15514. /*!
  15515. * async
  15516. * https://github.com/caolan/async
  15517. *
  15518. * Copyright 2010-2014 Caolan McMahon
  15519. * Released under the MIT license
  15520. */
  15521. /*jshint onevar: false, indent:4 */
  15522. /*global setImmediate: false, setTimeout: false, console: false */
  15523. (function () {
  15524. var async = {};
  15525. // global on the server, window in the browser
  15526. var root, previous_async;
  15527. root = this;
  15528. if (root != null) {
  15529. previous_async = root.async;
  15530. }
  15531. async.noConflict = function () {
  15532. root.async = previous_async;
  15533. return async;
  15534. };
  15535. function only_once(fn) {
  15536. var called = false;
  15537. return function() {
  15538. if (called) throw new Error("Callback was already called.");
  15539. called = true;
  15540. fn.apply(root, arguments);
  15541. }
  15542. }
  15543. //// cross-browser compatiblity functions ////
  15544. var _toString = Object.prototype.toString;
  15545. var _isArray = Array.isArray || function (obj) {
  15546. return _toString.call(obj) === '[object Array]';
  15547. };
  15548. var _each = function (arr, iterator) {
  15549. if (arr.forEach) {
  15550. return arr.forEach(iterator);
  15551. }
  15552. for (var i = 0; i < arr.length; i += 1) {
  15553. iterator(arr[i], i, arr);
  15554. }
  15555. };
  15556. var _map = function (arr, iterator) {
  15557. if (arr.map) {
  15558. return arr.map(iterator);
  15559. }
  15560. var results = [];
  15561. _each(arr, function (x, i, a) {
  15562. results.push(iterator(x, i, a));
  15563. });
  15564. return results;
  15565. };
  15566. var _reduce = function (arr, iterator, memo) {
  15567. if (arr.reduce) {
  15568. return arr.reduce(iterator, memo);
  15569. }
  15570. _each(arr, function (x, i, a) {
  15571. memo = iterator(memo, x, i, a);
  15572. });
  15573. return memo;
  15574. };
  15575. var _keys = function (obj) {
  15576. if (Object.keys) {
  15577. return Object.keys(obj);
  15578. }
  15579. var keys = [];
  15580. for (var k in obj) {
  15581. if (obj.hasOwnProperty(k)) {
  15582. keys.push(k);
  15583. }
  15584. }
  15585. return keys;
  15586. };
  15587. //// exported async module functions ////
  15588. //// nextTick implementation with browser-compatible fallback ////
  15589. if (typeof process === 'undefined' || !(process.nextTick)) {
  15590. if (typeof setImmediate === 'function') {
  15591. async.nextTick = function (fn) {
  15592. // not a direct alias for IE10 compatibility
  15593. setImmediate(fn);
  15594. };
  15595. async.setImmediate = async.nextTick;
  15596. }
  15597. else {
  15598. async.nextTick = function (fn) {
  15599. setTimeout(fn, 0);
  15600. };
  15601. async.setImmediate = async.nextTick;
  15602. }
  15603. }
  15604. else {
  15605. async.nextTick = process.nextTick;
  15606. if (typeof setImmediate !== 'undefined') {
  15607. async.setImmediate = function (fn) {
  15608. // not a direct alias for IE10 compatibility
  15609. setImmediate(fn);
  15610. };
  15611. }
  15612. else {
  15613. async.setImmediate = async.nextTick;
  15614. }
  15615. }
  15616. async.each = function (arr, iterator, callback) {
  15617. callback = callback || function () {};
  15618. if (!arr.length) {
  15619. return callback();
  15620. }
  15621. var completed = 0;
  15622. _each(arr, function (x) {
  15623. iterator(x, only_once(done) );
  15624. });
  15625. function done(err) {
  15626. if (err) {
  15627. callback(err);
  15628. callback = function () {};
  15629. }
  15630. else {
  15631. completed += 1;
  15632. if (completed >= arr.length) {
  15633. callback();
  15634. }
  15635. }
  15636. }
  15637. };
  15638. async.forEach = async.each;
  15639. async.eachSeries = function (arr, iterator, callback) {
  15640. callback = callback || function () {};
  15641. if (!arr.length) {
  15642. return callback();
  15643. }
  15644. var completed = 0;
  15645. var iterate = function () {
  15646. iterator(arr[completed], function (err) {
  15647. if (err) {
  15648. callback(err);
  15649. callback = function () {};
  15650. }
  15651. else {
  15652. completed += 1;
  15653. if (completed >= arr.length) {
  15654. callback();
  15655. }
  15656. else {
  15657. iterate();
  15658. }
  15659. }
  15660. });
  15661. };
  15662. iterate();
  15663. };
  15664. async.forEachSeries = async.eachSeries;
  15665. async.eachLimit = function (arr, limit, iterator, callback) {
  15666. var fn = _eachLimit(limit);
  15667. fn.apply(null, [arr, iterator, callback]);
  15668. };
  15669. async.forEachLimit = async.eachLimit;
  15670. var _eachLimit = function (limit) {
  15671. return function (arr, iterator, callback) {
  15672. callback = callback || function () {};
  15673. if (!arr.length || limit <= 0) {
  15674. return callback();
  15675. }
  15676. var completed = 0;
  15677. var started = 0;
  15678. var running = 0;
  15679. (function replenish () {
  15680. if (completed >= arr.length) {
  15681. return callback();
  15682. }
  15683. while (running < limit && started < arr.length) {
  15684. started += 1;
  15685. running += 1;
  15686. iterator(arr[started - 1], function (err) {
  15687. if (err) {
  15688. callback(err);
  15689. callback = function () {};
  15690. }
  15691. else {
  15692. completed += 1;
  15693. running -= 1;
  15694. if (completed >= arr.length) {
  15695. callback();
  15696. }
  15697. else {
  15698. replenish();
  15699. }
  15700. }
  15701. });
  15702. }
  15703. })();
  15704. };
  15705. };
  15706. var doParallel = function (fn) {
  15707. return function () {
  15708. var args = Array.prototype.slice.call(arguments);
  15709. return fn.apply(null, [async.each].concat(args));
  15710. };
  15711. };
  15712. var doParallelLimit = function(limit, fn) {
  15713. return function () {
  15714. var args = Array.prototype.slice.call(arguments);
  15715. return fn.apply(null, [_eachLimit(limit)].concat(args));
  15716. };
  15717. };
  15718. var doSeries = function (fn) {
  15719. return function () {
  15720. var args = Array.prototype.slice.call(arguments);
  15721. return fn.apply(null, [async.eachSeries].concat(args));
  15722. };
  15723. };
  15724. var _asyncMap = function (eachfn, arr, iterator, callback) {
  15725. arr = _map(arr, function (x, i) {
  15726. return {index: i, value: x};
  15727. });
  15728. if (!callback) {
  15729. eachfn(arr, function (x, callback) {
  15730. iterator(x.value, function (err) {
  15731. callback(err);
  15732. });
  15733. });
  15734. } else {
  15735. var results = [];
  15736. eachfn(arr, function (x, callback) {
  15737. iterator(x.value, function (err, v) {
  15738. results[x.index] = v;
  15739. callback(err);
  15740. });
  15741. }, function (err) {
  15742. callback(err, results);
  15743. });
  15744. }
  15745. };
  15746. async.map = doParallel(_asyncMap);
  15747. async.mapSeries = doSeries(_asyncMap);
  15748. async.mapLimit = function (arr, limit, iterator, callback) {
  15749. return _mapLimit(limit)(arr, iterator, callback);
  15750. };
  15751. var _mapLimit = function(limit) {
  15752. return doParallelLimit(limit, _asyncMap);
  15753. };
  15754. // reduce only has a series version, as doing reduce in parallel won't
  15755. // work in many situations.
  15756. async.reduce = function (arr, memo, iterator, callback) {
  15757. async.eachSeries(arr, function (x, callback) {
  15758. iterator(memo, x, function (err, v) {
  15759. memo = v;
  15760. callback(err);
  15761. });
  15762. }, function (err) {
  15763. callback(err, memo);
  15764. });
  15765. };
  15766. // inject alias
  15767. async.inject = async.reduce;
  15768. // foldl alias
  15769. async.foldl = async.reduce;
  15770. async.reduceRight = function (arr, memo, iterator, callback) {
  15771. var reversed = _map(arr, function (x) {
  15772. return x;
  15773. }).reverse();
  15774. async.reduce(reversed, memo, iterator, callback);
  15775. };
  15776. // foldr alias
  15777. async.foldr = async.reduceRight;
  15778. var _filter = function (eachfn, arr, iterator, callback) {
  15779. var results = [];
  15780. arr = _map(arr, function (x, i) {
  15781. return {index: i, value: x};
  15782. });
  15783. eachfn(arr, function (x, callback) {
  15784. iterator(x.value, function (v) {
  15785. if (v) {
  15786. results.push(x);
  15787. }
  15788. callback();
  15789. });
  15790. }, function (err) {
  15791. callback(_map(results.sort(function (a, b) {
  15792. return a.index - b.index;
  15793. }), function (x) {
  15794. return x.value;
  15795. }));
  15796. });
  15797. };
  15798. async.filter = doParallel(_filter);
  15799. async.filterSeries = doSeries(_filter);
  15800. // select alias
  15801. async.select = async.filter;
  15802. async.selectSeries = async.filterSeries;
  15803. var _reject = function (eachfn, arr, iterator, callback) {
  15804. var results = [];
  15805. arr = _map(arr, function (x, i) {
  15806. return {index: i, value: x};
  15807. });
  15808. eachfn(arr, function (x, callback) {
  15809. iterator(x.value, function (v) {
  15810. if (!v) {
  15811. results.push(x);
  15812. }
  15813. callback();
  15814. });
  15815. }, function (err) {
  15816. callback(_map(results.sort(function (a, b) {
  15817. return a.index - b.index;
  15818. }), function (x) {
  15819. return x.value;
  15820. }));
  15821. });
  15822. };
  15823. async.reject = doParallel(_reject);
  15824. async.rejectSeries = doSeries(_reject);
  15825. var _detect = function (eachfn, arr, iterator, main_callback) {
  15826. eachfn(arr, function (x, callback) {
  15827. iterator(x, function (result) {
  15828. if (result) {
  15829. main_callback(x);
  15830. main_callback = function () {};
  15831. }
  15832. else {
  15833. callback();
  15834. }
  15835. });
  15836. }, function (err) {
  15837. main_callback();
  15838. });
  15839. };
  15840. async.detect = doParallel(_detect);
  15841. async.detectSeries = doSeries(_detect);
  15842. async.some = function (arr, iterator, main_callback) {
  15843. async.each(arr, function (x, callback) {
  15844. iterator(x, function (v) {
  15845. if (v) {
  15846. main_callback(true);
  15847. main_callback = function () {};
  15848. }
  15849. callback();
  15850. });
  15851. }, function (err) {
  15852. main_callback(false);
  15853. });
  15854. };
  15855. // any alias
  15856. async.any = async.some;
  15857. async.every = function (arr, iterator, main_callback) {
  15858. async.each(arr, function (x, callback) {
  15859. iterator(x, function (v) {
  15860. if (!v) {
  15861. main_callback(false);
  15862. main_callback = function () {};
  15863. }
  15864. callback();
  15865. });
  15866. }, function (err) {
  15867. main_callback(true);
  15868. });
  15869. };
  15870. // all alias
  15871. async.all = async.every;
  15872. async.sortBy = function (arr, iterator, callback) {
  15873. async.map(arr, function (x, callback) {
  15874. iterator(x, function (err, criteria) {
  15875. if (err) {
  15876. callback(err);
  15877. }
  15878. else {
  15879. callback(null, {value: x, criteria: criteria});
  15880. }
  15881. });
  15882. }, function (err, results) {
  15883. if (err) {
  15884. return callback(err);
  15885. }
  15886. else {
  15887. var fn = function (left, right) {
  15888. var a = left.criteria, b = right.criteria;
  15889. return a < b ? -1 : a > b ? 1 : 0;
  15890. };
  15891. callback(null, _map(results.sort(fn), function (x) {
  15892. return x.value;
  15893. }));
  15894. }
  15895. });
  15896. };
  15897. async.auto = function (tasks, callback) {
  15898. callback = callback || function () {};
  15899. var keys = _keys(tasks);
  15900. var remainingTasks = keys.length
  15901. if (!remainingTasks) {
  15902. return callback();
  15903. }
  15904. var results = {};
  15905. var listeners = [];
  15906. var addListener = function (fn) {
  15907. listeners.unshift(fn);
  15908. };
  15909. var removeListener = function (fn) {
  15910. for (var i = 0; i < listeners.length; i += 1) {
  15911. if (listeners[i] === fn) {
  15912. listeners.splice(i, 1);
  15913. return;
  15914. }
  15915. }
  15916. };
  15917. var taskComplete = function () {
  15918. remainingTasks--
  15919. _each(listeners.slice(0), function (fn) {
  15920. fn();
  15921. });
  15922. };
  15923. addListener(function () {
  15924. if (!remainingTasks) {
  15925. var theCallback = callback;
  15926. // prevent final callback from calling itself if it errors
  15927. callback = function () {};
  15928. theCallback(null, results);
  15929. }
  15930. });
  15931. _each(keys, function (k) {
  15932. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  15933. var taskCallback = function (err) {
  15934. var args = Array.prototype.slice.call(arguments, 1);
  15935. if (args.length <= 1) {
  15936. args = args[0];
  15937. }
  15938. if (err) {
  15939. var safeResults = {};
  15940. _each(_keys(results), function(rkey) {
  15941. safeResults[rkey] = results[rkey];
  15942. });
  15943. safeResults[k] = args;
  15944. callback(err, safeResults);
  15945. // stop subsequent errors hitting callback multiple times
  15946. callback = function () {};
  15947. }
  15948. else {
  15949. results[k] = args;
  15950. async.setImmediate(taskComplete);
  15951. }
  15952. };
  15953. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  15954. var ready = function () {
  15955. return _reduce(requires, function (a, x) {
  15956. return (a && results.hasOwnProperty(x));
  15957. }, true) && !results.hasOwnProperty(k);
  15958. };
  15959. if (ready()) {
  15960. task[task.length - 1](taskCallback, results);
  15961. }
  15962. else {
  15963. var listener = function () {
  15964. if (ready()) {
  15965. removeListener(listener);
  15966. task[task.length - 1](taskCallback, results);
  15967. }
  15968. };
  15969. addListener(listener);
  15970. }
  15971. });
  15972. };
  15973. async.retry = function(times, task, callback) {
  15974. var DEFAULT_TIMES = 5;
  15975. var attempts = [];
  15976. // Use defaults if times not passed
  15977. if (typeof times === 'function') {
  15978. callback = task;
  15979. task = times;
  15980. times = DEFAULT_TIMES;
  15981. }
  15982. // Make sure times is a number
  15983. times = parseInt(times, 10) || DEFAULT_TIMES;
  15984. var wrappedTask = function(wrappedCallback, wrappedResults) {
  15985. var retryAttempt = function(task, finalAttempt) {
  15986. return function(seriesCallback) {
  15987. task(function(err, result){
  15988. seriesCallback(!err || finalAttempt, {err: err, result: result});
  15989. }, wrappedResults);
  15990. };
  15991. };
  15992. while (times) {
  15993. attempts.push(retryAttempt(task, !(times-=1)));
  15994. }
  15995. async.series(attempts, function(done, data){
  15996. data = data[data.length - 1];
  15997. (wrappedCallback || callback)(data.err, data.result);
  15998. });
  15999. }
  16000. // If a callback is passed, run this as a controll flow
  16001. return callback ? wrappedTask() : wrappedTask
  16002. };
  16003. async.waterfall = function (tasks, callback) {
  16004. callback = callback || function () {};
  16005. if (!_isArray(tasks)) {
  16006. var err = new Error('First argument to waterfall must be an array of functions');
  16007. return callback(err);
  16008. }
  16009. if (!tasks.length) {
  16010. return callback();
  16011. }
  16012. var wrapIterator = function (iterator) {
  16013. return function (err) {
  16014. if (err) {
  16015. callback.apply(null, arguments);
  16016. callback = function () {};
  16017. }
  16018. else {
  16019. var args = Array.prototype.slice.call(arguments, 1);
  16020. var next = iterator.next();
  16021. if (next) {
  16022. args.push(wrapIterator(next));
  16023. }
  16024. else {
  16025. args.push(callback);
  16026. }
  16027. async.setImmediate(function () {
  16028. iterator.apply(null, args);
  16029. });
  16030. }
  16031. };
  16032. };
  16033. wrapIterator(async.iterator(tasks))();
  16034. };
  16035. var _parallel = function(eachfn, tasks, callback) {
  16036. callback = callback || function () {};
  16037. if (_isArray(tasks)) {
  16038. eachfn.map(tasks, function (fn, callback) {
  16039. if (fn) {
  16040. fn(function (err) {
  16041. var args = Array.prototype.slice.call(arguments, 1);
  16042. if (args.length <= 1) {
  16043. args = args[0];
  16044. }
  16045. callback.call(null, err, args);
  16046. });
  16047. }
  16048. }, callback);
  16049. }
  16050. else {
  16051. var results = {};
  16052. eachfn.each(_keys(tasks), function (k, callback) {
  16053. tasks[k](function (err) {
  16054. var args = Array.prototype.slice.call(arguments, 1);
  16055. if (args.length <= 1) {
  16056. args = args[0];
  16057. }
  16058. results[k] = args;
  16059. callback(err);
  16060. });
  16061. }, function (err) {
  16062. callback(err, results);
  16063. });
  16064. }
  16065. };
  16066. async.parallel = function (tasks, callback) {
  16067. _parallel({ map: async.map, each: async.each }, tasks, callback);
  16068. };
  16069. async.parallelLimit = function(tasks, limit, callback) {
  16070. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  16071. };
  16072. async.series = function (tasks, callback) {
  16073. callback = callback || function () {};
  16074. if (_isArray(tasks)) {
  16075. async.mapSeries(tasks, function (fn, callback) {
  16076. if (fn) {
  16077. fn(function (err) {
  16078. var args = Array.prototype.slice.call(arguments, 1);
  16079. if (args.length <= 1) {
  16080. args = args[0];
  16081. }
  16082. callback.call(null, err, args);
  16083. });
  16084. }
  16085. }, callback);
  16086. }
  16087. else {
  16088. var results = {};
  16089. async.eachSeries(_keys(tasks), function (k, callback) {
  16090. tasks[k](function (err) {
  16091. var args = Array.prototype.slice.call(arguments, 1);
  16092. if (args.length <= 1) {
  16093. args = args[0];
  16094. }
  16095. results[k] = args;
  16096. callback(err);
  16097. });
  16098. }, function (err) {
  16099. callback(err, results);
  16100. });
  16101. }
  16102. };
  16103. async.iterator = function (tasks) {
  16104. var makeCallback = function (index) {
  16105. var fn = function () {
  16106. if (tasks.length) {
  16107. tasks[index].apply(null, arguments);
  16108. }
  16109. return fn.next();
  16110. };
  16111. fn.next = function () {
  16112. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  16113. };
  16114. return fn;
  16115. };
  16116. return makeCallback(0);
  16117. };
  16118. async.apply = function (fn) {
  16119. var args = Array.prototype.slice.call(arguments, 1);
  16120. return function () {
  16121. return fn.apply(
  16122. null, args.concat(Array.prototype.slice.call(arguments))
  16123. );
  16124. };
  16125. };
  16126. var _concat = function (eachfn, arr, fn, callback) {
  16127. var r = [];
  16128. eachfn(arr, function (x, cb) {
  16129. fn(x, function (err, y) {
  16130. r = r.concat(y || []);
  16131. cb(err);
  16132. });
  16133. }, function (err) {
  16134. callback(err, r);
  16135. });
  16136. };
  16137. async.concat = doParallel(_concat);
  16138. async.concatSeries = doSeries(_concat);
  16139. async.whilst = function (test, iterator, callback) {
  16140. if (test()) {
  16141. iterator(function (err) {
  16142. if (err) {
  16143. return callback(err);
  16144. }
  16145. async.whilst(test, iterator, callback);
  16146. });
  16147. }
  16148. else {
  16149. callback();
  16150. }
  16151. };
  16152. async.doWhilst = function (iterator, test, callback) {
  16153. iterator(function (err) {
  16154. if (err) {
  16155. return callback(err);
  16156. }
  16157. var args = Array.prototype.slice.call(arguments, 1);
  16158. if (test.apply(null, args)) {
  16159. async.doWhilst(iterator, test, callback);
  16160. }
  16161. else {
  16162. callback();
  16163. }
  16164. });
  16165. };
  16166. async.until = function (test, iterator, callback) {
  16167. if (!test()) {
  16168. iterator(function (err) {
  16169. if (err) {
  16170. return callback(err);
  16171. }
  16172. async.until(test, iterator, callback);
  16173. });
  16174. }
  16175. else {
  16176. callback();
  16177. }
  16178. };
  16179. async.doUntil = function (iterator, test, callback) {
  16180. iterator(function (err) {
  16181. if (err) {
  16182. return callback(err);
  16183. }
  16184. var args = Array.prototype.slice.call(arguments, 1);
  16185. if (!test.apply(null, args)) {
  16186. async.doUntil(iterator, test, callback);
  16187. }
  16188. else {
  16189. callback();
  16190. }
  16191. });
  16192. };
  16193. async.queue = function (worker, concurrency) {
  16194. if (concurrency === undefined) {
  16195. concurrency = 1;
  16196. }
  16197. function _insert(q, data, pos, callback) {
  16198. if (!q.started){
  16199. q.started = true;
  16200. }
  16201. if (!_isArray(data)) {
  16202. data = [data];
  16203. }
  16204. if(data.length == 0) {
  16205. // call drain immediately if there are no tasks
  16206. return async.setImmediate(function() {
  16207. if (q.drain) {
  16208. q.drain();
  16209. }
  16210. });
  16211. }
  16212. _each(data, function(task) {
  16213. var item = {
  16214. data: task,
  16215. callback: typeof callback === 'function' ? callback : null
  16216. };
  16217. if (pos) {
  16218. q.tasks.unshift(item);
  16219. } else {
  16220. q.tasks.push(item);
  16221. }
  16222. if (q.saturated && q.tasks.length === q.concurrency) {
  16223. q.saturated();
  16224. }
  16225. async.setImmediate(q.process);
  16226. });
  16227. }
  16228. var workers = 0;
  16229. var q = {
  16230. tasks: [],
  16231. concurrency: concurrency,
  16232. saturated: null,
  16233. empty: null,
  16234. drain: null,
  16235. started: false,
  16236. paused: false,
  16237. push: function (data, callback) {
  16238. _insert(q, data, false, callback);
  16239. },
  16240. kill: function () {
  16241. q.drain = null;
  16242. q.tasks = [];
  16243. },
  16244. unshift: function (data, callback) {
  16245. _insert(q, data, true, callback);
  16246. },
  16247. process: function () {
  16248. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  16249. var task = q.tasks.shift();
  16250. if (q.empty && q.tasks.length === 0) {
  16251. q.empty();
  16252. }
  16253. workers += 1;
  16254. var next = function () {
  16255. workers -= 1;
  16256. if (task.callback) {
  16257. task.callback.apply(task, arguments);
  16258. }
  16259. if (q.drain && q.tasks.length + workers === 0) {
  16260. q.drain();
  16261. }
  16262. q.process();
  16263. };
  16264. var cb = only_once(next);
  16265. worker(task.data, cb);
  16266. }
  16267. },
  16268. length: function () {
  16269. return q.tasks.length;
  16270. },
  16271. running: function () {
  16272. return workers;
  16273. },
  16274. idle: function() {
  16275. return q.tasks.length + workers === 0;
  16276. },
  16277. pause: function () {
  16278. if (q.paused === true) { return; }
  16279. q.paused = true;
  16280. q.process();
  16281. },
  16282. resume: function () {
  16283. if (q.paused === false) { return; }
  16284. q.paused = false;
  16285. q.process();
  16286. }
  16287. };
  16288. return q;
  16289. };
  16290. async.priorityQueue = function (worker, concurrency) {
  16291. function _compareTasks(a, b){
  16292. return a.priority - b.priority;
  16293. };
  16294. function _binarySearch(sequence, item, compare) {
  16295. var beg = -1,
  16296. end = sequence.length - 1;
  16297. while (beg < end) {
  16298. var mid = beg + ((end - beg + 1) >>> 1);
  16299. if (compare(item, sequence[mid]) >= 0) {
  16300. beg = mid;
  16301. } else {
  16302. end = mid - 1;
  16303. }
  16304. }
  16305. return beg;
  16306. }
  16307. function _insert(q, data, priority, callback) {
  16308. if (!q.started){
  16309. q.started = true;
  16310. }
  16311. if (!_isArray(data)) {
  16312. data = [data];
  16313. }
  16314. if(data.length == 0) {
  16315. // call drain immediately if there are no tasks
  16316. return async.setImmediate(function() {
  16317. if (q.drain) {
  16318. q.drain();
  16319. }
  16320. });
  16321. }
  16322. _each(data, function(task) {
  16323. var item = {
  16324. data: task,
  16325. priority: priority,
  16326. callback: typeof callback === 'function' ? callback : null
  16327. };
  16328. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  16329. if (q.saturated && q.tasks.length === q.concurrency) {
  16330. q.saturated();
  16331. }
  16332. async.setImmediate(q.process);
  16333. });
  16334. }
  16335. // Start with a normal queue
  16336. var q = async.queue(worker, concurrency);
  16337. // Override push to accept second parameter representing priority
  16338. q.push = function (data, priority, callback) {
  16339. _insert(q, data, priority, callback);
  16340. };
  16341. // Remove unshift function
  16342. delete q.unshift;
  16343. return q;
  16344. };
  16345. async.cargo = function (worker, payload) {
  16346. var working = false,
  16347. tasks = [];
  16348. var cargo = {
  16349. tasks: tasks,
  16350. payload: payload,
  16351. saturated: null,
  16352. empty: null,
  16353. drain: null,
  16354. drained: true,
  16355. push: function (data, callback) {
  16356. if (!_isArray(data)) {
  16357. data = [data];
  16358. }
  16359. _each(data, function(task) {
  16360. tasks.push({
  16361. data: task,
  16362. callback: typeof callback === 'function' ? callback : null
  16363. });
  16364. cargo.drained = false;
  16365. if (cargo.saturated && tasks.length === payload) {
  16366. cargo.saturated();
  16367. }
  16368. });
  16369. async.setImmediate(cargo.process);
  16370. },
  16371. process: function process() {
  16372. if (working) return;
  16373. if (tasks.length === 0) {
  16374. if(cargo.drain && !cargo.drained) cargo.drain();
  16375. cargo.drained = true;
  16376. return;
  16377. }
  16378. var ts = typeof payload === 'number'
  16379. ? tasks.splice(0, payload)
  16380. : tasks.splice(0, tasks.length);
  16381. var ds = _map(ts, function (task) {
  16382. return task.data;
  16383. });
  16384. if(cargo.empty) cargo.empty();
  16385. working = true;
  16386. worker(ds, function () {
  16387. working = false;
  16388. var args = arguments;
  16389. _each(ts, function (data) {
  16390. if (data.callback) {
  16391. data.callback.apply(null, args);
  16392. }
  16393. });
  16394. process();
  16395. });
  16396. },
  16397. length: function () {
  16398. return tasks.length;
  16399. },
  16400. running: function () {
  16401. return working;
  16402. }
  16403. };
  16404. return cargo;
  16405. };
  16406. var _console_fn = function (name) {
  16407. return function (fn) {
  16408. var args = Array.prototype.slice.call(arguments, 1);
  16409. fn.apply(null, args.concat([function (err) {
  16410. var args = Array.prototype.slice.call(arguments, 1);
  16411. if (typeof console !== 'undefined') {
  16412. if (err) {
  16413. if (console.error) {
  16414. console.error(err);
  16415. }
  16416. }
  16417. else if (console[name]) {
  16418. _each(args, function (x) {
  16419. console[name](x);
  16420. });
  16421. }
  16422. }
  16423. }]));
  16424. };
  16425. };
  16426. async.log = _console_fn('log');
  16427. async.dir = _console_fn('dir');
  16428. /*async.info = _console_fn('info');
  16429. async.warn = _console_fn('warn');
  16430. async.error = _console_fn('error');*/
  16431. async.memoize = function (fn, hasher) {
  16432. var memo = {};
  16433. var queues = {};
  16434. hasher = hasher || function (x) {
  16435. return x;
  16436. };
  16437. var memoized = function () {
  16438. var args = Array.prototype.slice.call(arguments);
  16439. var callback = args.pop();
  16440. var key = hasher.apply(null, args);
  16441. if (key in memo) {
  16442. async.nextTick(function () {
  16443. callback.apply(null, memo[key]);
  16444. });
  16445. }
  16446. else if (key in queues) {
  16447. queues[key].push(callback);
  16448. }
  16449. else {
  16450. queues[key] = [callback];
  16451. fn.apply(null, args.concat([function () {
  16452. memo[key] = arguments;
  16453. var q = queues[key];
  16454. delete queues[key];
  16455. for (var i = 0, l = q.length; i < l; i++) {
  16456. q[i].apply(null, arguments);
  16457. }
  16458. }]));
  16459. }
  16460. };
  16461. memoized.memo = memo;
  16462. memoized.unmemoized = fn;
  16463. return memoized;
  16464. };
  16465. async.unmemoize = function (fn) {
  16466. return function () {
  16467. return (fn.unmemoized || fn).apply(null, arguments);
  16468. };
  16469. };
  16470. async.times = function (count, iterator, callback) {
  16471. var counter = [];
  16472. for (var i = 0; i < count; i++) {
  16473. counter.push(i);
  16474. }
  16475. return async.map(counter, iterator, callback);
  16476. };
  16477. async.timesSeries = function (count, iterator, callback) {
  16478. var counter = [];
  16479. for (var i = 0; i < count; i++) {
  16480. counter.push(i);
  16481. }
  16482. return async.mapSeries(counter, iterator, callback);
  16483. };
  16484. async.seq = function (/* functions... */) {
  16485. var fns = arguments;
  16486. return function () {
  16487. var that = this;
  16488. var args = Array.prototype.slice.call(arguments);
  16489. var callback = args.pop();
  16490. async.reduce(fns, args, function (newargs, fn, cb) {
  16491. fn.apply(that, newargs.concat([function () {
  16492. var err = arguments[0];
  16493. var nextargs = Array.prototype.slice.call(arguments, 1);
  16494. cb(err, nextargs);
  16495. }]))
  16496. },
  16497. function (err, results) {
  16498. callback.apply(that, [err].concat(results));
  16499. });
  16500. };
  16501. };
  16502. async.compose = function (/* functions... */) {
  16503. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  16504. };
  16505. var _applyEach = function (eachfn, fns /*args...*/) {
  16506. var go = function () {
  16507. var that = this;
  16508. var args = Array.prototype.slice.call(arguments);
  16509. var callback = args.pop();
  16510. return eachfn(fns, function (fn, cb) {
  16511. fn.apply(that, args.concat([cb]));
  16512. },
  16513. callback);
  16514. };
  16515. if (arguments.length > 2) {
  16516. var args = Array.prototype.slice.call(arguments, 2);
  16517. return go.apply(this, args);
  16518. }
  16519. else {
  16520. return go;
  16521. }
  16522. };
  16523. async.applyEach = doParallel(_applyEach);
  16524. async.applyEachSeries = doSeries(_applyEach);
  16525. async.forever = function (fn, callback) {
  16526. function next(err) {
  16527. if (err) {
  16528. if (callback) {
  16529. return callback(err);
  16530. }
  16531. throw err;
  16532. }
  16533. fn(next);
  16534. }
  16535. next();
  16536. };
  16537. // Node.js
  16538. if (typeof module !== 'undefined' && module.exports) {
  16539. module.exports = async;
  16540. }
  16541. // AMD / RequireJS
  16542. else if (typeof define !== 'undefined' && define.amd) {
  16543. define([], function () {
  16544. return async;
  16545. });
  16546. }
  16547. // included directly via <script> tag
  16548. else {
  16549. root.async = async;
  16550. }
  16551. }());
  16552. }).call(this,require('_process'))
  16553. },{"_process":61}],61:[function(require,module,exports){
  16554. // shim for using process in browser
  16555. var process = module.exports = {};
  16556. var queue = [];
  16557. var draining = false;
  16558. function drainQueue() {
  16559. if (draining) {
  16560. return;
  16561. }
  16562. draining = true;
  16563. var currentQueue;
  16564. var len = queue.length;
  16565. while(len) {
  16566. currentQueue = queue;
  16567. queue = [];
  16568. var i = -1;
  16569. while (++i < len) {
  16570. currentQueue[i]();
  16571. }
  16572. len = queue.length;
  16573. }
  16574. draining = false;
  16575. }
  16576. process.nextTick = function (fun) {
  16577. queue.push(fun);
  16578. if (!draining) {
  16579. setTimeout(drainQueue, 0);
  16580. }
  16581. };
  16582. process.title = 'browser';
  16583. process.browser = true;
  16584. process.env = {};
  16585. process.argv = [];
  16586. process.version = ''; // empty string to avoid regexp issues
  16587. process.versions = {};
  16588. function noop() {}
  16589. process.on = noop;
  16590. process.addListener = noop;
  16591. process.once = noop;
  16592. process.off = noop;
  16593. process.removeListener = noop;
  16594. process.removeAllListeners = noop;
  16595. process.emit = noop;
  16596. process.binding = function (name) {
  16597. throw new Error('process.binding is not supported');
  16598. };
  16599. // TODO(shtylman)
  16600. process.cwd = function () { return '/' };
  16601. process.chdir = function (dir) {
  16602. throw new Error('process.chdir is not supported');
  16603. };
  16604. process.umask = function() { return 0; };
  16605. },{}],62:[function(require,module,exports){
  16606. // Copyright Joyent, Inc. and other Node contributors.
  16607. //
  16608. // Permission is hereby granted, free of charge, to any person obtaining a
  16609. // copy of this software and associated documentation files (the
  16610. // "Software"), to deal in the Software without restriction, including
  16611. // without limitation the rights to use, copy, modify, merge, publish,
  16612. // distribute, sublicense, and/or sell copies of the Software, and to permit
  16613. // persons to whom the Software is furnished to do so, subject to the
  16614. // following conditions:
  16615. //
  16616. // The above copyright notice and this permission notice shall be included
  16617. // in all copies or substantial portions of the Software.
  16618. //
  16619. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  16620. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  16621. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  16622. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  16623. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  16624. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  16625. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  16626. function EventEmitter() {
  16627. this._events = this._events || {};
  16628. this._maxListeners = this._maxListeners || undefined;
  16629. }
  16630. module.exports = EventEmitter;
  16631. // Backwards-compat with node 0.10.x
  16632. EventEmitter.EventEmitter = EventEmitter;
  16633. EventEmitter.prototype._events = undefined;
  16634. EventEmitter.prototype._maxListeners = undefined;
  16635. // By default EventEmitters will print a warning if more than 10 listeners are
  16636. // added to it. This is a useful default which helps finding memory leaks.
  16637. EventEmitter.defaultMaxListeners = 10;
  16638. // Obviously not all Emitters should be limited to 10. This function allows
  16639. // that to be increased. Set to zero for unlimited.
  16640. EventEmitter.prototype.setMaxListeners = function(n) {
  16641. if (!isNumber(n) || n < 0 || isNaN(n))
  16642. throw TypeError('n must be a positive number');
  16643. this._maxListeners = n;
  16644. return this;
  16645. };
  16646. EventEmitter.prototype.emit = function(type) {
  16647. var er, handler, len, args, i, listeners;
  16648. if (!this._events)
  16649. this._events = {};
  16650. // If there is no 'error' event listener then throw.
  16651. if (type === 'error') {
  16652. if (!this._events.error ||
  16653. (isObject(this._events.error) && !this._events.error.length)) {
  16654. er = arguments[1];
  16655. if (er instanceof Error) {
  16656. throw er; // Unhandled 'error' event
  16657. }
  16658. throw TypeError('Uncaught, unspecified "error" event.');
  16659. }
  16660. }
  16661. handler = this._events[type];
  16662. if (isUndefined(handler))
  16663. return false;
  16664. if (isFunction(handler)) {
  16665. switch (arguments.length) {
  16666. // fast cases
  16667. case 1:
  16668. handler.call(this);
  16669. break;
  16670. case 2:
  16671. handler.call(this, arguments[1]);
  16672. break;
  16673. case 3:
  16674. handler.call(this, arguments[1], arguments[2]);
  16675. break;
  16676. // slower
  16677. default:
  16678. len = arguments.length;
  16679. args = new Array(len - 1);
  16680. for (i = 1; i < len; i++)
  16681. args[i - 1] = arguments[i];
  16682. handler.apply(this, args);
  16683. }
  16684. } else if (isObject(handler)) {
  16685. len = arguments.length;
  16686. args = new Array(len - 1);
  16687. for (i = 1; i < len; i++)
  16688. args[i - 1] = arguments[i];
  16689. listeners = handler.slice();
  16690. len = listeners.length;
  16691. for (i = 0; i < len; i++)
  16692. listeners[i].apply(this, args);
  16693. }
  16694. return true;
  16695. };
  16696. EventEmitter.prototype.addListener = function(type, listener) {
  16697. var m;
  16698. if (!isFunction(listener))
  16699. throw TypeError('listener must be a function');
  16700. if (!this._events)
  16701. this._events = {};
  16702. // To avoid recursion in the case that type === "newListener"! Before
  16703. // adding it to the listeners, first emit "newListener".
  16704. if (this._events.newListener)
  16705. this.emit('newListener', type,
  16706. isFunction(listener.listener) ?
  16707. listener.listener : listener);
  16708. if (!this._events[type])
  16709. // Optimize the case of one listener. Don't need the extra array object.
  16710. this._events[type] = listener;
  16711. else if (isObject(this._events[type]))
  16712. // If we've already got an array, just append.
  16713. this._events[type].push(listener);
  16714. else
  16715. // Adding the second element, need to change to array.
  16716. this._events[type] = [this._events[type], listener];
  16717. // Check for listener leak
  16718. if (isObject(this._events[type]) && !this._events[type].warned) {
  16719. var m;
  16720. if (!isUndefined(this._maxListeners)) {
  16721. m = this._maxListeners;
  16722. } else {
  16723. m = EventEmitter.defaultMaxListeners;
  16724. }
  16725. if (m && m > 0 && this._events[type].length > m) {
  16726. this._events[type].warned = true;
  16727. console.error('(node) warning: possible EventEmitter memory ' +
  16728. 'leak detected. %d listeners added. ' +
  16729. 'Use emitter.setMaxListeners() to increase limit.',
  16730. this._events[type].length);
  16731. if (typeof console.trace === 'function') {
  16732. // not supported in IE 10
  16733. console.trace();
  16734. }
  16735. }
  16736. }
  16737. return this;
  16738. };
  16739. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  16740. EventEmitter.prototype.once = function(type, listener) {
  16741. if (!isFunction(listener))
  16742. throw TypeError('listener must be a function');
  16743. var fired = false;
  16744. function g() {
  16745. this.removeListener(type, g);
  16746. if (!fired) {
  16747. fired = true;
  16748. listener.apply(this, arguments);
  16749. }
  16750. }
  16751. g.listener = listener;
  16752. this.on(type, g);
  16753. return this;
  16754. };
  16755. // emits a 'removeListener' event iff the listener was removed
  16756. EventEmitter.prototype.removeListener = function(type, listener) {
  16757. var list, position, length, i;
  16758. if (!isFunction(listener))
  16759. throw TypeError('listener must be a function');
  16760. if (!this._events || !this._events[type])
  16761. return this;
  16762. list = this._events[type];
  16763. length = list.length;
  16764. position = -1;
  16765. if (list === listener ||
  16766. (isFunction(list.listener) && list.listener === listener)) {
  16767. delete this._events[type];
  16768. if (this._events.removeListener)
  16769. this.emit('removeListener', type, listener);
  16770. } else if (isObject(list)) {
  16771. for (i = length; i-- > 0;) {
  16772. if (list[i] === listener ||
  16773. (list[i].listener && list[i].listener === listener)) {
  16774. position = i;
  16775. break;
  16776. }
  16777. }
  16778. if (position < 0)
  16779. return this;
  16780. if (list.length === 1) {
  16781. list.length = 0;
  16782. delete this._events[type];
  16783. } else {
  16784. list.splice(position, 1);
  16785. }
  16786. if (this._events.removeListener)
  16787. this.emit('removeListener', type, listener);
  16788. }
  16789. return this;
  16790. };
  16791. EventEmitter.prototype.removeAllListeners = function(type) {
  16792. var key, listeners;
  16793. if (!this._events)
  16794. return this;
  16795. // not listening for removeListener, no need to emit
  16796. if (!this._events.removeListener) {
  16797. if (arguments.length === 0)
  16798. this._events = {};
  16799. else if (this._events[type])
  16800. delete this._events[type];
  16801. return this;
  16802. }
  16803. // emit removeListener for all listeners on all events
  16804. if (arguments.length === 0) {
  16805. for (key in this._events) {
  16806. if (key === 'removeListener') continue;
  16807. this.removeAllListeners(key);
  16808. }
  16809. this.removeAllListeners('removeListener');
  16810. this._events = {};
  16811. return this;
  16812. }
  16813. listeners = this._events[type];
  16814. if (isFunction(listeners)) {
  16815. this.removeListener(type, listeners);
  16816. } else {
  16817. // LIFO order
  16818. while (listeners.length)
  16819. this.removeListener(type, listeners[listeners.length - 1]);
  16820. }
  16821. delete this._events[type];
  16822. return this;
  16823. };
  16824. EventEmitter.prototype.listeners = function(type) {
  16825. var ret;
  16826. if (!this._events || !this._events[type])
  16827. ret = [];
  16828. else if (isFunction(this._events[type]))
  16829. ret = [this._events[type]];
  16830. else
  16831. ret = this._events[type].slice();
  16832. return ret;
  16833. };
  16834. EventEmitter.listenerCount = function(emitter, type) {
  16835. var ret;
  16836. if (!emitter._events || !emitter._events[type])
  16837. ret = 0;
  16838. else if (isFunction(emitter._events[type]))
  16839. ret = 1;
  16840. else
  16841. ret = emitter._events[type].length;
  16842. return ret;
  16843. };
  16844. function isFunction(arg) {
  16845. return typeof arg === 'function';
  16846. }
  16847. function isNumber(arg) {
  16848. return typeof arg === 'number';
  16849. }
  16850. function isObject(arg) {
  16851. return typeof arg === 'object' && arg !== null;
  16852. }
  16853. function isUndefined(arg) {
  16854. return arg === void 0;
  16855. }
  16856. },{}],63:[function(require,module,exports){
  16857. // i18next, v1.7.7
  16858. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  16859. // Distributed under MIT license
  16860. // http://i18next.com
  16861. (function() {
  16862. // add indexOf to non ECMA-262 standard compliant browsers
  16863. if (!Array.prototype.indexOf) {
  16864. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  16865. "use strict";
  16866. if (this == null) {
  16867. throw new TypeError();
  16868. }
  16869. var t = Object(this);
  16870. var len = t.length >>> 0;
  16871. if (len === 0) {
  16872. return -1;
  16873. }
  16874. var n = 0;
  16875. if (arguments.length > 0) {
  16876. n = Number(arguments[1]);
  16877. if (n != n) { // shortcut for verifying if it's NaN
  16878. n = 0;
  16879. } else if (n != 0 && n != Infinity && n != -Infinity) {
  16880. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  16881. }
  16882. }
  16883. if (n >= len) {
  16884. return -1;
  16885. }
  16886. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  16887. for (; k < len; k++) {
  16888. if (k in t && t[k] === searchElement) {
  16889. return k;
  16890. }
  16891. }
  16892. return -1;
  16893. }
  16894. }
  16895. // add lastIndexOf to non ECMA-262 standard compliant browsers
  16896. if (!Array.prototype.lastIndexOf) {
  16897. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  16898. "use strict";
  16899. if (this == null) {
  16900. throw new TypeError();
  16901. }
  16902. var t = Object(this);
  16903. var len = t.length >>> 0;
  16904. if (len === 0) {
  16905. return -1;
  16906. }
  16907. var n = len;
  16908. if (arguments.length > 1) {
  16909. n = Number(arguments[1]);
  16910. if (n != n) {
  16911. n = 0;
  16912. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  16913. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  16914. }
  16915. }
  16916. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  16917. for (; k >= 0; k--) {
  16918. if (k in t && t[k] === searchElement) {
  16919. return k;
  16920. }
  16921. }
  16922. return -1;
  16923. };
  16924. }
  16925. // Add string trim for IE8.
  16926. if (typeof String.prototype.trim !== 'function') {
  16927. String.prototype.trim = function() {
  16928. return this.replace(/^\s+|\s+$/g, '');
  16929. }
  16930. }
  16931. var root = this
  16932. , $ = root.jQuery || root.Zepto
  16933. , i18n = {}
  16934. , resStore = {}
  16935. , currentLng
  16936. , replacementCounter = 0
  16937. , languages = []
  16938. , initialized = false
  16939. , sync = {};
  16940. // Export the i18next object for **CommonJS**.
  16941. // If we're not in CommonJS, add `i18n` to the
  16942. // global object or to jquery.
  16943. if (typeof module !== 'undefined' && module.exports) {
  16944. if (!$) {
  16945. try {
  16946. $ = require('jquery');
  16947. } catch(e) {
  16948. // just ignore
  16949. }
  16950. }
  16951. if ($) {
  16952. $.i18n = $.i18n || i18n;
  16953. }
  16954. module.exports = i18n;
  16955. } else {
  16956. if ($) {
  16957. $.i18n = $.i18n || i18n;
  16958. }
  16959. root.i18n = root.i18n || i18n;
  16960. }
  16961. sync = {
  16962. load: function(lngs, options, cb) {
  16963. if (options.useLocalStorage) {
  16964. sync._loadLocal(lngs, options, function(err, store) {
  16965. var missingLngs = [];
  16966. for (var i = 0, len = lngs.length; i < len; i++) {
  16967. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  16968. }
  16969. if (missingLngs.length > 0) {
  16970. sync._fetch(missingLngs, options, function(err, fetched) {
  16971. f.extend(store, fetched);
  16972. sync._storeLocal(fetched);
  16973. cb(null, store);
  16974. });
  16975. } else {
  16976. cb(null, store);
  16977. }
  16978. });
  16979. } else {
  16980. sync._fetch(lngs, options, function(err, store){
  16981. cb(null, store);
  16982. });
  16983. }
  16984. },
  16985. _loadLocal: function(lngs, options, cb) {
  16986. var store = {}
  16987. , nowMS = new Date().getTime();
  16988. if(window.localStorage) {
  16989. var todo = lngs.length;
  16990. f.each(lngs, function(key, lng) {
  16991. var local = window.localStorage.getItem('res_' + lng);
  16992. if (local) {
  16993. local = JSON.parse(local);
  16994. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  16995. store[lng] = local;
  16996. }
  16997. }
  16998. todo--; // wait for all done befor callback
  16999. if (todo === 0) cb(null, store);
  17000. });
  17001. }
  17002. },
  17003. _storeLocal: function(store) {
  17004. if(window.localStorage) {
  17005. for (var m in store) {
  17006. store[m].i18nStamp = new Date().getTime();
  17007. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  17008. }
  17009. }
  17010. return;
  17011. },
  17012. _fetch: function(lngs, options, cb) {
  17013. var ns = options.ns
  17014. , store = {};
  17015. if (!options.dynamicLoad) {
  17016. var todo = ns.namespaces.length * lngs.length
  17017. , errors;
  17018. // load each file individual
  17019. f.each(ns.namespaces, function(nsIndex, nsValue) {
  17020. f.each(lngs, function(lngIndex, lngValue) {
  17021. // Call this once our translation has returned.
  17022. var loadComplete = function(err, data) {
  17023. if (err) {
  17024. errors = errors || [];
  17025. errors.push(err);
  17026. }
  17027. store[lngValue] = store[lngValue] || {};
  17028. store[lngValue][nsValue] = data;
  17029. todo--; // wait for all done befor callback
  17030. if (todo === 0) cb(errors, store);
  17031. };
  17032. if(typeof options.customLoad == 'function'){
  17033. // Use the specified custom callback.
  17034. options.customLoad(lngValue, nsValue, options, loadComplete);
  17035. } else {
  17036. //~ // Use our inbuilt sync.
  17037. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  17038. }
  17039. });
  17040. });
  17041. } else {
  17042. // Call this once our translation has returned.
  17043. var loadComplete = function(err, data) {
  17044. cb(null, data);
  17045. };
  17046. if(typeof options.customLoad == 'function'){
  17047. // Use the specified custom callback.
  17048. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  17049. } else {
  17050. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  17051. // load all needed stuff once
  17052. f.ajax({
  17053. url: url,
  17054. success: function(data, status, xhr) {
  17055. f.log('loaded: ' + url);
  17056. loadComplete(null, data);
  17057. },
  17058. error : function(xhr, status, error) {
  17059. f.log('failed loading: ' + url);
  17060. loadComplete('failed loading resource.json error: ' + error);
  17061. },
  17062. dataType: "json",
  17063. async : options.getAsync
  17064. });
  17065. }
  17066. }
  17067. },
  17068. _fetchOne: function(lng, ns, options, done) {
  17069. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  17070. f.ajax({
  17071. url: url,
  17072. success: function(data, status, xhr) {
  17073. f.log('loaded: ' + url);
  17074. done(null, data);
  17075. },
  17076. error : function(xhr, status, error) {
  17077. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  17078. // file loaded but invalid json, stop waste time !
  17079. f.error('There is a typo in: ' + url);
  17080. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  17081. f.log('Does not exist: ' + url);
  17082. } else {
  17083. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  17084. f.log(theStatus + ' when loading ' + url);
  17085. }
  17086. done(error, {});
  17087. },
  17088. dataType: "json",
  17089. async : options.getAsync
  17090. });
  17091. },
  17092. postMissing: function(lng, ns, key, defaultValue, lngs) {
  17093. var payload = {};
  17094. payload[key] = defaultValue;
  17095. var urls = [];
  17096. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  17097. for (var i = 0; i < o.fallbackLng.length; i++) {
  17098. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  17099. }
  17100. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  17101. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  17102. } else if (o.sendMissingTo === 'all') {
  17103. for (var i = 0, l = lngs.length; i < l; i++) {
  17104. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  17105. }
  17106. }
  17107. for (var y = 0, len = urls.length; y < len; y++) {
  17108. var item = urls[y];
  17109. f.ajax({
  17110. url: item.url,
  17111. type: o.sendType,
  17112. data: payload,
  17113. success: function(data, status, xhr) {
  17114. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  17115. // add key to resStore
  17116. var keys = key.split('.');
  17117. var x = 0;
  17118. var value = resStore[item.lng][ns];
  17119. while (keys[x]) {
  17120. if (x === keys.length - 1) {
  17121. value = value[keys[x]] = defaultValue;
  17122. } else {
  17123. value = value[keys[x]] = value[keys[x]] || {};
  17124. }
  17125. x++;
  17126. }
  17127. },
  17128. error : function(xhr, status, error) {
  17129. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  17130. },
  17131. dataType: "json",
  17132. async : o.postAsync
  17133. });
  17134. }
  17135. },
  17136. reload: reload
  17137. };
  17138. // defaults
  17139. var o = {
  17140. lng: undefined,
  17141. load: 'all',
  17142. preload: [],
  17143. lowerCaseLng: false,
  17144. returnObjectTrees: false,
  17145. fallbackLng: ['dev'],
  17146. fallbackNS: [],
  17147. detectLngQS: 'setLng',
  17148. detectLngFromLocalStorage: false,
  17149. ns: 'translation',
  17150. fallbackOnNull: true,
  17151. fallbackOnEmpty: false,
  17152. fallbackToDefaultNS: false,
  17153. nsseparator: ':',
  17154. keyseparator: '.',
  17155. selectorAttr: 'data-i18n',
  17156. debug: false,
  17157. resGetPath: 'locales/__lng__/__ns__.json',
  17158. resPostPath: 'locales/add/__lng__/__ns__',
  17159. getAsync: true,
  17160. postAsync: true,
  17161. resStore: undefined,
  17162. useLocalStorage: false,
  17163. localStorageExpirationTime: 7*24*60*60*1000,
  17164. dynamicLoad: false,
  17165. sendMissing: false,
  17166. sendMissingTo: 'fallback', // current | all
  17167. sendType: 'POST',
  17168. interpolationPrefix: '__',
  17169. interpolationSuffix: '__',
  17170. defaultVariables: false,
  17171. reusePrefix: '$t(',
  17172. reuseSuffix: ')',
  17173. pluralSuffix: '_plural',
  17174. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  17175. contextNotFound: ['context_not_found', Math.random()].join(''),
  17176. escapeInterpolation: false,
  17177. indefiniteSuffix: '_indefinite',
  17178. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  17179. setJqueryExt: true,
  17180. defaultValueFromContent: true,
  17181. useDataAttrOptions: false,
  17182. cookieExpirationTime: undefined,
  17183. useCookie: true,
  17184. cookieName: 'i18next',
  17185. cookieDomain: undefined,
  17186. objectTreeKeyHandler: undefined,
  17187. postProcess: undefined,
  17188. parseMissingKey: undefined,
  17189. missingKeyHandler: sync.postMissing,
  17190. shortcutFunction: 'sprintf' // or: defaultValue
  17191. };
  17192. function _extend(target, source) {
  17193. if (!source || typeof source === 'function') {
  17194. return target;
  17195. }
  17196. for (var attr in source) { target[attr] = source[attr]; }
  17197. return target;
  17198. }
  17199. function _deepExtend(target, source) {
  17200. for (var prop in source)
  17201. if (prop in target)
  17202. _deepExtend(target[prop], source[prop]);
  17203. else
  17204. target[prop] = source[prop];
  17205. return target;
  17206. }
  17207. function _each(object, callback, args) {
  17208. var name, i = 0,
  17209. length = object.length,
  17210. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  17211. if (args) {
  17212. if (isObj) {
  17213. for (name in object) {
  17214. if (callback.apply(object[name], args) === false) {
  17215. break;
  17216. }
  17217. }
  17218. } else {
  17219. for ( ; i < length; ) {
  17220. if (callback.apply(object[i++], args) === false) {
  17221. break;
  17222. }
  17223. }
  17224. }
  17225. // A special, fast, case for the most common use of each
  17226. } else {
  17227. if (isObj) {
  17228. for (name in object) {
  17229. if (callback.call(object[name], name, object[name]) === false) {
  17230. break;
  17231. }
  17232. }
  17233. } else {
  17234. for ( ; i < length; ) {
  17235. if (callback.call(object[i], i, object[i++]) === false) {
  17236. break;
  17237. }
  17238. }
  17239. }
  17240. }
  17241. return object;
  17242. }
  17243. var _entityMap = {
  17244. "&": "&amp;",
  17245. "<": "&lt;",
  17246. ">": "&gt;",
  17247. '"': '&quot;',
  17248. "'": '&#39;',
  17249. "/": '&#x2F;'
  17250. };
  17251. function _escape(data) {
  17252. if (typeof data === 'string') {
  17253. return data.replace(/[&<>"'\/]/g, function (s) {
  17254. return _entityMap[s];
  17255. });
  17256. }else{
  17257. return data;
  17258. }
  17259. }
  17260. function _ajax(options) {
  17261. // v0.5.0 of https://github.com/goloroden/http.js
  17262. var getXhr = function (callback) {
  17263. // Use the native XHR object if the browser supports it.
  17264. if (window.XMLHttpRequest) {
  17265. return callback(null, new XMLHttpRequest());
  17266. } else if (window.ActiveXObject) {
  17267. // In Internet Explorer check for ActiveX versions of the XHR object.
  17268. try {
  17269. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  17270. } catch (e) {
  17271. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  17272. }
  17273. }
  17274. // If no XHR support was found, throw an error.
  17275. return callback(new Error());
  17276. };
  17277. var encodeUsingUrlEncoding = function (data) {
  17278. if(typeof data === 'string') {
  17279. return data;
  17280. }
  17281. var result = [];
  17282. for(var dataItem in data) {
  17283. if(data.hasOwnProperty(dataItem)) {
  17284. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  17285. }
  17286. }
  17287. return result.join('&');
  17288. };
  17289. var utf8 = function (text) {
  17290. text = text.replace(/\r\n/g, '\n');
  17291. var result = '';
  17292. for(var i = 0; i < text.length; i++) {
  17293. var c = text.charCodeAt(i);
  17294. if(c < 128) {
  17295. result += String.fromCharCode(c);
  17296. } else if((c > 127) && (c < 2048)) {
  17297. result += String.fromCharCode((c >> 6) | 192);
  17298. result += String.fromCharCode((c & 63) | 128);
  17299. } else {
  17300. result += String.fromCharCode((c >> 12) | 224);
  17301. result += String.fromCharCode(((c >> 6) & 63) | 128);
  17302. result += String.fromCharCode((c & 63) | 128);
  17303. }
  17304. }
  17305. return result;
  17306. };
  17307. var base64 = function (text) {
  17308. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  17309. text = utf8(text);
  17310. var result = '',
  17311. chr1, chr2, chr3,
  17312. enc1, enc2, enc3, enc4,
  17313. i = 0;
  17314. do {
  17315. chr1 = text.charCodeAt(i++);
  17316. chr2 = text.charCodeAt(i++);
  17317. chr3 = text.charCodeAt(i++);
  17318. enc1 = chr1 >> 2;
  17319. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  17320. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  17321. enc4 = chr3 & 63;
  17322. if(isNaN(chr2)) {
  17323. enc3 = enc4 = 64;
  17324. } else if(isNaN(chr3)) {
  17325. enc4 = 64;
  17326. }
  17327. result +=
  17328. keyStr.charAt(enc1) +
  17329. keyStr.charAt(enc2) +
  17330. keyStr.charAt(enc3) +
  17331. keyStr.charAt(enc4);
  17332. chr1 = chr2 = chr3 = '';
  17333. enc1 = enc2 = enc3 = enc4 = '';
  17334. } while(i < text.length);
  17335. return result;
  17336. };
  17337. var mergeHeaders = function () {
  17338. // Use the first header object as base.
  17339. var result = arguments[0];
  17340. // Iterate through the remaining header objects and add them.
  17341. for(var i = 1; i < arguments.length; i++) {
  17342. var currentHeaders = arguments[i];
  17343. for(var header in currentHeaders) {
  17344. if(currentHeaders.hasOwnProperty(header)) {
  17345. result[header] = currentHeaders[header];
  17346. }
  17347. }
  17348. }
  17349. // Return the merged headers.
  17350. return result;
  17351. };
  17352. var ajax = function (method, url, options, callback) {
  17353. // Adjust parameters.
  17354. if(typeof options === 'function') {
  17355. callback = options;
  17356. options = {};
  17357. }
  17358. // Set default parameter values.
  17359. options.cache = options.cache || false;
  17360. options.data = options.data || {};
  17361. options.headers = options.headers || {};
  17362. options.jsonp = options.jsonp || false;
  17363. options.async = options.async === undefined ? true : options.async;
  17364. // Merge the various header objects.
  17365. var headers = mergeHeaders({
  17366. 'accept': '*/*',
  17367. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  17368. }, ajax.headers, options.headers);
  17369. // Encode the data according to the content-type.
  17370. var payload;
  17371. if (headers['content-type'] === 'application/json') {
  17372. payload = JSON.stringify(options.data);
  17373. } else {
  17374. payload = encodeUsingUrlEncoding(options.data);
  17375. }
  17376. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  17377. // if neccessary.
  17378. if(method === 'GET') {
  17379. // Setup the query string.
  17380. var queryString = [];
  17381. if(payload) {
  17382. queryString.push(payload);
  17383. payload = null;
  17384. }
  17385. // Handle caching.
  17386. if(!options.cache) {
  17387. queryString.push('_=' + (new Date()).getTime());
  17388. }
  17389. // If neccessary prepare the query string for a JSONP call.
  17390. if(options.jsonp) {
  17391. queryString.push('callback=' + options.jsonp);
  17392. queryString.push('jsonp=' + options.jsonp);
  17393. }
  17394. // Merge the query string and attach it to the url.
  17395. queryString = queryString.join('&');
  17396. if (queryString.length > 1) {
  17397. if (url.indexOf('?') > -1) {
  17398. url += '&' + queryString;
  17399. } else {
  17400. url += '?' + queryString;
  17401. }
  17402. }
  17403. // Make a JSONP call if neccessary.
  17404. if(options.jsonp) {
  17405. var head = document.getElementsByTagName('head')[0];
  17406. var script = document.createElement('script');
  17407. script.type = 'text/javascript';
  17408. script.src = url;
  17409. head.appendChild(script);
  17410. return;
  17411. }
  17412. }
  17413. // Since we got here, it is no JSONP request, so make a normal XHR request.
  17414. getXhr(function (err, xhr) {
  17415. if(err) return callback(err);
  17416. // Open the request.
  17417. xhr.open(method, url, options.async);
  17418. // Set the request headers.
  17419. for(var header in headers) {
  17420. if(headers.hasOwnProperty(header)) {
  17421. xhr.setRequestHeader(header, headers[header]);
  17422. }
  17423. }
  17424. // Handle the request events.
  17425. xhr.onreadystatechange = function () {
  17426. if(xhr.readyState === 4) {
  17427. var data = xhr.responseText || '';
  17428. // If no callback is given, return.
  17429. if(!callback) {
  17430. return;
  17431. }
  17432. // Return an object that provides access to the data as text and JSON.
  17433. callback(xhr.status, {
  17434. text: function () {
  17435. return data;
  17436. },
  17437. json: function () {
  17438. try {
  17439. return JSON.parse(data)
  17440. } catch (e) {
  17441. f.error('Can not parse JSON. URL: ' + url);
  17442. return {};
  17443. }
  17444. }
  17445. });
  17446. }
  17447. };
  17448. // Actually send the XHR request.
  17449. xhr.send(payload);
  17450. });
  17451. };
  17452. // Define the external interface.
  17453. var http = {
  17454. authBasic: function (username, password) {
  17455. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  17456. },
  17457. connect: function (url, options, callback) {
  17458. return ajax('CONNECT', url, options, callback);
  17459. },
  17460. del: function (url, options, callback) {
  17461. return ajax('DELETE', url, options, callback);
  17462. },
  17463. get: function (url, options, callback) {
  17464. return ajax('GET', url, options, callback);
  17465. },
  17466. head: function (url, options, callback) {
  17467. return ajax('HEAD', url, options, callback);
  17468. },
  17469. headers: function (headers) {
  17470. ajax.headers = headers || {};
  17471. },
  17472. isAllowed: function (url, verb, callback) {
  17473. this.options(url, function (status, data) {
  17474. callback(data.text().indexOf(verb) !== -1);
  17475. });
  17476. },
  17477. options: function (url, options, callback) {
  17478. return ajax('OPTIONS', url, options, callback);
  17479. },
  17480. patch: function (url, options, callback) {
  17481. return ajax('PATCH', url, options, callback);
  17482. },
  17483. post: function (url, options, callback) {
  17484. return ajax('POST', url, options, callback);
  17485. },
  17486. put: function (url, options, callback) {
  17487. return ajax('PUT', url, options, callback);
  17488. },
  17489. trace: function (url, options, callback) {
  17490. return ajax('TRACE', url, options, callback);
  17491. }
  17492. };
  17493. var methode = options.type ? options.type.toLowerCase() : 'get';
  17494. http[methode](options.url, options, function (status, data) {
  17495. // file: protocol always gives status code 0, so check for data
  17496. if (status === 200 || (status === 0 && data.text())) {
  17497. options.success(data.json(), status, null);
  17498. } else {
  17499. options.error(data.text(), status, null);
  17500. }
  17501. });
  17502. }
  17503. var _cookie = {
  17504. create: function(name,value,minutes,domain) {
  17505. var expires;
  17506. if (minutes) {
  17507. var date = new Date();
  17508. date.setTime(date.getTime()+(minutes*60*1000));
  17509. expires = "; expires="+date.toGMTString();
  17510. }
  17511. else expires = "";
  17512. domain = (domain)? "domain="+domain+";" : "";
  17513. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  17514. },
  17515. read: function(name) {
  17516. var nameEQ = name + "=";
  17517. var ca = document.cookie.split(';');
  17518. for(var i=0;i < ca.length;i++) {
  17519. var c = ca[i];
  17520. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  17521. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  17522. }
  17523. return null;
  17524. },
  17525. remove: function(name) {
  17526. this.create(name,"",-1);
  17527. }
  17528. };
  17529. var cookie_noop = {
  17530. create: function(name,value,minutes,domain) {},
  17531. read: function(name) { return null; },
  17532. remove: function(name) {}
  17533. };
  17534. // move dependent functions to a container so that
  17535. // they can be overriden easier in no jquery environment (node.js)
  17536. var f = {
  17537. extend: $ ? $.extend : _extend,
  17538. deepExtend: _deepExtend,
  17539. each: $ ? $.each : _each,
  17540. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  17541. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  17542. detectLanguage: detectLanguage,
  17543. escape: _escape,
  17544. log: function(str) {
  17545. if (o.debug && typeof console !== "undefined") console.log(str);
  17546. },
  17547. error: function(str) {
  17548. if (typeof console !== "undefined") console.error(str);
  17549. },
  17550. getCountyIndexOfLng: function(lng) {
  17551. var lng_index = 0;
  17552. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  17553. return lng_index;
  17554. },
  17555. toLanguages: function(lng) {
  17556. var log = this.log;
  17557. function applyCase(l) {
  17558. var ret = l;
  17559. if (typeof l === 'string' && l.indexOf('-') > -1) {
  17560. var parts = l.split('-');
  17561. ret = o.lowerCaseLng ?
  17562. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  17563. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  17564. } else {
  17565. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  17566. }
  17567. return ret;
  17568. }
  17569. var languages = [];
  17570. var whitelist = o.lngWhitelist || false;
  17571. var addLanguage = function(language){
  17572. //reject langs not whitelisted
  17573. if(!whitelist || whitelist.indexOf(language) > -1){
  17574. languages.push(language);
  17575. }else{
  17576. log('rejecting non-whitelisted language: ' + language);
  17577. }
  17578. };
  17579. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  17580. var parts = lng.split('-');
  17581. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  17582. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  17583. } else {
  17584. addLanguage(applyCase(lng));
  17585. }
  17586. for (var i = 0; i < o.fallbackLng.length; i++) {
  17587. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  17588. }
  17589. return languages;
  17590. },
  17591. regexEscape: function(str) {
  17592. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  17593. },
  17594. regexReplacementEscape: function(strOrFn) {
  17595. if (typeof strOrFn === 'string') {
  17596. return strOrFn.replace(/\$/g, "$$$$");
  17597. } else {
  17598. return strOrFn;
  17599. }
  17600. },
  17601. localStorage: {
  17602. setItem: function(key, value) {
  17603. if (window.localStorage) {
  17604. try {
  17605. window.localStorage.setItem(key, value);
  17606. } catch (e) {
  17607. f.log('failed to set value for key "' + key + '" to localStorage.');
  17608. }
  17609. }
  17610. }
  17611. }
  17612. };
  17613. function init(options, cb) {
  17614. if (typeof options === 'function') {
  17615. cb = options;
  17616. options = {};
  17617. }
  17618. options = options || {};
  17619. // override defaults with passed in options
  17620. f.extend(o, options);
  17621. delete o.fixLng; /* passed in each time */
  17622. // override functions: .log(), .detectLanguage(), etc
  17623. if (o.functions) {
  17624. delete o.functions;
  17625. f.extend(f, options.functions);
  17626. }
  17627. // create namespace object if namespace is passed in as string
  17628. if (typeof o.ns == 'string') {
  17629. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  17630. }
  17631. // fallback namespaces
  17632. if (typeof o.fallbackNS == 'string') {
  17633. o.fallbackNS = [o.fallbackNS];
  17634. }
  17635. // fallback languages
  17636. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  17637. o.fallbackLng = [o.fallbackLng];
  17638. }
  17639. // escape prefix/suffix
  17640. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  17641. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  17642. if (!o.lng) o.lng = f.detectLanguage();
  17643. languages = f.toLanguages(o.lng);
  17644. currentLng = languages[0];
  17645. f.log('currentLng set to: ' + currentLng);
  17646. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  17647. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  17648. }
  17649. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  17650. f.localStorage.setItem('i18next_lng', currentLng);
  17651. }
  17652. var lngTranslate = translate;
  17653. if (options.fixLng) {
  17654. lngTranslate = function(key, options) {
  17655. options = options || {};
  17656. options.lng = options.lng || lngTranslate.lng;
  17657. return translate(key, options);
  17658. };
  17659. lngTranslate.lng = currentLng;
  17660. }
  17661. pluralExtensions.setCurrentLng(currentLng);
  17662. // add JQuery extensions
  17663. if ($ && o.setJqueryExt) addJqueryFunct();
  17664. // jQuery deferred
  17665. var deferred;
  17666. if ($ && $.Deferred) {
  17667. deferred = $.Deferred();
  17668. }
  17669. // return immidiatly if res are passed in
  17670. if (o.resStore) {
  17671. resStore = o.resStore;
  17672. initialized = true;
  17673. if (cb) cb(lngTranslate);
  17674. if (deferred) deferred.resolve(lngTranslate);
  17675. if (deferred) return deferred.promise();
  17676. return;
  17677. }
  17678. // languages to load
  17679. var lngsToLoad = f.toLanguages(o.lng);
  17680. if (typeof o.preload === 'string') o.preload = [o.preload];
  17681. for (var i = 0, l = o.preload.length; i < l; i++) {
  17682. var pres = f.toLanguages(o.preload[i]);
  17683. for (var y = 0, len = pres.length; y < len; y++) {
  17684. if (lngsToLoad.indexOf(pres[y]) < 0) {
  17685. lngsToLoad.push(pres[y]);
  17686. }
  17687. }
  17688. }
  17689. // else load them
  17690. i18n.sync.load(lngsToLoad, o, function(err, store) {
  17691. resStore = store;
  17692. initialized = true;
  17693. if (cb) cb(lngTranslate);
  17694. if (deferred) deferred.resolve(lngTranslate);
  17695. });
  17696. if (deferred) return deferred.promise();
  17697. }
  17698. function preload(lngs, cb) {
  17699. if (typeof lngs === 'string') lngs = [lngs];
  17700. for (var i = 0, l = lngs.length; i < l; i++) {
  17701. if (o.preload.indexOf(lngs[i]) < 0) {
  17702. o.preload.push(lngs[i]);
  17703. }
  17704. }
  17705. return init(cb);
  17706. }
  17707. function addResourceBundle(lng, ns, resources, deep) {
  17708. if (typeof ns !== 'string') {
  17709. resources = ns;
  17710. ns = o.ns.defaultNs;
  17711. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  17712. o.ns.namespaces.push(ns);
  17713. }
  17714. resStore[lng] = resStore[lng] || {};
  17715. resStore[lng][ns] = resStore[lng][ns] || {};
  17716. if (deep) {
  17717. f.deepExtend(resStore[lng][ns], resources);
  17718. } else {
  17719. f.extend(resStore[lng][ns], resources);
  17720. }
  17721. }
  17722. function hasResourceBundle(lng, ns) {
  17723. if (typeof ns !== 'string') {
  17724. ns = o.ns.defaultNs;
  17725. }
  17726. resStore[lng] = resStore[lng] || {};
  17727. var res = resStore[lng][ns] || {};
  17728. var hasValues = false;
  17729. for(var prop in res) {
  17730. if (res.hasOwnProperty(prop)) {
  17731. hasValues = true;
  17732. }
  17733. }
  17734. return hasValues;
  17735. }
  17736. function removeResourceBundle(lng, ns) {
  17737. if (typeof ns !== 'string') {
  17738. ns = o.ns.defaultNs;
  17739. }
  17740. resStore[lng] = resStore[lng] || {};
  17741. resStore[lng][ns] = {};
  17742. }
  17743. function addResource(lng, ns, key, value) {
  17744. if (typeof ns !== 'string') {
  17745. resource = ns;
  17746. ns = o.ns.defaultNs;
  17747. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  17748. o.ns.namespaces.push(ns);
  17749. }
  17750. resStore[lng] = resStore[lng] || {};
  17751. resStore[lng][ns] = resStore[lng][ns] || {};
  17752. var keys = key.split(o.keyseparator);
  17753. var x = 0;
  17754. var node = resStore[lng][ns];
  17755. var origRef = node;
  17756. while (keys[x]) {
  17757. if (x == keys.length - 1)
  17758. node[keys[x]] = value;
  17759. else {
  17760. if (node[keys[x]] == null)
  17761. node[keys[x]] = {};
  17762. node = node[keys[x]];
  17763. }
  17764. x++;
  17765. }
  17766. }
  17767. function addResources(lng, ns, resources) {
  17768. if (typeof ns !== 'string') {
  17769. resource = ns;
  17770. ns = o.ns.defaultNs;
  17771. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  17772. o.ns.namespaces.push(ns);
  17773. }
  17774. for (var m in resources) {
  17775. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  17776. }
  17777. }
  17778. function setDefaultNamespace(ns) {
  17779. o.ns.defaultNs = ns;
  17780. }
  17781. function loadNamespace(namespace, cb) {
  17782. loadNamespaces([namespace], cb);
  17783. }
  17784. function loadNamespaces(namespaces, cb) {
  17785. var opts = {
  17786. dynamicLoad: o.dynamicLoad,
  17787. resGetPath: o.resGetPath,
  17788. getAsync: o.getAsync,
  17789. customLoad: o.customLoad,
  17790. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  17791. };
  17792. // languages to load
  17793. var lngsToLoad = f.toLanguages(o.lng);
  17794. if (typeof o.preload === 'string') o.preload = [o.preload];
  17795. for (var i = 0, l = o.preload.length; i < l; i++) {
  17796. var pres = f.toLanguages(o.preload[i]);
  17797. for (var y = 0, len = pres.length; y < len; y++) {
  17798. if (lngsToLoad.indexOf(pres[y]) < 0) {
  17799. lngsToLoad.push(pres[y]);
  17800. }
  17801. }
  17802. }
  17803. // check if we have to load
  17804. var lngNeedLoad = [];
  17805. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  17806. var needLoad = false;
  17807. var resSet = resStore[lngsToLoad[a]];
  17808. if (resSet) {
  17809. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  17810. if (!resSet[namespaces[b]]) needLoad = true;
  17811. }
  17812. } else {
  17813. needLoad = true;
  17814. }
  17815. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  17816. }
  17817. if (lngNeedLoad.length) {
  17818. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  17819. var todo = namespaces.length * lngNeedLoad.length;
  17820. // load each file individual
  17821. f.each(namespaces, function(nsIndex, nsValue) {
  17822. // append namespace to namespace array
  17823. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  17824. o.ns.namespaces.push(nsValue);
  17825. }
  17826. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  17827. resStore[lngValue] = resStore[lngValue] || {};
  17828. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  17829. todo--; // wait for all done befor callback
  17830. if (todo === 0 && cb) {
  17831. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  17832. cb();
  17833. }
  17834. });
  17835. });
  17836. });
  17837. } else {
  17838. if (cb) cb();
  17839. }
  17840. }
  17841. function setLng(lng, options, cb) {
  17842. if (typeof options === 'function') {
  17843. cb = options;
  17844. options = {};
  17845. } else if (!options) {
  17846. options = {};
  17847. }
  17848. options.lng = lng;
  17849. return init(options, cb);
  17850. }
  17851. function lng() {
  17852. return currentLng;
  17853. }
  17854. function reload(cb) {
  17855. resStore = {};
  17856. setLng(currentLng, cb);
  17857. }
  17858. function addJqueryFunct() {
  17859. // $.t shortcut
  17860. $.t = $.t || translate;
  17861. function parse(ele, key, options) {
  17862. if (key.length === 0) return;
  17863. var attr = 'text';
  17864. if (key.indexOf('[') === 0) {
  17865. var parts = key.split(']');
  17866. key = parts[1];
  17867. attr = parts[0].substr(1, parts[0].length-1);
  17868. }
  17869. if (key.indexOf(';') === key.length-1) {
  17870. key = key.substr(0, key.length-2);
  17871. }
  17872. var optionsToUse;
  17873. if (attr === 'html') {
  17874. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  17875. ele.html($.t(key, optionsToUse));
  17876. } else if (attr === 'text') {
  17877. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  17878. ele.text($.t(key, optionsToUse));
  17879. } else if (attr === 'prepend') {
  17880. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  17881. ele.prepend($.t(key, optionsToUse));
  17882. } else if (attr === 'append') {
  17883. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  17884. ele.append($.t(key, optionsToUse));
  17885. } else if (attr.indexOf("data-") === 0) {
  17886. var dataAttr = attr.substr(("data-").length);
  17887. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  17888. var translated = $.t(key, optionsToUse);
  17889. //we change into the data cache
  17890. ele.data(dataAttr, translated);
  17891. //we change into the dom
  17892. ele.attr(attr, translated);
  17893. } else {
  17894. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  17895. ele.attr(attr, $.t(key, optionsToUse));
  17896. }
  17897. }
  17898. function localize(ele, options) {
  17899. var key = ele.attr(o.selectorAttr);
  17900. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  17901. if (!key) return;
  17902. var target = ele
  17903. , targetSelector = ele.data("i18n-target");
  17904. if (targetSelector) {
  17905. target = ele.find(targetSelector) || ele;
  17906. }
  17907. if (!options && o.useDataAttrOptions === true) {
  17908. options = ele.data("i18n-options");
  17909. }
  17910. options = options || {};
  17911. if (key.indexOf(';') >= 0) {
  17912. var keys = key.split(';');
  17913. $.each(keys, function(m, k) {
  17914. if (k !== '') parse(target, k, options);
  17915. });
  17916. } else {
  17917. parse(target, key, options);
  17918. }
  17919. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  17920. }
  17921. // fn
  17922. $.fn.i18n = function (options) {
  17923. return this.each(function() {
  17924. // localize element itself
  17925. localize($(this), options);
  17926. // localize childs
  17927. var elements = $(this).find('[' + o.selectorAttr + ']');
  17928. elements.each(function() {
  17929. localize($(this), options);
  17930. });
  17931. });
  17932. };
  17933. }
  17934. function applyReplacement(str, replacementHash, nestedKey, options) {
  17935. if (!str) return str;
  17936. options = options || replacementHash; // first call uses replacement hash combined with options
  17937. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  17938. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  17939. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  17940. , unEscapingSuffix = 'HTML'+suffix;
  17941. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  17942. f.each(hash, function(key, value) {
  17943. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  17944. if (typeof value === 'object' && value !== null) {
  17945. str = applyReplacement(str, value, nextKey, options);
  17946. } else {
  17947. if (options.escapeInterpolation || o.escapeInterpolation) {
  17948. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  17949. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  17950. } else {
  17951. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  17952. }
  17953. // str = options.escapeInterpolation;
  17954. }
  17955. });
  17956. return str;
  17957. }
  17958. // append it to functions
  17959. f.applyReplacement = applyReplacement;
  17960. function applyReuse(translated, options) {
  17961. var comma = ',';
  17962. var options_open = '{';
  17963. var options_close = '}';
  17964. var opts = f.extend({}, options);
  17965. delete opts.postProcess;
  17966. while (translated.indexOf(o.reusePrefix) != -1) {
  17967. replacementCounter++;
  17968. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  17969. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  17970. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  17971. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  17972. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  17973. if (index_of_end_of_closing <= index_of_opening) {
  17974. f.error('there is an missing closing in following translation value', translated);
  17975. return '';
  17976. }
  17977. if (token_without_symbols.indexOf(comma) != -1) {
  17978. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  17979. 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) {
  17980. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  17981. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  17982. try {
  17983. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  17984. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  17985. } catch (e) {
  17986. }
  17987. }
  17988. }
  17989. var translated_token = _translate(token_without_symbols, opts);
  17990. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  17991. }
  17992. return translated;
  17993. }
  17994. function hasContext(options) {
  17995. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  17996. }
  17997. function needsPlural(options, lng) {
  17998. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  17999. }
  18000. function needsIndefiniteArticle(options) {
  18001. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  18002. }
  18003. function exists(key, options) {
  18004. options = options || {};
  18005. var notFound = _getDefaultValue(key, options)
  18006. , found = _find(key, options);
  18007. return found !== undefined || found === notFound;
  18008. }
  18009. function translate(key, options) {
  18010. options = options || {};
  18011. if (!initialized) {
  18012. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  18013. return options.defaultValue || '';
  18014. };
  18015. replacementCounter = 0;
  18016. return _translate.apply(null, arguments);
  18017. }
  18018. function _getDefaultValue(key, options) {
  18019. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  18020. }
  18021. function _injectSprintfProcessor() {
  18022. var values = [];
  18023. // mh: build array from second argument onwards
  18024. for (var i = 1; i < arguments.length; i++) {
  18025. values.push(arguments[i]);
  18026. }
  18027. return {
  18028. postProcess: 'sprintf',
  18029. sprintf: values
  18030. };
  18031. }
  18032. function _translate(potentialKeys, options) {
  18033. if (options && typeof options !== 'object') {
  18034. if (o.shortcutFunction === 'sprintf') {
  18035. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  18036. options = _injectSprintfProcessor.apply(null, arguments);
  18037. } else if (o.shortcutFunction === 'defaultValue') {
  18038. options = {
  18039. defaultValue: options
  18040. }
  18041. }
  18042. } else {
  18043. options = options || {};
  18044. }
  18045. if (typeof o.defaultVariables === 'object') {
  18046. options = f.extend({}, o.defaultVariables, options);
  18047. }
  18048. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  18049. if (typeof potentialKeys === 'string') {
  18050. potentialKeys = [potentialKeys];
  18051. }
  18052. var key = potentialKeys[0];
  18053. if (potentialKeys.length > 1) {
  18054. for (var i = 0; i < potentialKeys.length; i++) {
  18055. key = potentialKeys[i];
  18056. if (exists(key, options)) {
  18057. break;
  18058. }
  18059. }
  18060. }
  18061. var notFound = _getDefaultValue(key, options)
  18062. , found = _find(key, options)
  18063. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  18064. , ns = options.ns || o.ns.defaultNs
  18065. , parts;
  18066. // split ns and key
  18067. if (key.indexOf(o.nsseparator) > -1) {
  18068. parts = key.split(o.nsseparator);
  18069. ns = parts[0];
  18070. key = parts[1];
  18071. }
  18072. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  18073. if (options.lng) {
  18074. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  18075. } else {
  18076. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  18077. }
  18078. }
  18079. var postProcessor = options.postProcess || o.postProcess;
  18080. if (found !== undefined && postProcessor) {
  18081. if (postProcessors[postProcessor]) {
  18082. found = postProcessors[postProcessor](found, key, options);
  18083. }
  18084. }
  18085. // process notFound if function exists
  18086. var splitNotFound = notFound;
  18087. if (notFound.indexOf(o.nsseparator) > -1) {
  18088. parts = notFound.split(o.nsseparator);
  18089. splitNotFound = parts[1];
  18090. }
  18091. if (splitNotFound === key && o.parseMissingKey) {
  18092. notFound = o.parseMissingKey(notFound);
  18093. }
  18094. if (found === undefined) {
  18095. notFound = applyReplacement(notFound, options);
  18096. notFound = applyReuse(notFound, options);
  18097. if (postProcessor && postProcessors[postProcessor]) {
  18098. var val = _getDefaultValue(key, options);
  18099. found = postProcessors[postProcessor](val, key, options);
  18100. }
  18101. }
  18102. return (found !== undefined) ? found : notFound;
  18103. }
  18104. function _find(key, options) {
  18105. options = options || {};
  18106. var optionWithoutCount, translated
  18107. , notFound = _getDefaultValue(key, options)
  18108. , lngs = languages;
  18109. if (!resStore) { return notFound; } // no resStore to translate from
  18110. // CI mode
  18111. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  18112. // passed in lng
  18113. if (options.lngs) lngs = options.lngs;
  18114. if (options.lng) {
  18115. lngs = f.toLanguages(options.lng, options.fallbackLng);
  18116. if (!resStore[lngs[0]]) {
  18117. var oldAsync = o.getAsync;
  18118. o.getAsync = false;
  18119. i18n.sync.load(lngs, o, function(err, store) {
  18120. f.extend(resStore, store);
  18121. o.getAsync = oldAsync;
  18122. });
  18123. }
  18124. }
  18125. var ns = options.ns || o.ns.defaultNs;
  18126. if (key.indexOf(o.nsseparator) > -1) {
  18127. var parts = key.split(o.nsseparator);
  18128. ns = parts[0];
  18129. key = parts[1];
  18130. }
  18131. if (hasContext(options)) {
  18132. optionWithoutCount = f.extend({}, options);
  18133. delete optionWithoutCount.context;
  18134. optionWithoutCount.defaultValue = o.contextNotFound;
  18135. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  18136. translated = translate(contextKey, optionWithoutCount);
  18137. if (translated != o.contextNotFound) {
  18138. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  18139. } // else continue translation with original/nonContext key
  18140. }
  18141. if (needsPlural(options, lngs[0])) {
  18142. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  18143. delete optionWithoutCount.count;
  18144. delete optionWithoutCount.lng;
  18145. optionWithoutCount.defaultValue = o.pluralNotFound;
  18146. var pluralKey;
  18147. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  18148. pluralKey = ns + o.nsseparator + key;
  18149. } else {
  18150. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  18151. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  18152. if (pluralExtension >= 0) {
  18153. pluralKey = pluralKey + '_' + pluralExtension;
  18154. } else if (pluralExtension === 1) {
  18155. pluralKey = ns + o.nsseparator + key; // singular
  18156. }
  18157. }
  18158. translated = translate(pluralKey, optionWithoutCount);
  18159. if (translated != o.pluralNotFound) {
  18160. return applyReplacement(translated, {
  18161. count: options.count,
  18162. interpolationPrefix: options.interpolationPrefix,
  18163. interpolationSuffix: options.interpolationSuffix
  18164. }); // apply replacement for count only
  18165. } else if (lngs.length > 1) {
  18166. // remove failed lng
  18167. var clone = lngs.slice();
  18168. clone.shift();
  18169. options = f.extend(options, { lngs: clone });
  18170. delete options.lng;
  18171. // retry with fallbacks
  18172. translated = translate(ns + o.nsseparator + key, options);
  18173. if (translated != o.pluralNotFound) return translated;
  18174. } else {
  18175. return translated;
  18176. }
  18177. }
  18178. if (needsIndefiniteArticle(options)) {
  18179. var optionsWithoutIndef = f.extend({}, options);
  18180. delete optionsWithoutIndef.indefinite_article;
  18181. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  18182. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  18183. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  18184. translated = translate(indefiniteKey, optionsWithoutIndef);
  18185. if (translated != o.indefiniteNotFound) {
  18186. return translated;
  18187. }
  18188. }
  18189. var found;
  18190. var keys = key.split(o.keyseparator);
  18191. for (var i = 0, len = lngs.length; i < len; i++ ) {
  18192. if (found !== undefined) break;
  18193. var l = lngs[i];
  18194. var x = 0;
  18195. var value = resStore[l] && resStore[l][ns];
  18196. while (keys[x]) {
  18197. value = value && value[keys[x]];
  18198. x++;
  18199. }
  18200. if (value !== undefined) {
  18201. var valueType = Object.prototype.toString.apply(value);
  18202. if (typeof value === 'string') {
  18203. value = applyReplacement(value, options);
  18204. value = applyReuse(value, options);
  18205. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  18206. value = value.join('\n');
  18207. value = applyReplacement(value, options);
  18208. value = applyReuse(value, options);
  18209. } else if (value === null && o.fallbackOnNull === true) {
  18210. value = undefined;
  18211. } else if (value !== null) {
  18212. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  18213. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  18214. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  18215. } else {
  18216. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  18217. 'returned an object instead of string.';
  18218. f.log(value);
  18219. }
  18220. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  18221. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  18222. f.each(value, function(m) {
  18223. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  18224. });
  18225. value = copy;
  18226. }
  18227. }
  18228. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  18229. value = undefined;
  18230. found = value;
  18231. }
  18232. }
  18233. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  18234. // set flag for fallback lookup - avoid recursion
  18235. options.isFallbackLookup = true;
  18236. if (o.fallbackNS.length) {
  18237. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  18238. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  18239. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  18240. /* compare value without namespace */
  18241. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  18242. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  18243. if (foundValue !== notFoundValue) break;
  18244. }
  18245. }
  18246. } else {
  18247. found = _find(key, options); // fallback to default NS
  18248. }
  18249. options.isFallbackLookup = false;
  18250. }
  18251. return found;
  18252. }
  18253. function detectLanguage() {
  18254. var detectedLng;
  18255. var whitelist = o.lngWhitelist || [];
  18256. var userLngChoices = [];
  18257. // get from qs
  18258. var qsParm = [];
  18259. if (typeof window !== 'undefined') {
  18260. (function() {
  18261. var query = window.location.search.substring(1);
  18262. var params = query.split('&');
  18263. for (var i=0; i<params.length; i++) {
  18264. var pos = params[i].indexOf('=');
  18265. if (pos > 0) {
  18266. var key = params[i].substring(0,pos);
  18267. if (key == o.detectLngQS) {
  18268. userLngChoices.push(params[i].substring(pos+1));
  18269. }
  18270. }
  18271. }
  18272. })();
  18273. }
  18274. // get from cookie
  18275. if (o.useCookie && typeof document !== 'undefined') {
  18276. var c = f.cookie.read(o.cookieName);
  18277. if (c) userLngChoices.push(c);
  18278. }
  18279. // get from localStorage
  18280. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  18281. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  18282. }
  18283. // get from navigator
  18284. if (typeof navigator !== 'undefined') {
  18285. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  18286. for (var i=0;i<navigator.languages.length;i++) {
  18287. userLngChoices.push(navigator.languages[i]);
  18288. }
  18289. }
  18290. if (navigator.userLanguage) {
  18291. userLngChoices.push(navigator.userLanguage);
  18292. }
  18293. if (navigator.language) {
  18294. userLngChoices.push(navigator.language);
  18295. }
  18296. }
  18297. (function() {
  18298. for (var i=0;i<userLngChoices.length;i++) {
  18299. var lng = userLngChoices[i];
  18300. if (lng.indexOf('-') > -1) {
  18301. var parts = lng.split('-');
  18302. lng = o.lowerCaseLng ?
  18303. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  18304. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  18305. }
  18306. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  18307. detectedLng = lng;
  18308. break;
  18309. }
  18310. }
  18311. })();
  18312. //fallback
  18313. if (!detectedLng){
  18314. detectedLng = o.fallbackLng[0];
  18315. }
  18316. return detectedLng;
  18317. }
  18318. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  18319. /* [code, name, numbers, pluralsType] */
  18320. var _rules = [
  18321. ["ach", "Acholi", [1,2], 1],
  18322. ["af", "Afrikaans",[1,2], 2],
  18323. ["ak", "Akan", [1,2], 1],
  18324. ["am", "Amharic", [1,2], 1],
  18325. ["an", "Aragonese",[1,2], 2],
  18326. ["ar", "Arabic", [0,1,2,3,11,100],5],
  18327. ["arn", "Mapudungun",[1,2], 1],
  18328. ["ast", "Asturian", [1,2], 2],
  18329. ["ay", "Aymará", [1], 3],
  18330. ["az", "Azerbaijani",[1,2],2],
  18331. ["be", "Belarusian",[1,2,5],4],
  18332. ["bg", "Bulgarian",[1,2], 2],
  18333. ["bn", "Bengali", [1,2], 2],
  18334. ["bo", "Tibetan", [1], 3],
  18335. ["br", "Breton", [1,2], 1],
  18336. ["bs", "Bosnian", [1,2,5],4],
  18337. ["ca", "Catalan", [1,2], 2],
  18338. ["cgg", "Chiga", [1], 3],
  18339. ["cs", "Czech", [1,2,5],6],
  18340. ["csb", "Kashubian",[1,2,5],7],
  18341. ["cy", "Welsh", [1,2,3,8],8],
  18342. ["da", "Danish", [1,2], 2],
  18343. ["de", "German", [1,2], 2],
  18344. ["dev", "Development Fallback", [1,2], 2],
  18345. ["dz", "Dzongkha", [1], 3],
  18346. ["el", "Greek", [1,2], 2],
  18347. ["en", "English", [1,2], 2],
  18348. ["eo", "Esperanto",[1,2], 2],
  18349. ["es", "Spanish", [1,2], 2],
  18350. ["es_ar","Argentinean Spanish", [1,2], 2],
  18351. ["et", "Estonian", [1,2], 2],
  18352. ["eu", "Basque", [1,2], 2],
  18353. ["fa", "Persian", [1], 3],
  18354. ["fi", "Finnish", [1,2], 2],
  18355. ["fil", "Filipino", [1,2], 1],
  18356. ["fo", "Faroese", [1,2], 2],
  18357. ["fr", "French", [1,2], 9],
  18358. ["fur", "Friulian", [1,2], 2],
  18359. ["fy", "Frisian", [1,2], 2],
  18360. ["ga", "Irish", [1,2,3,7,11],10],
  18361. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  18362. ["gl", "Galician", [1,2], 2],
  18363. ["gu", "Gujarati", [1,2], 2],
  18364. ["gun", "Gun", [1,2], 1],
  18365. ["ha", "Hausa", [1,2], 2],
  18366. ["he", "Hebrew", [1,2], 2],
  18367. ["hi", "Hindi", [1,2], 2],
  18368. ["hr", "Croatian", [1,2,5],4],
  18369. ["hu", "Hungarian",[1,2], 2],
  18370. ["hy", "Armenian", [1,2], 2],
  18371. ["ia", "Interlingua",[1,2],2],
  18372. ["id", "Indonesian",[1], 3],
  18373. ["is", "Icelandic",[1,2], 12],
  18374. ["it", "Italian", [1,2], 2],
  18375. ["ja", "Japanese", [1], 3],
  18376. ["jbo", "Lojban", [1], 3],
  18377. ["jv", "Javanese", [0,1], 13],
  18378. ["ka", "Georgian", [1], 3],
  18379. ["kk", "Kazakh", [1], 3],
  18380. ["km", "Khmer", [1], 3],
  18381. ["kn", "Kannada", [1,2], 2],
  18382. ["ko", "Korean", [1], 3],
  18383. ["ku", "Kurdish", [1,2], 2],
  18384. ["kw", "Cornish", [1,2,3,4],14],
  18385. ["ky", "Kyrgyz", [1], 3],
  18386. ["lb", "Letzeburgesch",[1,2],2],
  18387. ["ln", "Lingala", [1,2], 1],
  18388. ["lo", "Lao", [1], 3],
  18389. ["lt", "Lithuanian",[1,2,10],15],
  18390. ["lv", "Latvian", [1,2,0],16],
  18391. ["mai", "Maithili", [1,2], 2],
  18392. ["mfe", "Mauritian Creole",[1,2],1],
  18393. ["mg", "Malagasy", [1,2], 1],
  18394. ["mi", "Maori", [1,2], 1],
  18395. ["mk", "Macedonian",[1,2],17],
  18396. ["ml", "Malayalam",[1,2], 2],
  18397. ["mn", "Mongolian",[1,2], 2],
  18398. ["mnk", "Mandinka", [0,1,2],18],
  18399. ["mr", "Marathi", [1,2], 2],
  18400. ["ms", "Malay", [1], 3],
  18401. ["mt", "Maltese", [1,2,11,20],19],
  18402. ["nah", "Nahuatl", [1,2], 2],
  18403. ["nap", "Neapolitan",[1,2], 2],
  18404. ["nb", "Norwegian Bokmal",[1,2],2],
  18405. ["ne", "Nepali", [1,2], 2],
  18406. ["nl", "Dutch", [1,2], 2],
  18407. ["nn", "Norwegian Nynorsk",[1,2],2],
  18408. ["no", "Norwegian",[1,2], 2],
  18409. ["nso", "Northern Sotho",[1,2],2],
  18410. ["oc", "Occitan", [1,2], 1],
  18411. ["or", "Oriya", [2,1], 2],
  18412. ["pa", "Punjabi", [1,2], 2],
  18413. ["pap", "Papiamento",[1,2], 2],
  18414. ["pl", "Polish", [1,2,5],7],
  18415. ["pms", "Piemontese",[1,2], 2],
  18416. ["ps", "Pashto", [1,2], 2],
  18417. ["pt", "Portuguese",[1,2], 2],
  18418. ["pt_br","Brazilian Portuguese",[1,2], 2],
  18419. ["rm", "Romansh", [1,2], 2],
  18420. ["ro", "Romanian", [1,2,20],20],
  18421. ["ru", "Russian", [1,2,5],4],
  18422. ["sah", "Yakut", [1], 3],
  18423. ["sco", "Scots", [1,2], 2],
  18424. ["se", "Northern Sami",[1,2], 2],
  18425. ["si", "Sinhala", [1,2], 2],
  18426. ["sk", "Slovak", [1,2,5],6],
  18427. ["sl", "Slovenian",[5,1,2,3],21],
  18428. ["so", "Somali", [1,2], 2],
  18429. ["son", "Songhay", [1,2], 2],
  18430. ["sq", "Albanian", [1,2], 2],
  18431. ["sr", "Serbian", [1,2,5],4],
  18432. ["su", "Sundanese",[1], 3],
  18433. ["sv", "Swedish", [1,2], 2],
  18434. ["sw", "Swahili", [1,2], 2],
  18435. ["ta", "Tamil", [1,2], 2],
  18436. ["te", "Telugu", [1,2], 2],
  18437. ["tg", "Tajik", [1,2], 1],
  18438. ["th", "Thai", [1], 3],
  18439. ["ti", "Tigrinya", [1,2], 1],
  18440. ["tk", "Turkmen", [1,2], 2],
  18441. ["tr", "Turkish", [1,2], 1],
  18442. ["tt", "Tatar", [1], 3],
  18443. ["ug", "Uyghur", [1], 3],
  18444. ["uk", "Ukrainian",[1,2,5],4],
  18445. ["ur", "Urdu", [1,2], 2],
  18446. ["uz", "Uzbek", [1,2], 1],
  18447. ["vi", "Vietnamese",[1], 3],
  18448. ["wa", "Walloon", [1,2], 1],
  18449. ["wo", "Wolof", [1], 3],
  18450. ["yo", "Yoruba", [1,2], 2],
  18451. ["zh", "Chinese", [1], 3]
  18452. ];
  18453. var _rulesPluralsTypes = {
  18454. 1: function(n) {return Number(n > 1);},
  18455. 2: function(n) {return Number(n != 1);},
  18456. 3: function(n) {return 0;},
  18457. 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);},
  18458. 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);},
  18459. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  18460. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  18461. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  18462. 9: function(n) {return Number(n >= 2);},
  18463. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  18464. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  18465. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  18466. 13: function(n) {return Number(n !== 0);},
  18467. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  18468. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  18469. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  18470. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  18471. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  18472. 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);},
  18473. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  18474. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  18475. };
  18476. var pluralExtensions = {
  18477. rules: (function () {
  18478. var l, rules = {};
  18479. for (l=_rules.length; l-- ;) {
  18480. rules[_rules[l][0]] = {
  18481. name: _rules[l][1],
  18482. numbers: _rules[l][2],
  18483. plurals: _rulesPluralsTypes[_rules[l][3]]
  18484. }
  18485. }
  18486. return rules;
  18487. }()),
  18488. // you can add your own pluralExtensions
  18489. addRule: function(lng, obj) {
  18490. pluralExtensions.rules[lng] = obj;
  18491. },
  18492. setCurrentLng: function(lng) {
  18493. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  18494. var parts = lng.split('-');
  18495. pluralExtensions.currentRule = {
  18496. lng: lng,
  18497. rule: pluralExtensions.rules[parts[0]]
  18498. };
  18499. }
  18500. },
  18501. needsPlural: function(lng, count) {
  18502. var parts = lng.split('-');
  18503. var ext;
  18504. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  18505. ext = pluralExtensions.currentRule.rule;
  18506. } else {
  18507. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  18508. }
  18509. if (ext && ext.numbers.length <= 1) {
  18510. return false;
  18511. } else {
  18512. return this.get(lng, count) !== 1;
  18513. }
  18514. },
  18515. get: function(lng, count) {
  18516. var parts = lng.split('-');
  18517. function getResult(l, c) {
  18518. var ext;
  18519. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  18520. ext = pluralExtensions.currentRule.rule;
  18521. } else {
  18522. ext = pluralExtensions.rules[l];
  18523. }
  18524. if (ext) {
  18525. var i;
  18526. if (ext.noAbs) {
  18527. i = ext.plurals(c);
  18528. } else {
  18529. i = ext.plurals(Math.abs(c));
  18530. }
  18531. var number = ext.numbers[i];
  18532. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  18533. if (number === 2) {
  18534. number = -1; // regular plural
  18535. } else if (number === 1) {
  18536. number = 1; // singular
  18537. }
  18538. }//console.log(count + '-' + number);
  18539. return number;
  18540. } else {
  18541. return c === 1 ? '1' : '-1';
  18542. }
  18543. }
  18544. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  18545. }
  18546. };
  18547. var postProcessors = {};
  18548. var addPostProcessor = function(name, fc) {
  18549. postProcessors[name] = fc;
  18550. };
  18551. // sprintf support
  18552. var sprintf = (function() {
  18553. function get_type(variable) {
  18554. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  18555. }
  18556. function str_repeat(input, multiplier) {
  18557. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  18558. return output.join('');
  18559. }
  18560. var str_format = function() {
  18561. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  18562. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  18563. }
  18564. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  18565. };
  18566. str_format.format = function(parse_tree, argv) {
  18567. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  18568. for (i = 0; i < tree_length; i++) {
  18569. node_type = get_type(parse_tree[i]);
  18570. if (node_type === 'string') {
  18571. output.push(parse_tree[i]);
  18572. }
  18573. else if (node_type === 'array') {
  18574. match = parse_tree[i]; // convenience purposes only
  18575. if (match[2]) { // keyword argument
  18576. arg = argv[cursor];
  18577. for (k = 0; k < match[2].length; k++) {
  18578. if (!arg.hasOwnProperty(match[2][k])) {
  18579. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  18580. }
  18581. arg = arg[match[2][k]];
  18582. }
  18583. }
  18584. else if (match[1]) { // positional argument (explicit)
  18585. arg = argv[match[1]];
  18586. }
  18587. else { // positional argument (implicit)
  18588. arg = argv[cursor++];
  18589. }
  18590. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  18591. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  18592. }
  18593. switch (match[8]) {
  18594. case 'b': arg = arg.toString(2); break;
  18595. case 'c': arg = String.fromCharCode(arg); break;
  18596. case 'd': arg = parseInt(arg, 10); break;
  18597. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  18598. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  18599. case 'o': arg = arg.toString(8); break;
  18600. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  18601. case 'u': arg = Math.abs(arg); break;
  18602. case 'x': arg = arg.toString(16); break;
  18603. case 'X': arg = arg.toString(16).toUpperCase(); break;
  18604. }
  18605. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  18606. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  18607. pad_length = match[6] - String(arg).length;
  18608. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  18609. output.push(match[5] ? arg + pad : pad + arg);
  18610. }
  18611. }
  18612. return output.join('');
  18613. };
  18614. str_format.cache = {};
  18615. str_format.parse = function(fmt) {
  18616. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  18617. while (_fmt) {
  18618. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  18619. parse_tree.push(match[0]);
  18620. }
  18621. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  18622. parse_tree.push('%');
  18623. }
  18624. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  18625. if (match[2]) {
  18626. arg_names |= 1;
  18627. var field_list = [], replacement_field = match[2], field_match = [];
  18628. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  18629. field_list.push(field_match[1]);
  18630. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  18631. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  18632. field_list.push(field_match[1]);
  18633. }
  18634. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  18635. field_list.push(field_match[1]);
  18636. }
  18637. else {
  18638. throw('[sprintf] huh?');
  18639. }
  18640. }
  18641. }
  18642. else {
  18643. throw('[sprintf] huh?');
  18644. }
  18645. match[2] = field_list;
  18646. }
  18647. else {
  18648. arg_names |= 2;
  18649. }
  18650. if (arg_names === 3) {
  18651. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  18652. }
  18653. parse_tree.push(match);
  18654. }
  18655. else {
  18656. throw('[sprintf] huh?');
  18657. }
  18658. _fmt = _fmt.substring(match[0].length);
  18659. }
  18660. return parse_tree;
  18661. };
  18662. return str_format;
  18663. })();
  18664. var vsprintf = function(fmt, argv) {
  18665. argv.unshift(fmt);
  18666. return sprintf.apply(null, argv);
  18667. };
  18668. addPostProcessor("sprintf", function(val, key, opts) {
  18669. if (!opts.sprintf) return val;
  18670. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  18671. return vsprintf(val, opts.sprintf);
  18672. } else if (typeof opts.sprintf === 'object') {
  18673. return sprintf(val, opts.sprintf);
  18674. }
  18675. return val;
  18676. });
  18677. // public api interface
  18678. i18n.init = init;
  18679. i18n.setLng = setLng;
  18680. i18n.preload = preload;
  18681. i18n.addResourceBundle = addResourceBundle;
  18682. i18n.hasResourceBundle = hasResourceBundle;
  18683. i18n.addResource = addResource;
  18684. i18n.addResources = addResources;
  18685. i18n.removeResourceBundle = removeResourceBundle;
  18686. i18n.loadNamespace = loadNamespace;
  18687. i18n.loadNamespaces = loadNamespaces;
  18688. i18n.setDefaultNamespace = setDefaultNamespace;
  18689. i18n.t = translate;
  18690. i18n.translate = translate;
  18691. i18n.exists = exists;
  18692. i18n.detectLanguage = f.detectLanguage;
  18693. i18n.pluralExtensions = pluralExtensions;
  18694. i18n.sync = sync;
  18695. i18n.functions = f;
  18696. i18n.lng = lng;
  18697. i18n.addPostProcessor = addPostProcessor;
  18698. i18n.options = o;
  18699. })();
  18700. },{"jquery":"jquery"}],64:[function(require,module,exports){
  18701. // Top level file is just a mixin of submodules & constants
  18702. 'use strict';
  18703. var assign = require('./lib/utils/common').assign;
  18704. var deflate = require('./lib/deflate');
  18705. var inflate = require('./lib/inflate');
  18706. var constants = require('./lib/zlib/constants');
  18707. var pako = {};
  18708. assign(pako, deflate, inflate, constants);
  18709. module.exports = pako;
  18710. },{"./lib/deflate":65,"./lib/inflate":66,"./lib/utils/common":67,"./lib/zlib/constants":70}],65:[function(require,module,exports){
  18711. 'use strict';
  18712. var zlib_deflate = require('./zlib/deflate.js');
  18713. var utils = require('./utils/common');
  18714. var strings = require('./utils/strings');
  18715. var msg = require('./zlib/messages');
  18716. var zstream = require('./zlib/zstream');
  18717. var toString = Object.prototype.toString;
  18718. /* Public constants ==========================================================*/
  18719. /* ===========================================================================*/
  18720. var Z_NO_FLUSH = 0;
  18721. var Z_FINISH = 4;
  18722. var Z_OK = 0;
  18723. var Z_STREAM_END = 1;
  18724. var Z_DEFAULT_COMPRESSION = -1;
  18725. var Z_DEFAULT_STRATEGY = 0;
  18726. var Z_DEFLATED = 8;
  18727. /* ===========================================================================*/
  18728. /**
  18729. * class Deflate
  18730. *
  18731. * Generic JS-style wrapper for zlib calls. If you don't need
  18732. * streaming behaviour - use more simple functions: [[deflate]],
  18733. * [[deflateRaw]] and [[gzip]].
  18734. **/
  18735. /* internal
  18736. * Deflate.chunks -> Array
  18737. *
  18738. * Chunks of output data, if [[Deflate#onData]] not overriden.
  18739. **/
  18740. /**
  18741. * Deflate.result -> Uint8Array|Array
  18742. *
  18743. * Compressed result, generated by default [[Deflate#onData]]
  18744. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  18745. * (call [[Deflate#push]] with `Z_FINISH` / `true` param).
  18746. **/
  18747. /**
  18748. * Deflate.err -> Number
  18749. *
  18750. * Error code after deflate finished. 0 (Z_OK) on success.
  18751. * You will not need it in real life, because deflate errors
  18752. * are possible only on wrong options or bad `onData` / `onEnd`
  18753. * custom handlers.
  18754. **/
  18755. /**
  18756. * Deflate.msg -> String
  18757. *
  18758. * Error message, if [[Deflate.err]] != 0
  18759. **/
  18760. /**
  18761. * new Deflate(options)
  18762. * - options (Object): zlib deflate options.
  18763. *
  18764. * Creates new deflator instance with specified params. Throws exception
  18765. * on bad params. Supported options:
  18766. *
  18767. * - `level`
  18768. * - `windowBits`
  18769. * - `memLevel`
  18770. * - `strategy`
  18771. *
  18772. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  18773. * for more information on these.
  18774. *
  18775. * Additional options, for internal needs:
  18776. *
  18777. * - `chunkSize` - size of generated data chunks (16K by default)
  18778. * - `raw` (Boolean) - do raw deflate
  18779. * - `gzip` (Boolean) - create gzip wrapper
  18780. * - `to` (String) - if equal to 'string', then result will be "binary string"
  18781. * (each char code [0..255])
  18782. * - `header` (Object) - custom header for gzip
  18783. * - `text` (Boolean) - true if compressed data believed to be text
  18784. * - `time` (Number) - modification time, unix timestamp
  18785. * - `os` (Number) - operation system code
  18786. * - `extra` (Array) - array of bytes with extra data (max 65536)
  18787. * - `name` (String) - file name (binary string)
  18788. * - `comment` (String) - comment (binary string)
  18789. * - `hcrc` (Boolean) - true if header crc should be added
  18790. *
  18791. * ##### Example:
  18792. *
  18793. * ```javascript
  18794. * var pako = require('pako')
  18795. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  18796. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  18797. *
  18798. * var deflate = new pako.Deflate({ level: 3});
  18799. *
  18800. * deflate.push(chunk1, false);
  18801. * deflate.push(chunk2, true); // true -> last chunk
  18802. *
  18803. * if (deflate.err) { throw new Error(deflate.err); }
  18804. *
  18805. * console.log(deflate.result);
  18806. * ```
  18807. **/
  18808. var Deflate = function(options) {
  18809. this.options = utils.assign({
  18810. level: Z_DEFAULT_COMPRESSION,
  18811. method: Z_DEFLATED,
  18812. chunkSize: 16384,
  18813. windowBits: 15,
  18814. memLevel: 8,
  18815. strategy: Z_DEFAULT_STRATEGY,
  18816. to: ''
  18817. }, options || {});
  18818. var opt = this.options;
  18819. if (opt.raw && (opt.windowBits > 0)) {
  18820. opt.windowBits = -opt.windowBits;
  18821. }
  18822. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  18823. opt.windowBits += 16;
  18824. }
  18825. this.err = 0; // error code, if happens (0 = Z_OK)
  18826. this.msg = ''; // error message
  18827. this.ended = false; // used to avoid multiple onEnd() calls
  18828. this.chunks = []; // chunks of compressed data
  18829. this.strm = new zstream();
  18830. this.strm.avail_out = 0;
  18831. var status = zlib_deflate.deflateInit2(
  18832. this.strm,
  18833. opt.level,
  18834. opt.method,
  18835. opt.windowBits,
  18836. opt.memLevel,
  18837. opt.strategy
  18838. );
  18839. if (status !== Z_OK) {
  18840. throw new Error(msg[status]);
  18841. }
  18842. if (opt.header) {
  18843. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  18844. }
  18845. };
  18846. /**
  18847. * Deflate#push(data[, mode]) -> Boolean
  18848. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  18849. * converted to utf8 byte sequence.
  18850. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  18851. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  18852. *
  18853. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  18854. * new compressed chunks. Returns `true` on success. The last data block must have
  18855. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  18856. * [[Deflate#onEnd]].
  18857. *
  18858. * On fail call [[Deflate#onEnd]] with error code and return false.
  18859. *
  18860. * We strongly recommend to use `Uint8Array` on input for best speed (output
  18861. * array format is detected automatically). Also, don't skip last param and always
  18862. * use the same type in your code (boolean or number). That will improve JS speed.
  18863. *
  18864. * For regular `Array`-s make sure all elements are [0..255].
  18865. *
  18866. * ##### Example
  18867. *
  18868. * ```javascript
  18869. * push(chunk, false); // push one of data chunks
  18870. * ...
  18871. * push(chunk, true); // push last chunk
  18872. * ```
  18873. **/
  18874. Deflate.prototype.push = function(data, mode) {
  18875. var strm = this.strm;
  18876. var chunkSize = this.options.chunkSize;
  18877. var status, _mode;
  18878. if (this.ended) { return false; }
  18879. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  18880. // Convert data if needed
  18881. if (typeof data === 'string') {
  18882. // If we need to compress text, change encoding to utf8.
  18883. strm.input = strings.string2buf(data);
  18884. } else if (toString.call(data) === '[object ArrayBuffer]') {
  18885. strm.input = new Uint8Array(data);
  18886. } else {
  18887. strm.input = data;
  18888. }
  18889. strm.next_in = 0;
  18890. strm.avail_in = strm.input.length;
  18891. do {
  18892. if (strm.avail_out === 0) {
  18893. strm.output = new utils.Buf8(chunkSize);
  18894. strm.next_out = 0;
  18895. strm.avail_out = chunkSize;
  18896. }
  18897. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  18898. if (status !== Z_STREAM_END && status !== Z_OK) {
  18899. this.onEnd(status);
  18900. this.ended = true;
  18901. return false;
  18902. }
  18903. if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) {
  18904. if (this.options.to === 'string') {
  18905. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  18906. } else {
  18907. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  18908. }
  18909. }
  18910. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  18911. // Finalize on the last chunk.
  18912. if (_mode === Z_FINISH) {
  18913. status = zlib_deflate.deflateEnd(this.strm);
  18914. this.onEnd(status);
  18915. this.ended = true;
  18916. return status === Z_OK;
  18917. }
  18918. return true;
  18919. };
  18920. /**
  18921. * Deflate#onData(chunk) -> Void
  18922. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  18923. * on js engine support. When string output requested, each chunk
  18924. * will be string.
  18925. *
  18926. * By default, stores data blocks in `chunks[]` property and glue
  18927. * those in `onEnd`. Override this handler, if you need another behaviour.
  18928. **/
  18929. Deflate.prototype.onData = function(chunk) {
  18930. this.chunks.push(chunk);
  18931. };
  18932. /**
  18933. * Deflate#onEnd(status) -> Void
  18934. * - status (Number): deflate status. 0 (Z_OK) on success,
  18935. * other if not.
  18936. *
  18937. * Called once after you tell deflate that input stream complete
  18938. * or error happenned. By default - join collected chunks,
  18939. * free memory and fill `results` / `err` properties.
  18940. **/
  18941. Deflate.prototype.onEnd = function(status) {
  18942. // On success - join
  18943. if (status === Z_OK) {
  18944. if (this.options.to === 'string') {
  18945. this.result = this.chunks.join('');
  18946. } else {
  18947. this.result = utils.flattenChunks(this.chunks);
  18948. }
  18949. }
  18950. this.chunks = [];
  18951. this.err = status;
  18952. this.msg = this.strm.msg;
  18953. };
  18954. /**
  18955. * deflate(data[, options]) -> Uint8Array|Array|String
  18956. * - data (Uint8Array|Array|String): input data to compress.
  18957. * - options (Object): zlib deflate options.
  18958. *
  18959. * Compress `data` with deflate alrorythm and `options`.
  18960. *
  18961. * Supported options are:
  18962. *
  18963. * - level
  18964. * - windowBits
  18965. * - memLevel
  18966. * - strategy
  18967. *
  18968. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  18969. * for more information on these.
  18970. *
  18971. * Sugar (options):
  18972. *
  18973. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  18974. * negative windowBits implicitly.
  18975. * - `to` (String) - if equal to 'string', then result will be "binary string"
  18976. * (each char code [0..255])
  18977. *
  18978. * ##### Example:
  18979. *
  18980. * ```javascript
  18981. * var pako = require('pako')
  18982. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  18983. *
  18984. * console.log(pako.deflate(data));
  18985. * ```
  18986. **/
  18987. function deflate(input, options) {
  18988. var deflator = new Deflate(options);
  18989. deflator.push(input, true);
  18990. // That will never happens, if you don't cheat with options :)
  18991. if (deflator.err) { throw deflator.msg; }
  18992. return deflator.result;
  18993. }
  18994. /**
  18995. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  18996. * - data (Uint8Array|Array|String): input data to compress.
  18997. * - options (Object): zlib deflate options.
  18998. *
  18999. * The same as [[deflate]], but creates raw data, without wrapper
  19000. * (header and adler32 crc).
  19001. **/
  19002. function deflateRaw(input, options) {
  19003. options = options || {};
  19004. options.raw = true;
  19005. return deflate(input, options);
  19006. }
  19007. /**
  19008. * gzip(data[, options]) -> Uint8Array|Array|String
  19009. * - data (Uint8Array|Array|String): input data to compress.
  19010. * - options (Object): zlib deflate options.
  19011. *
  19012. * The same as [[deflate]], but create gzip wrapper instead of
  19013. * deflate one.
  19014. **/
  19015. function gzip(input, options) {
  19016. options = options || {};
  19017. options.gzip = true;
  19018. return deflate(input, options);
  19019. }
  19020. exports.Deflate = Deflate;
  19021. exports.deflate = deflate;
  19022. exports.deflateRaw = deflateRaw;
  19023. exports.gzip = gzip;
  19024. },{"./utils/common":67,"./utils/strings":68,"./zlib/deflate.js":72,"./zlib/messages":77,"./zlib/zstream":79}],66:[function(require,module,exports){
  19025. 'use strict';
  19026. var zlib_inflate = require('./zlib/inflate.js');
  19027. var utils = require('./utils/common');
  19028. var strings = require('./utils/strings');
  19029. var c = require('./zlib/constants');
  19030. var msg = require('./zlib/messages');
  19031. var zstream = require('./zlib/zstream');
  19032. var gzheader = require('./zlib/gzheader');
  19033. var toString = Object.prototype.toString;
  19034. /**
  19035. * class Inflate
  19036. *
  19037. * Generic JS-style wrapper for zlib calls. If you don't need
  19038. * streaming behaviour - use more simple functions: [[inflate]]
  19039. * and [[inflateRaw]].
  19040. **/
  19041. /* internal
  19042. * inflate.chunks -> Array
  19043. *
  19044. * Chunks of output data, if [[Inflate#onData]] not overriden.
  19045. **/
  19046. /**
  19047. * Inflate.result -> Uint8Array|Array|String
  19048. *
  19049. * Uncompressed result, generated by default [[Inflate#onData]]
  19050. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  19051. * (call [[Inflate#push]] with `Z_FINISH` / `true` param).
  19052. **/
  19053. /**
  19054. * Inflate.err -> Number
  19055. *
  19056. * Error code after inflate finished. 0 (Z_OK) on success.
  19057. * Should be checked if broken data possible.
  19058. **/
  19059. /**
  19060. * Inflate.msg -> String
  19061. *
  19062. * Error message, if [[Inflate.err]] != 0
  19063. **/
  19064. /**
  19065. * new Inflate(options)
  19066. * - options (Object): zlib inflate options.
  19067. *
  19068. * Creates new inflator instance with specified params. Throws exception
  19069. * on bad params. Supported options:
  19070. *
  19071. * - `windowBits`
  19072. *
  19073. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19074. * for more information on these.
  19075. *
  19076. * Additional options, for internal needs:
  19077. *
  19078. * - `chunkSize` - size of generated data chunks (16K by default)
  19079. * - `raw` (Boolean) - do raw inflate
  19080. * - `to` (String) - if equal to 'string', then result will be converted
  19081. * from utf8 to utf16 (javascript) string. When string output requested,
  19082. * chunk length can differ from `chunkSize`, depending on content.
  19083. *
  19084. * By default, when no options set, autodetect deflate/gzip data format via
  19085. * wrapper header.
  19086. *
  19087. * ##### Example:
  19088. *
  19089. * ```javascript
  19090. * var pako = require('pako')
  19091. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  19092. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  19093. *
  19094. * var inflate = new pako.Inflate({ level: 3});
  19095. *
  19096. * inflate.push(chunk1, false);
  19097. * inflate.push(chunk2, true); // true -> last chunk
  19098. *
  19099. * if (inflate.err) { throw new Error(inflate.err); }
  19100. *
  19101. * console.log(inflate.result);
  19102. * ```
  19103. **/
  19104. var Inflate = function(options) {
  19105. this.options = utils.assign({
  19106. chunkSize: 16384,
  19107. windowBits: 0,
  19108. to: ''
  19109. }, options || {});
  19110. var opt = this.options;
  19111. // Force window size for `raw` data, if not set directly,
  19112. // because we have no header for autodetect.
  19113. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  19114. opt.windowBits = -opt.windowBits;
  19115. if (opt.windowBits === 0) { opt.windowBits = -15; }
  19116. }
  19117. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  19118. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  19119. !(options && options.windowBits)) {
  19120. opt.windowBits += 32;
  19121. }
  19122. // Gzip header has no info about windows size, we can do autodetect only
  19123. // for deflate. So, if window size not set, force it to max when gzip possible
  19124. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  19125. // bit 3 (16) -> gzipped data
  19126. // bit 4 (32) -> autodetect gzip/deflate
  19127. if ((opt.windowBits & 15) === 0) {
  19128. opt.windowBits |= 15;
  19129. }
  19130. }
  19131. this.err = 0; // error code, if happens (0 = Z_OK)
  19132. this.msg = ''; // error message
  19133. this.ended = false; // used to avoid multiple onEnd() calls
  19134. this.chunks = []; // chunks of compressed data
  19135. this.strm = new zstream();
  19136. this.strm.avail_out = 0;
  19137. var status = zlib_inflate.inflateInit2(
  19138. this.strm,
  19139. opt.windowBits
  19140. );
  19141. if (status !== c.Z_OK) {
  19142. throw new Error(msg[status]);
  19143. }
  19144. this.header = new gzheader();
  19145. zlib_inflate.inflateGetHeader(this.strm, this.header);
  19146. };
  19147. /**
  19148. * Inflate#push(data[, mode]) -> Boolean
  19149. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  19150. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  19151. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  19152. *
  19153. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  19154. * new output chunks. Returns `true` on success. The last data block must have
  19155. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  19156. * [[Inflate#onEnd]].
  19157. *
  19158. * On fail call [[Inflate#onEnd]] with error code and return false.
  19159. *
  19160. * We strongly recommend to use `Uint8Array` on input for best speed (output
  19161. * format is detected automatically). Also, don't skip last param and always
  19162. * use the same type in your code (boolean or number). That will improve JS speed.
  19163. *
  19164. * For regular `Array`-s make sure all elements are [0..255].
  19165. *
  19166. * ##### Example
  19167. *
  19168. * ```javascript
  19169. * push(chunk, false); // push one of data chunks
  19170. * ...
  19171. * push(chunk, true); // push last chunk
  19172. * ```
  19173. **/
  19174. Inflate.prototype.push = function(data, mode) {
  19175. var strm = this.strm;
  19176. var chunkSize = this.options.chunkSize;
  19177. var status, _mode;
  19178. var next_out_utf8, tail, utf8str;
  19179. if (this.ended) { return false; }
  19180. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  19181. // Convert data if needed
  19182. if (typeof data === 'string') {
  19183. // Only binary strings can be decompressed on practice
  19184. strm.input = strings.binstring2buf(data);
  19185. } else if (toString.call(data) === '[object ArrayBuffer]') {
  19186. strm.input = new Uint8Array(data);
  19187. } else {
  19188. strm.input = data;
  19189. }
  19190. strm.next_in = 0;
  19191. strm.avail_in = strm.input.length;
  19192. do {
  19193. if (strm.avail_out === 0) {
  19194. strm.output = new utils.Buf8(chunkSize);
  19195. strm.next_out = 0;
  19196. strm.avail_out = chunkSize;
  19197. }
  19198. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  19199. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  19200. this.onEnd(status);
  19201. this.ended = true;
  19202. return false;
  19203. }
  19204. if (strm.next_out) {
  19205. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) {
  19206. if (this.options.to === 'string') {
  19207. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  19208. tail = strm.next_out - next_out_utf8;
  19209. utf8str = strings.buf2string(strm.output, next_out_utf8);
  19210. // move tail
  19211. strm.next_out = tail;
  19212. strm.avail_out = chunkSize - tail;
  19213. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  19214. this.onData(utf8str);
  19215. } else {
  19216. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  19217. }
  19218. }
  19219. }
  19220. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  19221. if (status === c.Z_STREAM_END) {
  19222. _mode = c.Z_FINISH;
  19223. }
  19224. // Finalize on the last chunk.
  19225. if (_mode === c.Z_FINISH) {
  19226. status = zlib_inflate.inflateEnd(this.strm);
  19227. this.onEnd(status);
  19228. this.ended = true;
  19229. return status === c.Z_OK;
  19230. }
  19231. return true;
  19232. };
  19233. /**
  19234. * Inflate#onData(chunk) -> Void
  19235. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  19236. * on js engine support. When string output requested, each chunk
  19237. * will be string.
  19238. *
  19239. * By default, stores data blocks in `chunks[]` property and glue
  19240. * those in `onEnd`. Override this handler, if you need another behaviour.
  19241. **/
  19242. Inflate.prototype.onData = function(chunk) {
  19243. this.chunks.push(chunk);
  19244. };
  19245. /**
  19246. * Inflate#onEnd(status) -> Void
  19247. * - status (Number): inflate status. 0 (Z_OK) on success,
  19248. * other if not.
  19249. *
  19250. * Called once after you tell inflate that input stream complete
  19251. * or error happenned. By default - join collected chunks,
  19252. * free memory and fill `results` / `err` properties.
  19253. **/
  19254. Inflate.prototype.onEnd = function(status) {
  19255. // On success - join
  19256. if (status === c.Z_OK) {
  19257. if (this.options.to === 'string') {
  19258. // Glue & convert here, until we teach pako to send
  19259. // utf8 alligned strings to onData
  19260. this.result = this.chunks.join('');
  19261. } else {
  19262. this.result = utils.flattenChunks(this.chunks);
  19263. }
  19264. }
  19265. this.chunks = [];
  19266. this.err = status;
  19267. this.msg = this.strm.msg;
  19268. };
  19269. /**
  19270. * inflate(data[, options]) -> Uint8Array|Array|String
  19271. * - data (Uint8Array|Array|String): input data to decompress.
  19272. * - options (Object): zlib inflate options.
  19273. *
  19274. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  19275. * format via wrapper header by default. That's why we don't provide
  19276. * separate `ungzip` method.
  19277. *
  19278. * Supported options are:
  19279. *
  19280. * - windowBits
  19281. *
  19282. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19283. * for more information.
  19284. *
  19285. * Sugar (options):
  19286. *
  19287. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  19288. * negative windowBits implicitly.
  19289. * - `to` (String) - if equal to 'string', then result will be converted
  19290. * from utf8 to utf16 (javascript) string. When string output requested,
  19291. * chunk length can differ from `chunkSize`, depending on content.
  19292. *
  19293. *
  19294. * ##### Example:
  19295. *
  19296. * ```javascript
  19297. * var pako = require('pako')
  19298. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  19299. * , output;
  19300. *
  19301. * try {
  19302. * output = pako.inflate(input);
  19303. * } catch (err)
  19304. * console.log(err);
  19305. * }
  19306. * ```
  19307. **/
  19308. function inflate(input, options) {
  19309. var inflator = new Inflate(options);
  19310. inflator.push(input, true);
  19311. // That will never happens, if you don't cheat with options :)
  19312. if (inflator.err) { throw inflator.msg; }
  19313. return inflator.result;
  19314. }
  19315. /**
  19316. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  19317. * - data (Uint8Array|Array|String): input data to decompress.
  19318. * - options (Object): zlib inflate options.
  19319. *
  19320. * The same as [[inflate]], but creates raw data, without wrapper
  19321. * (header and adler32 crc).
  19322. **/
  19323. function inflateRaw(input, options) {
  19324. options = options || {};
  19325. options.raw = true;
  19326. return inflate(input, options);
  19327. }
  19328. /**
  19329. * ungzip(data[, options]) -> Uint8Array|Array|String
  19330. * - data (Uint8Array|Array|String): input data to decompress.
  19331. * - options (Object): zlib inflate options.
  19332. *
  19333. * Just shortcut to [[inflate]], because it autodetects format
  19334. * by header.content. Done for convenience.
  19335. **/
  19336. exports.Inflate = Inflate;
  19337. exports.inflate = inflate;
  19338. exports.inflateRaw = inflateRaw;
  19339. exports.ungzip = inflate;
  19340. },{"./utils/common":67,"./utils/strings":68,"./zlib/constants":70,"./zlib/gzheader":73,"./zlib/inflate.js":75,"./zlib/messages":77,"./zlib/zstream":79}],67:[function(require,module,exports){
  19341. 'use strict';
  19342. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  19343. (typeof Uint16Array !== 'undefined') &&
  19344. (typeof Int32Array !== 'undefined');
  19345. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  19346. var sources = Array.prototype.slice.call(arguments, 1);
  19347. while (sources.length) {
  19348. var source = sources.shift();
  19349. if (!source) { continue; }
  19350. if (typeof(source) !== 'object') {
  19351. throw new TypeError(source + 'must be non-object');
  19352. }
  19353. for (var p in source) {
  19354. if (source.hasOwnProperty(p)) {
  19355. obj[p] = source[p];
  19356. }
  19357. }
  19358. }
  19359. return obj;
  19360. };
  19361. // reduce buffer size, avoiding mem copy
  19362. exports.shrinkBuf = function (buf, size) {
  19363. if (buf.length === size) { return buf; }
  19364. if (buf.subarray) { return buf.subarray(0, size); }
  19365. buf.length = size;
  19366. return buf;
  19367. };
  19368. var fnTyped = {
  19369. arraySet: function (dest, src, src_offs, len, dest_offs) {
  19370. if (src.subarray && dest.subarray) {
  19371. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  19372. return;
  19373. }
  19374. // Fallback to ordinary array
  19375. for(var i=0; i<len; i++) {
  19376. dest[dest_offs + i] = src[src_offs + i];
  19377. }
  19378. },
  19379. // Join array of chunks to single array.
  19380. flattenChunks: function(chunks) {
  19381. var i, l, len, pos, chunk, result;
  19382. // calculate data length
  19383. len = 0;
  19384. for (i=0, l=chunks.length; i<l; i++) {
  19385. len += chunks[i].length;
  19386. }
  19387. // join chunks
  19388. result = new Uint8Array(len);
  19389. pos = 0;
  19390. for (i=0, l=chunks.length; i<l; i++) {
  19391. chunk = chunks[i];
  19392. result.set(chunk, pos);
  19393. pos += chunk.length;
  19394. }
  19395. return result;
  19396. }
  19397. };
  19398. var fnUntyped = {
  19399. arraySet: function (dest, src, src_offs, len, dest_offs) {
  19400. for(var i=0; i<len; i++) {
  19401. dest[dest_offs + i] = src[src_offs + i];
  19402. }
  19403. },
  19404. // Join array of chunks to single array.
  19405. flattenChunks: function(chunks) {
  19406. return [].concat.apply([], chunks);
  19407. }
  19408. };
  19409. // Enable/Disable typed arrays use, for testing
  19410. //
  19411. exports.setTyped = function (on) {
  19412. if (on) {
  19413. exports.Buf8 = Uint8Array;
  19414. exports.Buf16 = Uint16Array;
  19415. exports.Buf32 = Int32Array;
  19416. exports.assign(exports, fnTyped);
  19417. } else {
  19418. exports.Buf8 = Array;
  19419. exports.Buf16 = Array;
  19420. exports.Buf32 = Array;
  19421. exports.assign(exports, fnUntyped);
  19422. }
  19423. };
  19424. exports.setTyped(TYPED_OK);
  19425. },{}],68:[function(require,module,exports){
  19426. // String encode/decode helpers
  19427. 'use strict';
  19428. var utils = require('./common');
  19429. // Quick check if we can use fast array to bin string conversion
  19430. //
  19431. // - apply(Array) can fail on Android 2.2
  19432. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  19433. //
  19434. var STR_APPLY_OK = true;
  19435. var STR_APPLY_UIA_OK = true;
  19436. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  19437. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  19438. // Table with utf8 lengths (calculated by first byte of sequence)
  19439. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  19440. // because max possible codepoint is 0x10ffff
  19441. var _utf8len = new utils.Buf8(256);
  19442. for (var i=0; i<256; i++) {
  19443. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  19444. }
  19445. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  19446. // convert string to array (typed, when possible)
  19447. exports.string2buf = function (str) {
  19448. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  19449. // count binary size
  19450. for (m_pos = 0; m_pos < str_len; m_pos++) {
  19451. c = str.charCodeAt(m_pos);
  19452. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  19453. c2 = str.charCodeAt(m_pos+1);
  19454. if ((c2 & 0xfc00) === 0xdc00) {
  19455. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  19456. m_pos++;
  19457. }
  19458. }
  19459. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  19460. }
  19461. // allocate buffer
  19462. buf = new utils.Buf8(buf_len);
  19463. // convert
  19464. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  19465. c = str.charCodeAt(m_pos);
  19466. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  19467. c2 = str.charCodeAt(m_pos+1);
  19468. if ((c2 & 0xfc00) === 0xdc00) {
  19469. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  19470. m_pos++;
  19471. }
  19472. }
  19473. if (c < 0x80) {
  19474. /* one byte */
  19475. buf[i++] = c;
  19476. } else if (c < 0x800) {
  19477. /* two bytes */
  19478. buf[i++] = 0xC0 | (c >>> 6);
  19479. buf[i++] = 0x80 | (c & 0x3f);
  19480. } else if (c < 0x10000) {
  19481. /* three bytes */
  19482. buf[i++] = 0xE0 | (c >>> 12);
  19483. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  19484. buf[i++] = 0x80 | (c & 0x3f);
  19485. } else {
  19486. /* four bytes */
  19487. buf[i++] = 0xf0 | (c >>> 18);
  19488. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  19489. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  19490. buf[i++] = 0x80 | (c & 0x3f);
  19491. }
  19492. }
  19493. return buf;
  19494. };
  19495. // Helper (used in 2 places)
  19496. function buf2binstring(buf, len) {
  19497. // use fallback for big arrays to avoid stack overflow
  19498. if (len < 65537) {
  19499. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  19500. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  19501. }
  19502. }
  19503. var result = '';
  19504. for(var i=0; i < len; i++) {
  19505. result += String.fromCharCode(buf[i]);
  19506. }
  19507. return result;
  19508. }
  19509. // Convert byte array to binary string
  19510. exports.buf2binstring = function(buf) {
  19511. return buf2binstring(buf, buf.length);
  19512. };
  19513. // Convert binary string (typed, when possible)
  19514. exports.binstring2buf = function(str) {
  19515. var buf = new utils.Buf8(str.length);
  19516. for(var i=0, len=buf.length; i < len; i++) {
  19517. buf[i] = str.charCodeAt(i);
  19518. }
  19519. return buf;
  19520. };
  19521. // convert array to string
  19522. exports.buf2string = function (buf, max) {
  19523. var i, out, c, c_len;
  19524. var len = max || buf.length;
  19525. // Reserve max possible length (2 words per char)
  19526. // NB: by unknown reasons, Array is significantly faster for
  19527. // String.fromCharCode.apply than Uint16Array.
  19528. var utf16buf = new Array(len*2);
  19529. for (out=0, i=0; i<len;) {
  19530. c = buf[i++];
  19531. // quick process ascii
  19532. if (c < 0x80) { utf16buf[out++] = c; continue; }
  19533. c_len = _utf8len[c];
  19534. // skip 5 & 6 byte codes
  19535. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  19536. // apply mask on first byte
  19537. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  19538. // join the rest
  19539. while (c_len > 1 && i < len) {
  19540. c = (c << 6) | (buf[i++] & 0x3f);
  19541. c_len--;
  19542. }
  19543. // terminated by end of string?
  19544. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  19545. if (c < 0x10000) {
  19546. utf16buf[out++] = c;
  19547. } else {
  19548. c -= 0x10000;
  19549. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  19550. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  19551. }
  19552. }
  19553. return buf2binstring(utf16buf, out);
  19554. };
  19555. // Calculate max possible position in utf8 buffer,
  19556. // that will not break sequence. If that's not possible
  19557. // - (very small limits) return max size as is.
  19558. //
  19559. // buf[] - utf8 bytes array
  19560. // max - length limit (mandatory);
  19561. exports.utf8border = function(buf, max) {
  19562. var pos;
  19563. max = max || buf.length;
  19564. if (max > buf.length) { max = buf.length; }
  19565. // go back from last position, until start of sequence found
  19566. pos = max-1;
  19567. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  19568. // Fuckup - very small and broken sequence,
  19569. // return max, because we should return something anyway.
  19570. if (pos < 0) { return max; }
  19571. // If we came to start of buffer - that means vuffer is too small,
  19572. // return max too.
  19573. if (pos === 0) { return max; }
  19574. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  19575. };
  19576. },{"./common":67}],69:[function(require,module,exports){
  19577. 'use strict';
  19578. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  19579. // It doesn't worth to make additional optimizationa as in original.
  19580. // Small size is preferable.
  19581. function adler32(adler, buf, len, pos) {
  19582. var s1 = (adler & 0xffff) |0
  19583. , s2 = ((adler >>> 16) & 0xffff) |0
  19584. , n = 0;
  19585. while (len !== 0) {
  19586. // Set limit ~ twice less than 5552, to keep
  19587. // s2 in 31-bits, because we force signed ints.
  19588. // in other case %= will fail.
  19589. n = len > 2000 ? 2000 : len;
  19590. len -= n;
  19591. do {
  19592. s1 = (s1 + buf[pos++]) |0;
  19593. s2 = (s2 + s1) |0;
  19594. } while (--n);
  19595. s1 %= 65521;
  19596. s2 %= 65521;
  19597. }
  19598. return (s1 | (s2 << 16)) |0;
  19599. }
  19600. module.exports = adler32;
  19601. },{}],70:[function(require,module,exports){
  19602. module.exports = {
  19603. /* Allowed flush values; see deflate() and inflate() below for details */
  19604. Z_NO_FLUSH: 0,
  19605. Z_PARTIAL_FLUSH: 1,
  19606. Z_SYNC_FLUSH: 2,
  19607. Z_FULL_FLUSH: 3,
  19608. Z_FINISH: 4,
  19609. Z_BLOCK: 5,
  19610. Z_TREES: 6,
  19611. /* Return codes for the compression/decompression functions. Negative values
  19612. * are errors, positive values are used for special but normal events.
  19613. */
  19614. Z_OK: 0,
  19615. Z_STREAM_END: 1,
  19616. Z_NEED_DICT: 2,
  19617. Z_ERRNO: -1,
  19618. Z_STREAM_ERROR: -2,
  19619. Z_DATA_ERROR: -3,
  19620. //Z_MEM_ERROR: -4,
  19621. Z_BUF_ERROR: -5,
  19622. //Z_VERSION_ERROR: -6,
  19623. /* compression levels */
  19624. Z_NO_COMPRESSION: 0,
  19625. Z_BEST_SPEED: 1,
  19626. Z_BEST_COMPRESSION: 9,
  19627. Z_DEFAULT_COMPRESSION: -1,
  19628. Z_FILTERED: 1,
  19629. Z_HUFFMAN_ONLY: 2,
  19630. Z_RLE: 3,
  19631. Z_FIXED: 4,
  19632. Z_DEFAULT_STRATEGY: 0,
  19633. /* Possible values of the data_type field (though see inflate()) */
  19634. Z_BINARY: 0,
  19635. Z_TEXT: 1,
  19636. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  19637. Z_UNKNOWN: 2,
  19638. /* The deflate compression method */
  19639. Z_DEFLATED: 8
  19640. //Z_NULL: null // Use -1 or null inline, depending on var type
  19641. };
  19642. },{}],71:[function(require,module,exports){
  19643. 'use strict';
  19644. // Note: we can't get significant speed boost here.
  19645. // So write code to minimize size - no pregenerated tables
  19646. // and array tools dependencies.
  19647. // Use ordinary array, since untyped makes no boost here
  19648. function makeTable() {
  19649. var c, table = [];
  19650. for(var n =0; n < 256; n++){
  19651. c = n;
  19652. for(var k =0; k < 8; k++){
  19653. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  19654. }
  19655. table[n] = c;
  19656. }
  19657. return table;
  19658. }
  19659. // Create table on load. Just 255 signed longs. Not a problem.
  19660. var crcTable = makeTable();
  19661. function crc32(crc, buf, len, pos) {
  19662. var t = crcTable
  19663. , end = pos + len;
  19664. crc = crc ^ (-1);
  19665. for (var i = pos; i < end; i++ ) {
  19666. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  19667. }
  19668. return (crc ^ (-1)); // >>> 0;
  19669. }
  19670. module.exports = crc32;
  19671. },{}],72:[function(require,module,exports){
  19672. 'use strict';
  19673. var utils = require('../utils/common');
  19674. var trees = require('./trees');
  19675. var adler32 = require('./adler32');
  19676. var crc32 = require('./crc32');
  19677. var msg = require('./messages');
  19678. /* Public constants ==========================================================*/
  19679. /* ===========================================================================*/
  19680. /* Allowed flush values; see deflate() and inflate() below for details */
  19681. var Z_NO_FLUSH = 0;
  19682. var Z_PARTIAL_FLUSH = 1;
  19683. //var Z_SYNC_FLUSH = 2;
  19684. var Z_FULL_FLUSH = 3;
  19685. var Z_FINISH = 4;
  19686. var Z_BLOCK = 5;
  19687. //var Z_TREES = 6;
  19688. /* Return codes for the compression/decompression functions. Negative values
  19689. * are errors, positive values are used for special but normal events.
  19690. */
  19691. var Z_OK = 0;
  19692. var Z_STREAM_END = 1;
  19693. //var Z_NEED_DICT = 2;
  19694. //var Z_ERRNO = -1;
  19695. var Z_STREAM_ERROR = -2;
  19696. var Z_DATA_ERROR = -3;
  19697. //var Z_MEM_ERROR = -4;
  19698. var Z_BUF_ERROR = -5;
  19699. //var Z_VERSION_ERROR = -6;
  19700. /* compression levels */
  19701. //var Z_NO_COMPRESSION = 0;
  19702. //var Z_BEST_SPEED = 1;
  19703. //var Z_BEST_COMPRESSION = 9;
  19704. var Z_DEFAULT_COMPRESSION = -1;
  19705. var Z_FILTERED = 1;
  19706. var Z_HUFFMAN_ONLY = 2;
  19707. var Z_RLE = 3;
  19708. var Z_FIXED = 4;
  19709. var Z_DEFAULT_STRATEGY = 0;
  19710. /* Possible values of the data_type field (though see inflate()) */
  19711. //var Z_BINARY = 0;
  19712. //var Z_TEXT = 1;
  19713. //var Z_ASCII = 1; // = Z_TEXT
  19714. var Z_UNKNOWN = 2;
  19715. /* The deflate compression method */
  19716. var Z_DEFLATED = 8;
  19717. /*============================================================================*/
  19718. var MAX_MEM_LEVEL = 9;
  19719. /* Maximum value for memLevel in deflateInit2 */
  19720. var MAX_WBITS = 15;
  19721. /* 32K LZ77 window */
  19722. var DEF_MEM_LEVEL = 8;
  19723. var LENGTH_CODES = 29;
  19724. /* number of length codes, not counting the special END_BLOCK code */
  19725. var LITERALS = 256;
  19726. /* number of literal bytes 0..255 */
  19727. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  19728. /* number of Literal or Length codes, including the END_BLOCK code */
  19729. var D_CODES = 30;
  19730. /* number of distance codes */
  19731. var BL_CODES = 19;
  19732. /* number of codes used to transfer the bit lengths */
  19733. var HEAP_SIZE = 2*L_CODES + 1;
  19734. /* maximum heap size */
  19735. var MAX_BITS = 15;
  19736. /* All codes must not exceed MAX_BITS bits */
  19737. var MIN_MATCH = 3;
  19738. var MAX_MATCH = 258;
  19739. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  19740. var PRESET_DICT = 0x20;
  19741. var INIT_STATE = 42;
  19742. var EXTRA_STATE = 69;
  19743. var NAME_STATE = 73;
  19744. var COMMENT_STATE = 91;
  19745. var HCRC_STATE = 103;
  19746. var BUSY_STATE = 113;
  19747. var FINISH_STATE = 666;
  19748. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  19749. var BS_BLOCK_DONE = 2; /* block flush performed */
  19750. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  19751. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  19752. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  19753. function err(strm, errorCode) {
  19754. strm.msg = msg[errorCode];
  19755. return errorCode;
  19756. }
  19757. function rank(f) {
  19758. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  19759. }
  19760. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  19761. /* =========================================================================
  19762. * Flush as much pending output as possible. All deflate() output goes
  19763. * through this function so some applications may wish to modify it
  19764. * to avoid allocating a large strm->output buffer and copying into it.
  19765. * (See also read_buf()).
  19766. */
  19767. function flush_pending(strm) {
  19768. var s = strm.state;
  19769. //_tr_flush_bits(s);
  19770. var len = s.pending;
  19771. if (len > strm.avail_out) {
  19772. len = strm.avail_out;
  19773. }
  19774. if (len === 0) { return; }
  19775. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  19776. strm.next_out += len;
  19777. s.pending_out += len;
  19778. strm.total_out += len;
  19779. strm.avail_out -= len;
  19780. s.pending -= len;
  19781. if (s.pending === 0) {
  19782. s.pending_out = 0;
  19783. }
  19784. }
  19785. function flush_block_only (s, last) {
  19786. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  19787. s.block_start = s.strstart;
  19788. flush_pending(s.strm);
  19789. }
  19790. function put_byte(s, b) {
  19791. s.pending_buf[s.pending++] = b;
  19792. }
  19793. /* =========================================================================
  19794. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  19795. * IN assertion: the stream state is correct and there is enough room in
  19796. * pending_buf.
  19797. */
  19798. function putShortMSB(s, b) {
  19799. // put_byte(s, (Byte)(b >> 8));
  19800. // put_byte(s, (Byte)(b & 0xff));
  19801. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  19802. s.pending_buf[s.pending++] = b & 0xff;
  19803. }
  19804. /* ===========================================================================
  19805. * Read a new buffer from the current input stream, update the adler32
  19806. * and total number of bytes read. All deflate() input goes through
  19807. * this function so some applications may wish to modify it to avoid
  19808. * allocating a large strm->input buffer and copying from it.
  19809. * (See also flush_pending()).
  19810. */
  19811. function read_buf(strm, buf, start, size) {
  19812. var len = strm.avail_in;
  19813. if (len > size) { len = size; }
  19814. if (len === 0) { return 0; }
  19815. strm.avail_in -= len;
  19816. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  19817. if (strm.state.wrap === 1) {
  19818. strm.adler = adler32(strm.adler, buf, len, start);
  19819. }
  19820. else if (strm.state.wrap === 2) {
  19821. strm.adler = crc32(strm.adler, buf, len, start);
  19822. }
  19823. strm.next_in += len;
  19824. strm.total_in += len;
  19825. return len;
  19826. }
  19827. /* ===========================================================================
  19828. * Set match_start to the longest match starting at the given string and
  19829. * return its length. Matches shorter or equal to prev_length are discarded,
  19830. * in which case the result is equal to prev_length and match_start is
  19831. * garbage.
  19832. * IN assertions: cur_match is the head of the hash chain for the current
  19833. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  19834. * OUT assertion: the match length is not greater than s->lookahead.
  19835. */
  19836. function longest_match(s, cur_match) {
  19837. var chain_length = s.max_chain_length; /* max hash chain length */
  19838. var scan = s.strstart; /* current string */
  19839. var match; /* matched string */
  19840. var len; /* length of current match */
  19841. var best_len = s.prev_length; /* best match length so far */
  19842. var nice_match = s.nice_match; /* stop if match long enough */
  19843. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  19844. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  19845. var _win = s.window; // shortcut
  19846. var wmask = s.w_mask;
  19847. var prev = s.prev;
  19848. /* Stop when cur_match becomes <= limit. To simplify the code,
  19849. * we prevent matches with the string of window index 0.
  19850. */
  19851. var strend = s.strstart + MAX_MATCH;
  19852. var scan_end1 = _win[scan + best_len - 1];
  19853. var scan_end = _win[scan + best_len];
  19854. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  19855. * It is easy to get rid of this optimization if necessary.
  19856. */
  19857. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  19858. /* Do not waste too much time if we already have a good match: */
  19859. if (s.prev_length >= s.good_match) {
  19860. chain_length >>= 2;
  19861. }
  19862. /* Do not look for matches beyond the end of the input. This is necessary
  19863. * to make deflate deterministic.
  19864. */
  19865. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  19866. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  19867. do {
  19868. // Assert(cur_match < s->strstart, "no future");
  19869. match = cur_match;
  19870. /* Skip to next match if the match length cannot increase
  19871. * or if the match length is less than 2. Note that the checks below
  19872. * for insufficient lookahead only occur occasionally for performance
  19873. * reasons. Therefore uninitialized memory will be accessed, and
  19874. * conditional jumps will be made that depend on those values.
  19875. * However the length of the match is limited to the lookahead, so
  19876. * the output of deflate is not affected by the uninitialized values.
  19877. */
  19878. if (_win[match + best_len] !== scan_end ||
  19879. _win[match + best_len - 1] !== scan_end1 ||
  19880. _win[match] !== _win[scan] ||
  19881. _win[++match] !== _win[scan + 1]) {
  19882. continue;
  19883. }
  19884. /* The check at best_len-1 can be removed because it will be made
  19885. * again later. (This heuristic is not always a win.)
  19886. * It is not necessary to compare scan[2] and match[2] since they
  19887. * are always equal when the other bytes match, given that
  19888. * the hash keys are equal and that HASH_BITS >= 8.
  19889. */
  19890. scan += 2;
  19891. match++;
  19892. // Assert(*scan == *match, "match[2]?");
  19893. /* We check for insufficient lookahead only every 8th comparison;
  19894. * the 256th check will be made at strstart+258.
  19895. */
  19896. do {
  19897. /*jshint noempty:false*/
  19898. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  19899. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  19900. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  19901. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  19902. scan < strend);
  19903. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  19904. len = MAX_MATCH - (strend - scan);
  19905. scan = strend - MAX_MATCH;
  19906. if (len > best_len) {
  19907. s.match_start = cur_match;
  19908. best_len = len;
  19909. if (len >= nice_match) {
  19910. break;
  19911. }
  19912. scan_end1 = _win[scan + best_len - 1];
  19913. scan_end = _win[scan + best_len];
  19914. }
  19915. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  19916. if (best_len <= s.lookahead) {
  19917. return best_len;
  19918. }
  19919. return s.lookahead;
  19920. }
  19921. /* ===========================================================================
  19922. * Fill the window when the lookahead becomes insufficient.
  19923. * Updates strstart and lookahead.
  19924. *
  19925. * IN assertion: lookahead < MIN_LOOKAHEAD
  19926. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  19927. * At least one byte has been read, or avail_in == 0; reads are
  19928. * performed for at least two bytes (required for the zip translate_eol
  19929. * option -- not supported here).
  19930. */
  19931. function fill_window(s) {
  19932. var _w_size = s.w_size;
  19933. var p, n, m, more, str;
  19934. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  19935. do {
  19936. more = s.window_size - s.lookahead - s.strstart;
  19937. // JS ints have 32 bit, block below not needed
  19938. /* Deal with !@#$% 64K limit: */
  19939. //if (sizeof(int) <= 2) {
  19940. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  19941. // more = wsize;
  19942. //
  19943. // } else if (more == (unsigned)(-1)) {
  19944. // /* Very unlikely, but possible on 16 bit machine if
  19945. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  19946. // */
  19947. // more--;
  19948. // }
  19949. //}
  19950. /* If the window is almost full and there is insufficient lookahead,
  19951. * move the upper half to the lower one to make room in the upper half.
  19952. */
  19953. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  19954. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  19955. s.match_start -= _w_size;
  19956. s.strstart -= _w_size;
  19957. /* we now have strstart >= MAX_DIST */
  19958. s.block_start -= _w_size;
  19959. /* Slide the hash table (could be avoided with 32 bit values
  19960. at the expense of memory usage). We slide even when level == 0
  19961. to keep the hash table consistent if we switch back to level > 0
  19962. later. (Using level 0 permanently is not an optimal usage of
  19963. zlib, so we don't care about this pathological case.)
  19964. */
  19965. n = s.hash_size;
  19966. p = n;
  19967. do {
  19968. m = s.head[--p];
  19969. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  19970. } while (--n);
  19971. n = _w_size;
  19972. p = n;
  19973. do {
  19974. m = s.prev[--p];
  19975. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  19976. /* If n is not on any hash chain, prev[n] is garbage but
  19977. * its value will never be used.
  19978. */
  19979. } while (--n);
  19980. more += _w_size;
  19981. }
  19982. if (s.strm.avail_in === 0) {
  19983. break;
  19984. }
  19985. /* If there was no sliding:
  19986. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  19987. * more == window_size - lookahead - strstart
  19988. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  19989. * => more >= window_size - 2*WSIZE + 2
  19990. * In the BIG_MEM or MMAP case (not yet supported),
  19991. * window_size == input_size + MIN_LOOKAHEAD &&
  19992. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  19993. * Otherwise, window_size == 2*WSIZE so more >= 2.
  19994. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  19995. */
  19996. //Assert(more >= 2, "more < 2");
  19997. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  19998. s.lookahead += n;
  19999. /* Initialize the hash value now that we have some input: */
  20000. if (s.lookahead + s.insert >= MIN_MATCH) {
  20001. str = s.strstart - s.insert;
  20002. s.ins_h = s.window[str];
  20003. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  20004. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  20005. //#if MIN_MATCH != 3
  20006. // Call update_hash() MIN_MATCH-3 more times
  20007. //#endif
  20008. while (s.insert) {
  20009. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  20010. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  20011. s.prev[str & s.w_mask] = s.head[s.ins_h];
  20012. s.head[s.ins_h] = str;
  20013. str++;
  20014. s.insert--;
  20015. if (s.lookahead + s.insert < MIN_MATCH) {
  20016. break;
  20017. }
  20018. }
  20019. }
  20020. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  20021. * but this is not important since only literal bytes will be emitted.
  20022. */
  20023. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  20024. /* If the WIN_INIT bytes after the end of the current data have never been
  20025. * written, then zero those bytes in order to avoid memory check reports of
  20026. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  20027. * the longest match routines. Update the high water mark for the next
  20028. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  20029. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  20030. */
  20031. // if (s.high_water < s.window_size) {
  20032. // var curr = s.strstart + s.lookahead;
  20033. // var init = 0;
  20034. //
  20035. // if (s.high_water < curr) {
  20036. // /* Previous high water mark below current data -- zero WIN_INIT
  20037. // * bytes or up to end of window, whichever is less.
  20038. // */
  20039. // init = s.window_size - curr;
  20040. // if (init > WIN_INIT)
  20041. // init = WIN_INIT;
  20042. // zmemzero(s->window + curr, (unsigned)init);
  20043. // s->high_water = curr + init;
  20044. // }
  20045. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  20046. // /* High water mark at or above current data, but below current data
  20047. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  20048. // * to end of window, whichever is less.
  20049. // */
  20050. // init = (ulg)curr + WIN_INIT - s->high_water;
  20051. // if (init > s->window_size - s->high_water)
  20052. // init = s->window_size - s->high_water;
  20053. // zmemzero(s->window + s->high_water, (unsigned)init);
  20054. // s->high_water += init;
  20055. // }
  20056. // }
  20057. //
  20058. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  20059. // "not enough room for search");
  20060. }
  20061. /* ===========================================================================
  20062. * Copy without compression as much as possible from the input stream, return
  20063. * the current block state.
  20064. * This function does not insert new strings in the dictionary since
  20065. * uncompressible data is probably not useful. This function is used
  20066. * only for the level=0 compression option.
  20067. * NOTE: this function should be optimized to avoid extra copying from
  20068. * window to pending_buf.
  20069. */
  20070. function deflate_stored(s, flush) {
  20071. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  20072. * to pending_buf_size, and each stored block has a 5 byte header:
  20073. */
  20074. var max_block_size = 0xffff;
  20075. if (max_block_size > s.pending_buf_size - 5) {
  20076. max_block_size = s.pending_buf_size - 5;
  20077. }
  20078. /* Copy as much as possible from input to output: */
  20079. for (;;) {
  20080. /* Fill the window as much as possible: */
  20081. if (s.lookahead <= 1) {
  20082. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  20083. // s->block_start >= (long)s->w_size, "slide too late");
  20084. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  20085. // s.block_start >= s.w_size)) {
  20086. // throw new Error("slide too late");
  20087. // }
  20088. fill_window(s);
  20089. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  20090. return BS_NEED_MORE;
  20091. }
  20092. if (s.lookahead === 0) {
  20093. break;
  20094. }
  20095. /* flush the current block */
  20096. }
  20097. //Assert(s->block_start >= 0L, "block gone");
  20098. // if (s.block_start < 0) throw new Error("block gone");
  20099. s.strstart += s.lookahead;
  20100. s.lookahead = 0;
  20101. /* Emit a stored block if pending_buf will be full: */
  20102. var max_start = s.block_start + max_block_size;
  20103. if (s.strstart === 0 || s.strstart >= max_start) {
  20104. /* strstart == 0 is possible when wraparound on 16-bit machine */
  20105. s.lookahead = s.strstart - max_start;
  20106. s.strstart = max_start;
  20107. /*** FLUSH_BLOCK(s, 0); ***/
  20108. flush_block_only(s, false);
  20109. if (s.strm.avail_out === 0) {
  20110. return BS_NEED_MORE;
  20111. }
  20112. /***/
  20113. }
  20114. /* Flush if we may have to slide, otherwise block_start may become
  20115. * negative and the data will be gone:
  20116. */
  20117. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  20118. /*** FLUSH_BLOCK(s, 0); ***/
  20119. flush_block_only(s, false);
  20120. if (s.strm.avail_out === 0) {
  20121. return BS_NEED_MORE;
  20122. }
  20123. /***/
  20124. }
  20125. }
  20126. s.insert = 0;
  20127. if (flush === Z_FINISH) {
  20128. /*** FLUSH_BLOCK(s, 1); ***/
  20129. flush_block_only(s, true);
  20130. if (s.strm.avail_out === 0) {
  20131. return BS_FINISH_STARTED;
  20132. }
  20133. /***/
  20134. return BS_FINISH_DONE;
  20135. }
  20136. if (s.strstart > s.block_start) {
  20137. /*** FLUSH_BLOCK(s, 0); ***/
  20138. flush_block_only(s, false);
  20139. if (s.strm.avail_out === 0) {
  20140. return BS_NEED_MORE;
  20141. }
  20142. /***/
  20143. }
  20144. return BS_NEED_MORE;
  20145. }
  20146. /* ===========================================================================
  20147. * Compress as much as possible from the input stream, return the current
  20148. * block state.
  20149. * This function does not perform lazy evaluation of matches and inserts
  20150. * new strings in the dictionary only for unmatched strings or for short
  20151. * matches. It is used only for the fast compression options.
  20152. */
  20153. function deflate_fast(s, flush) {
  20154. var hash_head; /* head of the hash chain */
  20155. var bflush; /* set if current block must be flushed */
  20156. for (;;) {
  20157. /* Make sure that we always have enough lookahead, except
  20158. * at the end of the input file. We need MAX_MATCH bytes
  20159. * for the next match, plus MIN_MATCH bytes to insert the
  20160. * string following the next match.
  20161. */
  20162. if (s.lookahead < MIN_LOOKAHEAD) {
  20163. fill_window(s);
  20164. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  20165. return BS_NEED_MORE;
  20166. }
  20167. if (s.lookahead === 0) {
  20168. break; /* flush the current block */
  20169. }
  20170. }
  20171. /* Insert the string window[strstart .. strstart+2] in the
  20172. * dictionary, and set hash_head to the head of the hash chain:
  20173. */
  20174. hash_head = 0/*NIL*/;
  20175. if (s.lookahead >= MIN_MATCH) {
  20176. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20177. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20178. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20179. s.head[s.ins_h] = s.strstart;
  20180. /***/
  20181. }
  20182. /* Find the longest match, discarding those <= prev_length.
  20183. * At this point we have always match_length < MIN_MATCH
  20184. */
  20185. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  20186. /* To simplify the code, we prevent matches with the string
  20187. * of window index 0 (in particular we have to avoid a match
  20188. * of the string with itself at the start of the input file).
  20189. */
  20190. s.match_length = longest_match(s, hash_head);
  20191. /* longest_match() sets match_start */
  20192. }
  20193. if (s.match_length >= MIN_MATCH) {
  20194. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  20195. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  20196. s.match_length - MIN_MATCH, bflush); ***/
  20197. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  20198. s.lookahead -= s.match_length;
  20199. /* Insert new strings in the hash table only if the match length
  20200. * is not too large. This saves time but degrades compression.
  20201. */
  20202. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  20203. s.match_length--; /* string at strstart already in table */
  20204. do {
  20205. s.strstart++;
  20206. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20207. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20208. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20209. s.head[s.ins_h] = s.strstart;
  20210. /***/
  20211. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  20212. * always MIN_MATCH bytes ahead.
  20213. */
  20214. } while (--s.match_length !== 0);
  20215. s.strstart++;
  20216. } else
  20217. {
  20218. s.strstart += s.match_length;
  20219. s.match_length = 0;
  20220. s.ins_h = s.window[s.strstart];
  20221. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  20222. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  20223. //#if MIN_MATCH != 3
  20224. // Call UPDATE_HASH() MIN_MATCH-3 more times
  20225. //#endif
  20226. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  20227. * matter since it will be recomputed at next deflate call.
  20228. */
  20229. }
  20230. } else {
  20231. /* No match, output a literal byte */
  20232. //Tracevv((stderr,"%c", s.window[s.strstart]));
  20233. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  20234. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  20235. s.lookahead--;
  20236. s.strstart++;
  20237. }
  20238. if (bflush) {
  20239. /*** FLUSH_BLOCK(s, 0); ***/
  20240. flush_block_only(s, false);
  20241. if (s.strm.avail_out === 0) {
  20242. return BS_NEED_MORE;
  20243. }
  20244. /***/
  20245. }
  20246. }
  20247. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  20248. if (flush === Z_FINISH) {
  20249. /*** FLUSH_BLOCK(s, 1); ***/
  20250. flush_block_only(s, true);
  20251. if (s.strm.avail_out === 0) {
  20252. return BS_FINISH_STARTED;
  20253. }
  20254. /***/
  20255. return BS_FINISH_DONE;
  20256. }
  20257. if (s.last_lit) {
  20258. /*** FLUSH_BLOCK(s, 0); ***/
  20259. flush_block_only(s, false);
  20260. if (s.strm.avail_out === 0) {
  20261. return BS_NEED_MORE;
  20262. }
  20263. /***/
  20264. }
  20265. return BS_BLOCK_DONE;
  20266. }
  20267. /* ===========================================================================
  20268. * Same as above, but achieves better compression. We use a lazy
  20269. * evaluation for matches: a match is finally adopted only if there is
  20270. * no better match at the next window position.
  20271. */
  20272. function deflate_slow(s, flush) {
  20273. var hash_head; /* head of hash chain */
  20274. var bflush; /* set if current block must be flushed */
  20275. var max_insert;
  20276. /* Process the input block. */
  20277. for (;;) {
  20278. /* Make sure that we always have enough lookahead, except
  20279. * at the end of the input file. We need MAX_MATCH bytes
  20280. * for the next match, plus MIN_MATCH bytes to insert the
  20281. * string following the next match.
  20282. */
  20283. if (s.lookahead < MIN_LOOKAHEAD) {
  20284. fill_window(s);
  20285. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  20286. return BS_NEED_MORE;
  20287. }
  20288. if (s.lookahead === 0) { break; } /* flush the current block */
  20289. }
  20290. /* Insert the string window[strstart .. strstart+2] in the
  20291. * dictionary, and set hash_head to the head of the hash chain:
  20292. */
  20293. hash_head = 0/*NIL*/;
  20294. if (s.lookahead >= MIN_MATCH) {
  20295. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20296. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20297. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20298. s.head[s.ins_h] = s.strstart;
  20299. /***/
  20300. }
  20301. /* Find the longest match, discarding those <= prev_length.
  20302. */
  20303. s.prev_length = s.match_length;
  20304. s.prev_match = s.match_start;
  20305. s.match_length = MIN_MATCH-1;
  20306. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  20307. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  20308. /* To simplify the code, we prevent matches with the string
  20309. * of window index 0 (in particular we have to avoid a match
  20310. * of the string with itself at the start of the input file).
  20311. */
  20312. s.match_length = longest_match(s, hash_head);
  20313. /* longest_match() sets match_start */
  20314. if (s.match_length <= 5 &&
  20315. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  20316. /* If prev_match is also MIN_MATCH, match_start is garbage
  20317. * but we will ignore the current match anyway.
  20318. */
  20319. s.match_length = MIN_MATCH-1;
  20320. }
  20321. }
  20322. /* If there was a match at the previous step and the current
  20323. * match is not better, output the previous match:
  20324. */
  20325. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  20326. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  20327. /* Do not insert strings in hash table beyond this. */
  20328. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  20329. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  20330. s.prev_length - MIN_MATCH, bflush);***/
  20331. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  20332. /* Insert in hash table all strings up to the end of the match.
  20333. * strstart-1 and strstart are already inserted. If there is not
  20334. * enough lookahead, the last two strings are not inserted in
  20335. * the hash table.
  20336. */
  20337. s.lookahead -= s.prev_length-1;
  20338. s.prev_length -= 2;
  20339. do {
  20340. if (++s.strstart <= max_insert) {
  20341. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20342. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20343. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20344. s.head[s.ins_h] = s.strstart;
  20345. /***/
  20346. }
  20347. } while (--s.prev_length !== 0);
  20348. s.match_available = 0;
  20349. s.match_length = MIN_MATCH-1;
  20350. s.strstart++;
  20351. if (bflush) {
  20352. /*** FLUSH_BLOCK(s, 0); ***/
  20353. flush_block_only(s, false);
  20354. if (s.strm.avail_out === 0) {
  20355. return BS_NEED_MORE;
  20356. }
  20357. /***/
  20358. }
  20359. } else if (s.match_available) {
  20360. /* If there was no match at the previous position, output a
  20361. * single literal. If there was a match but the current match
  20362. * is longer, truncate the previous match to a single literal.
  20363. */
  20364. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  20365. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  20366. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  20367. if (bflush) {
  20368. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  20369. flush_block_only(s, false);
  20370. /***/
  20371. }
  20372. s.strstart++;
  20373. s.lookahead--;
  20374. if (s.strm.avail_out === 0) {
  20375. return BS_NEED_MORE;
  20376. }
  20377. } else {
  20378. /* There is no previous match to compare with, wait for
  20379. * the next step to decide.
  20380. */
  20381. s.match_available = 1;
  20382. s.strstart++;
  20383. s.lookahead--;
  20384. }
  20385. }
  20386. //Assert (flush != Z_NO_FLUSH, "no flush?");
  20387. if (s.match_available) {
  20388. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  20389. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  20390. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  20391. s.match_available = 0;
  20392. }
  20393. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  20394. if (flush === Z_FINISH) {
  20395. /*** FLUSH_BLOCK(s, 1); ***/
  20396. flush_block_only(s, true);
  20397. if (s.strm.avail_out === 0) {
  20398. return BS_FINISH_STARTED;
  20399. }
  20400. /***/
  20401. return BS_FINISH_DONE;
  20402. }
  20403. if (s.last_lit) {
  20404. /*** FLUSH_BLOCK(s, 0); ***/
  20405. flush_block_only(s, false);
  20406. if (s.strm.avail_out === 0) {
  20407. return BS_NEED_MORE;
  20408. }
  20409. /***/
  20410. }
  20411. return BS_BLOCK_DONE;
  20412. }
  20413. /* ===========================================================================
  20414. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  20415. * one. Do not maintain a hash table. (It will be regenerated if this run of
  20416. * deflate switches away from Z_RLE.)
  20417. */
  20418. function deflate_rle(s, flush) {
  20419. var bflush; /* set if current block must be flushed */
  20420. var prev; /* byte at distance one to match */
  20421. var scan, strend; /* scan goes up to strend for length of run */
  20422. var _win = s.window;
  20423. for (;;) {
  20424. /* Make sure that we always have enough lookahead, except
  20425. * at the end of the input file. We need MAX_MATCH bytes
  20426. * for the longest run, plus one for the unrolled loop.
  20427. */
  20428. if (s.lookahead <= MAX_MATCH) {
  20429. fill_window(s);
  20430. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  20431. return BS_NEED_MORE;
  20432. }
  20433. if (s.lookahead === 0) { break; } /* flush the current block */
  20434. }
  20435. /* See how many times the previous byte repeats */
  20436. s.match_length = 0;
  20437. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  20438. scan = s.strstart - 1;
  20439. prev = _win[scan];
  20440. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  20441. strend = s.strstart + MAX_MATCH;
  20442. do {
  20443. /*jshint noempty:false*/
  20444. } while (prev === _win[++scan] && prev === _win[++scan] &&
  20445. prev === _win[++scan] && prev === _win[++scan] &&
  20446. prev === _win[++scan] && prev === _win[++scan] &&
  20447. prev === _win[++scan] && prev === _win[++scan] &&
  20448. scan < strend);
  20449. s.match_length = MAX_MATCH - (strend - scan);
  20450. if (s.match_length > s.lookahead) {
  20451. s.match_length = s.lookahead;
  20452. }
  20453. }
  20454. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  20455. }
  20456. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  20457. if (s.match_length >= MIN_MATCH) {
  20458. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  20459. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  20460. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  20461. s.lookahead -= s.match_length;
  20462. s.strstart += s.match_length;
  20463. s.match_length = 0;
  20464. } else {
  20465. /* No match, output a literal byte */
  20466. //Tracevv((stderr,"%c", s->window[s->strstart]));
  20467. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  20468. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  20469. s.lookahead--;
  20470. s.strstart++;
  20471. }
  20472. if (bflush) {
  20473. /*** FLUSH_BLOCK(s, 0); ***/
  20474. flush_block_only(s, false);
  20475. if (s.strm.avail_out === 0) {
  20476. return BS_NEED_MORE;
  20477. }
  20478. /***/
  20479. }
  20480. }
  20481. s.insert = 0;
  20482. if (flush === Z_FINISH) {
  20483. /*** FLUSH_BLOCK(s, 1); ***/
  20484. flush_block_only(s, true);
  20485. if (s.strm.avail_out === 0) {
  20486. return BS_FINISH_STARTED;
  20487. }
  20488. /***/
  20489. return BS_FINISH_DONE;
  20490. }
  20491. if (s.last_lit) {
  20492. /*** FLUSH_BLOCK(s, 0); ***/
  20493. flush_block_only(s, false);
  20494. if (s.strm.avail_out === 0) {
  20495. return BS_NEED_MORE;
  20496. }
  20497. /***/
  20498. }
  20499. return BS_BLOCK_DONE;
  20500. }
  20501. /* ===========================================================================
  20502. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  20503. * (It will be regenerated if this run of deflate switches away from Huffman.)
  20504. */
  20505. function deflate_huff(s, flush) {
  20506. var bflush; /* set if current block must be flushed */
  20507. for (;;) {
  20508. /* Make sure that we have a literal to write. */
  20509. if (s.lookahead === 0) {
  20510. fill_window(s);
  20511. if (s.lookahead === 0) {
  20512. if (flush === Z_NO_FLUSH) {
  20513. return BS_NEED_MORE;
  20514. }
  20515. break; /* flush the current block */
  20516. }
  20517. }
  20518. /* Output a literal byte */
  20519. s.match_length = 0;
  20520. //Tracevv((stderr,"%c", s->window[s->strstart]));
  20521. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  20522. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  20523. s.lookahead--;
  20524. s.strstart++;
  20525. if (bflush) {
  20526. /*** FLUSH_BLOCK(s, 0); ***/
  20527. flush_block_only(s, false);
  20528. if (s.strm.avail_out === 0) {
  20529. return BS_NEED_MORE;
  20530. }
  20531. /***/
  20532. }
  20533. }
  20534. s.insert = 0;
  20535. if (flush === Z_FINISH) {
  20536. /*** FLUSH_BLOCK(s, 1); ***/
  20537. flush_block_only(s, true);
  20538. if (s.strm.avail_out === 0) {
  20539. return BS_FINISH_STARTED;
  20540. }
  20541. /***/
  20542. return BS_FINISH_DONE;
  20543. }
  20544. if (s.last_lit) {
  20545. /*** FLUSH_BLOCK(s, 0); ***/
  20546. flush_block_only(s, false);
  20547. if (s.strm.avail_out === 0) {
  20548. return BS_NEED_MORE;
  20549. }
  20550. /***/
  20551. }
  20552. return BS_BLOCK_DONE;
  20553. }
  20554. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  20555. * the desired pack level (0..9). The values given below have been tuned to
  20556. * exclude worst case performance for pathological files. Better values may be
  20557. * found for specific files.
  20558. */
  20559. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  20560. this.good_length = good_length;
  20561. this.max_lazy = max_lazy;
  20562. this.nice_length = nice_length;
  20563. this.max_chain = max_chain;
  20564. this.func = func;
  20565. };
  20566. var configuration_table;
  20567. configuration_table = [
  20568. /* good lazy nice chain */
  20569. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  20570. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  20571. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  20572. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  20573. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  20574. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  20575. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  20576. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  20577. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  20578. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  20579. ];
  20580. /* ===========================================================================
  20581. * Initialize the "longest match" routines for a new zlib stream
  20582. */
  20583. function lm_init(s) {
  20584. s.window_size = 2 * s.w_size;
  20585. /*** CLEAR_HASH(s); ***/
  20586. zero(s.head); // Fill with NIL (= 0);
  20587. /* Set the default configuration parameters:
  20588. */
  20589. s.max_lazy_match = configuration_table[s.level].max_lazy;
  20590. s.good_match = configuration_table[s.level].good_length;
  20591. s.nice_match = configuration_table[s.level].nice_length;
  20592. s.max_chain_length = configuration_table[s.level].max_chain;
  20593. s.strstart = 0;
  20594. s.block_start = 0;
  20595. s.lookahead = 0;
  20596. s.insert = 0;
  20597. s.match_length = s.prev_length = MIN_MATCH - 1;
  20598. s.match_available = 0;
  20599. s.ins_h = 0;
  20600. }
  20601. function DeflateState() {
  20602. this.strm = null; /* pointer back to this zlib stream */
  20603. this.status = 0; /* as the name implies */
  20604. this.pending_buf = null; /* output still pending */
  20605. this.pending_buf_size = 0; /* size of pending_buf */
  20606. this.pending_out = 0; /* next pending byte to output to the stream */
  20607. this.pending = 0; /* nb of bytes in the pending buffer */
  20608. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  20609. this.gzhead = null; /* gzip header information to write */
  20610. this.gzindex = 0; /* where in extra, name, or comment */
  20611. this.method = Z_DEFLATED; /* can only be DEFLATED */
  20612. this.last_flush = -1; /* value of flush param for previous deflate call */
  20613. this.w_size = 0; /* LZ77 window size (32K by default) */
  20614. this.w_bits = 0; /* log2(w_size) (8..16) */
  20615. this.w_mask = 0; /* w_size - 1 */
  20616. this.window = null;
  20617. /* Sliding window. Input bytes are read into the second half of the window,
  20618. * and move to the first half later to keep a dictionary of at least wSize
  20619. * bytes. With this organization, matches are limited to a distance of
  20620. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  20621. * performed with a length multiple of the block size.
  20622. */
  20623. this.window_size = 0;
  20624. /* Actual size of window: 2*wSize, except when the user input buffer
  20625. * is directly used as sliding window.
  20626. */
  20627. this.prev = null;
  20628. /* Link to older string with same hash index. To limit the size of this
  20629. * array to 64K, this link is maintained only for the last 32K strings.
  20630. * An index in this array is thus a window index modulo 32K.
  20631. */
  20632. this.head = null; /* Heads of the hash chains or NIL. */
  20633. this.ins_h = 0; /* hash index of string to be inserted */
  20634. this.hash_size = 0; /* number of elements in hash table */
  20635. this.hash_bits = 0; /* log2(hash_size) */
  20636. this.hash_mask = 0; /* hash_size-1 */
  20637. this.hash_shift = 0;
  20638. /* Number of bits by which ins_h must be shifted at each input
  20639. * step. It must be such that after MIN_MATCH steps, the oldest
  20640. * byte no longer takes part in the hash key, that is:
  20641. * hash_shift * MIN_MATCH >= hash_bits
  20642. */
  20643. this.block_start = 0;
  20644. /* Window position at the beginning of the current output block. Gets
  20645. * negative when the window is moved backwards.
  20646. */
  20647. this.match_length = 0; /* length of best match */
  20648. this.prev_match = 0; /* previous match */
  20649. this.match_available = 0; /* set if previous match exists */
  20650. this.strstart = 0; /* start of string to insert */
  20651. this.match_start = 0; /* start of matching string */
  20652. this.lookahead = 0; /* number of valid bytes ahead in window */
  20653. this.prev_length = 0;
  20654. /* Length of the best match at previous step. Matches not greater than this
  20655. * are discarded. This is used in the lazy match evaluation.
  20656. */
  20657. this.max_chain_length = 0;
  20658. /* To speed up deflation, hash chains are never searched beyond this
  20659. * length. A higher limit improves compression ratio but degrades the
  20660. * speed.
  20661. */
  20662. this.max_lazy_match = 0;
  20663. /* Attempt to find a better match only when the current match is strictly
  20664. * smaller than this value. This mechanism is used only for compression
  20665. * levels >= 4.
  20666. */
  20667. // That's alias to max_lazy_match, don't use directly
  20668. //this.max_insert_length = 0;
  20669. /* Insert new strings in the hash table only if the match length is not
  20670. * greater than this length. This saves time but degrades compression.
  20671. * max_insert_length is used only for compression levels <= 3.
  20672. */
  20673. this.level = 0; /* compression level (1..9) */
  20674. this.strategy = 0; /* favor or force Huffman coding*/
  20675. this.good_match = 0;
  20676. /* Use a faster search when the previous match is longer than this */
  20677. this.nice_match = 0; /* Stop searching when current match exceeds this */
  20678. /* used by trees.c: */
  20679. /* Didn't use ct_data typedef below to suppress compiler warning */
  20680. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  20681. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  20682. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  20683. // Use flat array of DOUBLE size, with interleaved fata,
  20684. // because JS does not support effective
  20685. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  20686. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  20687. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  20688. zero(this.dyn_ltree);
  20689. zero(this.dyn_dtree);
  20690. zero(this.bl_tree);
  20691. this.l_desc = null; /* desc. for literal tree */
  20692. this.d_desc = null; /* desc. for distance tree */
  20693. this.bl_desc = null; /* desc. for bit length tree */
  20694. //ush bl_count[MAX_BITS+1];
  20695. this.bl_count = new utils.Buf16(MAX_BITS+1);
  20696. /* number of codes at each bit length for an optimal tree */
  20697. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  20698. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  20699. zero(this.heap);
  20700. this.heap_len = 0; /* number of elements in the heap */
  20701. this.heap_max = 0; /* element of largest frequency */
  20702. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  20703. * The same heap array is used to build all trees.
  20704. */
  20705. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  20706. zero(this.depth);
  20707. /* Depth of each subtree used as tie breaker for trees of equal frequency
  20708. */
  20709. this.l_buf = 0; /* buffer index for literals or lengths */
  20710. this.lit_bufsize = 0;
  20711. /* Size of match buffer for literals/lengths. There are 4 reasons for
  20712. * limiting lit_bufsize to 64K:
  20713. * - frequencies can be kept in 16 bit counters
  20714. * - if compression is not successful for the first block, all input
  20715. * data is still in the window so we can still emit a stored block even
  20716. * when input comes from standard input. (This can also be done for
  20717. * all blocks if lit_bufsize is not greater than 32K.)
  20718. * - if compression is not successful for a file smaller than 64K, we can
  20719. * even emit a stored file instead of a stored block (saving 5 bytes).
  20720. * This is applicable only for zip (not gzip or zlib).
  20721. * - creating new Huffman trees less frequently may not provide fast
  20722. * adaptation to changes in the input data statistics. (Take for
  20723. * example a binary file with poorly compressible code followed by
  20724. * a highly compressible string table.) Smaller buffer sizes give
  20725. * fast adaptation but have of course the overhead of transmitting
  20726. * trees more frequently.
  20727. * - I can't count above 4
  20728. */
  20729. this.last_lit = 0; /* running index in l_buf */
  20730. this.d_buf = 0;
  20731. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  20732. * the same number of elements. To use different lengths, an extra flag
  20733. * array would be necessary.
  20734. */
  20735. this.opt_len = 0; /* bit length of current block with optimal trees */
  20736. this.static_len = 0; /* bit length of current block with static trees */
  20737. this.matches = 0; /* number of string matches in current block */
  20738. this.insert = 0; /* bytes at end of window left to insert */
  20739. this.bi_buf = 0;
  20740. /* Output buffer. bits are inserted starting at the bottom (least
  20741. * significant bits).
  20742. */
  20743. this.bi_valid = 0;
  20744. /* Number of valid bits in bi_buf. All bits above the last valid bit
  20745. * are always zero.
  20746. */
  20747. // Used for window memory init. We safely ignore it for JS. That makes
  20748. // sense only for pointers and memory check tools.
  20749. //this.high_water = 0;
  20750. /* High water mark offset in window for initialized bytes -- bytes above
  20751. * this are set to zero in order to avoid memory check warnings when
  20752. * longest match routines access bytes past the input. This is then
  20753. * updated to the new high water mark.
  20754. */
  20755. }
  20756. function deflateResetKeep(strm) {
  20757. var s;
  20758. if (!strm || !strm.state) {
  20759. return err(strm, Z_STREAM_ERROR);
  20760. }
  20761. strm.total_in = strm.total_out = 0;
  20762. strm.data_type = Z_UNKNOWN;
  20763. s = strm.state;
  20764. s.pending = 0;
  20765. s.pending_out = 0;
  20766. if (s.wrap < 0) {
  20767. s.wrap = -s.wrap;
  20768. /* was made negative by deflate(..., Z_FINISH); */
  20769. }
  20770. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  20771. strm.adler = (s.wrap === 2) ?
  20772. 0 // crc32(0, Z_NULL, 0)
  20773. :
  20774. 1; // adler32(0, Z_NULL, 0)
  20775. s.last_flush = Z_NO_FLUSH;
  20776. trees._tr_init(s);
  20777. return Z_OK;
  20778. }
  20779. function deflateReset(strm) {
  20780. var ret = deflateResetKeep(strm);
  20781. if (ret === Z_OK) {
  20782. lm_init(strm.state);
  20783. }
  20784. return ret;
  20785. }
  20786. function deflateSetHeader(strm, head) {
  20787. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  20788. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  20789. strm.state.gzhead = head;
  20790. return Z_OK;
  20791. }
  20792. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  20793. if (!strm) { // === Z_NULL
  20794. return Z_STREAM_ERROR;
  20795. }
  20796. var wrap = 1;
  20797. if (level === Z_DEFAULT_COMPRESSION) {
  20798. level = 6;
  20799. }
  20800. if (windowBits < 0) { /* suppress zlib wrapper */
  20801. wrap = 0;
  20802. windowBits = -windowBits;
  20803. }
  20804. else if (windowBits > 15) {
  20805. wrap = 2; /* write gzip wrapper instead */
  20806. windowBits -= 16;
  20807. }
  20808. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  20809. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  20810. strategy < 0 || strategy > Z_FIXED) {
  20811. return err(strm, Z_STREAM_ERROR);
  20812. }
  20813. if (windowBits === 8) {
  20814. windowBits = 9;
  20815. }
  20816. /* until 256-byte window bug fixed */
  20817. var s = new DeflateState();
  20818. strm.state = s;
  20819. s.strm = strm;
  20820. s.wrap = wrap;
  20821. s.gzhead = null;
  20822. s.w_bits = windowBits;
  20823. s.w_size = 1 << s.w_bits;
  20824. s.w_mask = s.w_size - 1;
  20825. s.hash_bits = memLevel + 7;
  20826. s.hash_size = 1 << s.hash_bits;
  20827. s.hash_mask = s.hash_size - 1;
  20828. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  20829. s.window = new utils.Buf8(s.w_size * 2);
  20830. s.head = new utils.Buf16(s.hash_size);
  20831. s.prev = new utils.Buf16(s.w_size);
  20832. // Don't need mem init magic for JS.
  20833. //s.high_water = 0; /* nothing written to s->window yet */
  20834. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  20835. s.pending_buf_size = s.lit_bufsize * 4;
  20836. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  20837. s.d_buf = s.lit_bufsize >> 1;
  20838. s.l_buf = (1 + 2) * s.lit_bufsize;
  20839. s.level = level;
  20840. s.strategy = strategy;
  20841. s.method = method;
  20842. return deflateReset(strm);
  20843. }
  20844. function deflateInit(strm, level) {
  20845. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  20846. }
  20847. function deflate(strm, flush) {
  20848. var old_flush, s;
  20849. var beg, val; // for gzip header write only
  20850. if (!strm || !strm.state ||
  20851. flush > Z_BLOCK || flush < 0) {
  20852. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  20853. }
  20854. s = strm.state;
  20855. if (!strm.output ||
  20856. (!strm.input && strm.avail_in !== 0) ||
  20857. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  20858. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  20859. }
  20860. s.strm = strm; /* just in case */
  20861. old_flush = s.last_flush;
  20862. s.last_flush = flush;
  20863. /* Write the header */
  20864. if (s.status === INIT_STATE) {
  20865. if (s.wrap === 2) { // GZIP header
  20866. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  20867. put_byte(s, 31);
  20868. put_byte(s, 139);
  20869. put_byte(s, 8);
  20870. if (!s.gzhead) { // s->gzhead == Z_NULL
  20871. put_byte(s, 0);
  20872. put_byte(s, 0);
  20873. put_byte(s, 0);
  20874. put_byte(s, 0);
  20875. put_byte(s, 0);
  20876. put_byte(s, s.level === 9 ? 2 :
  20877. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  20878. 4 : 0));
  20879. put_byte(s, OS_CODE);
  20880. s.status = BUSY_STATE;
  20881. }
  20882. else {
  20883. put_byte(s, (s.gzhead.text ? 1 : 0) +
  20884. (s.gzhead.hcrc ? 2 : 0) +
  20885. (!s.gzhead.extra ? 0 : 4) +
  20886. (!s.gzhead.name ? 0 : 8) +
  20887. (!s.gzhead.comment ? 0 : 16)
  20888. );
  20889. put_byte(s, s.gzhead.time & 0xff);
  20890. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  20891. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  20892. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  20893. put_byte(s, s.level === 9 ? 2 :
  20894. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  20895. 4 : 0));
  20896. put_byte(s, s.gzhead.os & 0xff);
  20897. if (s.gzhead.extra && s.gzhead.extra.length) {
  20898. put_byte(s, s.gzhead.extra.length & 0xff);
  20899. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  20900. }
  20901. if (s.gzhead.hcrc) {
  20902. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  20903. }
  20904. s.gzindex = 0;
  20905. s.status = EXTRA_STATE;
  20906. }
  20907. }
  20908. else // DEFLATE header
  20909. {
  20910. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  20911. var level_flags = -1;
  20912. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  20913. level_flags = 0;
  20914. } else if (s.level < 6) {
  20915. level_flags = 1;
  20916. } else if (s.level === 6) {
  20917. level_flags = 2;
  20918. } else {
  20919. level_flags = 3;
  20920. }
  20921. header |= (level_flags << 6);
  20922. if (s.strstart !== 0) { header |= PRESET_DICT; }
  20923. header += 31 - (header % 31);
  20924. s.status = BUSY_STATE;
  20925. putShortMSB(s, header);
  20926. /* Save the adler32 of the preset dictionary: */
  20927. if (s.strstart !== 0) {
  20928. putShortMSB(s, strm.adler >>> 16);
  20929. putShortMSB(s, strm.adler & 0xffff);
  20930. }
  20931. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  20932. }
  20933. }
  20934. //#ifdef GZIP
  20935. if (s.status === EXTRA_STATE) {
  20936. if (s.gzhead.extra/* != Z_NULL*/) {
  20937. beg = s.pending; /* start of bytes to update crc */
  20938. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  20939. if (s.pending === s.pending_buf_size) {
  20940. if (s.gzhead.hcrc && s.pending > beg) {
  20941. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  20942. }
  20943. flush_pending(strm);
  20944. beg = s.pending;
  20945. if (s.pending === s.pending_buf_size) {
  20946. break;
  20947. }
  20948. }
  20949. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  20950. s.gzindex++;
  20951. }
  20952. if (s.gzhead.hcrc && s.pending > beg) {
  20953. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  20954. }
  20955. if (s.gzindex === s.gzhead.extra.length) {
  20956. s.gzindex = 0;
  20957. s.status = NAME_STATE;
  20958. }
  20959. }
  20960. else {
  20961. s.status = NAME_STATE;
  20962. }
  20963. }
  20964. if (s.status === NAME_STATE) {
  20965. if (s.gzhead.name/* != Z_NULL*/) {
  20966. beg = s.pending; /* start of bytes to update crc */
  20967. //int val;
  20968. do {
  20969. if (s.pending === s.pending_buf_size) {
  20970. if (s.gzhead.hcrc && s.pending > beg) {
  20971. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  20972. }
  20973. flush_pending(strm);
  20974. beg = s.pending;
  20975. if (s.pending === s.pending_buf_size) {
  20976. val = 1;
  20977. break;
  20978. }
  20979. }
  20980. // JS specific: little magic to add zero terminator to end of string
  20981. if (s.gzindex < s.gzhead.name.length) {
  20982. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  20983. } else {
  20984. val = 0;
  20985. }
  20986. put_byte(s, val);
  20987. } while (val !== 0);
  20988. if (s.gzhead.hcrc && s.pending > beg){
  20989. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  20990. }
  20991. if (val === 0) {
  20992. s.gzindex = 0;
  20993. s.status = COMMENT_STATE;
  20994. }
  20995. }
  20996. else {
  20997. s.status = COMMENT_STATE;
  20998. }
  20999. }
  21000. if (s.status === COMMENT_STATE) {
  21001. if (s.gzhead.comment/* != Z_NULL*/) {
  21002. beg = s.pending; /* start of bytes to update crc */
  21003. //int val;
  21004. do {
  21005. if (s.pending === s.pending_buf_size) {
  21006. if (s.gzhead.hcrc && s.pending > beg) {
  21007. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21008. }
  21009. flush_pending(strm);
  21010. beg = s.pending;
  21011. if (s.pending === s.pending_buf_size) {
  21012. val = 1;
  21013. break;
  21014. }
  21015. }
  21016. // JS specific: little magic to add zero terminator to end of string
  21017. if (s.gzindex < s.gzhead.comment.length) {
  21018. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  21019. } else {
  21020. val = 0;
  21021. }
  21022. put_byte(s, val);
  21023. } while (val !== 0);
  21024. if (s.gzhead.hcrc && s.pending > beg) {
  21025. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21026. }
  21027. if (val === 0) {
  21028. s.status = HCRC_STATE;
  21029. }
  21030. }
  21031. else {
  21032. s.status = HCRC_STATE;
  21033. }
  21034. }
  21035. if (s.status === HCRC_STATE) {
  21036. if (s.gzhead.hcrc) {
  21037. if (s.pending + 2 > s.pending_buf_size) {
  21038. flush_pending(strm);
  21039. }
  21040. if (s.pending + 2 <= s.pending_buf_size) {
  21041. put_byte(s, strm.adler & 0xff);
  21042. put_byte(s, (strm.adler >> 8) & 0xff);
  21043. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  21044. s.status = BUSY_STATE;
  21045. }
  21046. }
  21047. else {
  21048. s.status = BUSY_STATE;
  21049. }
  21050. }
  21051. //#endif
  21052. /* Flush as much pending output as possible */
  21053. if (s.pending !== 0) {
  21054. flush_pending(strm);
  21055. if (strm.avail_out === 0) {
  21056. /* Since avail_out is 0, deflate will be called again with
  21057. * more output space, but possibly with both pending and
  21058. * avail_in equal to zero. There won't be anything to do,
  21059. * but this is not an error situation so make sure we
  21060. * return OK instead of BUF_ERROR at next call of deflate:
  21061. */
  21062. s.last_flush = -1;
  21063. return Z_OK;
  21064. }
  21065. /* Make sure there is something to do and avoid duplicate consecutive
  21066. * flushes. For repeated and useless calls with Z_FINISH, we keep
  21067. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  21068. */
  21069. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  21070. flush !== Z_FINISH) {
  21071. return err(strm, Z_BUF_ERROR);
  21072. }
  21073. /* User must not provide more input after the first FINISH: */
  21074. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  21075. return err(strm, Z_BUF_ERROR);
  21076. }
  21077. /* Start a new block or continue the current one.
  21078. */
  21079. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  21080. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  21081. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  21082. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  21083. configuration_table[s.level].func(s, flush));
  21084. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  21085. s.status = FINISH_STATE;
  21086. }
  21087. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  21088. if (strm.avail_out === 0) {
  21089. s.last_flush = -1;
  21090. /* avoid BUF_ERROR next call, see above */
  21091. }
  21092. return Z_OK;
  21093. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  21094. * of deflate should use the same flush parameter to make sure
  21095. * that the flush is complete. So we don't have to output an
  21096. * empty block here, this will be done at next call. This also
  21097. * ensures that for a very small output buffer, we emit at most
  21098. * one empty block.
  21099. */
  21100. }
  21101. if (bstate === BS_BLOCK_DONE) {
  21102. if (flush === Z_PARTIAL_FLUSH) {
  21103. trees._tr_align(s);
  21104. }
  21105. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  21106. trees._tr_stored_block(s, 0, 0, false);
  21107. /* For a full flush, this empty block will be recognized
  21108. * as a special marker by inflate_sync().
  21109. */
  21110. if (flush === Z_FULL_FLUSH) {
  21111. /*** CLEAR_HASH(s); ***/ /* forget history */
  21112. zero(s.head); // Fill with NIL (= 0);
  21113. if (s.lookahead === 0) {
  21114. s.strstart = 0;
  21115. s.block_start = 0;
  21116. s.insert = 0;
  21117. }
  21118. }
  21119. }
  21120. flush_pending(strm);
  21121. if (strm.avail_out === 0) {
  21122. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  21123. return Z_OK;
  21124. }
  21125. }
  21126. }
  21127. //Assert(strm->avail_out > 0, "bug2");
  21128. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  21129. if (flush !== Z_FINISH) { return Z_OK; }
  21130. if (s.wrap <= 0) { return Z_STREAM_END; }
  21131. /* Write the trailer */
  21132. if (s.wrap === 2) {
  21133. put_byte(s, strm.adler & 0xff);
  21134. put_byte(s, (strm.adler >> 8) & 0xff);
  21135. put_byte(s, (strm.adler >> 16) & 0xff);
  21136. put_byte(s, (strm.adler >> 24) & 0xff);
  21137. put_byte(s, strm.total_in & 0xff);
  21138. put_byte(s, (strm.total_in >> 8) & 0xff);
  21139. put_byte(s, (strm.total_in >> 16) & 0xff);
  21140. put_byte(s, (strm.total_in >> 24) & 0xff);
  21141. }
  21142. else
  21143. {
  21144. putShortMSB(s, strm.adler >>> 16);
  21145. putShortMSB(s, strm.adler & 0xffff);
  21146. }
  21147. flush_pending(strm);
  21148. /* If avail_out is zero, the application will call deflate again
  21149. * to flush the rest.
  21150. */
  21151. if (s.wrap > 0) { s.wrap = -s.wrap; }
  21152. /* write the trailer only once! */
  21153. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  21154. }
  21155. function deflateEnd(strm) {
  21156. var status;
  21157. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  21158. return Z_STREAM_ERROR;
  21159. }
  21160. status = strm.state.status;
  21161. if (status !== INIT_STATE &&
  21162. status !== EXTRA_STATE &&
  21163. status !== NAME_STATE &&
  21164. status !== COMMENT_STATE &&
  21165. status !== HCRC_STATE &&
  21166. status !== BUSY_STATE &&
  21167. status !== FINISH_STATE
  21168. ) {
  21169. return err(strm, Z_STREAM_ERROR);
  21170. }
  21171. strm.state = null;
  21172. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  21173. }
  21174. /* =========================================================================
  21175. * Copy the source state to the destination state
  21176. */
  21177. //function deflateCopy(dest, source) {
  21178. //
  21179. //}
  21180. exports.deflateInit = deflateInit;
  21181. exports.deflateInit2 = deflateInit2;
  21182. exports.deflateReset = deflateReset;
  21183. exports.deflateResetKeep = deflateResetKeep;
  21184. exports.deflateSetHeader = deflateSetHeader;
  21185. exports.deflate = deflate;
  21186. exports.deflateEnd = deflateEnd;
  21187. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  21188. /* Not implemented
  21189. exports.deflateBound = deflateBound;
  21190. exports.deflateCopy = deflateCopy;
  21191. exports.deflateSetDictionary = deflateSetDictionary;
  21192. exports.deflateParams = deflateParams;
  21193. exports.deflatePending = deflatePending;
  21194. exports.deflatePrime = deflatePrime;
  21195. exports.deflateTune = deflateTune;
  21196. */
  21197. },{"../utils/common":67,"./adler32":69,"./crc32":71,"./messages":77,"./trees":78}],73:[function(require,module,exports){
  21198. 'use strict';
  21199. function GZheader() {
  21200. /* true if compressed data believed to be text */
  21201. this.text = 0;
  21202. /* modification time */
  21203. this.time = 0;
  21204. /* extra flags (not used when writing a gzip file) */
  21205. this.xflags = 0;
  21206. /* operating system */
  21207. this.os = 0;
  21208. /* pointer to extra field or Z_NULL if none */
  21209. this.extra = null;
  21210. /* extra field length (valid if extra != Z_NULL) */
  21211. this.extra_len = 0; // Actually, we don't need it in JS,
  21212. // but leave for few code modifications
  21213. //
  21214. // Setup limits is not necessary because in js we should not preallocate memory
  21215. // for inflate use constant limit in 65536 bytes
  21216. //
  21217. /* space at extra (only when reading header) */
  21218. // this.extra_max = 0;
  21219. /* pointer to zero-terminated file name or Z_NULL */
  21220. this.name = '';
  21221. /* space at name (only when reading header) */
  21222. // this.name_max = 0;
  21223. /* pointer to zero-terminated comment or Z_NULL */
  21224. this.comment = '';
  21225. /* space at comment (only when reading header) */
  21226. // this.comm_max = 0;
  21227. /* true if there was or will be a header crc */
  21228. this.hcrc = 0;
  21229. /* true when done reading gzip header (not used when writing a gzip file) */
  21230. this.done = false;
  21231. }
  21232. module.exports = GZheader;
  21233. },{}],74:[function(require,module,exports){
  21234. 'use strict';
  21235. // See state defs from inflate.js
  21236. var BAD = 30; /* got a data error -- remain here until reset */
  21237. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  21238. /*
  21239. Decode literal, length, and distance codes and write out the resulting
  21240. literal and match bytes until either not enough input or output is
  21241. available, an end-of-block is encountered, or a data error is encountered.
  21242. When large enough input and output buffers are supplied to inflate(), for
  21243. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  21244. inflate execution time is spent in this routine.
  21245. Entry assumptions:
  21246. state.mode === LEN
  21247. strm.avail_in >= 6
  21248. strm.avail_out >= 258
  21249. start >= strm.avail_out
  21250. state.bits < 8
  21251. On return, state.mode is one of:
  21252. LEN -- ran out of enough output space or enough available input
  21253. TYPE -- reached end of block code, inflate() to interpret next block
  21254. BAD -- error in block data
  21255. Notes:
  21256. - The maximum input bits used by a length/distance pair is 15 bits for the
  21257. length code, 5 bits for the length extra, 15 bits for the distance code,
  21258. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  21259. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  21260. checking for available input while decoding.
  21261. - The maximum bytes that a single length/distance pair can output is 258
  21262. bytes, which is the maximum length that can be coded. inflate_fast()
  21263. requires strm.avail_out >= 258 for each loop to avoid checking for
  21264. output space.
  21265. */
  21266. module.exports = function inflate_fast(strm, start) {
  21267. var state;
  21268. var _in; /* local strm.input */
  21269. var last; /* have enough input while in < last */
  21270. var _out; /* local strm.output */
  21271. var beg; /* inflate()'s initial strm.output */
  21272. var end; /* while out < end, enough space available */
  21273. //#ifdef INFLATE_STRICT
  21274. var dmax; /* maximum distance from zlib header */
  21275. //#endif
  21276. var wsize; /* window size or zero if not using window */
  21277. var whave; /* valid bytes in the window */
  21278. var wnext; /* window write index */
  21279. var window; /* allocated sliding window, if wsize != 0 */
  21280. var hold; /* local strm.hold */
  21281. var bits; /* local strm.bits */
  21282. var lcode; /* local strm.lencode */
  21283. var dcode; /* local strm.distcode */
  21284. var lmask; /* mask for first level of length codes */
  21285. var dmask; /* mask for first level of distance codes */
  21286. var here; /* retrieved table entry */
  21287. var op; /* code bits, operation, extra bits, or */
  21288. /* window position, window bytes to copy */
  21289. var len; /* match length, unused bytes */
  21290. var dist; /* match distance */
  21291. var from; /* where to copy match from */
  21292. var from_source;
  21293. var input, output; // JS specific, because we have no pointers
  21294. /* copy state to local variables */
  21295. state = strm.state;
  21296. //here = state.here;
  21297. _in = strm.next_in;
  21298. input = strm.input;
  21299. last = _in + (strm.avail_in - 5);
  21300. _out = strm.next_out;
  21301. output = strm.output;
  21302. beg = _out - (start - strm.avail_out);
  21303. end = _out + (strm.avail_out - 257);
  21304. //#ifdef INFLATE_STRICT
  21305. dmax = state.dmax;
  21306. //#endif
  21307. wsize = state.wsize;
  21308. whave = state.whave;
  21309. wnext = state.wnext;
  21310. window = state.window;
  21311. hold = state.hold;
  21312. bits = state.bits;
  21313. lcode = state.lencode;
  21314. dcode = state.distcode;
  21315. lmask = (1 << state.lenbits) - 1;
  21316. dmask = (1 << state.distbits) - 1;
  21317. /* decode literals and length/distances until end-of-block or not enough
  21318. input data or output space */
  21319. top:
  21320. do {
  21321. if (bits < 15) {
  21322. hold += input[_in++] << bits;
  21323. bits += 8;
  21324. hold += input[_in++] << bits;
  21325. bits += 8;
  21326. }
  21327. here = lcode[hold & lmask];
  21328. dolen:
  21329. for (;;) { // Goto emulation
  21330. op = here >>> 24/*here.bits*/;
  21331. hold >>>= op;
  21332. bits -= op;
  21333. op = (here >>> 16) & 0xff/*here.op*/;
  21334. if (op === 0) { /* literal */
  21335. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  21336. // "inflate: literal '%c'\n" :
  21337. // "inflate: literal 0x%02x\n", here.val));
  21338. output[_out++] = here & 0xffff/*here.val*/;
  21339. }
  21340. else if (op & 16) { /* length base */
  21341. len = here & 0xffff/*here.val*/;
  21342. op &= 15; /* number of extra bits */
  21343. if (op) {
  21344. if (bits < op) {
  21345. hold += input[_in++] << bits;
  21346. bits += 8;
  21347. }
  21348. len += hold & ((1 << op) - 1);
  21349. hold >>>= op;
  21350. bits -= op;
  21351. }
  21352. //Tracevv((stderr, "inflate: length %u\n", len));
  21353. if (bits < 15) {
  21354. hold += input[_in++] << bits;
  21355. bits += 8;
  21356. hold += input[_in++] << bits;
  21357. bits += 8;
  21358. }
  21359. here = dcode[hold & dmask];
  21360. dodist:
  21361. for (;;) { // goto emulation
  21362. op = here >>> 24/*here.bits*/;
  21363. hold >>>= op;
  21364. bits -= op;
  21365. op = (here >>> 16) & 0xff/*here.op*/;
  21366. if (op & 16) { /* distance base */
  21367. dist = here & 0xffff/*here.val*/;
  21368. op &= 15; /* number of extra bits */
  21369. if (bits < op) {
  21370. hold += input[_in++] << bits;
  21371. bits += 8;
  21372. if (bits < op) {
  21373. hold += input[_in++] << bits;
  21374. bits += 8;
  21375. }
  21376. }
  21377. dist += hold & ((1 << op) - 1);
  21378. //#ifdef INFLATE_STRICT
  21379. if (dist > dmax) {
  21380. strm.msg = 'invalid distance too far back';
  21381. state.mode = BAD;
  21382. break top;
  21383. }
  21384. //#endif
  21385. hold >>>= op;
  21386. bits -= op;
  21387. //Tracevv((stderr, "inflate: distance %u\n", dist));
  21388. op = _out - beg; /* max distance in output */
  21389. if (dist > op) { /* see if copy from window */
  21390. op = dist - op; /* distance back in window */
  21391. if (op > whave) {
  21392. if (state.sane) {
  21393. strm.msg = 'invalid distance too far back';
  21394. state.mode = BAD;
  21395. break top;
  21396. }
  21397. // (!) This block is disabled in zlib defailts,
  21398. // don't enable it for binary compatibility
  21399. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  21400. // if (len <= op - whave) {
  21401. // do {
  21402. // output[_out++] = 0;
  21403. // } while (--len);
  21404. // continue top;
  21405. // }
  21406. // len -= op - whave;
  21407. // do {
  21408. // output[_out++] = 0;
  21409. // } while (--op > whave);
  21410. // if (op === 0) {
  21411. // from = _out - dist;
  21412. // do {
  21413. // output[_out++] = output[from++];
  21414. // } while (--len);
  21415. // continue top;
  21416. // }
  21417. //#endif
  21418. }
  21419. from = 0; // window index
  21420. from_source = window;
  21421. if (wnext === 0) { /* very common case */
  21422. from += wsize - op;
  21423. if (op < len) { /* some from window */
  21424. len -= op;
  21425. do {
  21426. output[_out++] = window[from++];
  21427. } while (--op);
  21428. from = _out - dist; /* rest from output */
  21429. from_source = output;
  21430. }
  21431. }
  21432. else if (wnext < op) { /* wrap around window */
  21433. from += wsize + wnext - op;
  21434. op -= wnext;
  21435. if (op < len) { /* some from end of window */
  21436. len -= op;
  21437. do {
  21438. output[_out++] = window[from++];
  21439. } while (--op);
  21440. from = 0;
  21441. if (wnext < len) { /* some from start of window */
  21442. op = wnext;
  21443. len -= op;
  21444. do {
  21445. output[_out++] = window[from++];
  21446. } while (--op);
  21447. from = _out - dist; /* rest from output */
  21448. from_source = output;
  21449. }
  21450. }
  21451. }
  21452. else { /* contiguous in window */
  21453. from += wnext - op;
  21454. if (op < len) { /* some from window */
  21455. len -= op;
  21456. do {
  21457. output[_out++] = window[from++];
  21458. } while (--op);
  21459. from = _out - dist; /* rest from output */
  21460. from_source = output;
  21461. }
  21462. }
  21463. while (len > 2) {
  21464. output[_out++] = from_source[from++];
  21465. output[_out++] = from_source[from++];
  21466. output[_out++] = from_source[from++];
  21467. len -= 3;
  21468. }
  21469. if (len) {
  21470. output[_out++] = from_source[from++];
  21471. if (len > 1) {
  21472. output[_out++] = from_source[from++];
  21473. }
  21474. }
  21475. }
  21476. else {
  21477. from = _out - dist; /* copy direct from output */
  21478. do { /* minimum length is three */
  21479. output[_out++] = output[from++];
  21480. output[_out++] = output[from++];
  21481. output[_out++] = output[from++];
  21482. len -= 3;
  21483. } while (len > 2);
  21484. if (len) {
  21485. output[_out++] = output[from++];
  21486. if (len > 1) {
  21487. output[_out++] = output[from++];
  21488. }
  21489. }
  21490. }
  21491. }
  21492. else if ((op & 64) === 0) { /* 2nd level distance code */
  21493. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  21494. continue dodist;
  21495. }
  21496. else {
  21497. strm.msg = 'invalid distance code';
  21498. state.mode = BAD;
  21499. break top;
  21500. }
  21501. break; // need to emulate goto via "continue"
  21502. }
  21503. }
  21504. else if ((op & 64) === 0) { /* 2nd level length code */
  21505. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  21506. continue dolen;
  21507. }
  21508. else if (op & 32) { /* end-of-block */
  21509. //Tracevv((stderr, "inflate: end of block\n"));
  21510. state.mode = TYPE;
  21511. break top;
  21512. }
  21513. else {
  21514. strm.msg = 'invalid literal/length code';
  21515. state.mode = BAD;
  21516. break top;
  21517. }
  21518. break; // need to emulate goto via "continue"
  21519. }
  21520. } while (_in < last && _out < end);
  21521. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  21522. len = bits >> 3;
  21523. _in -= len;
  21524. bits -= len << 3;
  21525. hold &= (1 << bits) - 1;
  21526. /* update state and return */
  21527. strm.next_in = _in;
  21528. strm.next_out = _out;
  21529. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  21530. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  21531. state.hold = hold;
  21532. state.bits = bits;
  21533. return;
  21534. };
  21535. },{}],75:[function(require,module,exports){
  21536. 'use strict';
  21537. var utils = require('../utils/common');
  21538. var adler32 = require('./adler32');
  21539. var crc32 = require('./crc32');
  21540. var inflate_fast = require('./inffast');
  21541. var inflate_table = require('./inftrees');
  21542. var CODES = 0;
  21543. var LENS = 1;
  21544. var DISTS = 2;
  21545. /* Public constants ==========================================================*/
  21546. /* ===========================================================================*/
  21547. /* Allowed flush values; see deflate() and inflate() below for details */
  21548. //var Z_NO_FLUSH = 0;
  21549. //var Z_PARTIAL_FLUSH = 1;
  21550. //var Z_SYNC_FLUSH = 2;
  21551. //var Z_FULL_FLUSH = 3;
  21552. var Z_FINISH = 4;
  21553. var Z_BLOCK = 5;
  21554. var Z_TREES = 6;
  21555. /* Return codes for the compression/decompression functions. Negative values
  21556. * are errors, positive values are used for special but normal events.
  21557. */
  21558. var Z_OK = 0;
  21559. var Z_STREAM_END = 1;
  21560. var Z_NEED_DICT = 2;
  21561. //var Z_ERRNO = -1;
  21562. var Z_STREAM_ERROR = -2;
  21563. var Z_DATA_ERROR = -3;
  21564. var Z_MEM_ERROR = -4;
  21565. var Z_BUF_ERROR = -5;
  21566. //var Z_VERSION_ERROR = -6;
  21567. /* The deflate compression method */
  21568. var Z_DEFLATED = 8;
  21569. /* STATES ====================================================================*/
  21570. /* ===========================================================================*/
  21571. var HEAD = 1; /* i: waiting for magic header */
  21572. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  21573. var TIME = 3; /* i: waiting for modification time (gzip) */
  21574. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  21575. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  21576. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  21577. var NAME = 7; /* i: waiting for end of file name (gzip) */
  21578. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  21579. var HCRC = 9; /* i: waiting for header crc (gzip) */
  21580. var DICTID = 10; /* i: waiting for dictionary check value */
  21581. var DICT = 11; /* waiting for inflateSetDictionary() call */
  21582. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  21583. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  21584. var STORED = 14; /* i: waiting for stored size (length and complement) */
  21585. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  21586. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  21587. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  21588. var LENLENS = 18; /* i: waiting for code length code lengths */
  21589. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  21590. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  21591. var LEN = 21; /* i: waiting for length/lit/eob code */
  21592. var LENEXT = 22; /* i: waiting for length extra bits */
  21593. var DIST = 23; /* i: waiting for distance code */
  21594. var DISTEXT = 24; /* i: waiting for distance extra bits */
  21595. var MATCH = 25; /* o: waiting for output space to copy string */
  21596. var LIT = 26; /* o: waiting for output space to write literal */
  21597. var CHECK = 27; /* i: waiting for 32-bit check value */
  21598. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  21599. var DONE = 29; /* finished check, done -- remain here until reset */
  21600. var BAD = 30; /* got a data error -- remain here until reset */
  21601. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  21602. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  21603. /* ===========================================================================*/
  21604. var ENOUGH_LENS = 852;
  21605. var ENOUGH_DISTS = 592;
  21606. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  21607. var MAX_WBITS = 15;
  21608. /* 32K LZ77 window */
  21609. var DEF_WBITS = MAX_WBITS;
  21610. function ZSWAP32(q) {
  21611. return (((q >>> 24) & 0xff) +
  21612. ((q >>> 8) & 0xff00) +
  21613. ((q & 0xff00) << 8) +
  21614. ((q & 0xff) << 24));
  21615. }
  21616. function InflateState() {
  21617. this.mode = 0; /* current inflate mode */
  21618. this.last = false; /* true if processing last block */
  21619. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  21620. this.havedict = false; /* true if dictionary provided */
  21621. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  21622. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  21623. this.check = 0; /* protected copy of check value */
  21624. this.total = 0; /* protected copy of output count */
  21625. // TODO: may be {}
  21626. this.head = null; /* where to save gzip header information */
  21627. /* sliding window */
  21628. this.wbits = 0; /* log base 2 of requested window size */
  21629. this.wsize = 0; /* window size or zero if not using window */
  21630. this.whave = 0; /* valid bytes in the window */
  21631. this.wnext = 0; /* window write index */
  21632. this.window = null; /* allocated sliding window, if needed */
  21633. /* bit accumulator */
  21634. this.hold = 0; /* input bit accumulator */
  21635. this.bits = 0; /* number of bits in "in" */
  21636. /* for string and stored block copying */
  21637. this.length = 0; /* literal or length of data to copy */
  21638. this.offset = 0; /* distance back to copy string from */
  21639. /* for table and code decoding */
  21640. this.extra = 0; /* extra bits needed */
  21641. /* fixed and dynamic code tables */
  21642. this.lencode = null; /* starting table for length/literal codes */
  21643. this.distcode = null; /* starting table for distance codes */
  21644. this.lenbits = 0; /* index bits for lencode */
  21645. this.distbits = 0; /* index bits for distcode */
  21646. /* dynamic table building */
  21647. this.ncode = 0; /* number of code length code lengths */
  21648. this.nlen = 0; /* number of length code lengths */
  21649. this.ndist = 0; /* number of distance code lengths */
  21650. this.have = 0; /* number of code lengths in lens[] */
  21651. this.next = null; /* next available space in codes[] */
  21652. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  21653. this.work = new utils.Buf16(288); /* work area for code table building */
  21654. /*
  21655. because we don't have pointers in js, we use lencode and distcode directly
  21656. as buffers so we don't need codes
  21657. */
  21658. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  21659. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  21660. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  21661. this.sane = 0; /* if false, allow invalid distance too far */
  21662. this.back = 0; /* bits back of last unprocessed length/lit */
  21663. this.was = 0; /* initial length of match */
  21664. }
  21665. function inflateResetKeep(strm) {
  21666. var state;
  21667. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21668. state = strm.state;
  21669. strm.total_in = strm.total_out = state.total = 0;
  21670. strm.msg = ''; /*Z_NULL*/
  21671. if (state.wrap) { /* to support ill-conceived Java test suite */
  21672. strm.adler = state.wrap & 1;
  21673. }
  21674. state.mode = HEAD;
  21675. state.last = 0;
  21676. state.havedict = 0;
  21677. state.dmax = 32768;
  21678. state.head = null/*Z_NULL*/;
  21679. state.hold = 0;
  21680. state.bits = 0;
  21681. //state.lencode = state.distcode = state.next = state.codes;
  21682. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  21683. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  21684. state.sane = 1;
  21685. state.back = -1;
  21686. //Tracev((stderr, "inflate: reset\n"));
  21687. return Z_OK;
  21688. }
  21689. function inflateReset(strm) {
  21690. var state;
  21691. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21692. state = strm.state;
  21693. state.wsize = 0;
  21694. state.whave = 0;
  21695. state.wnext = 0;
  21696. return inflateResetKeep(strm);
  21697. }
  21698. function inflateReset2(strm, windowBits) {
  21699. var wrap;
  21700. var state;
  21701. /* get the state */
  21702. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21703. state = strm.state;
  21704. /* extract wrap request from windowBits parameter */
  21705. if (windowBits < 0) {
  21706. wrap = 0;
  21707. windowBits = -windowBits;
  21708. }
  21709. else {
  21710. wrap = (windowBits >> 4) + 1;
  21711. if (windowBits < 48) {
  21712. windowBits &= 15;
  21713. }
  21714. }
  21715. /* set number of window bits, free window if different */
  21716. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  21717. return Z_STREAM_ERROR;
  21718. }
  21719. if (state.window !== null && state.wbits !== windowBits) {
  21720. state.window = null;
  21721. }
  21722. /* update state and reset the rest of it */
  21723. state.wrap = wrap;
  21724. state.wbits = windowBits;
  21725. return inflateReset(strm);
  21726. }
  21727. function inflateInit2(strm, windowBits) {
  21728. var ret;
  21729. var state;
  21730. if (!strm) { return Z_STREAM_ERROR; }
  21731. //strm.msg = Z_NULL; /* in case we return an error */
  21732. state = new InflateState();
  21733. //if (state === Z_NULL) return Z_MEM_ERROR;
  21734. //Tracev((stderr, "inflate: allocated\n"));
  21735. strm.state = state;
  21736. state.window = null/*Z_NULL*/;
  21737. ret = inflateReset2(strm, windowBits);
  21738. if (ret !== Z_OK) {
  21739. strm.state = null/*Z_NULL*/;
  21740. }
  21741. return ret;
  21742. }
  21743. function inflateInit(strm) {
  21744. return inflateInit2(strm, DEF_WBITS);
  21745. }
  21746. /*
  21747. Return state with length and distance decoding tables and index sizes set to
  21748. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  21749. If BUILDFIXED is defined, then instead this routine builds the tables the
  21750. first time it's called, and returns those tables the first time and
  21751. thereafter. This reduces the size of the code by about 2K bytes, in
  21752. exchange for a little execution time. However, BUILDFIXED should not be
  21753. used for threaded applications, since the rewriting of the tables and virgin
  21754. may not be thread-safe.
  21755. */
  21756. var virgin = true;
  21757. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  21758. function fixedtables(state) {
  21759. /* build fixed huffman tables if first call (may not be thread safe) */
  21760. if (virgin) {
  21761. var sym;
  21762. lenfix = new utils.Buf32(512);
  21763. distfix = new utils.Buf32(32);
  21764. /* literal/length table */
  21765. sym = 0;
  21766. while (sym < 144) { state.lens[sym++] = 8; }
  21767. while (sym < 256) { state.lens[sym++] = 9; }
  21768. while (sym < 280) { state.lens[sym++] = 7; }
  21769. while (sym < 288) { state.lens[sym++] = 8; }
  21770. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  21771. /* distance table */
  21772. sym = 0;
  21773. while (sym < 32) { state.lens[sym++] = 5; }
  21774. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  21775. /* do this just once */
  21776. virgin = false;
  21777. }
  21778. state.lencode = lenfix;
  21779. state.lenbits = 9;
  21780. state.distcode = distfix;
  21781. state.distbits = 5;
  21782. }
  21783. /*
  21784. Update the window with the last wsize (normally 32K) bytes written before
  21785. returning. If window does not exist yet, create it. This is only called
  21786. when a window is already in use, or when output has been written during this
  21787. inflate call, but the end of the deflate stream has not been reached yet.
  21788. It is also called to create a window for dictionary data when a dictionary
  21789. is loaded.
  21790. Providing output buffers larger than 32K to inflate() should provide a speed
  21791. advantage, since only the last 32K of output is copied to the sliding window
  21792. upon return from inflate(), and since all distances after the first 32K of
  21793. output will fall in the output data, making match copies simpler and faster.
  21794. The advantage may be dependent on the size of the processor's data caches.
  21795. */
  21796. function updatewindow(strm, src, end, copy) {
  21797. var dist;
  21798. var state = strm.state;
  21799. /* if it hasn't been done already, allocate space for the window */
  21800. if (state.window === null) {
  21801. state.wsize = 1 << state.wbits;
  21802. state.wnext = 0;
  21803. state.whave = 0;
  21804. state.window = new utils.Buf8(state.wsize);
  21805. }
  21806. /* copy state->wsize or less output bytes into the circular window */
  21807. if (copy >= state.wsize) {
  21808. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  21809. state.wnext = 0;
  21810. state.whave = state.wsize;
  21811. }
  21812. else {
  21813. dist = state.wsize - state.wnext;
  21814. if (dist > copy) {
  21815. dist = copy;
  21816. }
  21817. //zmemcpy(state->window + state->wnext, end - copy, dist);
  21818. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  21819. copy -= dist;
  21820. if (copy) {
  21821. //zmemcpy(state->window, end - copy, copy);
  21822. utils.arraySet(state.window,src, end - copy, copy, 0);
  21823. state.wnext = copy;
  21824. state.whave = state.wsize;
  21825. }
  21826. else {
  21827. state.wnext += dist;
  21828. if (state.wnext === state.wsize) { state.wnext = 0; }
  21829. if (state.whave < state.wsize) { state.whave += dist; }
  21830. }
  21831. }
  21832. return 0;
  21833. }
  21834. function inflate(strm, flush) {
  21835. var state;
  21836. var input, output; // input/output buffers
  21837. var next; /* next input INDEX */
  21838. var put; /* next output INDEX */
  21839. var have, left; /* available input and output */
  21840. var hold; /* bit buffer */
  21841. var bits; /* bits in bit buffer */
  21842. var _in, _out; /* save starting available input and output */
  21843. var copy; /* number of stored or match bytes to copy */
  21844. var from; /* where to copy match bytes from */
  21845. var from_source;
  21846. var here = 0; /* current decoding table entry */
  21847. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  21848. //var last; /* parent table entry */
  21849. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  21850. var len; /* length to copy for repeats, bits to drop */
  21851. var ret; /* return code */
  21852. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  21853. var opts;
  21854. var n; // temporary var for NEED_BITS
  21855. var order = /* permutation of code lengths */
  21856. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  21857. if (!strm || !strm.state || !strm.output ||
  21858. (!strm.input && strm.avail_in !== 0)) {
  21859. return Z_STREAM_ERROR;
  21860. }
  21861. state = strm.state;
  21862. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  21863. //--- LOAD() ---
  21864. put = strm.next_out;
  21865. output = strm.output;
  21866. left = strm.avail_out;
  21867. next = strm.next_in;
  21868. input = strm.input;
  21869. have = strm.avail_in;
  21870. hold = state.hold;
  21871. bits = state.bits;
  21872. //---
  21873. _in = have;
  21874. _out = left;
  21875. ret = Z_OK;
  21876. inf_leave: // goto emulation
  21877. for (;;) {
  21878. switch (state.mode) {
  21879. case HEAD:
  21880. if (state.wrap === 0) {
  21881. state.mode = TYPEDO;
  21882. break;
  21883. }
  21884. //=== NEEDBITS(16);
  21885. while (bits < 16) {
  21886. if (have === 0) { break inf_leave; }
  21887. have--;
  21888. hold += input[next++] << bits;
  21889. bits += 8;
  21890. }
  21891. //===//
  21892. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  21893. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  21894. //=== CRC2(state.check, hold);
  21895. hbuf[0] = hold & 0xff;
  21896. hbuf[1] = (hold >>> 8) & 0xff;
  21897. state.check = crc32(state.check, hbuf, 2, 0);
  21898. //===//
  21899. //=== INITBITS();
  21900. hold = 0;
  21901. bits = 0;
  21902. //===//
  21903. state.mode = FLAGS;
  21904. break;
  21905. }
  21906. state.flags = 0; /* expect zlib header */
  21907. if (state.head) {
  21908. state.head.done = false;
  21909. }
  21910. if (!(state.wrap & 1) || /* check if zlib header allowed */
  21911. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  21912. strm.msg = 'incorrect header check';
  21913. state.mode = BAD;
  21914. break;
  21915. }
  21916. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  21917. strm.msg = 'unknown compression method';
  21918. state.mode = BAD;
  21919. break;
  21920. }
  21921. //--- DROPBITS(4) ---//
  21922. hold >>>= 4;
  21923. bits -= 4;
  21924. //---//
  21925. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  21926. if (state.wbits === 0) {
  21927. state.wbits = len;
  21928. }
  21929. else if (len > state.wbits) {
  21930. strm.msg = 'invalid window size';
  21931. state.mode = BAD;
  21932. break;
  21933. }
  21934. state.dmax = 1 << len;
  21935. //Tracev((stderr, "inflate: zlib header ok\n"));
  21936. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  21937. state.mode = hold & 0x200 ? DICTID : TYPE;
  21938. //=== INITBITS();
  21939. hold = 0;
  21940. bits = 0;
  21941. //===//
  21942. break;
  21943. case FLAGS:
  21944. //=== NEEDBITS(16); */
  21945. while (bits < 16) {
  21946. if (have === 0) { break inf_leave; }
  21947. have--;
  21948. hold += input[next++] << bits;
  21949. bits += 8;
  21950. }
  21951. //===//
  21952. state.flags = hold;
  21953. if ((state.flags & 0xff) !== Z_DEFLATED) {
  21954. strm.msg = 'unknown compression method';
  21955. state.mode = BAD;
  21956. break;
  21957. }
  21958. if (state.flags & 0xe000) {
  21959. strm.msg = 'unknown header flags set';
  21960. state.mode = BAD;
  21961. break;
  21962. }
  21963. if (state.head) {
  21964. state.head.text = ((hold >> 8) & 1);
  21965. }
  21966. if (state.flags & 0x0200) {
  21967. //=== CRC2(state.check, hold);
  21968. hbuf[0] = hold & 0xff;
  21969. hbuf[1] = (hold >>> 8) & 0xff;
  21970. state.check = crc32(state.check, hbuf, 2, 0);
  21971. //===//
  21972. }
  21973. //=== INITBITS();
  21974. hold = 0;
  21975. bits = 0;
  21976. //===//
  21977. state.mode = TIME;
  21978. /* falls through */
  21979. case TIME:
  21980. //=== NEEDBITS(32); */
  21981. while (bits < 32) {
  21982. if (have === 0) { break inf_leave; }
  21983. have--;
  21984. hold += input[next++] << bits;
  21985. bits += 8;
  21986. }
  21987. //===//
  21988. if (state.head) {
  21989. state.head.time = hold;
  21990. }
  21991. if (state.flags & 0x0200) {
  21992. //=== CRC4(state.check, hold)
  21993. hbuf[0] = hold & 0xff;
  21994. hbuf[1] = (hold >>> 8) & 0xff;
  21995. hbuf[2] = (hold >>> 16) & 0xff;
  21996. hbuf[3] = (hold >>> 24) & 0xff;
  21997. state.check = crc32(state.check, hbuf, 4, 0);
  21998. //===
  21999. }
  22000. //=== INITBITS();
  22001. hold = 0;
  22002. bits = 0;
  22003. //===//
  22004. state.mode = OS;
  22005. /* falls through */
  22006. case OS:
  22007. //=== NEEDBITS(16); */
  22008. while (bits < 16) {
  22009. if (have === 0) { break inf_leave; }
  22010. have--;
  22011. hold += input[next++] << bits;
  22012. bits += 8;
  22013. }
  22014. //===//
  22015. if (state.head) {
  22016. state.head.xflags = (hold & 0xff);
  22017. state.head.os = (hold >> 8);
  22018. }
  22019. if (state.flags & 0x0200) {
  22020. //=== CRC2(state.check, hold);
  22021. hbuf[0] = hold & 0xff;
  22022. hbuf[1] = (hold >>> 8) & 0xff;
  22023. state.check = crc32(state.check, hbuf, 2, 0);
  22024. //===//
  22025. }
  22026. //=== INITBITS();
  22027. hold = 0;
  22028. bits = 0;
  22029. //===//
  22030. state.mode = EXLEN;
  22031. /* falls through */
  22032. case EXLEN:
  22033. if (state.flags & 0x0400) {
  22034. //=== NEEDBITS(16); */
  22035. while (bits < 16) {
  22036. if (have === 0) { break inf_leave; }
  22037. have--;
  22038. hold += input[next++] << bits;
  22039. bits += 8;
  22040. }
  22041. //===//
  22042. state.length = hold;
  22043. if (state.head) {
  22044. state.head.extra_len = hold;
  22045. }
  22046. if (state.flags & 0x0200) {
  22047. //=== CRC2(state.check, hold);
  22048. hbuf[0] = hold & 0xff;
  22049. hbuf[1] = (hold >>> 8) & 0xff;
  22050. state.check = crc32(state.check, hbuf, 2, 0);
  22051. //===//
  22052. }
  22053. //=== INITBITS();
  22054. hold = 0;
  22055. bits = 0;
  22056. //===//
  22057. }
  22058. else if (state.head) {
  22059. state.head.extra = null/*Z_NULL*/;
  22060. }
  22061. state.mode = EXTRA;
  22062. /* falls through */
  22063. case EXTRA:
  22064. if (state.flags & 0x0400) {
  22065. copy = state.length;
  22066. if (copy > have) { copy = have; }
  22067. if (copy) {
  22068. if (state.head) {
  22069. len = state.head.extra_len - state.length;
  22070. if (!state.head.extra) {
  22071. // Use untyped array for more conveniend processing later
  22072. state.head.extra = new Array(state.head.extra_len);
  22073. }
  22074. utils.arraySet(
  22075. state.head.extra,
  22076. input,
  22077. next,
  22078. // extra field is limited to 65536 bytes
  22079. // - no need for additional size check
  22080. copy,
  22081. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  22082. len
  22083. );
  22084. //zmemcpy(state.head.extra + len, next,
  22085. // len + copy > state.head.extra_max ?
  22086. // state.head.extra_max - len : copy);
  22087. }
  22088. if (state.flags & 0x0200) {
  22089. state.check = crc32(state.check, input, copy, next);
  22090. }
  22091. have -= copy;
  22092. next += copy;
  22093. state.length -= copy;
  22094. }
  22095. if (state.length) { break inf_leave; }
  22096. }
  22097. state.length = 0;
  22098. state.mode = NAME;
  22099. /* falls through */
  22100. case NAME:
  22101. if (state.flags & 0x0800) {
  22102. if (have === 0) { break inf_leave; }
  22103. copy = 0;
  22104. do {
  22105. // TODO: 2 or 1 bytes?
  22106. len = input[next + copy++];
  22107. /* use constant limit because in js we should not preallocate memory */
  22108. if (state.head && len &&
  22109. (state.length < 65536 /*state.head.name_max*/)) {
  22110. state.head.name += String.fromCharCode(len);
  22111. }
  22112. } while (len && copy < have);
  22113. if (state.flags & 0x0200) {
  22114. state.check = crc32(state.check, input, copy, next);
  22115. }
  22116. have -= copy;
  22117. next += copy;
  22118. if (len) { break inf_leave; }
  22119. }
  22120. else if (state.head) {
  22121. state.head.name = null;
  22122. }
  22123. state.length = 0;
  22124. state.mode = COMMENT;
  22125. /* falls through */
  22126. case COMMENT:
  22127. if (state.flags & 0x1000) {
  22128. if (have === 0) { break inf_leave; }
  22129. copy = 0;
  22130. do {
  22131. len = input[next + copy++];
  22132. /* use constant limit because in js we should not preallocate memory */
  22133. if (state.head && len &&
  22134. (state.length < 65536 /*state.head.comm_max*/)) {
  22135. state.head.comment += String.fromCharCode(len);
  22136. }
  22137. } while (len && copy < have);
  22138. if (state.flags & 0x0200) {
  22139. state.check = crc32(state.check, input, copy, next);
  22140. }
  22141. have -= copy;
  22142. next += copy;
  22143. if (len) { break inf_leave; }
  22144. }
  22145. else if (state.head) {
  22146. state.head.comment = null;
  22147. }
  22148. state.mode = HCRC;
  22149. /* falls through */
  22150. case HCRC:
  22151. if (state.flags & 0x0200) {
  22152. //=== NEEDBITS(16); */
  22153. while (bits < 16) {
  22154. if (have === 0) { break inf_leave; }
  22155. have--;
  22156. hold += input[next++] << bits;
  22157. bits += 8;
  22158. }
  22159. //===//
  22160. if (hold !== (state.check & 0xffff)) {
  22161. strm.msg = 'header crc mismatch';
  22162. state.mode = BAD;
  22163. break;
  22164. }
  22165. //=== INITBITS();
  22166. hold = 0;
  22167. bits = 0;
  22168. //===//
  22169. }
  22170. if (state.head) {
  22171. state.head.hcrc = ((state.flags >> 9) & 1);
  22172. state.head.done = true;
  22173. }
  22174. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  22175. state.mode = TYPE;
  22176. break;
  22177. case DICTID:
  22178. //=== NEEDBITS(32); */
  22179. while (bits < 32) {
  22180. if (have === 0) { break inf_leave; }
  22181. have--;
  22182. hold += input[next++] << bits;
  22183. bits += 8;
  22184. }
  22185. //===//
  22186. strm.adler = state.check = ZSWAP32(hold);
  22187. //=== INITBITS();
  22188. hold = 0;
  22189. bits = 0;
  22190. //===//
  22191. state.mode = DICT;
  22192. /* falls through */
  22193. case DICT:
  22194. if (state.havedict === 0) {
  22195. //--- RESTORE() ---
  22196. strm.next_out = put;
  22197. strm.avail_out = left;
  22198. strm.next_in = next;
  22199. strm.avail_in = have;
  22200. state.hold = hold;
  22201. state.bits = bits;
  22202. //---
  22203. return Z_NEED_DICT;
  22204. }
  22205. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  22206. state.mode = TYPE;
  22207. /* falls through */
  22208. case TYPE:
  22209. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  22210. /* falls through */
  22211. case TYPEDO:
  22212. if (state.last) {
  22213. //--- BYTEBITS() ---//
  22214. hold >>>= bits & 7;
  22215. bits -= bits & 7;
  22216. //---//
  22217. state.mode = CHECK;
  22218. break;
  22219. }
  22220. //=== NEEDBITS(3); */
  22221. while (bits < 3) {
  22222. if (have === 0) { break inf_leave; }
  22223. have--;
  22224. hold += input[next++] << bits;
  22225. bits += 8;
  22226. }
  22227. //===//
  22228. state.last = (hold & 0x01)/*BITS(1)*/;
  22229. //--- DROPBITS(1) ---//
  22230. hold >>>= 1;
  22231. bits -= 1;
  22232. //---//
  22233. switch ((hold & 0x03)/*BITS(2)*/) {
  22234. case 0: /* stored block */
  22235. //Tracev((stderr, "inflate: stored block%s\n",
  22236. // state.last ? " (last)" : ""));
  22237. state.mode = STORED;
  22238. break;
  22239. case 1: /* fixed block */
  22240. fixedtables(state);
  22241. //Tracev((stderr, "inflate: fixed codes block%s\n",
  22242. // state.last ? " (last)" : ""));
  22243. state.mode = LEN_; /* decode codes */
  22244. if (flush === Z_TREES) {
  22245. //--- DROPBITS(2) ---//
  22246. hold >>>= 2;
  22247. bits -= 2;
  22248. //---//
  22249. break inf_leave;
  22250. }
  22251. break;
  22252. case 2: /* dynamic block */
  22253. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  22254. // state.last ? " (last)" : ""));
  22255. state.mode = TABLE;
  22256. break;
  22257. case 3:
  22258. strm.msg = 'invalid block type';
  22259. state.mode = BAD;
  22260. }
  22261. //--- DROPBITS(2) ---//
  22262. hold >>>= 2;
  22263. bits -= 2;
  22264. //---//
  22265. break;
  22266. case STORED:
  22267. //--- BYTEBITS() ---// /* go to byte boundary */
  22268. hold >>>= bits & 7;
  22269. bits -= bits & 7;
  22270. //---//
  22271. //=== NEEDBITS(32); */
  22272. while (bits < 32) {
  22273. if (have === 0) { break inf_leave; }
  22274. have--;
  22275. hold += input[next++] << bits;
  22276. bits += 8;
  22277. }
  22278. //===//
  22279. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  22280. strm.msg = 'invalid stored block lengths';
  22281. state.mode = BAD;
  22282. break;
  22283. }
  22284. state.length = hold & 0xffff;
  22285. //Tracev((stderr, "inflate: stored length %u\n",
  22286. // state.length));
  22287. //=== INITBITS();
  22288. hold = 0;
  22289. bits = 0;
  22290. //===//
  22291. state.mode = COPY_;
  22292. if (flush === Z_TREES) { break inf_leave; }
  22293. /* falls through */
  22294. case COPY_:
  22295. state.mode = COPY;
  22296. /* falls through */
  22297. case COPY:
  22298. copy = state.length;
  22299. if (copy) {
  22300. if (copy > have) { copy = have; }
  22301. if (copy > left) { copy = left; }
  22302. if (copy === 0) { break inf_leave; }
  22303. //--- zmemcpy(put, next, copy); ---
  22304. utils.arraySet(output, input, next, copy, put);
  22305. //---//
  22306. have -= copy;
  22307. next += copy;
  22308. left -= copy;
  22309. put += copy;
  22310. state.length -= copy;
  22311. break;
  22312. }
  22313. //Tracev((stderr, "inflate: stored end\n"));
  22314. state.mode = TYPE;
  22315. break;
  22316. case TABLE:
  22317. //=== NEEDBITS(14); */
  22318. while (bits < 14) {
  22319. if (have === 0) { break inf_leave; }
  22320. have--;
  22321. hold += input[next++] << bits;
  22322. bits += 8;
  22323. }
  22324. //===//
  22325. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  22326. //--- DROPBITS(5) ---//
  22327. hold >>>= 5;
  22328. bits -= 5;
  22329. //---//
  22330. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  22331. //--- DROPBITS(5) ---//
  22332. hold >>>= 5;
  22333. bits -= 5;
  22334. //---//
  22335. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  22336. //--- DROPBITS(4) ---//
  22337. hold >>>= 4;
  22338. bits -= 4;
  22339. //---//
  22340. //#ifndef PKZIP_BUG_WORKAROUND
  22341. if (state.nlen > 286 || state.ndist > 30) {
  22342. strm.msg = 'too many length or distance symbols';
  22343. state.mode = BAD;
  22344. break;
  22345. }
  22346. //#endif
  22347. //Tracev((stderr, "inflate: table sizes ok\n"));
  22348. state.have = 0;
  22349. state.mode = LENLENS;
  22350. /* falls through */
  22351. case LENLENS:
  22352. while (state.have < state.ncode) {
  22353. //=== NEEDBITS(3);
  22354. while (bits < 3) {
  22355. if (have === 0) { break inf_leave; }
  22356. have--;
  22357. hold += input[next++] << bits;
  22358. bits += 8;
  22359. }
  22360. //===//
  22361. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  22362. //--- DROPBITS(3) ---//
  22363. hold >>>= 3;
  22364. bits -= 3;
  22365. //---//
  22366. }
  22367. while (state.have < 19) {
  22368. state.lens[order[state.have++]] = 0;
  22369. }
  22370. // We have separate tables & no pointers. 2 commented lines below not needed.
  22371. //state.next = state.codes;
  22372. //state.lencode = state.next;
  22373. // Switch to use dynamic table
  22374. state.lencode = state.lendyn;
  22375. state.lenbits = 7;
  22376. opts = {bits: state.lenbits};
  22377. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  22378. state.lenbits = opts.bits;
  22379. if (ret) {
  22380. strm.msg = 'invalid code lengths set';
  22381. state.mode = BAD;
  22382. break;
  22383. }
  22384. //Tracev((stderr, "inflate: code lengths ok\n"));
  22385. state.have = 0;
  22386. state.mode = CODELENS;
  22387. /* falls through */
  22388. case CODELENS:
  22389. while (state.have < state.nlen + state.ndist) {
  22390. for (;;) {
  22391. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  22392. here_bits = here >>> 24;
  22393. here_op = (here >>> 16) & 0xff;
  22394. here_val = here & 0xffff;
  22395. if ((here_bits) <= bits) { break; }
  22396. //--- PULLBYTE() ---//
  22397. if (have === 0) { break inf_leave; }
  22398. have--;
  22399. hold += input[next++] << bits;
  22400. bits += 8;
  22401. //---//
  22402. }
  22403. if (here_val < 16) {
  22404. //--- DROPBITS(here.bits) ---//
  22405. hold >>>= here_bits;
  22406. bits -= here_bits;
  22407. //---//
  22408. state.lens[state.have++] = here_val;
  22409. }
  22410. else {
  22411. if (here_val === 16) {
  22412. //=== NEEDBITS(here.bits + 2);
  22413. n = here_bits + 2;
  22414. while (bits < n) {
  22415. if (have === 0) { break inf_leave; }
  22416. have--;
  22417. hold += input[next++] << bits;
  22418. bits += 8;
  22419. }
  22420. //===//
  22421. //--- DROPBITS(here.bits) ---//
  22422. hold >>>= here_bits;
  22423. bits -= here_bits;
  22424. //---//
  22425. if (state.have === 0) {
  22426. strm.msg = 'invalid bit length repeat';
  22427. state.mode = BAD;
  22428. break;
  22429. }
  22430. len = state.lens[state.have - 1];
  22431. copy = 3 + (hold & 0x03);//BITS(2);
  22432. //--- DROPBITS(2) ---//
  22433. hold >>>= 2;
  22434. bits -= 2;
  22435. //---//
  22436. }
  22437. else if (here_val === 17) {
  22438. //=== NEEDBITS(here.bits + 3);
  22439. n = here_bits + 3;
  22440. while (bits < n) {
  22441. if (have === 0) { break inf_leave; }
  22442. have--;
  22443. hold += input[next++] << bits;
  22444. bits += 8;
  22445. }
  22446. //===//
  22447. //--- DROPBITS(here.bits) ---//
  22448. hold >>>= here_bits;
  22449. bits -= here_bits;
  22450. //---//
  22451. len = 0;
  22452. copy = 3 + (hold & 0x07);//BITS(3);
  22453. //--- DROPBITS(3) ---//
  22454. hold >>>= 3;
  22455. bits -= 3;
  22456. //---//
  22457. }
  22458. else {
  22459. //=== NEEDBITS(here.bits + 7);
  22460. n = here_bits + 7;
  22461. while (bits < n) {
  22462. if (have === 0) { break inf_leave; }
  22463. have--;
  22464. hold += input[next++] << bits;
  22465. bits += 8;
  22466. }
  22467. //===//
  22468. //--- DROPBITS(here.bits) ---//
  22469. hold >>>= here_bits;
  22470. bits -= here_bits;
  22471. //---//
  22472. len = 0;
  22473. copy = 11 + (hold & 0x7f);//BITS(7);
  22474. //--- DROPBITS(7) ---//
  22475. hold >>>= 7;
  22476. bits -= 7;
  22477. //---//
  22478. }
  22479. if (state.have + copy > state.nlen + state.ndist) {
  22480. strm.msg = 'invalid bit length repeat';
  22481. state.mode = BAD;
  22482. break;
  22483. }
  22484. while (copy--) {
  22485. state.lens[state.have++] = len;
  22486. }
  22487. }
  22488. }
  22489. /* handle error breaks in while */
  22490. if (state.mode === BAD) { break; }
  22491. /* check for end-of-block code (better have one) */
  22492. if (state.lens[256] === 0) {
  22493. strm.msg = 'invalid code -- missing end-of-block';
  22494. state.mode = BAD;
  22495. break;
  22496. }
  22497. /* build code tables -- note: do not change the lenbits or distbits
  22498. values here (9 and 6) without reading the comments in inftrees.h
  22499. concerning the ENOUGH constants, which depend on those values */
  22500. state.lenbits = 9;
  22501. opts = {bits: state.lenbits};
  22502. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  22503. // We have separate tables & no pointers. 2 commented lines below not needed.
  22504. // state.next_index = opts.table_index;
  22505. state.lenbits = opts.bits;
  22506. // state.lencode = state.next;
  22507. if (ret) {
  22508. strm.msg = 'invalid literal/lengths set';
  22509. state.mode = BAD;
  22510. break;
  22511. }
  22512. state.distbits = 6;
  22513. //state.distcode.copy(state.codes);
  22514. // Switch to use dynamic table
  22515. state.distcode = state.distdyn;
  22516. opts = {bits: state.distbits};
  22517. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  22518. // We have separate tables & no pointers. 2 commented lines below not needed.
  22519. // state.next_index = opts.table_index;
  22520. state.distbits = opts.bits;
  22521. // state.distcode = state.next;
  22522. if (ret) {
  22523. strm.msg = 'invalid distances set';
  22524. state.mode = BAD;
  22525. break;
  22526. }
  22527. //Tracev((stderr, 'inflate: codes ok\n'));
  22528. state.mode = LEN_;
  22529. if (flush === Z_TREES) { break inf_leave; }
  22530. /* falls through */
  22531. case LEN_:
  22532. state.mode = LEN;
  22533. /* falls through */
  22534. case LEN:
  22535. if (have >= 6 && left >= 258) {
  22536. //--- RESTORE() ---
  22537. strm.next_out = put;
  22538. strm.avail_out = left;
  22539. strm.next_in = next;
  22540. strm.avail_in = have;
  22541. state.hold = hold;
  22542. state.bits = bits;
  22543. //---
  22544. inflate_fast(strm, _out);
  22545. //--- LOAD() ---
  22546. put = strm.next_out;
  22547. output = strm.output;
  22548. left = strm.avail_out;
  22549. next = strm.next_in;
  22550. input = strm.input;
  22551. have = strm.avail_in;
  22552. hold = state.hold;
  22553. bits = state.bits;
  22554. //---
  22555. if (state.mode === TYPE) {
  22556. state.back = -1;
  22557. }
  22558. break;
  22559. }
  22560. state.back = 0;
  22561. for (;;) {
  22562. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  22563. here_bits = here >>> 24;
  22564. here_op = (here >>> 16) & 0xff;
  22565. here_val = here & 0xffff;
  22566. if (here_bits <= bits) { break; }
  22567. //--- PULLBYTE() ---//
  22568. if (have === 0) { break inf_leave; }
  22569. have--;
  22570. hold += input[next++] << bits;
  22571. bits += 8;
  22572. //---//
  22573. }
  22574. if (here_op && (here_op & 0xf0) === 0) {
  22575. last_bits = here_bits;
  22576. last_op = here_op;
  22577. last_val = here_val;
  22578. for (;;) {
  22579. here = state.lencode[last_val +
  22580. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  22581. here_bits = here >>> 24;
  22582. here_op = (here >>> 16) & 0xff;
  22583. here_val = here & 0xffff;
  22584. if ((last_bits + here_bits) <= bits) { break; }
  22585. //--- PULLBYTE() ---//
  22586. if (have === 0) { break inf_leave; }
  22587. have--;
  22588. hold += input[next++] << bits;
  22589. bits += 8;
  22590. //---//
  22591. }
  22592. //--- DROPBITS(last.bits) ---//
  22593. hold >>>= last_bits;
  22594. bits -= last_bits;
  22595. //---//
  22596. state.back += last_bits;
  22597. }
  22598. //--- DROPBITS(here.bits) ---//
  22599. hold >>>= here_bits;
  22600. bits -= here_bits;
  22601. //---//
  22602. state.back += here_bits;
  22603. state.length = here_val;
  22604. if (here_op === 0) {
  22605. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  22606. // "inflate: literal '%c'\n" :
  22607. // "inflate: literal 0x%02x\n", here.val));
  22608. state.mode = LIT;
  22609. break;
  22610. }
  22611. if (here_op & 32) {
  22612. //Tracevv((stderr, "inflate: end of block\n"));
  22613. state.back = -1;
  22614. state.mode = TYPE;
  22615. break;
  22616. }
  22617. if (here_op & 64) {
  22618. strm.msg = 'invalid literal/length code';
  22619. state.mode = BAD;
  22620. break;
  22621. }
  22622. state.extra = here_op & 15;
  22623. state.mode = LENEXT;
  22624. /* falls through */
  22625. case LENEXT:
  22626. if (state.extra) {
  22627. //=== NEEDBITS(state.extra);
  22628. n = state.extra;
  22629. while (bits < n) {
  22630. if (have === 0) { break inf_leave; }
  22631. have--;
  22632. hold += input[next++] << bits;
  22633. bits += 8;
  22634. }
  22635. //===//
  22636. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  22637. //--- DROPBITS(state.extra) ---//
  22638. hold >>>= state.extra;
  22639. bits -= state.extra;
  22640. //---//
  22641. state.back += state.extra;
  22642. }
  22643. //Tracevv((stderr, "inflate: length %u\n", state.length));
  22644. state.was = state.length;
  22645. state.mode = DIST;
  22646. /* falls through */
  22647. case DIST:
  22648. for (;;) {
  22649. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  22650. here_bits = here >>> 24;
  22651. here_op = (here >>> 16) & 0xff;
  22652. here_val = here & 0xffff;
  22653. if ((here_bits) <= bits) { break; }
  22654. //--- PULLBYTE() ---//
  22655. if (have === 0) { break inf_leave; }
  22656. have--;
  22657. hold += input[next++] << bits;
  22658. bits += 8;
  22659. //---//
  22660. }
  22661. if ((here_op & 0xf0) === 0) {
  22662. last_bits = here_bits;
  22663. last_op = here_op;
  22664. last_val = here_val;
  22665. for (;;) {
  22666. here = state.distcode[last_val +
  22667. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  22668. here_bits = here >>> 24;
  22669. here_op = (here >>> 16) & 0xff;
  22670. here_val = here & 0xffff;
  22671. if ((last_bits + here_bits) <= bits) { break; }
  22672. //--- PULLBYTE() ---//
  22673. if (have === 0) { break inf_leave; }
  22674. have--;
  22675. hold += input[next++] << bits;
  22676. bits += 8;
  22677. //---//
  22678. }
  22679. //--- DROPBITS(last.bits) ---//
  22680. hold >>>= last_bits;
  22681. bits -= last_bits;
  22682. //---//
  22683. state.back += last_bits;
  22684. }
  22685. //--- DROPBITS(here.bits) ---//
  22686. hold >>>= here_bits;
  22687. bits -= here_bits;
  22688. //---//
  22689. state.back += here_bits;
  22690. if (here_op & 64) {
  22691. strm.msg = 'invalid distance code';
  22692. state.mode = BAD;
  22693. break;
  22694. }
  22695. state.offset = here_val;
  22696. state.extra = (here_op) & 15;
  22697. state.mode = DISTEXT;
  22698. /* falls through */
  22699. case DISTEXT:
  22700. if (state.extra) {
  22701. //=== NEEDBITS(state.extra);
  22702. n = state.extra;
  22703. while (bits < n) {
  22704. if (have === 0) { break inf_leave; }
  22705. have--;
  22706. hold += input[next++] << bits;
  22707. bits += 8;
  22708. }
  22709. //===//
  22710. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  22711. //--- DROPBITS(state.extra) ---//
  22712. hold >>>= state.extra;
  22713. bits -= state.extra;
  22714. //---//
  22715. state.back += state.extra;
  22716. }
  22717. //#ifdef INFLATE_STRICT
  22718. if (state.offset > state.dmax) {
  22719. strm.msg = 'invalid distance too far back';
  22720. state.mode = BAD;
  22721. break;
  22722. }
  22723. //#endif
  22724. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  22725. state.mode = MATCH;
  22726. /* falls through */
  22727. case MATCH:
  22728. if (left === 0) { break inf_leave; }
  22729. copy = _out - left;
  22730. if (state.offset > copy) { /* copy from window */
  22731. copy = state.offset - copy;
  22732. if (copy > state.whave) {
  22733. if (state.sane) {
  22734. strm.msg = 'invalid distance too far back';
  22735. state.mode = BAD;
  22736. break;
  22737. }
  22738. // (!) This block is disabled in zlib defailts,
  22739. // don't enable it for binary compatibility
  22740. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  22741. // Trace((stderr, "inflate.c too far\n"));
  22742. // copy -= state.whave;
  22743. // if (copy > state.length) { copy = state.length; }
  22744. // if (copy > left) { copy = left; }
  22745. // left -= copy;
  22746. // state.length -= copy;
  22747. // do {
  22748. // output[put++] = 0;
  22749. // } while (--copy);
  22750. // if (state.length === 0) { state.mode = LEN; }
  22751. // break;
  22752. //#endif
  22753. }
  22754. if (copy > state.wnext) {
  22755. copy -= state.wnext;
  22756. from = state.wsize - copy;
  22757. }
  22758. else {
  22759. from = state.wnext - copy;
  22760. }
  22761. if (copy > state.length) { copy = state.length; }
  22762. from_source = state.window;
  22763. }
  22764. else { /* copy from output */
  22765. from_source = output;
  22766. from = put - state.offset;
  22767. copy = state.length;
  22768. }
  22769. if (copy > left) { copy = left; }
  22770. left -= copy;
  22771. state.length -= copy;
  22772. do {
  22773. output[put++] = from_source[from++];
  22774. } while (--copy);
  22775. if (state.length === 0) { state.mode = LEN; }
  22776. break;
  22777. case LIT:
  22778. if (left === 0) { break inf_leave; }
  22779. output[put++] = state.length;
  22780. left--;
  22781. state.mode = LEN;
  22782. break;
  22783. case CHECK:
  22784. if (state.wrap) {
  22785. //=== NEEDBITS(32);
  22786. while (bits < 32) {
  22787. if (have === 0) { break inf_leave; }
  22788. have--;
  22789. // Use '|' insdead of '+' to make sure that result is signed
  22790. hold |= input[next++] << bits;
  22791. bits += 8;
  22792. }
  22793. //===//
  22794. _out -= left;
  22795. strm.total_out += _out;
  22796. state.total += _out;
  22797. if (_out) {
  22798. strm.adler = state.check =
  22799. /*UPDATE(state.check, put - _out, _out);*/
  22800. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  22801. }
  22802. _out = left;
  22803. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  22804. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  22805. strm.msg = 'incorrect data check';
  22806. state.mode = BAD;
  22807. break;
  22808. }
  22809. //=== INITBITS();
  22810. hold = 0;
  22811. bits = 0;
  22812. //===//
  22813. //Tracev((stderr, "inflate: check matches trailer\n"));
  22814. }
  22815. state.mode = LENGTH;
  22816. /* falls through */
  22817. case LENGTH:
  22818. if (state.wrap && state.flags) {
  22819. //=== NEEDBITS(32);
  22820. while (bits < 32) {
  22821. if (have === 0) { break inf_leave; }
  22822. have--;
  22823. hold += input[next++] << bits;
  22824. bits += 8;
  22825. }
  22826. //===//
  22827. if (hold !== (state.total & 0xffffffff)) {
  22828. strm.msg = 'incorrect length check';
  22829. state.mode = BAD;
  22830. break;
  22831. }
  22832. //=== INITBITS();
  22833. hold = 0;
  22834. bits = 0;
  22835. //===//
  22836. //Tracev((stderr, "inflate: length matches trailer\n"));
  22837. }
  22838. state.mode = DONE;
  22839. /* falls through */
  22840. case DONE:
  22841. ret = Z_STREAM_END;
  22842. break inf_leave;
  22843. case BAD:
  22844. ret = Z_DATA_ERROR;
  22845. break inf_leave;
  22846. case MEM:
  22847. return Z_MEM_ERROR;
  22848. case SYNC:
  22849. /* falls through */
  22850. default:
  22851. return Z_STREAM_ERROR;
  22852. }
  22853. }
  22854. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  22855. /*
  22856. Return from inflate(), updating the total counts and the check value.
  22857. If there was no progress during the inflate() call, return a buffer
  22858. error. Call updatewindow() to create and/or update the window state.
  22859. Note: a memory error from inflate() is non-recoverable.
  22860. */
  22861. //--- RESTORE() ---
  22862. strm.next_out = put;
  22863. strm.avail_out = left;
  22864. strm.next_in = next;
  22865. strm.avail_in = have;
  22866. state.hold = hold;
  22867. state.bits = bits;
  22868. //---
  22869. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  22870. (state.mode < CHECK || flush !== Z_FINISH))) {
  22871. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  22872. state.mode = MEM;
  22873. return Z_MEM_ERROR;
  22874. }
  22875. }
  22876. _in -= strm.avail_in;
  22877. _out -= strm.avail_out;
  22878. strm.total_in += _in;
  22879. strm.total_out += _out;
  22880. state.total += _out;
  22881. if (state.wrap && _out) {
  22882. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  22883. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  22884. }
  22885. strm.data_type = state.bits + (state.last ? 64 : 0) +
  22886. (state.mode === TYPE ? 128 : 0) +
  22887. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  22888. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  22889. ret = Z_BUF_ERROR;
  22890. }
  22891. return ret;
  22892. }
  22893. function inflateEnd(strm) {
  22894. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  22895. return Z_STREAM_ERROR;
  22896. }
  22897. var state = strm.state;
  22898. if (state.window) {
  22899. state.window = null;
  22900. }
  22901. strm.state = null;
  22902. return Z_OK;
  22903. }
  22904. function inflateGetHeader(strm, head) {
  22905. var state;
  22906. /* check state */
  22907. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22908. state = strm.state;
  22909. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  22910. /* save header structure */
  22911. state.head = head;
  22912. head.done = false;
  22913. return Z_OK;
  22914. }
  22915. exports.inflateReset = inflateReset;
  22916. exports.inflateReset2 = inflateReset2;
  22917. exports.inflateResetKeep = inflateResetKeep;
  22918. exports.inflateInit = inflateInit;
  22919. exports.inflateInit2 = inflateInit2;
  22920. exports.inflate = inflate;
  22921. exports.inflateEnd = inflateEnd;
  22922. exports.inflateGetHeader = inflateGetHeader;
  22923. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  22924. /* Not implemented
  22925. exports.inflateCopy = inflateCopy;
  22926. exports.inflateGetDictionary = inflateGetDictionary;
  22927. exports.inflateMark = inflateMark;
  22928. exports.inflatePrime = inflatePrime;
  22929. exports.inflateSetDictionary = inflateSetDictionary;
  22930. exports.inflateSync = inflateSync;
  22931. exports.inflateSyncPoint = inflateSyncPoint;
  22932. exports.inflateUndermine = inflateUndermine;
  22933. */
  22934. },{"../utils/common":67,"./adler32":69,"./crc32":71,"./inffast":74,"./inftrees":76}],76:[function(require,module,exports){
  22935. 'use strict';
  22936. var utils = require('../utils/common');
  22937. var MAXBITS = 15;
  22938. var ENOUGH_LENS = 852;
  22939. var ENOUGH_DISTS = 592;
  22940. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  22941. var CODES = 0;
  22942. var LENS = 1;
  22943. var DISTS = 2;
  22944. var lbase = [ /* Length codes 257..285 base */
  22945. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  22946. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  22947. ];
  22948. var lext = [ /* Length codes 257..285 extra */
  22949. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  22950. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  22951. ];
  22952. var dbase = [ /* Distance codes 0..29 base */
  22953. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  22954. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  22955. 8193, 12289, 16385, 24577, 0, 0
  22956. ];
  22957. var dext = [ /* Distance codes 0..29 extra */
  22958. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  22959. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  22960. 28, 28, 29, 29, 64, 64
  22961. ];
  22962. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  22963. {
  22964. var bits = opts.bits;
  22965. //here = opts.here; /* table entry for duplication */
  22966. var len = 0; /* a code's length in bits */
  22967. var sym = 0; /* index of code symbols */
  22968. var min = 0, max = 0; /* minimum and maximum code lengths */
  22969. var root = 0; /* number of index bits for root table */
  22970. var curr = 0; /* number of index bits for current table */
  22971. var drop = 0; /* code bits to drop for sub-table */
  22972. var left = 0; /* number of prefix codes available */
  22973. var used = 0; /* code entries in table used */
  22974. var huff = 0; /* Huffman code */
  22975. var incr; /* for incrementing code, index */
  22976. var fill; /* index for replicating entries */
  22977. var low; /* low bits for current root entry */
  22978. var mask; /* mask for low root bits */
  22979. var next; /* next available space in table */
  22980. var base = null; /* base value table to use */
  22981. var base_index = 0;
  22982. // var shoextra; /* extra bits table to use */
  22983. var end; /* use base and extra for symbol > end */
  22984. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  22985. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  22986. var extra = null;
  22987. var extra_index = 0;
  22988. var here_bits, here_op, here_val;
  22989. /*
  22990. Process a set of code lengths to create a canonical Huffman code. The
  22991. code lengths are lens[0..codes-1]. Each length corresponds to the
  22992. symbols 0..codes-1. The Huffman code is generated by first sorting the
  22993. symbols by length from short to long, and retaining the symbol order
  22994. for codes with equal lengths. Then the code starts with all zero bits
  22995. for the first code of the shortest length, and the codes are integer
  22996. increments for the same length, and zeros are appended as the length
  22997. increases. For the deflate format, these bits are stored backwards
  22998. from their more natural integer increment ordering, and so when the
  22999. decoding tables are built in the large loop below, the integer codes
  23000. are incremented backwards.
  23001. This routine assumes, but does not check, that all of the entries in
  23002. lens[] are in the range 0..MAXBITS. The caller must assure this.
  23003. 1..MAXBITS is interpreted as that code length. zero means that that
  23004. symbol does not occur in this code.
  23005. The codes are sorted by computing a count of codes for each length,
  23006. creating from that a table of starting indices for each length in the
  23007. sorted table, and then entering the symbols in order in the sorted
  23008. table. The sorted table is work[], with that space being provided by
  23009. the caller.
  23010. The length counts are used for other purposes as well, i.e. finding
  23011. the minimum and maximum length codes, determining if there are any
  23012. codes at all, checking for a valid set of lengths, and looking ahead
  23013. at length counts to determine sub-table sizes when building the
  23014. decoding tables.
  23015. */
  23016. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  23017. for (len = 0; len <= MAXBITS; len++) {
  23018. count[len] = 0;
  23019. }
  23020. for (sym = 0; sym < codes; sym++) {
  23021. count[lens[lens_index + sym]]++;
  23022. }
  23023. /* bound code lengths, force root to be within code lengths */
  23024. root = bits;
  23025. for (max = MAXBITS; max >= 1; max--) {
  23026. if (count[max] !== 0) { break; }
  23027. }
  23028. if (root > max) {
  23029. root = max;
  23030. }
  23031. if (max === 0) { /* no symbols to code at all */
  23032. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  23033. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  23034. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  23035. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  23036. //table.op[opts.table_index] = 64;
  23037. //table.bits[opts.table_index] = 1;
  23038. //table.val[opts.table_index++] = 0;
  23039. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  23040. opts.bits = 1;
  23041. return 0; /* no symbols, but wait for decoding to report error */
  23042. }
  23043. for (min = 1; min < max; min++) {
  23044. if (count[min] !== 0) { break; }
  23045. }
  23046. if (root < min) {
  23047. root = min;
  23048. }
  23049. /* check for an over-subscribed or incomplete set of lengths */
  23050. left = 1;
  23051. for (len = 1; len <= MAXBITS; len++) {
  23052. left <<= 1;
  23053. left -= count[len];
  23054. if (left < 0) {
  23055. return -1;
  23056. } /* over-subscribed */
  23057. }
  23058. if (left > 0 && (type === CODES || max !== 1)) {
  23059. return -1; /* incomplete set */
  23060. }
  23061. /* generate offsets into symbol table for each length for sorting */
  23062. offs[1] = 0;
  23063. for (len = 1; len < MAXBITS; len++) {
  23064. offs[len + 1] = offs[len] + count[len];
  23065. }
  23066. /* sort symbols by length, by symbol order within each length */
  23067. for (sym = 0; sym < codes; sym++) {
  23068. if (lens[lens_index + sym] !== 0) {
  23069. work[offs[lens[lens_index + sym]]++] = sym;
  23070. }
  23071. }
  23072. /*
  23073. Create and fill in decoding tables. In this loop, the table being
  23074. filled is at next and has curr index bits. The code being used is huff
  23075. with length len. That code is converted to an index by dropping drop
  23076. bits off of the bottom. For codes where len is less than drop + curr,
  23077. those top drop + curr - len bits are incremented through all values to
  23078. fill the table with replicated entries.
  23079. root is the number of index bits for the root table. When len exceeds
  23080. root, sub-tables are created pointed to by the root entry with an index
  23081. of the low root bits of huff. This is saved in low to check for when a
  23082. new sub-table should be started. drop is zero when the root table is
  23083. being filled, and drop is root when sub-tables are being filled.
  23084. When a new sub-table is needed, it is necessary to look ahead in the
  23085. code lengths to determine what size sub-table is needed. The length
  23086. counts are used for this, and so count[] is decremented as codes are
  23087. entered in the tables.
  23088. used keeps track of how many table entries have been allocated from the
  23089. provided *table space. It is checked for LENS and DIST tables against
  23090. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  23091. the initial root table size constants. See the comments in inftrees.h
  23092. for more information.
  23093. sym increments through all symbols, and the loop terminates when
  23094. all codes of length max, i.e. all codes, have been processed. This
  23095. routine permits incomplete codes, so another loop after this one fills
  23096. in the rest of the decoding tables with invalid code markers.
  23097. */
  23098. /* set up for code type */
  23099. // poor man optimization - use if-else instead of switch,
  23100. // to avoid deopts in old v8
  23101. if (type === CODES) {
  23102. base = extra = work; /* dummy value--not used */
  23103. end = 19;
  23104. } else if (type === LENS) {
  23105. base = lbase;
  23106. base_index -= 257;
  23107. extra = lext;
  23108. extra_index -= 257;
  23109. end = 256;
  23110. } else { /* DISTS */
  23111. base = dbase;
  23112. extra = dext;
  23113. end = -1;
  23114. }
  23115. /* initialize opts for loop */
  23116. huff = 0; /* starting code */
  23117. sym = 0; /* starting code symbol */
  23118. len = min; /* starting code length */
  23119. next = table_index; /* current table to fill in */
  23120. curr = root; /* current table index bits */
  23121. drop = 0; /* current bits to drop from code for index */
  23122. low = -1; /* trigger new sub-table when len > root */
  23123. used = 1 << root; /* use root table entries */
  23124. mask = used - 1; /* mask for comparing low */
  23125. /* check available table space */
  23126. if ((type === LENS && used > ENOUGH_LENS) ||
  23127. (type === DISTS && used > ENOUGH_DISTS)) {
  23128. return 1;
  23129. }
  23130. var i=0;
  23131. /* process all codes and make table entries */
  23132. for (;;) {
  23133. i++;
  23134. /* create table entry */
  23135. here_bits = len - drop;
  23136. if (work[sym] < end) {
  23137. here_op = 0;
  23138. here_val = work[sym];
  23139. }
  23140. else if (work[sym] > end) {
  23141. here_op = extra[extra_index + work[sym]];
  23142. here_val = base[base_index + work[sym]];
  23143. }
  23144. else {
  23145. here_op = 32 + 64; /* end of block */
  23146. here_val = 0;
  23147. }
  23148. /* replicate for those indices with low len bits equal to huff */
  23149. incr = 1 << (len - drop);
  23150. fill = 1 << curr;
  23151. min = fill; /* save offset to next table */
  23152. do {
  23153. fill -= incr;
  23154. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  23155. } while (fill !== 0);
  23156. /* backwards increment the len-bit code huff */
  23157. incr = 1 << (len - 1);
  23158. while (huff & incr) {
  23159. incr >>= 1;
  23160. }
  23161. if (incr !== 0) {
  23162. huff &= incr - 1;
  23163. huff += incr;
  23164. } else {
  23165. huff = 0;
  23166. }
  23167. /* go to next symbol, update count, len */
  23168. sym++;
  23169. if (--count[len] === 0) {
  23170. if (len === max) { break; }
  23171. len = lens[lens_index + work[sym]];
  23172. }
  23173. /* create new sub-table if needed */
  23174. if (len > root && (huff & mask) !== low) {
  23175. /* if first time, transition to sub-tables */
  23176. if (drop === 0) {
  23177. drop = root;
  23178. }
  23179. /* increment past last table */
  23180. next += min; /* here min is 1 << curr */
  23181. /* determine length of next table */
  23182. curr = len - drop;
  23183. left = 1 << curr;
  23184. while (curr + drop < max) {
  23185. left -= count[curr + drop];
  23186. if (left <= 0) { break; }
  23187. curr++;
  23188. left <<= 1;
  23189. }
  23190. /* check for enough space */
  23191. used += 1 << curr;
  23192. if ((type === LENS && used > ENOUGH_LENS) ||
  23193. (type === DISTS && used > ENOUGH_DISTS)) {
  23194. return 1;
  23195. }
  23196. /* point entry in root table to sub-table */
  23197. low = huff & mask;
  23198. /*table.op[low] = curr;
  23199. table.bits[low] = root;
  23200. table.val[low] = next - opts.table_index;*/
  23201. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  23202. }
  23203. }
  23204. /* fill in remaining table entry if code is incomplete (guaranteed to have
  23205. at most one remaining entry, since if the code is incomplete, the
  23206. maximum code length that was allowed to get this far is one bit) */
  23207. if (huff !== 0) {
  23208. //table.op[next + huff] = 64; /* invalid code marker */
  23209. //table.bits[next + huff] = len - drop;
  23210. //table.val[next + huff] = 0;
  23211. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  23212. }
  23213. /* set return parameters */
  23214. //opts.table_index += used;
  23215. opts.bits = root;
  23216. return 0;
  23217. };
  23218. },{"../utils/common":67}],77:[function(require,module,exports){
  23219. 'use strict';
  23220. module.exports = {
  23221. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  23222. '1': 'stream end', /* Z_STREAM_END 1 */
  23223. '0': '', /* Z_OK 0 */
  23224. '-1': 'file error', /* Z_ERRNO (-1) */
  23225. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  23226. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  23227. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  23228. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  23229. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  23230. };
  23231. },{}],78:[function(require,module,exports){
  23232. 'use strict';
  23233. var utils = require('../utils/common');
  23234. /* Public constants ==========================================================*/
  23235. /* ===========================================================================*/
  23236. //var Z_FILTERED = 1;
  23237. //var Z_HUFFMAN_ONLY = 2;
  23238. //var Z_RLE = 3;
  23239. var Z_FIXED = 4;
  23240. //var Z_DEFAULT_STRATEGY = 0;
  23241. /* Possible values of the data_type field (though see inflate()) */
  23242. var Z_BINARY = 0;
  23243. var Z_TEXT = 1;
  23244. //var Z_ASCII = 1; // = Z_TEXT
  23245. var Z_UNKNOWN = 2;
  23246. /*============================================================================*/
  23247. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  23248. // From zutil.h
  23249. var STORED_BLOCK = 0;
  23250. var STATIC_TREES = 1;
  23251. var DYN_TREES = 2;
  23252. /* The three kinds of block type */
  23253. var MIN_MATCH = 3;
  23254. var MAX_MATCH = 258;
  23255. /* The minimum and maximum match lengths */
  23256. // From deflate.h
  23257. /* ===========================================================================
  23258. * Internal compression state.
  23259. */
  23260. var LENGTH_CODES = 29;
  23261. /* number of length codes, not counting the special END_BLOCK code */
  23262. var LITERALS = 256;
  23263. /* number of literal bytes 0..255 */
  23264. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  23265. /* number of Literal or Length codes, including the END_BLOCK code */
  23266. var D_CODES = 30;
  23267. /* number of distance codes */
  23268. var BL_CODES = 19;
  23269. /* number of codes used to transfer the bit lengths */
  23270. var HEAP_SIZE = 2*L_CODES + 1;
  23271. /* maximum heap size */
  23272. var MAX_BITS = 15;
  23273. /* All codes must not exceed MAX_BITS bits */
  23274. var Buf_size = 16;
  23275. /* size of bit buffer in bi_buf */
  23276. /* ===========================================================================
  23277. * Constants
  23278. */
  23279. var MAX_BL_BITS = 7;
  23280. /* Bit length codes must not exceed MAX_BL_BITS bits */
  23281. var END_BLOCK = 256;
  23282. /* end of block literal code */
  23283. var REP_3_6 = 16;
  23284. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  23285. var REPZ_3_10 = 17;
  23286. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  23287. var REPZ_11_138 = 18;
  23288. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  23289. var extra_lbits = /* extra bits for each length code */
  23290. [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];
  23291. var extra_dbits = /* extra bits for each distance code */
  23292. [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];
  23293. var extra_blbits = /* extra bits for each bit length code */
  23294. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  23295. var bl_order =
  23296. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  23297. /* The lengths of the bit length codes are sent in order of decreasing
  23298. * probability, to avoid transmitting the lengths for unused bit length codes.
  23299. */
  23300. /* ===========================================================================
  23301. * Local data. These are initialized only once.
  23302. */
  23303. // We pre-fill arrays with 0 to avoid uninitialized gaps
  23304. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  23305. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  23306. var static_ltree = new Array((L_CODES+2) * 2);
  23307. zero(static_ltree);
  23308. /* The static literal tree. Since the bit lengths are imposed, there is no
  23309. * need for the L_CODES extra codes used during heap construction. However
  23310. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  23311. * below).
  23312. */
  23313. var static_dtree = new Array(D_CODES * 2);
  23314. zero(static_dtree);
  23315. /* The static distance tree. (Actually a trivial tree since all codes use
  23316. * 5 bits.)
  23317. */
  23318. var _dist_code = new Array(DIST_CODE_LEN);
  23319. zero(_dist_code);
  23320. /* Distance codes. The first 256 values correspond to the distances
  23321. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  23322. * the 15 bit distances.
  23323. */
  23324. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  23325. zero(_length_code);
  23326. /* length code for each normalized match length (0 == MIN_MATCH) */
  23327. var base_length = new Array(LENGTH_CODES);
  23328. zero(base_length);
  23329. /* First normalized length for each code (0 = MIN_MATCH) */
  23330. var base_dist = new Array(D_CODES);
  23331. zero(base_dist);
  23332. /* First normalized distance for each code (0 = distance of 1) */
  23333. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  23334. this.static_tree = static_tree; /* static tree or NULL */
  23335. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  23336. this.extra_base = extra_base; /* base index for extra_bits */
  23337. this.elems = elems; /* max number of elements in the tree */
  23338. this.max_length = max_length; /* max bit length for the codes */
  23339. // show if `static_tree` has data or dummy - needed for monomorphic objects
  23340. this.has_stree = static_tree && static_tree.length;
  23341. };
  23342. var static_l_desc;
  23343. var static_d_desc;
  23344. var static_bl_desc;
  23345. var TreeDesc = function(dyn_tree, stat_desc) {
  23346. this.dyn_tree = dyn_tree; /* the dynamic tree */
  23347. this.max_code = 0; /* largest code with non zero frequency */
  23348. this.stat_desc = stat_desc; /* the corresponding static tree */
  23349. };
  23350. function d_code(dist) {
  23351. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  23352. }
  23353. /* ===========================================================================
  23354. * Output a short LSB first on the stream.
  23355. * IN assertion: there is enough room in pendingBuf.
  23356. */
  23357. function put_short (s, w) {
  23358. // put_byte(s, (uch)((w) & 0xff));
  23359. // put_byte(s, (uch)((ush)(w) >> 8));
  23360. s.pending_buf[s.pending++] = (w) & 0xff;
  23361. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  23362. }
  23363. /* ===========================================================================
  23364. * Send a value on a given number of bits.
  23365. * IN assertion: length <= 16 and value fits in length bits.
  23366. */
  23367. function send_bits(s, value, length) {
  23368. if (s.bi_valid > (Buf_size - length)) {
  23369. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  23370. put_short(s, s.bi_buf);
  23371. s.bi_buf = value >> (Buf_size - s.bi_valid);
  23372. s.bi_valid += length - Buf_size;
  23373. } else {
  23374. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  23375. s.bi_valid += length;
  23376. }
  23377. }
  23378. function send_code(s, c, tree) {
  23379. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  23380. }
  23381. /* ===========================================================================
  23382. * Reverse the first len bits of a code, using straightforward code (a faster
  23383. * method would use a table)
  23384. * IN assertion: 1 <= len <= 15
  23385. */
  23386. function bi_reverse(code, len) {
  23387. var res = 0;
  23388. do {
  23389. res |= code & 1;
  23390. code >>>= 1;
  23391. res <<= 1;
  23392. } while (--len > 0);
  23393. return res >>> 1;
  23394. }
  23395. /* ===========================================================================
  23396. * Flush the bit buffer, keeping at most 7 bits in it.
  23397. */
  23398. function bi_flush(s) {
  23399. if (s.bi_valid === 16) {
  23400. put_short(s, s.bi_buf);
  23401. s.bi_buf = 0;
  23402. s.bi_valid = 0;
  23403. } else if (s.bi_valid >= 8) {
  23404. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  23405. s.bi_buf >>= 8;
  23406. s.bi_valid -= 8;
  23407. }
  23408. }
  23409. /* ===========================================================================
  23410. * Compute the optimal bit lengths for a tree and update the total bit length
  23411. * for the current block.
  23412. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  23413. * above are the tree nodes sorted by increasing frequency.
  23414. * OUT assertions: the field len is set to the optimal bit length, the
  23415. * array bl_count contains the frequencies for each bit length.
  23416. * The length opt_len is updated; static_len is also updated if stree is
  23417. * not null.
  23418. */
  23419. function gen_bitlen(s, desc)
  23420. // deflate_state *s;
  23421. // tree_desc *desc; /* the tree descriptor */
  23422. {
  23423. var tree = desc.dyn_tree;
  23424. var max_code = desc.max_code;
  23425. var stree = desc.stat_desc.static_tree;
  23426. var has_stree = desc.stat_desc.has_stree;
  23427. var extra = desc.stat_desc.extra_bits;
  23428. var base = desc.stat_desc.extra_base;
  23429. var max_length = desc.stat_desc.max_length;
  23430. var h; /* heap index */
  23431. var n, m; /* iterate over the tree elements */
  23432. var bits; /* bit length */
  23433. var xbits; /* extra bits */
  23434. var f; /* frequency */
  23435. var overflow = 0; /* number of elements with bit length too large */
  23436. for (bits = 0; bits <= MAX_BITS; bits++) {
  23437. s.bl_count[bits] = 0;
  23438. }
  23439. /* In a first pass, compute the optimal bit lengths (which may
  23440. * overflow in the case of the bit length tree).
  23441. */
  23442. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  23443. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  23444. n = s.heap[h];
  23445. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  23446. if (bits > max_length) {
  23447. bits = max_length;
  23448. overflow++;
  23449. }
  23450. tree[n*2 + 1]/*.Len*/ = bits;
  23451. /* We overwrite tree[n].Dad which is no longer needed */
  23452. if (n > max_code) { continue; } /* not a leaf node */
  23453. s.bl_count[bits]++;
  23454. xbits = 0;
  23455. if (n >= base) {
  23456. xbits = extra[n-base];
  23457. }
  23458. f = tree[n * 2]/*.Freq*/;
  23459. s.opt_len += f * (bits + xbits);
  23460. if (has_stree) {
  23461. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  23462. }
  23463. }
  23464. if (overflow === 0) { return; }
  23465. // Trace((stderr,"\nbit length overflow\n"));
  23466. /* This happens for example on obj2 and pic of the Calgary corpus */
  23467. /* Find the first bit length which could increase: */
  23468. do {
  23469. bits = max_length-1;
  23470. while (s.bl_count[bits] === 0) { bits--; }
  23471. s.bl_count[bits]--; /* move one leaf down the tree */
  23472. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  23473. s.bl_count[max_length]--;
  23474. /* The brother of the overflow item also moves one step up,
  23475. * but this does not affect bl_count[max_length]
  23476. */
  23477. overflow -= 2;
  23478. } while (overflow > 0);
  23479. /* Now recompute all bit lengths, scanning in increasing frequency.
  23480. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  23481. * lengths instead of fixing only the wrong ones. This idea is taken
  23482. * from 'ar' written by Haruhiko Okumura.)
  23483. */
  23484. for (bits = max_length; bits !== 0; bits--) {
  23485. n = s.bl_count[bits];
  23486. while (n !== 0) {
  23487. m = s.heap[--h];
  23488. if (m > max_code) { continue; }
  23489. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  23490. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  23491. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  23492. tree[m*2 + 1]/*.Len*/ = bits;
  23493. }
  23494. n--;
  23495. }
  23496. }
  23497. }
  23498. /* ===========================================================================
  23499. * Generate the codes for a given tree and bit counts (which need not be
  23500. * optimal).
  23501. * IN assertion: the array bl_count contains the bit length statistics for
  23502. * the given tree and the field len is set for all tree elements.
  23503. * OUT assertion: the field code is set for all tree elements of non
  23504. * zero code length.
  23505. */
  23506. function gen_codes(tree, max_code, bl_count)
  23507. // ct_data *tree; /* the tree to decorate */
  23508. // int max_code; /* largest code with non zero frequency */
  23509. // ushf *bl_count; /* number of codes at each bit length */
  23510. {
  23511. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  23512. var code = 0; /* running code value */
  23513. var bits; /* bit index */
  23514. var n; /* code index */
  23515. /* The distribution counts are first used to generate the code values
  23516. * without bit reversal.
  23517. */
  23518. for (bits = 1; bits <= MAX_BITS; bits++) {
  23519. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  23520. }
  23521. /* Check that the bit counts in bl_count are consistent. The last code
  23522. * must be all ones.
  23523. */
  23524. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  23525. // "inconsistent bit counts");
  23526. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  23527. for (n = 0; n <= max_code; n++) {
  23528. var len = tree[n*2 + 1]/*.Len*/;
  23529. if (len === 0) { continue; }
  23530. /* Now reverse the bits */
  23531. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  23532. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  23533. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  23534. }
  23535. }
  23536. /* ===========================================================================
  23537. * Initialize the various 'constant' tables.
  23538. */
  23539. function tr_static_init() {
  23540. var n; /* iterates over tree elements */
  23541. var bits; /* bit counter */
  23542. var length; /* length value */
  23543. var code; /* code value */
  23544. var dist; /* distance index */
  23545. var bl_count = new Array(MAX_BITS+1);
  23546. /* number of codes at each bit length for an optimal tree */
  23547. // do check in _tr_init()
  23548. //if (static_init_done) return;
  23549. /* For some embedded targets, global variables are not initialized: */
  23550. /*#ifdef NO_INIT_GLOBAL_POINTERS
  23551. static_l_desc.static_tree = static_ltree;
  23552. static_l_desc.extra_bits = extra_lbits;
  23553. static_d_desc.static_tree = static_dtree;
  23554. static_d_desc.extra_bits = extra_dbits;
  23555. static_bl_desc.extra_bits = extra_blbits;
  23556. #endif*/
  23557. /* Initialize the mapping length (0..255) -> length code (0..28) */
  23558. length = 0;
  23559. for (code = 0; code < LENGTH_CODES-1; code++) {
  23560. base_length[code] = length;
  23561. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  23562. _length_code[length++] = code;
  23563. }
  23564. }
  23565. //Assert (length == 256, "tr_static_init: length != 256");
  23566. /* Note that the length 255 (match length 258) can be represented
  23567. * in two different ways: code 284 + 5 bits or code 285, so we
  23568. * overwrite length_code[255] to use the best encoding:
  23569. */
  23570. _length_code[length-1] = code;
  23571. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  23572. dist = 0;
  23573. for (code = 0 ; code < 16; code++) {
  23574. base_dist[code] = dist;
  23575. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  23576. _dist_code[dist++] = code;
  23577. }
  23578. }
  23579. //Assert (dist == 256, "tr_static_init: dist != 256");
  23580. dist >>= 7; /* from now on, all distances are divided by 128 */
  23581. for ( ; code < D_CODES; code++) {
  23582. base_dist[code] = dist << 7;
  23583. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  23584. _dist_code[256 + dist++] = code;
  23585. }
  23586. }
  23587. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  23588. /* Construct the codes of the static literal tree */
  23589. for (bits = 0; bits <= MAX_BITS; bits++) {
  23590. bl_count[bits] = 0;
  23591. }
  23592. n = 0;
  23593. while (n <= 143) {
  23594. static_ltree[n*2 + 1]/*.Len*/ = 8;
  23595. n++;
  23596. bl_count[8]++;
  23597. }
  23598. while (n <= 255) {
  23599. static_ltree[n*2 + 1]/*.Len*/ = 9;
  23600. n++;
  23601. bl_count[9]++;
  23602. }
  23603. while (n <= 279) {
  23604. static_ltree[n*2 + 1]/*.Len*/ = 7;
  23605. n++;
  23606. bl_count[7]++;
  23607. }
  23608. while (n <= 287) {
  23609. static_ltree[n*2 + 1]/*.Len*/ = 8;
  23610. n++;
  23611. bl_count[8]++;
  23612. }
  23613. /* Codes 286 and 287 do not exist, but we must include them in the
  23614. * tree construction to get a canonical Huffman tree (longest code
  23615. * all ones)
  23616. */
  23617. gen_codes(static_ltree, L_CODES+1, bl_count);
  23618. /* The static distance tree is trivial: */
  23619. for (n = 0; n < D_CODES; n++) {
  23620. static_dtree[n*2 + 1]/*.Len*/ = 5;
  23621. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  23622. }
  23623. // Now data ready and we can init static trees
  23624. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  23625. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  23626. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  23627. //static_init_done = true;
  23628. }
  23629. /* ===========================================================================
  23630. * Initialize a new block.
  23631. */
  23632. function init_block(s) {
  23633. var n; /* iterates over tree elements */
  23634. /* Initialize the trees. */
  23635. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  23636. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  23637. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  23638. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  23639. s.opt_len = s.static_len = 0;
  23640. s.last_lit = s.matches = 0;
  23641. }
  23642. /* ===========================================================================
  23643. * Flush the bit buffer and align the output on a byte boundary
  23644. */
  23645. function bi_windup(s)
  23646. {
  23647. if (s.bi_valid > 8) {
  23648. put_short(s, s.bi_buf);
  23649. } else if (s.bi_valid > 0) {
  23650. //put_byte(s, (Byte)s->bi_buf);
  23651. s.pending_buf[s.pending++] = s.bi_buf;
  23652. }
  23653. s.bi_buf = 0;
  23654. s.bi_valid = 0;
  23655. }
  23656. /* ===========================================================================
  23657. * Copy a stored block, storing first the length and its
  23658. * one's complement if requested.
  23659. */
  23660. function copy_block(s, buf, len, header)
  23661. //DeflateState *s;
  23662. //charf *buf; /* the input data */
  23663. //unsigned len; /* its length */
  23664. //int header; /* true if block header must be written */
  23665. {
  23666. bi_windup(s); /* align on byte boundary */
  23667. if (header) {
  23668. put_short(s, len);
  23669. put_short(s, ~len);
  23670. }
  23671. // while (len--) {
  23672. // put_byte(s, *buf++);
  23673. // }
  23674. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  23675. s.pending += len;
  23676. }
  23677. /* ===========================================================================
  23678. * Compares to subtrees, using the tree depth as tie breaker when
  23679. * the subtrees have equal frequency. This minimizes the worst case length.
  23680. */
  23681. function smaller(tree, n, m, depth) {
  23682. var _n2 = n*2;
  23683. var _m2 = m*2;
  23684. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  23685. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  23686. }
  23687. /* ===========================================================================
  23688. * Restore the heap property by moving down the tree starting at node k,
  23689. * exchanging a node with the smallest of its two sons if necessary, stopping
  23690. * when the heap property is re-established (each father smaller than its
  23691. * two sons).
  23692. */
  23693. function pqdownheap(s, tree, k)
  23694. // deflate_state *s;
  23695. // ct_data *tree; /* the tree to restore */
  23696. // int k; /* node to move down */
  23697. {
  23698. var v = s.heap[k];
  23699. var j = k << 1; /* left son of k */
  23700. while (j <= s.heap_len) {
  23701. /* Set j to the smallest of the two sons: */
  23702. if (j < s.heap_len &&
  23703. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  23704. j++;
  23705. }
  23706. /* Exit if v is smaller than both sons */
  23707. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  23708. /* Exchange v with the smallest son */
  23709. s.heap[k] = s.heap[j];
  23710. k = j;
  23711. /* And continue down the tree, setting j to the left son of k */
  23712. j <<= 1;
  23713. }
  23714. s.heap[k] = v;
  23715. }
  23716. // inlined manually
  23717. // var SMALLEST = 1;
  23718. /* ===========================================================================
  23719. * Send the block data compressed using the given Huffman trees
  23720. */
  23721. function compress_block(s, ltree, dtree)
  23722. // deflate_state *s;
  23723. // const ct_data *ltree; /* literal tree */
  23724. // const ct_data *dtree; /* distance tree */
  23725. {
  23726. var dist; /* distance of matched string */
  23727. var lc; /* match length or unmatched char (if dist == 0) */
  23728. var lx = 0; /* running index in l_buf */
  23729. var code; /* the code to send */
  23730. var extra; /* number of extra bits to send */
  23731. if (s.last_lit !== 0) {
  23732. do {
  23733. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  23734. lc = s.pending_buf[s.l_buf + lx];
  23735. lx++;
  23736. if (dist === 0) {
  23737. send_code(s, lc, ltree); /* send a literal byte */
  23738. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  23739. } else {
  23740. /* Here, lc is the match length - MIN_MATCH */
  23741. code = _length_code[lc];
  23742. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  23743. extra = extra_lbits[code];
  23744. if (extra !== 0) {
  23745. lc -= base_length[code];
  23746. send_bits(s, lc, extra); /* send the extra length bits */
  23747. }
  23748. dist--; /* dist is now the match distance - 1 */
  23749. code = d_code(dist);
  23750. //Assert (code < D_CODES, "bad d_code");
  23751. send_code(s, code, dtree); /* send the distance code */
  23752. extra = extra_dbits[code];
  23753. if (extra !== 0) {
  23754. dist -= base_dist[code];
  23755. send_bits(s, dist, extra); /* send the extra distance bits */
  23756. }
  23757. } /* literal or match pair ? */
  23758. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  23759. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  23760. // "pendingBuf overflow");
  23761. } while (lx < s.last_lit);
  23762. }
  23763. send_code(s, END_BLOCK, ltree);
  23764. }
  23765. /* ===========================================================================
  23766. * Construct one Huffman tree and assigns the code bit strings and lengths.
  23767. * Update the total bit length for the current block.
  23768. * IN assertion: the field freq is set for all tree elements.
  23769. * OUT assertions: the fields len and code are set to the optimal bit length
  23770. * and corresponding code. The length opt_len is updated; static_len is
  23771. * also updated if stree is not null. The field max_code is set.
  23772. */
  23773. function build_tree(s, desc)
  23774. // deflate_state *s;
  23775. // tree_desc *desc; /* the tree descriptor */
  23776. {
  23777. var tree = desc.dyn_tree;
  23778. var stree = desc.stat_desc.static_tree;
  23779. var has_stree = desc.stat_desc.has_stree;
  23780. var elems = desc.stat_desc.elems;
  23781. var n, m; /* iterate over heap elements */
  23782. var max_code = -1; /* largest code with non zero frequency */
  23783. var node; /* new node being created */
  23784. /* Construct the initial heap, with least frequent element in
  23785. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  23786. * heap[0] is not used.
  23787. */
  23788. s.heap_len = 0;
  23789. s.heap_max = HEAP_SIZE;
  23790. for (n = 0; n < elems; n++) {
  23791. if (tree[n * 2]/*.Freq*/ !== 0) {
  23792. s.heap[++s.heap_len] = max_code = n;
  23793. s.depth[n] = 0;
  23794. } else {
  23795. tree[n*2 + 1]/*.Len*/ = 0;
  23796. }
  23797. }
  23798. /* The pkzip format requires that at least one distance code exists,
  23799. * and that at least one bit should be sent even if there is only one
  23800. * possible code. So to avoid special checks later on we force at least
  23801. * two codes of non zero frequency.
  23802. */
  23803. while (s.heap_len < 2) {
  23804. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  23805. tree[node * 2]/*.Freq*/ = 1;
  23806. s.depth[node] = 0;
  23807. s.opt_len--;
  23808. if (has_stree) {
  23809. s.static_len -= stree[node*2 + 1]/*.Len*/;
  23810. }
  23811. /* node is 0 or 1 so it does not have extra bits */
  23812. }
  23813. desc.max_code = max_code;
  23814. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  23815. * establish sub-heaps of increasing lengths:
  23816. */
  23817. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  23818. /* Construct the Huffman tree by repeatedly combining the least two
  23819. * frequent nodes.
  23820. */
  23821. node = elems; /* next internal node of the tree */
  23822. do {
  23823. //pqremove(s, tree, n); /* n = node of least frequency */
  23824. /*** pqremove ***/
  23825. n = s.heap[1/*SMALLEST*/];
  23826. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  23827. pqdownheap(s, tree, 1/*SMALLEST*/);
  23828. /***/
  23829. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  23830. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  23831. s.heap[--s.heap_max] = m;
  23832. /* Create a new node father of n and m */
  23833. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  23834. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  23835. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  23836. /* and insert the new node in the heap */
  23837. s.heap[1/*SMALLEST*/] = node++;
  23838. pqdownheap(s, tree, 1/*SMALLEST*/);
  23839. } while (s.heap_len >= 2);
  23840. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  23841. /* At this point, the fields freq and dad are set. We can now
  23842. * generate the bit lengths.
  23843. */
  23844. gen_bitlen(s, desc);
  23845. /* The field len is now set, we can generate the bit codes */
  23846. gen_codes(tree, max_code, s.bl_count);
  23847. }
  23848. /* ===========================================================================
  23849. * Scan a literal or distance tree to determine the frequencies of the codes
  23850. * in the bit length tree.
  23851. */
  23852. function scan_tree(s, tree, max_code)
  23853. // deflate_state *s;
  23854. // ct_data *tree; /* the tree to be scanned */
  23855. // int max_code; /* and its largest code of non zero frequency */
  23856. {
  23857. var n; /* iterates over all tree elements */
  23858. var prevlen = -1; /* last emitted length */
  23859. var curlen; /* length of current code */
  23860. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  23861. var count = 0; /* repeat count of the current code */
  23862. var max_count = 7; /* max repeat count */
  23863. var min_count = 4; /* min repeat count */
  23864. if (nextlen === 0) {
  23865. max_count = 138;
  23866. min_count = 3;
  23867. }
  23868. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  23869. for (n = 0; n <= max_code; n++) {
  23870. curlen = nextlen;
  23871. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  23872. if (++count < max_count && curlen === nextlen) {
  23873. continue;
  23874. } else if (count < min_count) {
  23875. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  23876. } else if (curlen !== 0) {
  23877. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  23878. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  23879. } else if (count <= 10) {
  23880. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  23881. } else {
  23882. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  23883. }
  23884. count = 0;
  23885. prevlen = curlen;
  23886. if (nextlen === 0) {
  23887. max_count = 138;
  23888. min_count = 3;
  23889. } else if (curlen === nextlen) {
  23890. max_count = 6;
  23891. min_count = 3;
  23892. } else {
  23893. max_count = 7;
  23894. min_count = 4;
  23895. }
  23896. }
  23897. }
  23898. /* ===========================================================================
  23899. * Send a literal or distance tree in compressed form, using the codes in
  23900. * bl_tree.
  23901. */
  23902. function send_tree(s, tree, max_code)
  23903. // deflate_state *s;
  23904. // ct_data *tree; /* the tree to be scanned */
  23905. // int max_code; /* and its largest code of non zero frequency */
  23906. {
  23907. var n; /* iterates over all tree elements */
  23908. var prevlen = -1; /* last emitted length */
  23909. var curlen; /* length of current code */
  23910. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  23911. var count = 0; /* repeat count of the current code */
  23912. var max_count = 7; /* max repeat count */
  23913. var min_count = 4; /* min repeat count */
  23914. /* tree[max_code+1].Len = -1; */ /* guard already set */
  23915. if (nextlen === 0) {
  23916. max_count = 138;
  23917. min_count = 3;
  23918. }
  23919. for (n = 0; n <= max_code; n++) {
  23920. curlen = nextlen;
  23921. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  23922. if (++count < max_count && curlen === nextlen) {
  23923. continue;
  23924. } else if (count < min_count) {
  23925. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  23926. } else if (curlen !== 0) {
  23927. if (curlen !== prevlen) {
  23928. send_code(s, curlen, s.bl_tree);
  23929. count--;
  23930. }
  23931. //Assert(count >= 3 && count <= 6, " 3_6?");
  23932. send_code(s, REP_3_6, s.bl_tree);
  23933. send_bits(s, count-3, 2);
  23934. } else if (count <= 10) {
  23935. send_code(s, REPZ_3_10, s.bl_tree);
  23936. send_bits(s, count-3, 3);
  23937. } else {
  23938. send_code(s, REPZ_11_138, s.bl_tree);
  23939. send_bits(s, count-11, 7);
  23940. }
  23941. count = 0;
  23942. prevlen = curlen;
  23943. if (nextlen === 0) {
  23944. max_count = 138;
  23945. min_count = 3;
  23946. } else if (curlen === nextlen) {
  23947. max_count = 6;
  23948. min_count = 3;
  23949. } else {
  23950. max_count = 7;
  23951. min_count = 4;
  23952. }
  23953. }
  23954. }
  23955. /* ===========================================================================
  23956. * Construct the Huffman tree for the bit lengths and return the index in
  23957. * bl_order of the last bit length code to send.
  23958. */
  23959. function build_bl_tree(s) {
  23960. var max_blindex; /* index of last bit length code of non zero freq */
  23961. /* Determine the bit length frequencies for literal and distance trees */
  23962. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  23963. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  23964. /* Build the bit length tree: */
  23965. build_tree(s, s.bl_desc);
  23966. /* opt_len now includes the length of the tree representations, except
  23967. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  23968. */
  23969. /* Determine the number of bit length codes to send. The pkzip format
  23970. * requires that at least 4 bit length codes be sent. (appnote.txt says
  23971. * 3 but the actual value used is 4.)
  23972. */
  23973. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  23974. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  23975. break;
  23976. }
  23977. }
  23978. /* Update opt_len to include the bit length tree and counts */
  23979. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  23980. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  23981. // s->opt_len, s->static_len));
  23982. return max_blindex;
  23983. }
  23984. /* ===========================================================================
  23985. * Send the header for a block using dynamic Huffman trees: the counts, the
  23986. * lengths of the bit length codes, the literal tree and the distance tree.
  23987. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  23988. */
  23989. function send_all_trees(s, lcodes, dcodes, blcodes)
  23990. // deflate_state *s;
  23991. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  23992. {
  23993. var rank; /* index in bl_order */
  23994. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  23995. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  23996. // "too many codes");
  23997. //Tracev((stderr, "\nbl counts: "));
  23998. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  23999. send_bits(s, dcodes-1, 5);
  24000. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  24001. for (rank = 0; rank < blcodes; rank++) {
  24002. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  24003. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  24004. }
  24005. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  24006. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  24007. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  24008. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  24009. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  24010. }
  24011. /* ===========================================================================
  24012. * Check if the data type is TEXT or BINARY, using the following algorithm:
  24013. * - TEXT if the two conditions below are satisfied:
  24014. * a) There are no non-portable control characters belonging to the
  24015. * "black list" (0..6, 14..25, 28..31).
  24016. * b) There is at least one printable character belonging to the
  24017. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  24018. * - BINARY otherwise.
  24019. * - The following partially-portable control characters form a
  24020. * "gray list" that is ignored in this detection algorithm:
  24021. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  24022. * IN assertion: the fields Freq of dyn_ltree are set.
  24023. */
  24024. function detect_data_type(s) {
  24025. /* black_mask is the bit mask of black-listed bytes
  24026. * set bits 0..6, 14..25, and 28..31
  24027. * 0xf3ffc07f = binary 11110011111111111100000001111111
  24028. */
  24029. var black_mask = 0xf3ffc07f;
  24030. var n;
  24031. /* Check for non-textual ("black-listed") bytes. */
  24032. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  24033. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  24034. return Z_BINARY;
  24035. }
  24036. }
  24037. /* Check for textual ("white-listed") bytes. */
  24038. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  24039. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  24040. return Z_TEXT;
  24041. }
  24042. for (n = 32; n < LITERALS; n++) {
  24043. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  24044. return Z_TEXT;
  24045. }
  24046. }
  24047. /* There are no "black-listed" or "white-listed" bytes:
  24048. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  24049. */
  24050. return Z_BINARY;
  24051. }
  24052. var static_init_done = false;
  24053. /* ===========================================================================
  24054. * Initialize the tree data structures for a new zlib stream.
  24055. */
  24056. function _tr_init(s)
  24057. {
  24058. if (!static_init_done) {
  24059. tr_static_init();
  24060. static_init_done = true;
  24061. }
  24062. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  24063. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  24064. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  24065. s.bi_buf = 0;
  24066. s.bi_valid = 0;
  24067. /* Initialize the first block of the first file: */
  24068. init_block(s);
  24069. }
  24070. /* ===========================================================================
  24071. * Send a stored block
  24072. */
  24073. function _tr_stored_block(s, buf, stored_len, last)
  24074. //DeflateState *s;
  24075. //charf *buf; /* input block */
  24076. //ulg stored_len; /* length of input block */
  24077. //int last; /* one if this is the last block for a file */
  24078. {
  24079. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  24080. copy_block(s, buf, stored_len, true); /* with header */
  24081. }
  24082. /* ===========================================================================
  24083. * Send one empty static block to give enough lookahead for inflate.
  24084. * This takes 10 bits, of which 7 may remain in the bit buffer.
  24085. */
  24086. function _tr_align(s) {
  24087. send_bits(s, STATIC_TREES<<1, 3);
  24088. send_code(s, END_BLOCK, static_ltree);
  24089. bi_flush(s);
  24090. }
  24091. /* ===========================================================================
  24092. * Determine the best encoding for the current block: dynamic trees, static
  24093. * trees or store, and output the encoded block to the zip file.
  24094. */
  24095. function _tr_flush_block(s, buf, stored_len, last)
  24096. //DeflateState *s;
  24097. //charf *buf; /* input block, or NULL if too old */
  24098. //ulg stored_len; /* length of input block */
  24099. //int last; /* one if this is the last block for a file */
  24100. {
  24101. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  24102. var max_blindex = 0; /* index of last bit length code of non zero freq */
  24103. /* Build the Huffman trees unless a stored block is forced */
  24104. if (s.level > 0) {
  24105. /* Check if the file is binary or text */
  24106. if (s.strm.data_type === Z_UNKNOWN) {
  24107. s.strm.data_type = detect_data_type(s);
  24108. }
  24109. /* Construct the literal and distance trees */
  24110. build_tree(s, s.l_desc);
  24111. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  24112. // s->static_len));
  24113. build_tree(s, s.d_desc);
  24114. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  24115. // s->static_len));
  24116. /* At this point, opt_len and static_len are the total bit lengths of
  24117. * the compressed block data, excluding the tree representations.
  24118. */
  24119. /* Build the bit length tree for the above two trees, and get the index
  24120. * in bl_order of the last bit length code to send.
  24121. */
  24122. max_blindex = build_bl_tree(s);
  24123. /* Determine the best encoding. Compute the block lengths in bytes. */
  24124. opt_lenb = (s.opt_len+3+7) >>> 3;
  24125. static_lenb = (s.static_len+3+7) >>> 3;
  24126. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  24127. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  24128. // s->last_lit));
  24129. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  24130. } else {
  24131. // Assert(buf != (char*)0, "lost buf");
  24132. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  24133. }
  24134. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  24135. /* 4: two words for the lengths */
  24136. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  24137. * Otherwise we can't have processed more than WSIZE input bytes since
  24138. * the last block flush, because compression would have been
  24139. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  24140. * transform a block into a stored block.
  24141. */
  24142. _tr_stored_block(s, buf, stored_len, last);
  24143. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  24144. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  24145. compress_block(s, static_ltree, static_dtree);
  24146. } else {
  24147. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  24148. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  24149. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  24150. }
  24151. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  24152. /* The above check is made mod 2^32, for files larger than 512 MB
  24153. * and uLong implemented on 32 bits.
  24154. */
  24155. init_block(s);
  24156. if (last) {
  24157. bi_windup(s);
  24158. }
  24159. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  24160. // s->compressed_len-7*last));
  24161. }
  24162. /* ===========================================================================
  24163. * Save the match info and tally the frequency counts. Return true if
  24164. * the current block must be flushed.
  24165. */
  24166. function _tr_tally(s, dist, lc)
  24167. // deflate_state *s;
  24168. // unsigned dist; /* distance of matched string */
  24169. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  24170. {
  24171. //var out_length, in_length, dcode;
  24172. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  24173. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  24174. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  24175. s.last_lit++;
  24176. if (dist === 0) {
  24177. /* lc is the unmatched char */
  24178. s.dyn_ltree[lc*2]/*.Freq*/++;
  24179. } else {
  24180. s.matches++;
  24181. /* Here, lc is the match length - MIN_MATCH */
  24182. dist--; /* dist = match distance - 1 */
  24183. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  24184. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  24185. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  24186. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  24187. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  24188. }
  24189. // (!) This block is disabled in zlib defailts,
  24190. // don't enable it for binary compatibility
  24191. //#ifdef TRUNCATE_BLOCK
  24192. // /* Try to guess if it is profitable to stop the current block here */
  24193. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  24194. // /* Compute an upper bound for the compressed length */
  24195. // out_length = s.last_lit*8;
  24196. // in_length = s.strstart - s.block_start;
  24197. //
  24198. // for (dcode = 0; dcode < D_CODES; dcode++) {
  24199. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  24200. // }
  24201. // out_length >>>= 3;
  24202. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  24203. // // s->last_lit, in_length, out_length,
  24204. // // 100L - out_length*100L/in_length));
  24205. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  24206. // return true;
  24207. // }
  24208. // }
  24209. //#endif
  24210. return (s.last_lit === s.lit_bufsize-1);
  24211. /* We avoid equality with lit_bufsize because of wraparound at 64K
  24212. * on 16 bit machines and because stored blocks are restricted to
  24213. * 64K-1 bytes.
  24214. */
  24215. }
  24216. exports._tr_init = _tr_init;
  24217. exports._tr_stored_block = _tr_stored_block;
  24218. exports._tr_flush_block = _tr_flush_block;
  24219. exports._tr_tally = _tr_tally;
  24220. exports._tr_align = _tr_align;
  24221. },{"../utils/common":67}],79:[function(require,module,exports){
  24222. 'use strict';
  24223. function ZStream() {
  24224. /* next input byte */
  24225. this.input = null; // JS specific, because we have no pointers
  24226. this.next_in = 0;
  24227. /* number of bytes available at input */
  24228. this.avail_in = 0;
  24229. /* total number of input bytes read so far */
  24230. this.total_in = 0;
  24231. /* next output byte should be put there */
  24232. this.output = null; // JS specific, because we have no pointers
  24233. this.next_out = 0;
  24234. /* remaining free space at output */
  24235. this.avail_out = 0;
  24236. /* total number of bytes output so far */
  24237. this.total_out = 0;
  24238. /* last error message, NULL if no error */
  24239. this.msg = ''/*Z_NULL*/;
  24240. /* not visible by applications */
  24241. this.state = null;
  24242. /* best guess about the data type: binary or text */
  24243. this.data_type = 2/*Z_UNKNOWN*/;
  24244. /* adler32 value of the uncompressed data */
  24245. this.adler = 0;
  24246. }
  24247. module.exports = ZStream;
  24248. },{}],80:[function(require,module,exports){
  24249. module.exports = require('./lib/retry');
  24250. },{"./lib/retry":81}],81:[function(require,module,exports){
  24251. var RetryOperation = require('./retry_operation');
  24252. exports.operation = function(options) {
  24253. var timeouts = exports.timeouts(options);
  24254. return new RetryOperation(timeouts);
  24255. };
  24256. exports.timeouts = function(options) {
  24257. if (options instanceof Array) {
  24258. return [].concat(options);
  24259. }
  24260. var opts = {
  24261. retries: 10,
  24262. factor: 2,
  24263. minTimeout: 1 * 1000,
  24264. maxTimeout: Infinity,
  24265. randomize: false
  24266. };
  24267. for (var key in options) {
  24268. opts[key] = options[key];
  24269. }
  24270. if (opts.minTimeout > opts.maxTimeout) {
  24271. throw new Error('minTimeout is greater than maxTimeout');
  24272. }
  24273. var timeouts = [];
  24274. for (var i = 0; i < opts.retries; i++) {
  24275. timeouts.push(this._createTimeout(i, opts));
  24276. }
  24277. // sort the array numerically ascending
  24278. timeouts.sort(function(a,b) {
  24279. return a - b;
  24280. });
  24281. return timeouts;
  24282. };
  24283. exports._createTimeout = function(attempt, opts) {
  24284. var random = (opts.randomize)
  24285. ? (Math.random() + 1)
  24286. : 1;
  24287. var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
  24288. timeout = Math.min(timeout, opts.maxTimeout);
  24289. return timeout;
  24290. };
  24291. },{"./retry_operation":82}],82:[function(require,module,exports){
  24292. function RetryOperation(timeouts) {
  24293. this._timeouts = timeouts;
  24294. this._fn = null;
  24295. this._errors = [];
  24296. this._attempts = 1;
  24297. this._operationTimeout = null;
  24298. this._operationTimeoutCb = null;
  24299. this._timeout = null;
  24300. }
  24301. module.exports = RetryOperation;
  24302. RetryOperation.prototype.retry = function(err) {
  24303. if (this._timeout) {
  24304. clearTimeout(this._timeout);
  24305. }
  24306. if (!err) {
  24307. return false;
  24308. }
  24309. this._errors.push(err);
  24310. var timeout = this._timeouts.shift();
  24311. if (timeout === undefined) {
  24312. return false;
  24313. }
  24314. this._attempts++;
  24315. var self = this;
  24316. setTimeout(function() {
  24317. self._fn(self._attempts);
  24318. if (self._operationTimeoutCb) {
  24319. self._timeout = setTimeout(function() {
  24320. self._operationTimeoutCb(self._attempts);
  24321. }, self._operationTimeout);
  24322. }
  24323. }, timeout);
  24324. return true;
  24325. };
  24326. RetryOperation.prototype.attempt = function(fn, timeoutOps) {
  24327. this._fn = fn;
  24328. if (timeoutOps) {
  24329. if (timeoutOps.timeout) {
  24330. this._operationTimeout = timeoutOps.timeout;
  24331. }
  24332. if (timeoutOps.cb) {
  24333. this._operationTimeoutCb = timeoutOps.cb;
  24334. }
  24335. }
  24336. this._fn(this._attempts);
  24337. var self = this;
  24338. if (this._operationTimeoutCb) {
  24339. this._timeout = setTimeout(function() {
  24340. self._operationTimeoutCb();
  24341. }, self._operationTimeout);
  24342. }
  24343. };
  24344. RetryOperation.prototype.try = function(fn) {
  24345. console.log('Using RetryOperation.try() is deprecated');
  24346. this.attempt(fn);
  24347. };
  24348. RetryOperation.prototype.start = function(fn) {
  24349. console.log('Using RetryOperation.start() is deprecated');
  24350. this.attempt(fn);
  24351. };
  24352. RetryOperation.prototype.start = RetryOperation.prototype.try;
  24353. RetryOperation.prototype.errors = function() {
  24354. return this._errors;
  24355. };
  24356. RetryOperation.prototype.attempts = function() {
  24357. return this._attempts;
  24358. };
  24359. RetryOperation.prototype.mainError = function() {
  24360. if (this._errors.length === 0) {
  24361. return null;
  24362. }
  24363. var counts = {};
  24364. var mainError = null;
  24365. var mainErrorCount = 0;
  24366. for (var i = 0; i < this._errors.length; i++) {
  24367. var error = this._errors[i];
  24368. var message = error.message;
  24369. var count = (counts[message] || 0) + 1;
  24370. counts[message] = count;
  24371. if (count >= mainErrorCount) {
  24372. mainError = error;
  24373. mainErrorCount = count;
  24374. }
  24375. }
  24376. return mainError;
  24377. };
  24378. },{}],83:[function(require,module,exports){
  24379. /* Copyright @ 2015 Atlassian Pty Ltd
  24380. *
  24381. * Licensed under the Apache License, Version 2.0 (the "License");
  24382. * you may not use this file except in compliance with the License.
  24383. * You may obtain a copy of the License at
  24384. *
  24385. * http://www.apache.org/licenses/LICENSE-2.0
  24386. *
  24387. * Unless required by applicable law or agreed to in writing, software
  24388. * distributed under the License is distributed on an "AS IS" BASIS,
  24389. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  24390. * See the License for the specific language governing permissions and
  24391. * limitations under the License.
  24392. */
  24393. module.exports = function arrayEquals(array) {
  24394. // if the other array is a falsy value, return
  24395. if (!array)
  24396. return false;
  24397. // compare lengths - can save a lot of time
  24398. if (this.length != array.length)
  24399. return false;
  24400. for (var i = 0, l = this.length; i < l; i++) {
  24401. // Check if we have nested arrays
  24402. if (this[i] instanceof Array && array[i] instanceof Array) {
  24403. // recurse into the nested arrays
  24404. if (!arrayEquals.apply(this[i], [array[i]]))
  24405. return false;
  24406. } else if (this[i] != array[i]) {
  24407. // Warning - two different object instances will never be equal:
  24408. // {x:20} != {x:20}
  24409. return false;
  24410. }
  24411. }
  24412. return true;
  24413. }
  24414. },{}],84:[function(require,module,exports){
  24415. /* Copyright @ 2015 Atlassian Pty Ltd
  24416. *
  24417. * Licensed under the Apache License, Version 2.0 (the "License");
  24418. * you may not use this file except in compliance with the License.
  24419. * You may obtain a copy of the License at
  24420. *
  24421. * http://www.apache.org/licenses/LICENSE-2.0
  24422. *
  24423. * Unless required by applicable law or agreed to in writing, software
  24424. * distributed under the License is distributed on an "AS IS" BASIS,
  24425. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  24426. * See the License for the specific language governing permissions and
  24427. * limitations under the License.
  24428. */
  24429. exports.Interop = require('./interop');
  24430. },{"./interop":85}],85:[function(require,module,exports){
  24431. /* Copyright @ 2015 Atlassian Pty Ltd
  24432. *
  24433. * Licensed under the Apache License, Version 2.0 (the "License");
  24434. * you may not use this file except in compliance with the License.
  24435. * You may obtain a copy of the License at
  24436. *
  24437. * http://www.apache.org/licenses/LICENSE-2.0
  24438. *
  24439. * Unless required by applicable law or agreed to in writing, software
  24440. * distributed under the License is distributed on an "AS IS" BASIS,
  24441. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  24442. * See the License for the specific language governing permissions and
  24443. * limitations under the License.
  24444. */
  24445. "use strict";
  24446. var transform = require('./transform');
  24447. var arrayEquals = require('./array-equals');
  24448. function Interop() {
  24449. /**
  24450. * This map holds the most recent Unified Plan offer/answer SDP that was
  24451. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  24452. * the SDP string as values.
  24453. *
  24454. * @type {{}}
  24455. */
  24456. this.cache = {};
  24457. }
  24458. module.exports = Interop;
  24459. /**
  24460. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  24461. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  24462. * application.
  24463. *
  24464. * @param desc
  24465. * @returns {*}
  24466. */
  24467. Interop.prototype.toPlanB = function(desc) {
  24468. //#region Preliminary input validation.
  24469. if (typeof desc !== 'object' || desc === null ||
  24470. typeof desc.sdp !== 'string') {
  24471. console.warn('An empty description was passed as an argument.');
  24472. return desc;
  24473. }
  24474. // Objectify the SDP for easier manipulation.
  24475. var session = transform.parse(desc.sdp);
  24476. // If the SDP contains no media, there's nothing to transform.
  24477. if (typeof session.media === 'undefined' ||
  24478. !Array.isArray(session.media) || session.media.length === 0) {
  24479. console.warn('The description has no media.');
  24480. return desc;
  24481. }
  24482. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  24483. // SDP has a video, an audio and a data "channel" at most.
  24484. if (session.media.length <= 3 && session.media.every(function(m) {
  24485. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  24486. })) {
  24487. console.warn('This description does not look like Unified Plan.');
  24488. return desc;
  24489. }
  24490. //#endregion
  24491. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  24492. // -> Unified Plan transformation.
  24493. this.cache[desc.type] = desc.sdp;
  24494. //#region Convert from Unified Plan to Plan B.
  24495. // We rebuild the session.media array.
  24496. var media = session.media;
  24497. session.media = [];
  24498. // Associative array that maps channel types to channel objects for fast
  24499. // access to channel objects by their type, e.g. type2bl['audio']->channel
  24500. // obj.
  24501. var type2bl = {};
  24502. // Used to build the group:BUNDLE value after the channels construction
  24503. // loop.
  24504. var types = [];
  24505. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  24506. media.forEach(function(unifiedLine) {
  24507. // rtcp-mux is required in the Plan B SDP.
  24508. if ((typeof unifiedLine.rtcpMux !== 'string' ||
  24509. unifiedLine.rtcpMux !== 'rtcp-mux') &&
  24510. unifiedLine.direction !== 'inactive') {
  24511. throw new Error('Cannot convert to Plan B because m-lines ' +
  24512. 'without the rtcp-mux attribute were found.');
  24513. }
  24514. if (unifiedLine.type === 'application') {
  24515. session.media.push(unifiedLine);
  24516. types.push(unifiedLine.mid);
  24517. return;
  24518. }
  24519. // If we don't have a channel for this unifiedLine.type, then use this unifiedLine
  24520. // as the channel basis.
  24521. if (typeof type2bl[unifiedLine.type] === 'undefined') {
  24522. type2bl[unifiedLine.type] = unifiedLine;
  24523. }
  24524. // Add sources to the channel and handle a=msid.
  24525. if (typeof unifiedLine.sources === 'object') {
  24526. Object.keys(unifiedLine.sources).forEach(function(ssrc) {
  24527. if (typeof type2bl[unifiedLine.type].sources !== 'object')
  24528. type2bl[unifiedLine.type].sources = {};
  24529. // Assign the sources to the channel.
  24530. type2bl[unifiedLine.type].sources[ssrc] = unifiedLine.sources[ssrc];
  24531. if (typeof unifiedLine.msid !== 'undefined') {
  24532. // In Plan B the msid is an SSRC attribute. Also, we don't
  24533. // care about the obsolete label and mslabel attributes.
  24534. //
  24535. // Note that it is not guaranteed that the unifiedLine will have
  24536. // an msid. recvonly channels in particular don't have one.
  24537. type2bl[unifiedLine.type].sources[ssrc].msid = unifiedLine.msid;
  24538. }
  24539. // NOTE ssrcs in ssrc groups will share msids, as
  24540. // draft-uberti-rtcweb-plan-00 mandates.
  24541. });
  24542. }
  24543. // Add ssrc groups to the channel.
  24544. if (typeof unifiedLine.ssrcGroups !== 'undefined' &&
  24545. Array.isArray(unifiedLine.ssrcGroups)) {
  24546. // Create the ssrcGroups array, if it's not defined.
  24547. if (typeof type2bl[unifiedLine.type].ssrcGroups === 'undefined' ||
  24548. !Array.isArray(type2bl[unifiedLine.type].ssrcGroups)) {
  24549. type2bl[unifiedLine.type].ssrcGroups = [];
  24550. }
  24551. type2bl[unifiedLine.type].ssrcGroups = type2bl[unifiedLine.type].ssrcGroups.concat(unifiedLine.ssrcGroups);
  24552. }
  24553. if (type2bl[unifiedLine.type] === unifiedLine) {
  24554. // Copy ICE related stuff from the principal media line.
  24555. unifiedLine.candidates = media[0].candidates;
  24556. unifiedLine.iceUfrag = media[0].iceUfrag;
  24557. unifiedLine.icePwd = media[0].icePwd;
  24558. unifiedLine.fingerprint = media[0].fingerprint;
  24559. // Plan B mids are in ['audio', 'video', 'data']
  24560. unifiedLine.mid = unifiedLine.type;
  24561. // Plan B doesn't support/need the bundle-only attribute.
  24562. delete unifiedLine.bundleOnly;
  24563. // In Plan B the msid is an SSRC attribute.
  24564. delete unifiedLine.msid;
  24565. // Used to build the group:BUNDLE value after this loop.
  24566. types.push(unifiedLine.type);
  24567. // Add the channel to the new media array.
  24568. session.media.push(unifiedLine);
  24569. }
  24570. });
  24571. // We regenerate the BUNDLE group with the new mids.
  24572. session.groups.some(function(group) {
  24573. if (group.type === 'BUNDLE') {
  24574. group.mids = types.join(' ');
  24575. return true;
  24576. }
  24577. });
  24578. // msid semantic
  24579. session.msidSemantic = {
  24580. semantic: 'WMS',
  24581. token: '*'
  24582. };
  24583. var resStr = transform.write(session);
  24584. return new RTCSessionDescription({
  24585. type: desc.type,
  24586. sdp: resStr
  24587. });
  24588. //#endregion
  24589. };
  24590. /**
  24591. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  24592. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  24593. * to FF.
  24594. *
  24595. * @param desc
  24596. * @returns {*}
  24597. */
  24598. Interop.prototype.toUnifiedPlan = function(desc) {
  24599. //#region Preliminary input validation.
  24600. if (typeof desc !== 'object' || desc === null ||
  24601. typeof desc.sdp !== 'string') {
  24602. console.warn('An empty description was passed as an argument.');
  24603. return desc;
  24604. }
  24605. var session = transform.parse(desc.sdp);
  24606. // If the SDP contains no media, there's nothing to transform.
  24607. if (typeof session.media === 'undefined' ||
  24608. !Array.isArray(session.media) || session.media.length === 0) {
  24609. console.warn('The description has no media.');
  24610. return desc;
  24611. }
  24612. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  24613. // a video, an audio and a data "channel" at most.
  24614. if (session.media.length > 3 || !session.media.every(function(m) {
  24615. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  24616. })) {
  24617. console.warn('This description does not look like Plan B.');
  24618. return desc;
  24619. }
  24620. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  24621. var mids = [];
  24622. session.media.forEach(function(m) {
  24623. mids.push(m.mid);
  24624. });
  24625. var hasBundle = false;
  24626. if (typeof session.groups !== 'undefined' &&
  24627. Array.isArray(session.groups)) {
  24628. hasBundle = session.groups.every(function(g) {
  24629. return g.type !== 'BUNDLE' ||
  24630. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  24631. });
  24632. }
  24633. if (!hasBundle) {
  24634. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  24635. " are not bundled were found.");
  24636. }
  24637. //#endregion
  24638. //#region Convert from Plan B to Unified Plan.
  24639. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  24640. // rebuild an equivalent Unified Plan offer/answer.
  24641. //
  24642. // For example, if this is a local answer (in Unified Plan style) that we
  24643. // convert to Plan B prior to handing it over to the application (the
  24644. // PeerConnection wrapper called us, for instance, after a successful
  24645. // createAnswer), we want to remember the m-line at which we've seen the
  24646. // (local) SSRC. That's because when the application wants to do call the
  24647. // SLD method, forcing us to do the inverse transformation (from Plan B to
  24648. // Unified Plan), we need to know to which m-line to assign the (local)
  24649. // SSRC. We also need to know all the other m-lines that the original
  24650. // answer had and include them in the transformed answer as well.
  24651. //
  24652. // Another example is if this is a remote offer that we convert to Plan B
  24653. // prior to giving it to the application, we want to remember the mid at
  24654. // which we've seen the (remote) SSRC.
  24655. //
  24656. // In the iteration that follows, we use the cached Unified Plan (if it
  24657. // exists) to assign mids to ssrcs.
  24658. var cached;
  24659. if (typeof this.cache[desc.type] !== 'undefined') {
  24660. cached = transform.parse(this.cache[desc.type]);
  24661. }
  24662. // A helper map that sends mids to m-line objects. We use it later to
  24663. // rebuild the Unified Plan style session.media array.
  24664. var mid2ul = {};
  24665. session.media.forEach(function(bLine) {
  24666. if ((typeof bLine.rtcpMux !== 'string' ||
  24667. bLine.rtcpMux !== 'rtcp-mux') &&
  24668. bLine.direction !== 'inactive') {
  24669. throw new Error("Cannot convert to Unified Plan because m-lines " +
  24670. "without the rtcp-mux attribute were found.");
  24671. }
  24672. if (bLine.type === 'application') {
  24673. mid2ul[bLine.mid] = bLine;
  24674. return;
  24675. }
  24676. // With rtcp-mux and bundle all the channels should have the same ICE
  24677. // stuff.
  24678. var sources = bLine.sources;
  24679. var ssrcGroups = bLine.ssrcGroups;
  24680. var candidates = bLine.candidates;
  24681. var iceUfrag = bLine.iceUfrag;
  24682. var icePwd = bLine.icePwd;
  24683. var fingerprint = bLine.fingerprint;
  24684. var port = bLine.port;
  24685. // We'll use the "bLine" object as a prototype for each new "mLine"
  24686. // that we create, but first we need to clean it up a bit.
  24687. delete bLine.sources;
  24688. delete bLine.ssrcGroups;
  24689. delete bLine.candidates;
  24690. delete bLine.iceUfrag;
  24691. delete bLine.icePwd;
  24692. delete bLine.fingerprint;
  24693. delete bLine.port;
  24694. delete bLine.mid;
  24695. // inverted ssrc group map
  24696. var ssrc2group = {};
  24697. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  24698. ssrcGroups.forEach(function (ssrcGroup) {
  24699. // TODO(gp) find out how to receive simulcast with FF. For the
  24700. // time being, hide it.
  24701. if (ssrcGroup.semantics === 'SIM') {
  24702. return;
  24703. }
  24704. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  24705. Array.isArray(ssrcGroup.ssrcs)) {
  24706. ssrcGroup.ssrcs.forEach(function (ssrc) {
  24707. if (typeof ssrc2group[ssrc] === 'undefined') {
  24708. ssrc2group[ssrc] = [];
  24709. }
  24710. ssrc2group[ssrc].push(ssrcGroup);
  24711. });
  24712. }
  24713. });
  24714. }
  24715. // ssrc to m-line index.
  24716. var ssrc2ml = {};
  24717. if (typeof sources === 'object') {
  24718. // Explode the Plan B channel sources with one m-line per source.
  24719. Object.keys(sources).forEach(function(ssrc) {
  24720. // The (unified) m-line for this SSRC. We either create it from
  24721. // scratch or, if it's a grouped SSRC, we re-use a related
  24722. // mline. In other words, if the source is grouped with another
  24723. // source, put the two together in the same m-line.
  24724. var unifiedLine;
  24725. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  24726. Array.isArray(ssrc2group[ssrc])) {
  24727. ssrc2group[ssrc].some(function (ssrcGroup) {
  24728. // ssrcGroup.ssrcs *is* an Array, no need to check
  24729. // again here.
  24730. return ssrcGroup.ssrcs.some(function (related) {
  24731. if (typeof ssrc2ml[related] === 'object') {
  24732. unifiedLine = ssrc2ml[related];
  24733. return true;
  24734. }
  24735. });
  24736. });
  24737. }
  24738. if (typeof unifiedLine === 'object') {
  24739. // the m-line already exists. Just add the source.
  24740. unifiedLine.sources[ssrc] = sources[ssrc];
  24741. delete sources[ssrc].msid;
  24742. } else {
  24743. // Use the "bLine" as a prototype for the "unifiedLine".
  24744. unifiedLine = Object.create(bLine);
  24745. ssrc2ml[ssrc] = unifiedLine;
  24746. if (typeof sources[ssrc].msid !== 'undefined') {
  24747. // Assign the msid of the source to the m-line. Note
  24748. // that it is not guaranteed that the source will have
  24749. // msid. In particular "recvonly" sources don't have an
  24750. // msid. Note that "recvonly" is a term only defined
  24751. // for m-lines.
  24752. unifiedLine.msid = sources[ssrc].msid;
  24753. delete sources[ssrc].msid;
  24754. }
  24755. // We assign one SSRC per media line.
  24756. unifiedLine.sources = {};
  24757. unifiedLine.sources[ssrc] = sources[ssrc];
  24758. unifiedLine.ssrcGroups = ssrc2group[ssrc];
  24759. // Use the cached Unified Plan SDP (if it exists) to assign
  24760. // SSRCs to mids.
  24761. if (typeof cached !== 'undefined' &&
  24762. typeof cached.media !== 'undefined' &&
  24763. Array.isArray(cached.media)) {
  24764. cached.media.forEach(function (m) {
  24765. if (typeof m.sources === 'object') {
  24766. Object.keys(m.sources).forEach(function (s) {
  24767. if (s === ssrc) {
  24768. unifiedLine.mid = m.mid;
  24769. }
  24770. });
  24771. }
  24772. });
  24773. }
  24774. if (typeof unifiedLine.mid === 'undefined') {
  24775. // If this is an SSRC that we see for the first time
  24776. // assign it a new mid. This is typically the case when
  24777. // this method is called to transform a remote
  24778. // description for the first time or when there is a
  24779. // new SSRC in the remote description because a new
  24780. // peer has joined the conference. Local SSRCs should
  24781. // have already been added to the map in the toPlanB
  24782. // method.
  24783. //
  24784. // Because FF generates answers in Unified Plan style,
  24785. // we MUST already have a cached answer with all the
  24786. // local SSRCs mapped to some m-line/mid.
  24787. if (desc.type === 'answer') {
  24788. throw new Error("An unmapped SSRC was found.");
  24789. }
  24790. unifiedLine.mid = [bLine.type, '-', ssrc].join('');
  24791. }
  24792. // Include the candidates in the 1st media line.
  24793. unifiedLine.candidates = candidates;
  24794. unifiedLine.iceUfrag = iceUfrag;
  24795. unifiedLine.icePwd = icePwd;
  24796. unifiedLine.fingerprint = fingerprint;
  24797. unifiedLine.port = port;
  24798. mid2ul[unifiedLine.mid] = unifiedLine;
  24799. }
  24800. });
  24801. }
  24802. });
  24803. // Rebuild the media array in the right order and add the missing mLines
  24804. // (missing from the Plan B SDP).
  24805. session.media = [];
  24806. mids = []; // reuse
  24807. if (desc.type === 'answer') {
  24808. // The media lines in the answer must match the media lines in the
  24809. // offer. The order is important too. Here we assume that Firefox is the
  24810. // answerer, so we merely have to use the reconstructed (unified) answer
  24811. // to update the cached (unified) answer accordingly.
  24812. //
  24813. // In the general case, one would have to use the cached (unified) offer
  24814. // to find the m-lines that are missing from the reconstructed answer,
  24815. // potentially grabbing them from the cached (unified) answer. One has
  24816. // to be carefull with this approach because inactive m-lines do not
  24817. // always have an mid, making it tricky (impossible?) to find where
  24818. // exactly and which m-lines are missing from the reconstructed answer.
  24819. for (var i = 0; i < cached.media.length; i++) {
  24820. var unifiedLine = cached.media[i];
  24821. if (typeof mid2ul[unifiedLine.mid] === 'undefined') {
  24822. // The mid isn't in the reconstructed (unified) answer.
  24823. // This is either a (unified) m-line containing a remote
  24824. // track only, or a (unified) m-line containing a remote
  24825. // track and a local track that has been removed.
  24826. // In either case, it MUST exist in the cached
  24827. // (unified) answer.
  24828. //
  24829. // In case this is a removed local track, clean-up
  24830. // the (unified) m-line and make sure it's 'recvonly' or
  24831. // 'inactive'.
  24832. delete unifiedLine.msid;
  24833. delete unifiedLine.sources;
  24834. delete unifiedLine.ssrcGroups;
  24835. if (!unifiedLine.direction
  24836. || unifiedLine.direction === 'sendrecv')
  24837. unifiedLine.direction = 'recvonly';
  24838. if (!unifiedLine.direction
  24839. || unifiedLine.direction === 'sendonly')
  24840. unifiedLine.direction = 'inactive';
  24841. } else {
  24842. // This is an (unified) m-line/channel that contains a local
  24843. // track (sendrecv or sendonly channel) or it's a unified
  24844. // recvonly m-line/channel. In either case, since we're
  24845. // going from PlanB -> Unified Plan this m-line MUST
  24846. // exist in the cached answer.
  24847. }
  24848. session.media.push(unifiedLine);
  24849. if (typeof unifiedLine.mid === 'string') {
  24850. // inactive lines don't/may not have an mid.
  24851. mids.push(unifiedLine.mid);
  24852. }
  24853. }
  24854. } else {
  24855. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  24856. // under any circumstances. If we are no longer interested in sending a
  24857. // track, we just remove the msid and ssrc attributes and set it to
  24858. // either a=recvonly (as the reofferer, we must use recvonly if the
  24859. // other side was previously sending on the m-section, but we can also
  24860. // leave the possibility open if it wasn't previously in use), or
  24861. // a=inacive.
  24862. if (typeof cached !== 'undefined' &&
  24863. typeof cached.media !== 'undefined' &&
  24864. Array.isArray(cached.media)) {
  24865. cached.media.forEach(function(unifiedLine) {
  24866. mids.push(unifiedLine.mid);
  24867. if (typeof mid2ul[unifiedLine.mid] !== 'undefined') {
  24868. session.media.push(mid2ul[unifiedLine.mid]);
  24869. } else {
  24870. delete unifiedLine.msid;
  24871. delete unifiedLine.sources;
  24872. delete unifiedLine.ssrcGroups;
  24873. if (!unifiedLine.direction
  24874. || unifiedLine.direction === 'sendrecv')
  24875. unifiedLine.direction = 'recvonly';
  24876. if (!unifiedLine.direction
  24877. || unifiedLine.direction === 'sendonly')
  24878. unifiedLine.direction = 'inactive';
  24879. session.media.push(unifiedLine);
  24880. }
  24881. });
  24882. }
  24883. // Add all the remaining (new) m-lines of the transformed SDP.
  24884. Object.keys(mid2ul).forEach(function(mid) {
  24885. if (mids.indexOf(mid) === -1) {
  24886. mids.push(mid);
  24887. if (typeof mid2ul[mid].direction === 'recvonly') {
  24888. // This is a remote recvonly channel. Add its SSRC to the
  24889. // appropriate sendrecv or sendonly channel.
  24890. // TODO(gp) what if we don't have sendrecv/sendonly channel?
  24891. session.media.some(function (unifiedLine) {
  24892. if ((unifiedLine.direction === 'sendrecv' ||
  24893. unifiedLine.direction === 'sendonly') &&
  24894. unifiedLine.type === mid2ul[mid].type) {
  24895. // mid2ul[mid] shouldn't have any ssrc-groups
  24896. Object.keys(mid2ul[mid].sources).forEach(function (ssrc) {
  24897. unifiedLine.sources[ssrc] = mid2ul[mid].sources[ssrc];
  24898. });
  24899. return true;
  24900. }
  24901. });
  24902. } else {
  24903. session.media.push(mid2ul[mid]);
  24904. }
  24905. }
  24906. });
  24907. }
  24908. // We regenerate the BUNDLE group (since we regenerated the mids)
  24909. session.groups.some(function(group) {
  24910. if (group.type === 'BUNDLE') {
  24911. group.mids = mids.join(' ');
  24912. return true;
  24913. }
  24914. });
  24915. // msid semantic
  24916. session.msidSemantic = {
  24917. semantic: 'WMS',
  24918. token: '*'
  24919. };
  24920. var resStr = transform.write(session);
  24921. // Cache the transformed SDP (Unified Plan) for later re-use in this
  24922. // function.
  24923. this.cache[desc.type] = resStr;
  24924. return new RTCSessionDescription({
  24925. type: desc.type,
  24926. sdp: resStr
  24927. });
  24928. //#endregion
  24929. };
  24930. },{"./array-equals":83,"./transform":86}],86:[function(require,module,exports){
  24931. /* Copyright @ 2015 Atlassian Pty Ltd
  24932. *
  24933. * Licensed under the Apache License, Version 2.0 (the "License");
  24934. * you may not use this file except in compliance with the License.
  24935. * You may obtain a copy of the License at
  24936. *
  24937. * http://www.apache.org/licenses/LICENSE-2.0
  24938. *
  24939. * Unless required by applicable law or agreed to in writing, software
  24940. * distributed under the License is distributed on an "AS IS" BASIS,
  24941. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  24942. * See the License for the specific language governing permissions and
  24943. * limitations under the License.
  24944. */
  24945. var transform = require('sdp-transform');
  24946. exports.write = function(session, opts) {
  24947. if (typeof session !== 'undefined' &&
  24948. typeof session.media !== 'undefined' &&
  24949. Array.isArray(session.media)) {
  24950. session.media.forEach(function (mLine) {
  24951. // expand sources to ssrcs
  24952. if (typeof mLine.sources !== 'undefined' &&
  24953. Object.keys(mLine.sources).length !== 0) {
  24954. mLine.ssrcs = [];
  24955. Object.keys(mLine.sources).forEach(function (ssrc) {
  24956. var source = mLine.sources[ssrc];
  24957. Object.keys(source).forEach(function (attribute) {
  24958. mLine.ssrcs.push({
  24959. id: ssrc,
  24960. attribute: attribute,
  24961. value: source[attribute]
  24962. });
  24963. });
  24964. });
  24965. delete mLine.sources;
  24966. }
  24967. // join ssrcs in ssrc groups
  24968. if (typeof mLine.ssrcGroups !== 'undefined' &&
  24969. Array.isArray(mLine.ssrcGroups)) {
  24970. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  24971. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  24972. Array.isArray(ssrcGroup.ssrcs)) {
  24973. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  24974. }
  24975. });
  24976. }
  24977. });
  24978. }
  24979. // join group mids
  24980. if (typeof session !== 'undefined' &&
  24981. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  24982. session.groups.forEach(function (g) {
  24983. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  24984. g.mids = g.mids.join(' ');
  24985. }
  24986. });
  24987. }
  24988. return transform.write(session, opts);
  24989. };
  24990. exports.parse = function(sdp) {
  24991. var session = transform.parse(sdp);
  24992. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  24993. Array.isArray(session.media)) {
  24994. session.media.forEach(function (mLine) {
  24995. // group sources attributes by ssrc
  24996. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  24997. mLine.sources = {};
  24998. mLine.ssrcs.forEach(function (ssrc) {
  24999. if (!mLine.sources[ssrc.id])
  25000. mLine.sources[ssrc.id] = {};
  25001. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  25002. });
  25003. delete mLine.ssrcs;
  25004. }
  25005. // split ssrcs in ssrc groups
  25006. if (typeof mLine.ssrcGroups !== 'undefined' &&
  25007. Array.isArray(mLine.ssrcGroups)) {
  25008. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  25009. if (typeof ssrcGroup.ssrcs === 'string') {
  25010. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  25011. }
  25012. });
  25013. }
  25014. });
  25015. }
  25016. // split group mids
  25017. if (typeof session !== 'undefined' &&
  25018. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  25019. session.groups.forEach(function (g) {
  25020. if (typeof g.mids === 'string') {
  25021. g.mids = g.mids.split(' ');
  25022. }
  25023. });
  25024. }
  25025. return session;
  25026. };
  25027. },{"sdp-transform":88}],87:[function(require,module,exports){
  25028. var grammar = module.exports = {
  25029. v: [{
  25030. name: 'version',
  25031. reg: /^(\d*)$/
  25032. }],
  25033. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  25034. // NB: sessionId will be a String in most cases because it is huge
  25035. name: 'origin',
  25036. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  25037. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  25038. format: "%s %s %d %s IP%d %s"
  25039. }],
  25040. // default parsing of these only (though some of these feel outdated)
  25041. s: [{ name: 'name' }],
  25042. i: [{ name: 'description' }],
  25043. u: [{ name: 'uri' }],
  25044. e: [{ name: 'email' }],
  25045. p: [{ name: 'phone' }],
  25046. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  25047. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  25048. //k: [{}], // outdated thing ignored
  25049. t: [{ //t=0 0
  25050. name: 'timing',
  25051. reg: /^(\d*) (\d*)/,
  25052. names: ['start', 'stop'],
  25053. format: "%d %d"
  25054. }],
  25055. c: [{ //c=IN IP4 10.47.197.26
  25056. name: 'connection',
  25057. reg: /^IN IP(\d) (\S*)/,
  25058. names: ['version', 'ip'],
  25059. format: "IN IP%d %s"
  25060. }],
  25061. b: [{ //b=AS:4000
  25062. push: 'bandwidth',
  25063. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  25064. names: ['type', 'limit'],
  25065. format: "%s:%s"
  25066. }],
  25067. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  25068. // NB: special - pushes to session
  25069. // TODO: rtp/fmtp should be filtered by the payloads found here?
  25070. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  25071. names: ['type', 'port', 'protocol', 'payloads'],
  25072. format: "%s %d %s %s"
  25073. }],
  25074. a: [
  25075. { //a=rtpmap:110 opus/48000/2
  25076. push: 'rtp',
  25077. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  25078. names: ['payload', 'codec', 'rate', 'encoding'],
  25079. format: function (o) {
  25080. return (o.encoding) ?
  25081. "rtpmap:%d %s/%s/%s":
  25082. "rtpmap:%d %s/%s";
  25083. }
  25084. },
  25085. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  25086. push: 'fmtp',
  25087. reg: /^fmtp:(\d*) (\S*)/,
  25088. names: ['payload', 'config'],
  25089. format: "fmtp:%d %s"
  25090. },
  25091. { //a=control:streamid=0
  25092. name: 'control',
  25093. reg: /^control:(.*)/,
  25094. format: "control:%s"
  25095. },
  25096. { //a=rtcp:65179 IN IP4 193.84.77.194
  25097. name: 'rtcp',
  25098. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  25099. names: ['port', 'netType', 'ipVer', 'address'],
  25100. format: function (o) {
  25101. return (o.address != null) ?
  25102. "rtcp:%d %s IP%d %s":
  25103. "rtcp:%d";
  25104. }
  25105. },
  25106. { //a=rtcp-fb:98 trr-int 100
  25107. push: 'rtcpFbTrrInt',
  25108. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  25109. names: ['payload', 'value'],
  25110. format: "rtcp-fb:%d trr-int %d"
  25111. },
  25112. { //a=rtcp-fb:98 nack rpsi
  25113. push: 'rtcpFb',
  25114. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  25115. names: ['payload', 'type', 'subtype'],
  25116. format: function (o) {
  25117. return (o.subtype != null) ?
  25118. "rtcp-fb:%s %s %s":
  25119. "rtcp-fb:%s %s";
  25120. }
  25121. },
  25122. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  25123. //a=extmap:1/recvonly URI-gps-string
  25124. push: 'ext',
  25125. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  25126. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  25127. format: function (o) {
  25128. return (o.config != null) ?
  25129. "extmap:%s %s %s":
  25130. "extmap:%s %s";
  25131. }
  25132. },
  25133. {
  25134. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  25135. push: 'crypto',
  25136. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  25137. names: ['id', 'suite', 'config', 'sessionConfig'],
  25138. format: function (o) {
  25139. return (o.sessionConfig != null) ?
  25140. "crypto:%d %s %s %s":
  25141. "crypto:%d %s %s";
  25142. }
  25143. },
  25144. { //a=setup:actpass
  25145. name: 'setup',
  25146. reg: /^setup:(\w*)/,
  25147. format: "setup:%s"
  25148. },
  25149. { //a=mid:1
  25150. name: 'mid',
  25151. reg: /^mid:([^\s]*)/,
  25152. format: "mid:%s"
  25153. },
  25154. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  25155. name: 'msid',
  25156. reg: /^msid:(.*)/,
  25157. format: "msid:%s"
  25158. },
  25159. { //a=ptime:20
  25160. name: 'ptime',
  25161. reg: /^ptime:(\d*)/,
  25162. format: "ptime:%d"
  25163. },
  25164. { //a=maxptime:60
  25165. name: 'maxptime',
  25166. reg: /^maxptime:(\d*)/,
  25167. format: "maxptime:%d"
  25168. },
  25169. { //a=sendrecv
  25170. name: 'direction',
  25171. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  25172. },
  25173. { //a=ice-lite
  25174. name: 'icelite',
  25175. reg: /^(ice-lite)/
  25176. },
  25177. { //a=ice-ufrag:F7gI
  25178. name: 'iceUfrag',
  25179. reg: /^ice-ufrag:(\S*)/,
  25180. format: "ice-ufrag:%s"
  25181. },
  25182. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  25183. name: 'icePwd',
  25184. reg: /^ice-pwd:(\S*)/,
  25185. format: "ice-pwd:%s"
  25186. },
  25187. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  25188. name: 'fingerprint',
  25189. reg: /^fingerprint:(\S*) (\S*)/,
  25190. names: ['type', 'hash'],
  25191. format: "fingerprint:%s %s"
  25192. },
  25193. {
  25194. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  25195. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  25196. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  25197. push:'candidates',
  25198. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  25199. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  25200. format: function (o) {
  25201. var str = "candidate:%s %d %s %d %s %d typ %s";
  25202. // NB: candidate has two optional chunks, so %void middle one if it's missing
  25203. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  25204. if (o.generation != null) {
  25205. str += " generation %d";
  25206. }
  25207. return str;
  25208. }
  25209. },
  25210. { //a=end-of-candidates (keep after the candidates line for readability)
  25211. name: 'endOfCandidates',
  25212. reg: /^(end-of-candidates)/
  25213. },
  25214. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  25215. name: 'remoteCandidates',
  25216. reg: /^remote-candidates:(.*)/,
  25217. format: "remote-candidates:%s"
  25218. },
  25219. { //a=ice-options:google-ice
  25220. name: 'iceOptions',
  25221. reg: /^ice-options:(\S*)/,
  25222. format: "ice-options:%s"
  25223. },
  25224. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  25225. push: "ssrcs",
  25226. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  25227. names: ['id', 'attribute', 'value'],
  25228. format: "ssrc:%d %s:%s"
  25229. },
  25230. { //a=ssrc-group:FEC 1 2
  25231. push: "ssrcGroups",
  25232. reg: /^ssrc-group:(\w*) (.*)/,
  25233. names: ['semantics', 'ssrcs'],
  25234. format: "ssrc-group:%s %s"
  25235. },
  25236. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  25237. name: "msidSemantic",
  25238. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  25239. names: ['semantic', 'token'],
  25240. format: "msid-semantic: %s %s" // space after ":" is not accidental
  25241. },
  25242. { //a=group:BUNDLE audio video
  25243. push: 'groups',
  25244. reg: /^group:(\w*) (.*)/,
  25245. names: ['type', 'mids'],
  25246. format: "group:%s %s"
  25247. },
  25248. { //a=rtcp-mux
  25249. name: 'rtcpMux',
  25250. reg: /^(rtcp-mux)/
  25251. },
  25252. { //a=rtcp-rsize
  25253. name: 'rtcpRsize',
  25254. reg: /^(rtcp-rsize)/
  25255. },
  25256. { // any a= that we don't understand is kepts verbatim on media.invalid
  25257. push: 'invalid',
  25258. names: ["value"]
  25259. }
  25260. ]
  25261. };
  25262. // set sensible defaults to avoid polluting the grammar with boring details
  25263. Object.keys(grammar).forEach(function (key) {
  25264. var objs = grammar[key];
  25265. objs.forEach(function (obj) {
  25266. if (!obj.reg) {
  25267. obj.reg = /(.*)/;
  25268. }
  25269. if (!obj.format) {
  25270. obj.format = "%s";
  25271. }
  25272. });
  25273. });
  25274. },{}],88:[function(require,module,exports){
  25275. var parser = require('./parser');
  25276. var writer = require('./writer');
  25277. exports.write = writer;
  25278. exports.parse = parser.parse;
  25279. exports.parseFmtpConfig = parser.parseFmtpConfig;
  25280. exports.parsePayloads = parser.parsePayloads;
  25281. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  25282. },{"./parser":89,"./writer":90}],89:[function(require,module,exports){
  25283. var toIntIfInt = function (v) {
  25284. return String(Number(v)) === v ? Number(v) : v;
  25285. };
  25286. var attachProperties = function (match, location, names, rawName) {
  25287. if (rawName && !names) {
  25288. location[rawName] = toIntIfInt(match[1]);
  25289. }
  25290. else {
  25291. for (var i = 0; i < names.length; i += 1) {
  25292. if (match[i+1] != null) {
  25293. location[names[i]] = toIntIfInt(match[i+1]);
  25294. }
  25295. }
  25296. }
  25297. };
  25298. var parseReg = function (obj, location, content) {
  25299. var needsBlank = obj.name && obj.names;
  25300. if (obj.push && !location[obj.push]) {
  25301. location[obj.push] = [];
  25302. }
  25303. else if (needsBlank && !location[obj.name]) {
  25304. location[obj.name] = {};
  25305. }
  25306. var keyLocation = obj.push ?
  25307. {} : // blank object that will be pushed
  25308. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  25309. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  25310. if (obj.push) {
  25311. location[obj.push].push(keyLocation);
  25312. }
  25313. };
  25314. var grammar = require('./grammar');
  25315. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  25316. exports.parse = function (sdp) {
  25317. var session = {}
  25318. , media = []
  25319. , location = session; // points at where properties go under (one of the above)
  25320. // parse lines we understand
  25321. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  25322. var type = l[0];
  25323. var content = l.slice(2);
  25324. if (type === 'm') {
  25325. media.push({rtp: [], fmtp: []});
  25326. location = media[media.length-1]; // point at latest media line
  25327. }
  25328. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  25329. var obj = grammar[type][j];
  25330. if (obj.reg.test(content)) {
  25331. return parseReg(obj, location, content);
  25332. }
  25333. }
  25334. });
  25335. session.media = media; // link it up
  25336. return session;
  25337. };
  25338. var fmtpReducer = function (acc, expr) {
  25339. var s = expr.split('=');
  25340. if (s.length === 2) {
  25341. acc[s[0]] = toIntIfInt(s[1]);
  25342. }
  25343. return acc;
  25344. };
  25345. exports.parseFmtpConfig = function (str) {
  25346. return str.split(';').reduce(fmtpReducer, {});
  25347. };
  25348. exports.parsePayloads = function (str) {
  25349. return str.split(' ').map(Number);
  25350. };
  25351. exports.parseRemoteCandidates = function (str) {
  25352. var candidates = [];
  25353. var parts = str.split(' ').map(toIntIfInt);
  25354. for (var i = 0; i < parts.length; i += 3) {
  25355. candidates.push({
  25356. component: parts[i],
  25357. ip: parts[i + 1],
  25358. port: parts[i + 2]
  25359. });
  25360. }
  25361. return candidates;
  25362. };
  25363. },{"./grammar":87}],90:[function(require,module,exports){
  25364. var grammar = require('./grammar');
  25365. // customized util.format - discards excess arguments and can void middle ones
  25366. var formatRegExp = /%[sdv%]/g;
  25367. var format = function (formatStr) {
  25368. var i = 1;
  25369. var args = arguments;
  25370. var len = args.length;
  25371. return formatStr.replace(formatRegExp, function (x) {
  25372. if (i >= len) {
  25373. return x; // missing argument
  25374. }
  25375. var arg = args[i];
  25376. i += 1;
  25377. switch (x) {
  25378. case '%%':
  25379. return '%';
  25380. case '%s':
  25381. return String(arg);
  25382. case '%d':
  25383. return Number(arg);
  25384. case '%v':
  25385. return '';
  25386. }
  25387. });
  25388. // NB: we discard excess arguments - they are typically undefined from makeLine
  25389. };
  25390. var makeLine = function (type, obj, location) {
  25391. var str = obj.format instanceof Function ?
  25392. (obj.format(obj.push ? location : location[obj.name])) :
  25393. obj.format;
  25394. var args = [type + '=' + str];
  25395. if (obj.names) {
  25396. for (var i = 0; i < obj.names.length; i += 1) {
  25397. var n = obj.names[i];
  25398. if (obj.name) {
  25399. args.push(location[obj.name][n]);
  25400. }
  25401. else { // for mLine and push attributes
  25402. args.push(location[obj.names[i]]);
  25403. }
  25404. }
  25405. }
  25406. else {
  25407. args.push(location[obj.name]);
  25408. }
  25409. return format.apply(null, args);
  25410. };
  25411. // RFC specified order
  25412. // TODO: extend this with all the rest
  25413. var defaultOuterOrder = [
  25414. 'v', 'o', 's', 'i',
  25415. 'u', 'e', 'p', 'c',
  25416. 'b', 't', 'r', 'z', 'a'
  25417. ];
  25418. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  25419. module.exports = function (session, opts) {
  25420. opts = opts || {};
  25421. // ensure certain properties exist
  25422. if (session.version == null) {
  25423. session.version = 0; // "v=0" must be there (only defined version atm)
  25424. }
  25425. if (session.name == null) {
  25426. session.name = " "; // "s= " must be there if no meaningful name set
  25427. }
  25428. session.media.forEach(function (mLine) {
  25429. if (mLine.payloads == null) {
  25430. mLine.payloads = "";
  25431. }
  25432. });
  25433. var outerOrder = opts.outerOrder || defaultOuterOrder;
  25434. var innerOrder = opts.innerOrder || defaultInnerOrder;
  25435. var sdp = [];
  25436. // loop through outerOrder for matching properties on session
  25437. outerOrder.forEach(function (type) {
  25438. grammar[type].forEach(function (obj) {
  25439. if (obj.name in session && session[obj.name] != null) {
  25440. sdp.push(makeLine(type, obj, session));
  25441. }
  25442. else if (obj.push in session && session[obj.push] != null) {
  25443. session[obj.push].forEach(function (el) {
  25444. sdp.push(makeLine(type, obj, el));
  25445. });
  25446. }
  25447. });
  25448. });
  25449. // then for each media line, follow the innerOrder
  25450. session.media.forEach(function (mLine) {
  25451. sdp.push(makeLine('m', grammar.m[0], mLine));
  25452. innerOrder.forEach(function (type) {
  25453. grammar[type].forEach(function (obj) {
  25454. if (obj.name in mLine && mLine[obj.name] != null) {
  25455. sdp.push(makeLine(type, obj, mLine));
  25456. }
  25457. else if (obj.push in mLine && mLine[obj.push] != null) {
  25458. mLine[obj.push].forEach(function (el) {
  25459. sdp.push(makeLine(type, obj, el));
  25460. });
  25461. }
  25462. });
  25463. });
  25464. });
  25465. return sdp.join('\r\n') + '\r\n';
  25466. };
  25467. },{"./grammar":87}],91:[function(require,module,exports){
  25468. /* Copyright @ 2015 Atlassian Pty Ltd
  25469. *
  25470. * Licensed under the Apache License, Version 2.0 (the "License");
  25471. * you may not use this file except in compliance with the License.
  25472. * You may obtain a copy of the License at
  25473. *
  25474. * http://www.apache.org/licenses/LICENSE-2.0
  25475. *
  25476. * Unless required by applicable law or agreed to in writing, software
  25477. * distributed under the License is distributed on an "AS IS" BASIS,
  25478. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  25479. * See the License for the specific language governing permissions and
  25480. * limitations under the License.
  25481. */
  25482. var transform = require('sdp-transform');
  25483. var transformUtils = require('./transform-utils');
  25484. var parseSsrcs = transformUtils.parseSsrcs;
  25485. var writeSsrcs = transformUtils.writeSsrcs;
  25486. //region Constants
  25487. var DEFAULT_NUM_OF_LAYERS = 3;
  25488. //endregion
  25489. //region Ctor
  25490. function Simulcast(options) {
  25491. this.options = options ? options : {};
  25492. if (!this.options.numOfLayers) {
  25493. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  25494. }
  25495. this.layers = [];
  25496. }
  25497. //endregion
  25498. //region Stateless private utility functions
  25499. /**
  25500. * Returns a random integer between min (included) and max (excluded)
  25501. * Using Math.round() gives a non-uniform distribution!
  25502. * @returns {number}
  25503. */
  25504. function generateSSRC() {
  25505. var min = 0, max = 0xffffffff;
  25506. return Math.floor(Math.random() * (max - min)) + min;
  25507. };
  25508. function processVideo(session, action) {
  25509. if (session == null || !Array.isArray(session.media)) {
  25510. return;
  25511. }
  25512. session.media.forEach(function (mLine) {
  25513. if (mLine.type === 'video') {
  25514. action(mLine);
  25515. }
  25516. });
  25517. }
  25518. function validateDescription(desc)
  25519. {
  25520. return desc && desc != null
  25521. && desc.type && desc.type != ''
  25522. && desc.sdp && desc.sdp != '';
  25523. }
  25524. function explodeRemoteSimulcast(mLine) {
  25525. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  25526. return;
  25527. }
  25528. var sources = parseSsrcs(mLine);
  25529. var order = [];
  25530. // Find the SIM group and explode its sources.
  25531. var j = mLine.ssrcGroups.length;
  25532. while (j--) {
  25533. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  25534. continue;
  25535. }
  25536. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  25537. for (var i = 0; i < simulcastSsrcs.length; i++) {
  25538. var ssrc = simulcastSsrcs[i];
  25539. order.push(ssrc);
  25540. var parts = sources[ssrc].msid.split(' ');
  25541. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  25542. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  25543. // Remove all the groups that this SSRC participates in.
  25544. mLine.ssrcGroups.forEach(function (relatedGroup) {
  25545. if (relatedGroup.semantics === 'SIM') {
  25546. return;
  25547. }
  25548. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  25549. if (relatedSsrcs.indexOf(ssrc) === -1) {
  25550. return;
  25551. }
  25552. // Nuke all the related SSRCs.
  25553. relatedSsrcs.forEach(function (relatedSSRC) {
  25554. sources[relatedSSRC].msid = sources[ssrc].msid;
  25555. sources[relatedSSRC].cname = sources[ssrc].cname;
  25556. if (relatedSSRC !== ssrc) {
  25557. order.push(relatedSSRC);
  25558. }
  25559. });
  25560. // Schedule the related group for nuking.
  25561. })
  25562. }
  25563. mLine.ssrcs = writeSsrcs(sources, order);
  25564. mLine.ssrcGroups.splice(j, 1);
  25565. };
  25566. }
  25567. function squeezeRemoteSimulcast(mLine) {
  25568. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  25569. return;
  25570. }
  25571. var sources = parseSsrcs(mLine);
  25572. // Find the SIM group and nuke it.
  25573. mLine.ssrcGroups.some(function (simulcastGroup) {
  25574. if (simulcastGroup.semantics !== 'SIM') {
  25575. return false;
  25576. }
  25577. // Schedule the SIM group for nuking.
  25578. simulcastGroup.nuke = true;
  25579. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  25580. // Nuke all the higher layer SSRCs.
  25581. for (var i = 1; i < simulcastSsrcs.length; i++) {
  25582. var ssrc = simulcastSsrcs[i];
  25583. delete sources[ssrc];
  25584. // Remove all the groups that this SSRC participates in.
  25585. mLine.ssrcGroups.forEach(function (relatedGroup) {
  25586. if (relatedGroup.semantics === 'SIM') {
  25587. return;
  25588. }
  25589. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  25590. if (relatedSsrcs.indexOf(ssrc) === -1) {
  25591. return;
  25592. }
  25593. // Nuke all the related SSRCs.
  25594. relatedSsrcs.forEach(function (relatedSSRC) {
  25595. delete sources[relatedSSRC];
  25596. });
  25597. // Schedule the related group for nuking.
  25598. relatedGroup.nuke = true;
  25599. })
  25600. }
  25601. return true;
  25602. });
  25603. mLine.ssrcs = writeSsrcs(sources);
  25604. // Nuke all the scheduled groups.
  25605. var i = mLine.ssrcGroups.length;
  25606. while (i--) {
  25607. if (mLine.ssrcGroups[i].nuke) {
  25608. mLine.ssrcGroups.splice(i, 1);
  25609. }
  25610. }
  25611. }
  25612. function removeGoogConference(mLine) {
  25613. if (!mLine || !Array.isArray(mLine.invalid)) {
  25614. return;
  25615. }
  25616. var i = mLine.invalid.length;
  25617. while (i--) {
  25618. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  25619. mLine.invalid.splice(i, 1);
  25620. }
  25621. }
  25622. }
  25623. function assertGoogConference(mLine) {
  25624. if (!mLine) {
  25625. return;
  25626. }
  25627. if (!Array.isArray(mLine.invalid)) {
  25628. mLine.invalid = [];
  25629. }
  25630. if (!mLine.invalid.some(
  25631. function (i) { return i.value === 'x-google-flag:conference' })) {
  25632. mLine.invalid.push({'value': 'x-google-flag:conference'});
  25633. }
  25634. }
  25635. //endregion
  25636. //region "Private" functions
  25637. /**
  25638. *
  25639. * @param mLine
  25640. * @private
  25641. */
  25642. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  25643. if (!mLine || mLine.type !== 'video') {
  25644. return;
  25645. }
  25646. var sources = parseSsrcs(mLine);
  25647. if (Object.keys(sources).length === 0) {
  25648. // no sources, disable simulcast.
  25649. if (this.layers.length !== 0) {
  25650. this.layers = [];
  25651. }
  25652. return;
  25653. }
  25654. // find the base layer (we'll reuse its msid and cname).
  25655. var baseLayerSSRC = Object.keys(sources)[0];
  25656. var baseLayer = sources[baseLayerSSRC];
  25657. // todo(gp) handle screen sharing.
  25658. // check if base CNAME has changed and reinitialise layers.
  25659. if (this.layers.length > 0
  25660. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  25661. this.layers = [];
  25662. }
  25663. // (re)initialise layers
  25664. if (this.layers.length < 1) {
  25665. // first push the base layer.
  25666. this.layers.push({
  25667. ssrc: baseLayerSSRC,
  25668. msid: baseLayer.msid,
  25669. cname: baseLayer.cname
  25670. });
  25671. var rtx = false; // RFC 4588
  25672. if (Array.isArray(mLine.rtp)) {
  25673. rtx = mLine.rtp.some(
  25674. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  25675. }
  25676. if (rtx) {
  25677. this.layers[0].rtx = generateSSRC();
  25678. }
  25679. // now push additional layers.
  25680. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  25681. var layer = { ssrc: generateSSRC() };
  25682. if (rtx) {
  25683. layer.rtx = generateSSRC();
  25684. }
  25685. this.layers.push(layer);
  25686. }
  25687. }
  25688. };
  25689. /**
  25690. *
  25691. * @param mLine
  25692. * @private
  25693. */
  25694. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  25695. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  25696. var sources = {};
  25697. var msid = this.layers[0].msid;
  25698. var cname = this.layers[0].cname;
  25699. var simulcastSsrcs = [];
  25700. var ssrcGroups = [];
  25701. for (var i = 0; i < this.layers.length; i++) {
  25702. var layer = this.layers[i];
  25703. sources[layer.ssrc] = { msid: msid, cname: cname };
  25704. simulcastSsrcs.push(layer.ssrc);
  25705. if (layer.rtx) {
  25706. sources[layer.rtx] = {
  25707. msid: msid,
  25708. cname: cname
  25709. }
  25710. ssrcGroups.push({
  25711. semantics: 'FID',
  25712. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  25713. });
  25714. }
  25715. }
  25716. ssrcGroups.push({
  25717. semantics: 'SIM',
  25718. ssrcs: simulcastSsrcs.join(' ')
  25719. });
  25720. mLine.ssrcGroups = ssrcGroups;
  25721. mLine.ssrcs = writeSsrcs(sources);
  25722. }
  25723. }
  25724. //endregion
  25725. //region "Public" functions
  25726. Simulcast.prototype.isSupported = function () {
  25727. return window.chrome;
  25728. // TODO this needs improvements. For example I doubt that Chrome in Android
  25729. // has simulcast support. Also, only recent versions of Chromium have native
  25730. // simulcast support.
  25731. }
  25732. /**
  25733. *
  25734. * @param desc
  25735. * @returns {RTCSessionDescription}
  25736. */
  25737. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  25738. if (!validateDescription(desc)) {
  25739. return desc;
  25740. }
  25741. var session = transform.parse(desc.sdp);
  25742. var self = this;
  25743. processVideo(session, function (mLine) {
  25744. // Handle simulcast reception.
  25745. if (self.options.explodeRemoteSimulcast) {
  25746. explodeRemoteSimulcast(mLine);
  25747. } else {
  25748. squeezeRemoteSimulcast(mLine);
  25749. }
  25750. // If native simulcast is enabled, we must append the x-goog-conference
  25751. // attribute to the SDP.
  25752. if (self.layers.length < 1) {
  25753. removeGoogConference(mLine);
  25754. } else {
  25755. assertGoogConference(mLine);
  25756. }
  25757. });
  25758. return new RTCSessionDescription({
  25759. type: desc.type,
  25760. sdp: transform.write(session)
  25761. });
  25762. };
  25763. /**
  25764. *
  25765. * @param desc
  25766. * @returns {RTCSessionDescription}
  25767. */
  25768. Simulcast.prototype.mungeLocalDescription = function (desc) {
  25769. if (!validateDescription(desc) || !this.isSupported()) {
  25770. return desc;
  25771. }
  25772. var session = transform.parse(desc.sdp);
  25773. var self = this;
  25774. processVideo(session, function (mLine) {
  25775. // Initialize native simulcast layers, if not already done.
  25776. self._maybeInitializeLayers(mLine);
  25777. // Update the SDP with the simulcast layers.
  25778. self._restoreSimulcastView(mLine);
  25779. });
  25780. return new RTCSessionDescription({
  25781. type: desc.type,
  25782. sdp: transform.write(session)
  25783. });
  25784. };
  25785. //endregion
  25786. module.exports = Simulcast;
  25787. },{"./transform-utils":92,"sdp-transform":94}],92:[function(require,module,exports){
  25788. /* Copyright @ 2015 Atlassian Pty Ltd
  25789. *
  25790. * Licensed under the Apache License, Version 2.0 (the "License");
  25791. * you may not use this file except in compliance with the License.
  25792. * You may obtain a copy of the License at
  25793. *
  25794. * http://www.apache.org/licenses/LICENSE-2.0
  25795. *
  25796. * Unless required by applicable law or agreed to in writing, software
  25797. * distributed under the License is distributed on an "AS IS" BASIS,
  25798. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  25799. * See the License for the specific language governing permissions and
  25800. * limitations under the License.
  25801. */
  25802. exports.writeSsrcs = function(sources, order) {
  25803. var ssrcs = [];
  25804. // expand sources to ssrcs
  25805. if (typeof sources !== 'undefined' &&
  25806. Object.keys(sources).length !== 0) {
  25807. if (Array.isArray(order)) {
  25808. for (var i = 0; i < order.length; i++) {
  25809. var ssrc = order[i];
  25810. var source = sources[ssrc];
  25811. Object.keys(source).forEach(function (attribute) {
  25812. ssrcs.push({
  25813. id: ssrc,
  25814. attribute: attribute,
  25815. value: source[attribute]
  25816. });
  25817. });
  25818. }
  25819. } else {
  25820. Object.keys(sources).forEach(function (ssrc) {
  25821. var source = sources[ssrc];
  25822. Object.keys(source).forEach(function (attribute) {
  25823. ssrcs.push({
  25824. id: ssrc,
  25825. attribute: attribute,
  25826. value: source[attribute]
  25827. });
  25828. });
  25829. });
  25830. }
  25831. }
  25832. return ssrcs;
  25833. };
  25834. exports.parseSsrcs = function (mLine) {
  25835. var sources = {};
  25836. // group sources attributes by ssrc.
  25837. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  25838. mLine.ssrcs.forEach(function (ssrc) {
  25839. if (!sources[ssrc.id])
  25840. sources[ssrc.id] = {};
  25841. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  25842. });
  25843. }
  25844. return sources;
  25845. };
  25846. },{}],93:[function(require,module,exports){
  25847. arguments[4][87][0].apply(exports,arguments)
  25848. },{"dup":87}],94:[function(require,module,exports){
  25849. arguments[4][88][0].apply(exports,arguments)
  25850. },{"./parser":95,"./writer":96,"dup":88}],95:[function(require,module,exports){
  25851. arguments[4][89][0].apply(exports,arguments)
  25852. },{"./grammar":93,"dup":89}],96:[function(require,module,exports){
  25853. arguments[4][90][0].apply(exports,arguments)
  25854. },{"./grammar":93,"dup":90}],97:[function(require,module,exports){
  25855. var grammar = module.exports = {
  25856. v: [{
  25857. name: 'version',
  25858. reg: /^(\d*)$/
  25859. }],
  25860. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  25861. // NB: sessionId will be a String in most cases because it is huge
  25862. name: 'origin',
  25863. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  25864. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  25865. format: "%s %s %d %s IP%d %s"
  25866. }],
  25867. // default parsing of these only (though some of these feel outdated)
  25868. s: [{ name: 'name' }],
  25869. i: [{ name: 'description' }],
  25870. u: [{ name: 'uri' }],
  25871. e: [{ name: 'email' }],
  25872. p: [{ name: 'phone' }],
  25873. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  25874. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  25875. //k: [{}], // outdated thing ignored
  25876. t: [{ //t=0 0
  25877. name: 'timing',
  25878. reg: /^(\d*) (\d*)/,
  25879. names: ['start', 'stop'],
  25880. format: "%d %d"
  25881. }],
  25882. c: [{ //c=IN IP4 10.47.197.26
  25883. name: 'connection',
  25884. reg: /^IN IP(\d) (\S*)/,
  25885. names: ['version', 'ip'],
  25886. format: "IN IP%d %s"
  25887. }],
  25888. b: [{ //b=AS:4000
  25889. push: 'bandwidth',
  25890. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  25891. names: ['type', 'limit'],
  25892. format: "%s:%s"
  25893. }],
  25894. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  25895. // NB: special - pushes to session
  25896. // TODO: rtp/fmtp should be filtered by the payloads found here?
  25897. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  25898. names: ['type', 'port', 'protocol', 'payloads'],
  25899. format: "%s %d %s %s"
  25900. }],
  25901. a: [
  25902. { //a=rtpmap:110 opus/48000/2
  25903. push: 'rtp',
  25904. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  25905. names: ['payload', 'codec', 'rate', 'encoding'],
  25906. format: function (o) {
  25907. return (o.encoding) ?
  25908. "rtpmap:%d %s/%s/%s":
  25909. "rtpmap:%d %s/%s";
  25910. }
  25911. },
  25912. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  25913. push: 'fmtp',
  25914. reg: /^fmtp:(\d*) (\S*)/,
  25915. names: ['payload', 'config'],
  25916. format: "fmtp:%d %s"
  25917. },
  25918. { //a=control:streamid=0
  25919. name: 'control',
  25920. reg: /^control:(.*)/,
  25921. format: "control:%s"
  25922. },
  25923. { //a=rtcp:65179 IN IP4 193.84.77.194
  25924. name: 'rtcp',
  25925. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  25926. names: ['port', 'netType', 'ipVer', 'address'],
  25927. format: function (o) {
  25928. return (o.address != null) ?
  25929. "rtcp:%d %s IP%d %s":
  25930. "rtcp:%d";
  25931. }
  25932. },
  25933. { //a=rtcp-fb:98 trr-int 100
  25934. push: 'rtcpFbTrrInt',
  25935. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  25936. names: ['payload', 'value'],
  25937. format: "rtcp-fb:%d trr-int %d"
  25938. },
  25939. { //a=rtcp-fb:98 nack rpsi
  25940. push: 'rtcpFb',
  25941. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  25942. names: ['payload', 'type', 'subtype'],
  25943. format: function (o) {
  25944. return (o.subtype != null) ?
  25945. "rtcp-fb:%s %s %s":
  25946. "rtcp-fb:%s %s";
  25947. }
  25948. },
  25949. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  25950. //a=extmap:1/recvonly URI-gps-string
  25951. push: 'ext',
  25952. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  25953. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  25954. format: function (o) {
  25955. return (o.config != null) ?
  25956. "extmap:%s %s %s":
  25957. "extmap:%s %s";
  25958. }
  25959. },
  25960. {
  25961. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  25962. push: 'crypto',
  25963. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  25964. names: ['id', 'suite', 'config', 'sessionConfig'],
  25965. format: function (o) {
  25966. return (o.sessionConfig != null) ?
  25967. "crypto:%d %s %s %s":
  25968. "crypto:%d %s %s";
  25969. }
  25970. },
  25971. { //a=setup:actpass
  25972. name: 'setup',
  25973. reg: /^setup:(\w*)/,
  25974. format: "setup:%s"
  25975. },
  25976. { //a=mid:1
  25977. name: 'mid',
  25978. reg: /^mid:([^\s]*)/,
  25979. format: "mid:%s"
  25980. },
  25981. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  25982. name: 'msid',
  25983. reg: /^msid:(.*)/,
  25984. format: "msid:%s"
  25985. },
  25986. { //a=ptime:20
  25987. name: 'ptime',
  25988. reg: /^ptime:(\d*)/,
  25989. format: "ptime:%d"
  25990. },
  25991. { //a=maxptime:60
  25992. name: 'maxptime',
  25993. reg: /^maxptime:(\d*)/,
  25994. format: "maxptime:%d"
  25995. },
  25996. { //a=sendrecv
  25997. name: 'direction',
  25998. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  25999. },
  26000. { //a=ice-lite
  26001. name: 'icelite',
  26002. reg: /^(ice-lite)/
  26003. },
  26004. { //a=ice-ufrag:F7gI
  26005. name: 'iceUfrag',
  26006. reg: /^ice-ufrag:(\S*)/,
  26007. format: "ice-ufrag:%s"
  26008. },
  26009. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  26010. name: 'icePwd',
  26011. reg: /^ice-pwd:(\S*)/,
  26012. format: "ice-pwd:%s"
  26013. },
  26014. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  26015. name: 'fingerprint',
  26016. reg: /^fingerprint:(\S*) (\S*)/,
  26017. names: ['type', 'hash'],
  26018. format: "fingerprint:%s %s"
  26019. },
  26020. {
  26021. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  26022. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  26023. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  26024. push:'candidates',
  26025. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  26026. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  26027. format: function (o) {
  26028. var str = "candidate:%s %d %s %d %s %d typ %s";
  26029. // NB: candidate has two optional chunks, so %void middle one if it's missing
  26030. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  26031. if (o.generation != null) {
  26032. str += " generation %d";
  26033. }
  26034. return str;
  26035. }
  26036. },
  26037. { //a=end-of-candidates (keep after the candidates line for readability)
  26038. name: 'endOfCandidates',
  26039. reg: /^(end-of-candidates)/
  26040. },
  26041. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  26042. name: 'remoteCandidates',
  26043. reg: /^remote-candidates:(.*)/,
  26044. format: "remote-candidates:%s"
  26045. },
  26046. { //a=ice-options:google-ice
  26047. name: 'iceOptions',
  26048. reg: /^ice-options:(\S*)/,
  26049. format: "ice-options:%s"
  26050. },
  26051. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  26052. push: "ssrcs",
  26053. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  26054. names: ['id', 'attribute', 'value'],
  26055. format: "ssrc:%d %s:%s"
  26056. },
  26057. { //a=ssrc-group:FEC 1 2
  26058. push: "ssrcGroups",
  26059. reg: /^ssrc-group:(\w*) (.*)/,
  26060. names: ['semantics', 'ssrcs'],
  26061. format: "ssrc-group:%s %s"
  26062. },
  26063. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  26064. name: "msidSemantic",
  26065. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  26066. names: ['semantic', 'token'],
  26067. format: "msid-semantic: %s %s" // space after ":" is not accidental
  26068. },
  26069. { //a=group:BUNDLE audio video
  26070. push: 'groups',
  26071. reg: /^group:(\w*) (.*)/,
  26072. names: ['type', 'mids'],
  26073. format: "group:%s %s"
  26074. },
  26075. { //a=rtcp-mux
  26076. name: 'rtcpMux',
  26077. reg: /^(rtcp-mux)/
  26078. },
  26079. { // any a= that we don't understand is kepts verbatim on media.invalid
  26080. push: 'invalid',
  26081. names: ["value"]
  26082. }
  26083. ]
  26084. };
  26085. // set sensible defaults to avoid polluting the grammar with boring details
  26086. Object.keys(grammar).forEach(function (key) {
  26087. var objs = grammar[key];
  26088. objs.forEach(function (obj) {
  26089. if (!obj.reg) {
  26090. obj.reg = /(.*)/;
  26091. }
  26092. if (!obj.format) {
  26093. obj.format = "%s";
  26094. }
  26095. });
  26096. });
  26097. },{}],98:[function(require,module,exports){
  26098. arguments[4][88][0].apply(exports,arguments)
  26099. },{"./parser":99,"./writer":100,"dup":88}],99:[function(require,module,exports){
  26100. arguments[4][89][0].apply(exports,arguments)
  26101. },{"./grammar":97,"dup":89}],100:[function(require,module,exports){
  26102. arguments[4][90][0].apply(exports,arguments)
  26103. },{"./grammar":97,"dup":90}],101:[function(require,module,exports){
  26104. /*
  26105. * Copyright @ 2015 Atlassian Pty Ltd
  26106. *
  26107. * Licensed under the Apache License, Version 2.0 (the "License");
  26108. * you may not use this file except in compliance with the License.
  26109. * You may obtain a copy of the License at
  26110. *
  26111. * http://www.apache.org/licenses/LICENSE-2.0
  26112. *
  26113. * Unless required by applicable law or agreed to in writing, software
  26114. * distributed under the License is distributed on an "AS IS" BASIS,
  26115. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  26116. * See the License for the specific language governing permissions and
  26117. * limitations under the License.
  26118. */
  26119. var MediaStreamType = {
  26120. VIDEO_TYPE: "Video",
  26121. AUDIO_TYPE: "Audio"
  26122. };
  26123. module.exports = MediaStreamType;
  26124. },{}],102:[function(require,module,exports){
  26125. /*
  26126. * Copyright @ 2015 Atlassian Pty Ltd
  26127. *
  26128. * Licensed under the Apache License, Version 2.0 (the "License");
  26129. * you may not use this file except in compliance with the License.
  26130. * You may obtain a copy of the License at
  26131. *
  26132. * http://www.apache.org/licenses/LICENSE-2.0
  26133. *
  26134. * Unless required by applicable law or agreed to in writing, software
  26135. * distributed under the License is distributed on an "AS IS" BASIS,
  26136. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  26137. * See the License for the specific language governing permissions and
  26138. * limitations under the License.
  26139. */
  26140. var RTCBrowserType = {
  26141. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  26142. RTC_BROWSER_FIREFOX: "rtc_browser.firefox"
  26143. };
  26144. module.exports = RTCBrowserType;
  26145. },{}],103:[function(require,module,exports){
  26146. /*
  26147. * Copyright @ 2015 Atlassian Pty Ltd
  26148. *
  26149. * Licensed under the Apache License, Version 2.0 (the "License");
  26150. * you may not use this file except in compliance with the License.
  26151. * You may obtain a copy of the License at
  26152. *
  26153. * http://www.apache.org/licenses/LICENSE-2.0
  26154. *
  26155. * Unless required by applicable law or agreed to in writing, software
  26156. * distributed under the License is distributed on an "AS IS" BASIS,
  26157. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  26158. * See the License for the specific language governing permissions and
  26159. * limitations under the License.
  26160. */
  26161. var RTCEvents = {
  26162. LASTN_CHANGED: "rtc.lastn_changed",
  26163. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  26164. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  26165. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed"
  26166. };
  26167. module.exports = RTCEvents;
  26168. },{}],104:[function(require,module,exports){
  26169. /*
  26170. * Copyright @ 2015 Atlassian Pty Ltd
  26171. *
  26172. * Licensed under the Apache License, Version 2.0 (the "License");
  26173. * you may not use this file except in compliance with the License.
  26174. * You may obtain a copy of the License at
  26175. *
  26176. * http://www.apache.org/licenses/LICENSE-2.0
  26177. *
  26178. * Unless required by applicable law or agreed to in writing, software
  26179. * distributed under the License is distributed on an "AS IS" BASIS,
  26180. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  26181. * See the License for the specific language governing permissions and
  26182. * limitations under the License.
  26183. */
  26184. var Resolutions = {
  26185. "1080": {
  26186. width: 1920,
  26187. height: 1080,
  26188. order: 7
  26189. },
  26190. "fullhd": {
  26191. width: 1920,
  26192. height: 1080,
  26193. order: 7
  26194. },
  26195. "720": {
  26196. width: 1280,
  26197. height: 720,
  26198. order: 6
  26199. },
  26200. "hd": {
  26201. width: 1280,
  26202. height: 720,
  26203. order: 6
  26204. },
  26205. "960": {
  26206. width: 960,
  26207. height: 720,
  26208. order: 5
  26209. },
  26210. "640": {
  26211. width: 640,
  26212. height: 480,
  26213. order: 4
  26214. },
  26215. "vga": {
  26216. width: 640,
  26217. height: 480,
  26218. order: 4
  26219. },
  26220. "360": {
  26221. width: 640,
  26222. height: 360,
  26223. order: 3
  26224. },
  26225. "320": {
  26226. width: 320,
  26227. height: 240,
  26228. order: 2
  26229. },
  26230. "180": {
  26231. width: 320,
  26232. height: 180,
  26233. order: 1
  26234. }
  26235. };
  26236. module.exports = Resolutions;
  26237. },{}],105:[function(require,module,exports){
  26238. /*
  26239. * Copyright @ 2015 Atlassian Pty Ltd
  26240. *
  26241. * Licensed under the Apache License, Version 2.0 (the "License");
  26242. * you may not use this file except in compliance with the License.
  26243. * You may obtain a copy of the License at
  26244. *
  26245. * http://www.apache.org/licenses/LICENSE-2.0
  26246. *
  26247. * Unless required by applicable law or agreed to in writing, software
  26248. * distributed under the License is distributed on an "AS IS" BASIS,
  26249. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  26250. * See the License for the specific language governing permissions and
  26251. * limitations under the License.
  26252. */
  26253. var StreamEventTypes = {
  26254. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  26255. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  26256. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  26257. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  26258. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended",
  26259. EVENT_TYPE_REMOTE_CHANGED: "stream.changed"
  26260. };
  26261. module.exports = StreamEventTypes;
  26262. },{}],106:[function(require,module,exports){
  26263. /*
  26264. * Copyright @ 2015 Atlassian Pty Ltd
  26265. *
  26266. * Licensed under the Apache License, Version 2.0 (the "License");
  26267. * you may not use this file except in compliance with the License.
  26268. * You may obtain a copy of the License at
  26269. *
  26270. * http://www.apache.org/licenses/LICENSE-2.0
  26271. *
  26272. * Unless required by applicable law or agreed to in writing, software
  26273. * distributed under the License is distributed on an "AS IS" BASIS,
  26274. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  26275. * See the License for the specific language governing permissions and
  26276. * limitations under the License.
  26277. */
  26278. var UIEvents = {
  26279. NICKNAME_CHANGED: "UI.nickname_changed",
  26280. SELECTED_ENDPOINT: "UI.selected_endpoint",
  26281. PINNED_ENDPOINT: "UI.pinned_endpoint"
  26282. };
  26283. module.exports = UIEvents;
  26284. },{}],107:[function(require,module,exports){
  26285. /*
  26286. * Copyright @ 2015 Atlassian Pty Ltd
  26287. *
  26288. * Licensed under the Apache License, Version 2.0 (the "License");
  26289. * you may not use this file except in compliance with the License.
  26290. * You may obtain a copy of the License at
  26291. *
  26292. * http://www.apache.org/licenses/LICENSE-2.0
  26293. *
  26294. * Unless required by applicable law or agreed to in writing, software
  26295. * distributed under the License is distributed on an "AS IS" BASIS,
  26296. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  26297. * See the License for the specific language governing permissions and
  26298. * limitations under the License.
  26299. */
  26300. var AuthenticationEvents = {
  26301. /**
  26302. * Event callback arguments:
  26303. * function(authenticationEnabled, userIdentity)
  26304. * authenticationEnabled - indicates whether authentication has been enabled
  26305. * in this session
  26306. * userIdentity - if user has been logged in then it contains user name. If
  26307. * contains 'null' or 'undefined' then user is not logged in.
  26308. */
  26309. IDENTITY_UPDATED: "authentication.identity_updated"
  26310. };
  26311. module.exports = AuthenticationEvents;
  26312. },{}],108:[function(require,module,exports){
  26313. /*
  26314. * Copyright @ 2015 Atlassian Pty Ltd
  26315. *
  26316. * Licensed under the Apache License, Version 2.0 (the "License");
  26317. * you may not use this file except in compliance with the License.
  26318. * You may obtain a copy of the License at
  26319. *
  26320. * http://www.apache.org/licenses/LICENSE-2.0
  26321. *
  26322. * Unless required by applicable law or agreed to in writing, software
  26323. * distributed under the License is distributed on an "AS IS" BASIS,
  26324. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  26325. * See the License for the specific language governing permissions and
  26326. * limitations under the License.
  26327. */
  26328. var CQEvents = {
  26329. LOCALSTATS_UPDATED: "cq.localstats_updated",
  26330. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  26331. STOP: "cq.stop"
  26332. };
  26333. module.exports = CQEvents;
  26334. },{}],109:[function(require,module,exports){
  26335. /*
  26336. * Copyright @ 2015 Atlassian Pty Ltd
  26337. *
  26338. * Licensed under the Apache License, Version 2.0 (the "License");
  26339. * you may not use this file except in compliance with the License.
  26340. * You may obtain a copy of the License at
  26341. *
  26342. * http://www.apache.org/licenses/LICENSE-2.0
  26343. *
  26344. * Unless required by applicable law or agreed to in writing, software
  26345. * distributed under the License is distributed on an "AS IS" BASIS,
  26346. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  26347. * See the License for the specific language governing permissions and
  26348. * limitations under the License.
  26349. */
  26350. var DesktopSharingEventTypes = {
  26351. INIT: "ds.init",
  26352. SWITCHING_DONE: "ds.switching_done",
  26353. NEW_STREAM_CREATED: "ds.new_stream_created"
  26354. };
  26355. module.exports = DesktopSharingEventTypes;
  26356. },{}],110:[function(require,module,exports){
  26357. /*
  26358. * Copyright @ 2015 Atlassian Pty Ltd
  26359. *
  26360. * Licensed under the Apache License, Version 2.0 (the "License");
  26361. * you may not use this file except in compliance with the License.
  26362. * You may obtain a copy of the License at
  26363. *
  26364. * http://www.apache.org/licenses/LICENSE-2.0
  26365. *
  26366. * Unless required by applicable law or agreed to in writing, software
  26367. * distributed under the License is distributed on an "AS IS" BASIS,
  26368. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  26369. * See the License for the specific language governing permissions and
  26370. * limitations under the License.
  26371. */
  26372. var Events = {
  26373. DTMF_SUPPORT_CHANGED: "members.dtmf_support_changed"
  26374. };
  26375. module.exports = Events;
  26376. },{}],111:[function(require,module,exports){
  26377. /*
  26378. * Copyright @ 2015 Atlassian Pty Ltd
  26379. *
  26380. * Licensed under the Apache License, Version 2.0 (the "License");
  26381. * you may not use this file except in compliance with the License.
  26382. * You may obtain a copy of the License at
  26383. *
  26384. * http://www.apache.org/licenses/LICENSE-2.0
  26385. *
  26386. * Unless required by applicable law or agreed to in writing, software
  26387. * distributed under the License is distributed on an "AS IS" BASIS,
  26388. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  26389. * See the License for the specific language governing permissions and
  26390. * limitations under the License.
  26391. */
  26392. module.exports = {
  26393. getLanguages : function () {
  26394. var languages = [];
  26395. for(var lang in this)
  26396. {
  26397. if(typeof this[lang] === "string")
  26398. languages.push(this[lang]);
  26399. }
  26400. return languages;
  26401. },
  26402. EN: "en",
  26403. BG: "bg",
  26404. DE: "de",
  26405. TR: "tr",
  26406. FR: "fr"
  26407. }
  26408. },{}],112:[function(require,module,exports){
  26409. /*
  26410. * Copyright @ 2015 Atlassian Pty Ltd
  26411. *
  26412. * Licensed under the Apache License, Version 2.0 (the "License");
  26413. * you may not use this file except in compliance with the License.
  26414. * You may obtain a copy of the License at
  26415. *
  26416. * http://www.apache.org/licenses/LICENSE-2.0
  26417. *
  26418. * Unless required by applicable law or agreed to in writing, software
  26419. * distributed under the License is distributed on an "AS IS" BASIS,
  26420. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  26421. * See the License for the specific language governing permissions and
  26422. * limitations under the License.
  26423. */
  26424. var XMPPEvents = {
  26425. CONNECTION_FAILED: "xmpp.connection.failed",
  26426. CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle",
  26427. CALL_TERMINATED: "xmpp.callterminated.jingle",
  26428. CALL_INCOMING: "xmpp.callincoming.jingle",
  26429. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  26430. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  26431. KICKED: "xmpp.kicked",
  26432. BRIDGE_DOWN: "xmpp.bridge_down",
  26433. USER_ID_CHANGED: "xmpp.user_id_changed",
  26434. STREAMS_CHANGED: "xmpp.streams_changed",
  26435. // We joined the MUC
  26436. MUC_JOINED: "xmpp.muc_joined",
  26437. // A member joined the MUC
  26438. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  26439. // A member left the MUC
  26440. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  26441. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  26442. MUC_DESTROYED: "xmpp.muc_destroyed",
  26443. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  26444. REMOTE_STATS: "xmpp.remote_stats",
  26445. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  26446. PRESENCE_STATUS: "xmpp.presence_status",
  26447. RESERVATION_ERROR: "xmpp.room_reservation_error",
  26448. SUBJECT_CHANGED: "xmpp.subject_changed",
  26449. MESSAGE_RECEIVED: "xmpp.message_received",
  26450. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  26451. PASSWORD_REQUIRED: "xmpp.password_required",
  26452. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  26453. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  26454. ETHERPAD: "xmpp.etherpad",
  26455. DEVICE_AVAILABLE: "xmpp.device_available",
  26456. START_MUTED: "xmpp.start_muted"
  26457. };
  26458. module.exports = XMPPEvents;
  26459. },{}]},{},[1])(1)
  26460. });