Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

app.bundle.js 849KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751
  1. !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.APP=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. /* jshint -W117 */
  3. /* application specific logic */
  4. var APP =
  5. {
  6. init: function () {
  7. this.UI = require("./modules/UI/UI");
  8. this.API = require("./modules/API/API");
  9. this.connectionquality = require("./modules/connectionquality/connectionquality");
  10. this.statistics = require("./modules/statistics/statistics");
  11. this.RTC = require("./modules/RTC/RTC");
  12. this.simulcast = require("./modules/simulcast/simulcast");
  13. this.desktopsharing = require("./modules/desktopsharing/desktopsharing");
  14. this.xmpp = require("./modules/xmpp/xmpp");
  15. this.keyboardshortcut = require("./modules/keyboardshortcut/keyboardshortcut");
  16. this.translation = require("./modules/translation/translation");
  17. }
  18. };
  19. function init() {
  20. APP.RTC.start();
  21. APP.xmpp.start(APP.UI.getCredentials());
  22. APP.statistics.start();
  23. APP.connectionquality.init();
  24. // Set default desktop sharing method
  25. APP.desktopsharing.init();
  26. APP.keyboardshortcut.init();
  27. }
  28. $(document).ready(function () {
  29. APP.init();
  30. APP.translation.init();
  31. if(APP.API.isEnabled())
  32. APP.API.init();
  33. APP.UI.start(init);
  34. });
  35. $(window).bind('beforeunload', function () {
  36. if(APP.API.isEnabled())
  37. APP.API.dispose();
  38. });
  39. module.exports = APP;
  40. },{"./modules/API/API":2,"./modules/RTC/RTC":6,"./modules/UI/UI":8,"./modules/connectionquality/connectionquality":34,"./modules/desktopsharing/desktopsharing":35,"./modules/keyboardshortcut/keyboardshortcut":36,"./modules/simulcast/simulcast":42,"./modules/statistics/statistics":45,"./modules/translation/translation":46,"./modules/xmpp/xmpp":60}],2:[function(require,module,exports){
  41. /**
  42. * Implements API class that communicates with external api class
  43. * and provides interface to access Jitsi Meet features by external
  44. * applications that embed Jitsi Meet
  45. */
  46. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  47. /**
  48. * List of the available commands.
  49. * @type {{
  50. * displayName: inputDisplayNameHandler,
  51. * muteAudio: toggleAudio,
  52. * muteVideo: toggleVideo,
  53. * filmStrip: toggleFilmStrip
  54. * }}
  55. */
  56. var commands =
  57. {
  58. displayName: APP.UI.inputDisplayNameHandler,
  59. muteAudio: APP.UI.toggleAudio,
  60. muteVideo: APP.UI.toggleVideo,
  61. toggleFilmStrip: APP.UI.toggleFilmStrip,
  62. toggleChat: APP.UI.toggleChat,
  63. toggleContactList: APP.UI.toggleContactList
  64. };
  65. /**
  66. * Maps the supported events and their status
  67. * (true it the event is enabled and false if it is disabled)
  68. * @type {{
  69. * incomingMessage: boolean,
  70. * outgoingMessage: boolean,
  71. * displayNameChange: boolean,
  72. * participantJoined: boolean,
  73. * participantLeft: boolean
  74. * }}
  75. */
  76. var events =
  77. {
  78. incomingMessage: false,
  79. outgoingMessage:false,
  80. displayNameChange: false,
  81. participantJoined: false,
  82. participantLeft: false
  83. };
  84. var displayName = {};
  85. /**
  86. * Processes commands from external applicaiton.
  87. * @param message the object with the command
  88. */
  89. function processCommand(message)
  90. {
  91. if(message.action != "execute")
  92. {
  93. console.error("Unknown action of the message");
  94. return;
  95. }
  96. for(var key in message)
  97. {
  98. if(commands[key])
  99. commands[key].apply(null, message[key]);
  100. }
  101. }
  102. /**
  103. * Processes events objects from external applications
  104. * @param event the event
  105. */
  106. function processEvent(event) {
  107. if(!event.action)
  108. {
  109. console.error("Event with no action is received.");
  110. return;
  111. }
  112. var i = 0;
  113. switch(event.action)
  114. {
  115. case "add":
  116. for(; i < event.events.length; i++)
  117. {
  118. events[event.events[i]] = true;
  119. }
  120. break;
  121. case "remove":
  122. for(; i < event.events.length; i++)
  123. {
  124. events[event.events[i]] = false;
  125. }
  126. break;
  127. default:
  128. console.error("Unknown action for event.");
  129. }
  130. }
  131. /**
  132. * Sends message to the external application.
  133. * @param object
  134. */
  135. function sendMessage(object) {
  136. window.parent.postMessage(JSON.stringify(object), "*");
  137. }
  138. /**
  139. * Processes a message event from the external application
  140. * @param event the message event
  141. */
  142. function processMessage(event)
  143. {
  144. var message;
  145. try {
  146. message = JSON.parse(event.data);
  147. } catch (e) {}
  148. if(!message.type)
  149. return;
  150. switch (message.type)
  151. {
  152. case "command":
  153. processCommand(message);
  154. break;
  155. case "event":
  156. processEvent(message);
  157. break;
  158. default:
  159. console.error("Unknown type of the message");
  160. return;
  161. }
  162. }
  163. function setupListeners() {
  164. APP.xmpp.addListener(XMPPEvents.MUC_ENTER, function (from) {
  165. API.triggerEvent("participantJoined", {jid: from});
  166. });
  167. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid) {
  168. if (from != myjid)
  169. API.triggerEvent("incomingMessage",
  170. {"from": from, "nick": nick, "message": txt});
  171. });
  172. APP.xmpp.addListener(XMPPEvents.MUC_LEFT, function (jid) {
  173. API.triggerEvent("participantLeft", {jid: jid});
  174. });
  175. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {
  176. name = displayName[jid];
  177. if(!name || name != newDisplayName) {
  178. API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});
  179. displayName[jid] = newDisplayName;
  180. }
  181. });
  182. APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {
  183. APP.API.triggerEvent("outgoingMessage", {"message": body});
  184. });
  185. }
  186. var API = {
  187. /**
  188. * Check whether the API should be enabled or not.
  189. * @returns {boolean}
  190. */
  191. isEnabled: function () {
  192. var hash = location.hash;
  193. if(hash && hash.indexOf("external") > -1 && window.postMessage)
  194. return true;
  195. return false;
  196. },
  197. /**
  198. * Initializes the APIConnector. Setups message event listeners that will
  199. * receive information from external applications that embed Jitsi Meet.
  200. * It also sends a message to the external application that APIConnector
  201. * is initialized.
  202. */
  203. init: function () {
  204. if (window.addEventListener)
  205. {
  206. window.addEventListener('message',
  207. processMessage, false);
  208. }
  209. else
  210. {
  211. window.attachEvent('onmessage', processMessage);
  212. }
  213. sendMessage({type: "system", loaded: true});
  214. setupListeners();
  215. },
  216. /**
  217. * Checks whether the event is enabled ot not.
  218. * @param name the name of the event.
  219. * @returns {*}
  220. */
  221. isEventEnabled: function (name) {
  222. return events[name];
  223. },
  224. /**
  225. * Sends event object to the external application that has been subscribed
  226. * for that event.
  227. * @param name the name event
  228. * @param object data associated with the event
  229. */
  230. triggerEvent: function (name, object) {
  231. if(this.isEnabled() && this.isEventEnabled(name))
  232. sendMessage({
  233. type: "event", action: "result", event: name, result: object});
  234. },
  235. /**
  236. * Removes the listeners.
  237. */
  238. dispose: function () {
  239. if(window.removeEventListener)
  240. {
  241. window.removeEventListener("message",
  242. processMessage, false);
  243. }
  244. else
  245. {
  246. window.detachEvent('onmessage', processMessage);
  247. }
  248. }
  249. };
  250. module.exports = API;
  251. },{"../../service/xmpp/XMPPEvents":88}],3:[function(require,module,exports){
  252. /* global Strophe, updateLargeVideo, focusedVideoSrc*/
  253. // cache datachannels to avoid garbage collection
  254. // https://code.google.com/p/chromium/issues/detail?id=405545
  255. var RTCEvents = require("../../service/RTC/RTCEvents");
  256. var _dataChannels = [];
  257. var eventEmitter = null;
  258. var DataChannels =
  259. {
  260. /**
  261. * Callback triggered by PeerConnection when new data channel is opened
  262. * on the bridge.
  263. * @param event the event info object.
  264. */
  265. onDataChannel: function (event)
  266. {
  267. var dataChannel = event.channel;
  268. dataChannel.onopen = function () {
  269. console.info("Data channel opened by the Videobridge!", dataChannel);
  270. // Code sample for sending string and/or binary data
  271. // Sends String message to the bridge
  272. //dataChannel.send("Hello bridge!");
  273. // Sends 12 bytes binary message to the bridge
  274. //dataChannel.send(new ArrayBuffer(12));
  275. // when the data channel becomes available, tell the bridge about video
  276. // selections so that it can do adaptive simulcast,
  277. // we want the notification to trigger even if userJid is undefined,
  278. // or null.
  279. var userJid = APP.UI.getLargeVideoState().userResourceJid;
  280. // we want the notification to trigger even if userJid is undefined,
  281. // or null.
  282. onSelectedEndpointChanged(userJid);
  283. };
  284. dataChannel.onerror = function (error) {
  285. console.error("Data Channel Error:", error, dataChannel);
  286. };
  287. dataChannel.onmessage = function (event) {
  288. var data = event.data;
  289. // JSON
  290. var obj;
  291. try {
  292. obj = JSON.parse(data);
  293. }
  294. catch (e) {
  295. console.error(
  296. "Failed to parse data channel message as JSON: ",
  297. data,
  298. dataChannel);
  299. }
  300. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  301. var colibriClass = obj.colibriClass;
  302. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  303. // Endpoint ID from the Videobridge.
  304. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  305. console.info(
  306. "Data channel new dominant speaker event: ",
  307. dominantSpeakerEndpoint);
  308. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  309. }
  310. else if ("InLastNChangeEvent" === colibriClass)
  311. {
  312. var oldValue = obj.oldValue;
  313. var newValue = obj.newValue;
  314. // Make sure that oldValue and newValue are of type boolean.
  315. var type;
  316. if ((type = typeof oldValue) !== 'boolean') {
  317. if (type === 'string') {
  318. oldValue = (oldValue == "true");
  319. } else {
  320. oldValue = new Boolean(oldValue).valueOf();
  321. }
  322. }
  323. if ((type = typeof newValue) !== 'boolean') {
  324. if (type === 'string') {
  325. newValue = (newValue == "true");
  326. } else {
  327. newValue = new Boolean(newValue).valueOf();
  328. }
  329. }
  330. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  331. }
  332. else if ("LastNEndpointsChangeEvent" === colibriClass)
  333. {
  334. // The new/latest list of last-n endpoint IDs.
  335. var lastNEndpoints = obj.lastNEndpoints;
  336. // The list of endpoint IDs which are entering the list of
  337. // last-n at this time i.e. were not in the old list of last-n
  338. // endpoint IDs.
  339. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  340. var stream = obj.stream;
  341. console.log(
  342. "Data channel new last-n event: ",
  343. lastNEndpoints, endpointsEnteringLastN, obj);
  344. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  345. lastNEndpoints, endpointsEnteringLastN, obj);
  346. }
  347. else if ("SimulcastLayersChangedEvent" === colibriClass)
  348. {
  349. eventEmitter.emit(RTCEvents.SIMULCAST_LAYER_CHANGED,
  350. obj.endpointSimulcastLayers);
  351. }
  352. else if ("SimulcastLayersChangingEvent" === colibriClass)
  353. {
  354. eventEmitter.emit(RTCEvents.SIMULCAST_LAYER_CHANGING,
  355. obj.endpointSimulcastLayers);
  356. }
  357. else if ("StartSimulcastLayerEvent" === colibriClass)
  358. {
  359. eventEmitter.emit(RTCEvents.SIMULCAST_START, obj.simulcastLayer);
  360. }
  361. else if ("StopSimulcastLayerEvent" === colibriClass)
  362. {
  363. eventEmitter.emit(RTCEvents.SIMULCAST_STOP, obj.simulcastLayer);
  364. }
  365. else
  366. {
  367. console.debug("Data channel JSON-formatted message: ", obj);
  368. }
  369. }
  370. };
  371. dataChannel.onclose = function ()
  372. {
  373. console.info("The Data Channel closed", dataChannel);
  374. var idx = _dataChannels.indexOf(dataChannel);
  375. if (idx > -1)
  376. _dataChannels = _dataChannels.splice(idx, 1);
  377. };
  378. _dataChannels.push(dataChannel);
  379. },
  380. /**
  381. * Binds "ondatachannel" event listener to given PeerConnection instance.
  382. * @param peerConnection WebRTC peer connection instance.
  383. */
  384. init: function (peerConnection, emitter) {
  385. if(!config.openSctp)
  386. return;
  387. peerConnection.ondatachannel = this.onDataChannel;
  388. eventEmitter = emitter;
  389. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  390. // Although it's not a requirement to open separate channels from both bridge
  391. // and peer as single channel can be used for sending and receiving data.
  392. // So either channel opened by the bridge or the one opened here is enough
  393. // for communication with the bridge.
  394. /*var dataChannelOptions =
  395. {
  396. reliable: true
  397. };
  398. var dataChannel
  399. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  400. // Can be used only when is in open state
  401. dataChannel.onopen = function ()
  402. {
  403. dataChannel.send("My channel !!!");
  404. };
  405. dataChannel.onmessage = function (event)
  406. {
  407. var msgData = event.data;
  408. console.info("Got My Data Channel Message:", msgData, dataChannel);
  409. };*/
  410. },
  411. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  412. handlePinnedEndpointEvent: onPinnedEndpointChanged
  413. };
  414. function onSelectedEndpointChanged(userResource)
  415. {
  416. console.log('selected endpoint changed: ', userResource);
  417. if (_dataChannels && _dataChannels.length != 0)
  418. {
  419. _dataChannels.some(function (dataChannel) {
  420. if (dataChannel.readyState == 'open')
  421. {
  422. console.log('sending selected endpoint changed '
  423. + 'notification to the bridge: ', userResource);
  424. dataChannel.send(JSON.stringify({
  425. 'colibriClass': 'SelectedEndpointChangedEvent',
  426. 'selectedEndpoint':
  427. (!userResource || userResource === null)?
  428. null : userResource
  429. }));
  430. return true;
  431. }
  432. });
  433. }
  434. }
  435. function onPinnedEndpointChanged(userResource)
  436. {
  437. console.log('pinned endpoint changed: ', userResource);
  438. if (_dataChannels && _dataChannels.length != 0)
  439. {
  440. _dataChannels.some(function (dataChannel) {
  441. if (dataChannel.readyState == 'open')
  442. {
  443. dataChannel.send(JSON.stringify({
  444. 'colibriClass': 'PinnedEndpointChangedEvent',
  445. 'pinnedEndpoint':
  446. (!userResource || userResource == null)?
  447. null : userResource
  448. }));
  449. return true;
  450. }
  451. });
  452. }
  453. }
  454. module.exports = DataChannels;
  455. },{"../../service/RTC/RTCEvents":80}],4:[function(require,module,exports){
  456. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  457. function LocalStream(stream, type, eventEmitter, videoType)
  458. {
  459. this.stream = stream;
  460. this.eventEmitter = eventEmitter;
  461. this.type = type;
  462. this.videoType = videoType;
  463. var self = this;
  464. if(type == "audio")
  465. {
  466. this.getTracks = function () {
  467. return self.stream.getAudioTracks();
  468. };
  469. }
  470. else
  471. {
  472. this.getTracks = function () {
  473. return self.stream.getVideoTracks();
  474. };
  475. }
  476. this.stream.onended = function()
  477. {
  478. self.streamEnded();
  479. };
  480. }
  481. LocalStream.prototype.streamEnded = function () {
  482. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  483. }
  484. LocalStream.prototype.getOriginalStream = function()
  485. {
  486. return this.stream;
  487. }
  488. LocalStream.prototype.isAudioStream = function () {
  489. return (this.stream.getAudioTracks() && this.stream.getAudioTracks().length > 0);
  490. };
  491. LocalStream.prototype.mute = function()
  492. {
  493. var ismuted = false;
  494. var tracks = this.getTracks();
  495. for (var idx = 0; idx < tracks.length; idx++) {
  496. ismuted = !tracks[idx].enabled;
  497. tracks[idx].enabled = ismuted;
  498. }
  499. return ismuted;
  500. };
  501. LocalStream.prototype.setMute = function(mute)
  502. {
  503. var tracks = this.getTracks();
  504. for (var idx = 0; idx < tracks.length; idx++) {
  505. tracks[idx].enabled = mute;
  506. }
  507. };
  508. LocalStream.prototype.isMuted = function () {
  509. var tracks = [];
  510. if(this.type == "audio")
  511. {
  512. tracks = this.stream.getAudioTracks();
  513. }
  514. else
  515. {
  516. tracks = this.stream.getVideoTracks();
  517. }
  518. for (var idx = 0; idx < tracks.length; idx++) {
  519. if(tracks[idx].enabled)
  520. return false;
  521. }
  522. return true;
  523. }
  524. LocalStream.prototype.getId = function () {
  525. return this.stream.getTracks()[0].id;
  526. }
  527. module.exports = LocalStream;
  528. },{"../../service/RTC/StreamEventTypes.js":82}],5:[function(require,module,exports){
  529. ////These lines should be uncommented when require works in app.js
  530. var RTCBrowserType = require("../../service/RTC/RTCBrowserType.js");
  531. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  532. /**
  533. * Creates a MediaStream object for the given data, session id and ssrc.
  534. * It is a wrapper class for the MediaStream.
  535. *
  536. * @param data the data object from which we obtain the stream,
  537. * the peerjid, etc.
  538. * @param sid the session id
  539. * @param ssrc the ssrc corresponding to this MediaStream
  540. *
  541. * @constructor
  542. */
  543. function MediaStream(data, sid, ssrc, browser) {
  544. // XXX(gp) to minimize headaches in the future, we should build our
  545. // abstractions around tracks and not streams. ORTC is track based API.
  546. // Mozilla expects m-lines to represent media tracks.
  547. //
  548. // Practically, what I'm saying is that we should have a MediaTrack class
  549. // and not a MediaStream class.
  550. //
  551. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  552. // a track might have an associated RTX and FEC sources.
  553. this.sid = sid;
  554. this.stream = data.stream;
  555. this.peerjid = data.peerjid;
  556. this.ssrc = ssrc;
  557. this.type = (this.stream.getVideoTracks().length > 0)?
  558. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  559. this.videoType = null;
  560. this.muted = false;
  561. if(browser == RTCBrowserType.RTC_BROWSER_FIREFOX)
  562. {
  563. if (!this.getVideoTracks)
  564. this.getVideoTracks = function () { return []; };
  565. if (!this.getAudioTracks)
  566. this.getAudioTracks = function () { return []; };
  567. }
  568. }
  569. MediaStream.prototype.getOriginalStream = function()
  570. {
  571. return this.stream;
  572. }
  573. MediaStream.prototype.setMute = function (value)
  574. {
  575. this.stream.muted = value;
  576. this.muted = value;
  577. }
  578. module.exports = MediaStream;
  579. },{"../../service/RTC/MediaStreamTypes":78,"../../service/RTC/RTCBrowserType.js":79}],6:[function(require,module,exports){
  580. var EventEmitter = require("events");
  581. var RTCUtils = require("./RTCUtils.js");
  582. var LocalStream = require("./LocalStream.js");
  583. var DataChannels = require("./DataChannels");
  584. var MediaStream = require("./MediaStream.js");
  585. var DesktopSharingEventTypes
  586. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  587. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  588. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  589. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  590. var UIEvents = require("../../service/UI/UIEvents");
  591. var eventEmitter = new EventEmitter();
  592. var RTC = {
  593. rtcUtils: null,
  594. localStreams: [],
  595. remoteStreams: {},
  596. localAudio: null,
  597. localVideo: null,
  598. addStreamListener: function (listener, eventType) {
  599. eventEmitter.on(eventType, listener);
  600. },
  601. addListener: function (type, listener) {
  602. eventEmitter.on(type, listener);
  603. },
  604. removeStreamListener: function (listener, eventType) {
  605. if(!(eventType instanceof StreamEventTypes))
  606. throw "Illegal argument";
  607. eventEmitter.removeListener(eventType, listener);
  608. },
  609. createLocalStream: function (stream, type, change) {
  610. var localStream = new LocalStream(stream, type, eventEmitter);
  611. //in firefox we have only one stream object
  612. if(this.localStreams.length == 0 ||
  613. this.localStreams[0].getOriginalStream() != stream)
  614. this.localStreams.push(localStream);
  615. if(type == "audio")
  616. {
  617. this.localAudio = localStream;
  618. }
  619. else
  620. {
  621. this.localVideo = localStream;
  622. }
  623. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  624. if(change)
  625. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  626. eventEmitter.emit(eventType, localStream);
  627. return localStream;
  628. },
  629. removeLocalStream: function (stream) {
  630. for(var i = 0; i < this.localStreams.length; i++)
  631. {
  632. if(this.localStreams[i].getOriginalStream() === stream) {
  633. delete this.localStreams[i];
  634. return;
  635. }
  636. }
  637. },
  638. createRemoteStream: function (data, sid, thessrc) {
  639. var remoteStream = new MediaStream(data, sid, thessrc,
  640. this.getBrowserType());
  641. var jid = data.peerjid || APP.xmpp.myJid();
  642. if(!this.remoteStreams[jid]) {
  643. this.remoteStreams[jid] = {};
  644. }
  645. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  646. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  647. console.debug("ADD remote stream ", remoteStream.type, " ", jid, " ", thessrc);
  648. return remoteStream;
  649. },
  650. getBrowserType: function () {
  651. return this.rtcUtils.browser;
  652. },
  653. getPCConstraints: function () {
  654. return this.rtcUtils.pc_constraints;
  655. },
  656. getUserMediaWithConstraints:function(um, success_callback,
  657. failure_callback, resolution,
  658. bandwidth, fps, desktopStream)
  659. {
  660. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  661. failure_callback, resolution, bandwidth, fps, desktopStream);
  662. },
  663. attachMediaStream: function (element, stream) {
  664. this.rtcUtils.attachMediaStream(element, stream);
  665. },
  666. getStreamID: function (stream) {
  667. return this.rtcUtils.getStreamID(stream);
  668. },
  669. getVideoSrc: function (element) {
  670. return this.rtcUtils.getVideoSrc(element);
  671. },
  672. setVideoSrc: function (element, src) {
  673. this.rtcUtils.setVideoSrc(element, src);
  674. },
  675. dispose: function() {
  676. if (this.rtcUtils) {
  677. this.rtcUtils = null;
  678. }
  679. },
  680. stop: function () {
  681. this.dispose();
  682. },
  683. start: function () {
  684. var self = this;
  685. APP.desktopsharing.addListener(
  686. function (stream, isUsingScreenStream, callback) {
  687. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  688. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  689. APP.xmpp.addListener(XMPPEvents.CHANGED_STREAMS, function (jid, changedStreams) {
  690. for(var i = 0; i < changedStreams.length; i++) {
  691. var type = changedStreams[i].type;
  692. if (type != "audio") {
  693. var peerStreams = self.remoteStreams[jid];
  694. if(!peerStreams)
  695. continue;
  696. var videoStream = peerStreams[MediaStreamType.VIDEO_TYPE];
  697. if(!videoStream)
  698. continue;
  699. videoStream.videoType = changedStreams[i].type;
  700. }
  701. }
  702. });
  703. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  704. DataChannels.init(event.peerconnection, eventEmitter);
  705. });
  706. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  707. DataChannels.handleSelectedEndpointEvent);
  708. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  709. DataChannels.handlePinnedEndpointEvent);
  710. this.rtcUtils = new RTCUtils(this);
  711. this.rtcUtils.obtainAudioAndVideoPermissions();
  712. },
  713. muteRemoteVideoStream: function (jid, value) {
  714. var stream;
  715. if(this.remoteStreams[jid] &&
  716. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE])
  717. {
  718. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  719. }
  720. if(!stream)
  721. return false;
  722. if (value != stream.muted) {
  723. stream.setMute(value);
  724. return true;
  725. }
  726. return false;
  727. },
  728. switchVideoStreams: function (new_stream) {
  729. this.localVideo.stream = new_stream;
  730. this.localStreams = [];
  731. //in firefox we have only one stream object
  732. if (this.localAudio.getOriginalStream() != new_stream)
  733. this.localStreams.push(this.localAudio);
  734. this.localStreams.push(this.localVideo);
  735. },
  736. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  737. var oldStream = this.localVideo.getOriginalStream();
  738. var type = (isUsingScreenStream? "screen" : "video");
  739. this.localVideo = this.createLocalStream(stream, "video", true, type);
  740. // Stop the stream to trigger onended event for old stream
  741. oldStream.stop();
  742. APP.xmpp.switchStreams(stream, oldStream,callback);
  743. },
  744. /**
  745. * Checks if video identified by given src is desktop stream.
  746. * @param videoSrc eg.
  747. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  748. * @returns {boolean}
  749. */
  750. isVideoSrcDesktop: function (jid) {
  751. if(!jid)
  752. return false;
  753. var isDesktop = false;
  754. var stream = null;
  755. if (APP.xmpp.myJid() &&
  756. APP.xmpp.myResource() === jid) {
  757. // local video
  758. stream = this.localVideo;
  759. } else {
  760. var peerStreams = this.remoteStreams[jid];
  761. if(!peerStreams)
  762. return false;
  763. stream = peerStreams[MediaStreamType.VIDEO_TYPE];
  764. }
  765. if(stream)
  766. isDesktop = (stream.videoType === "screen");
  767. return isDesktop;
  768. }
  769. };
  770. module.exports = RTC;
  771. },{"../../service/RTC/MediaStreamTypes":78,"../../service/RTC/StreamEventTypes.js":82,"../../service/UI/UIEvents":83,"../../service/desktopsharing/DesktopSharingEventTypes":86,"../../service/xmpp/XMPPEvents":88,"./DataChannels":3,"./LocalStream.js":4,"./MediaStream.js":5,"./RTCUtils.js":7,"events":89}],7:[function(require,module,exports){
  772. var RTCBrowserType = require("../../service/RTC/RTCBrowserType.js");
  773. var Resolutions = require("../../service/RTC/Resolutions");
  774. var currentResolution = null;
  775. function getPreviousResolution(resolution) {
  776. if(!Resolutions[resolution])
  777. return null;
  778. var order = Resolutions[resolution].order;
  779. var res = null;
  780. var resName = null;
  781. for(var i in Resolutions)
  782. {
  783. var tmp = Resolutions[i];
  784. if(res == null || (res.order < tmp.order && tmp.order < order))
  785. {
  786. resName = i;
  787. res = tmp;
  788. }
  789. }
  790. return resName;
  791. }
  792. function setResolutionConstraints(constraints, resolution, isAndroid)
  793. {
  794. if (resolution && !constraints.video || isAndroid) {
  795. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  796. }
  797. if(Resolutions[resolution])
  798. {
  799. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  800. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  801. }
  802. else
  803. {
  804. if (isAndroid) {
  805. constraints.video.mandatory.minWidth = 320;
  806. constraints.video.mandatory.minHeight = 240;
  807. constraints.video.mandatory.maxFrameRate = 15;
  808. }
  809. }
  810. if (constraints.video.mandatory.minWidth)
  811. constraints.video.mandatory.maxWidth = constraints.video.mandatory.minWidth;
  812. if (constraints.video.mandatory.minHeight)
  813. constraints.video.mandatory.maxHeight = constraints.video.mandatory.minHeight;
  814. }
  815. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  816. {
  817. var constraints = {audio: false, video: false};
  818. if (um.indexOf('video') >= 0) {
  819. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  820. }
  821. if (um.indexOf('audio') >= 0) {
  822. constraints.audio = { mandatory: {}, optional: []};// same behaviour as true
  823. }
  824. if (um.indexOf('screen') >= 0) {
  825. constraints.video = {
  826. mandatory: {
  827. chromeMediaSource: "screen",
  828. googLeakyBucket: true,
  829. maxWidth: window.screen.width,
  830. maxHeight: window.screen.height,
  831. maxFrameRate: 3
  832. },
  833. optional: []
  834. };
  835. }
  836. if (um.indexOf('desktop') >= 0) {
  837. constraints.video = {
  838. mandatory: {
  839. chromeMediaSource: "desktop",
  840. chromeMediaSourceId: desktopStream,
  841. googLeakyBucket: true,
  842. maxWidth: window.screen.width,
  843. maxHeight: window.screen.height,
  844. maxFrameRate: 3
  845. },
  846. optional: []
  847. };
  848. }
  849. if (constraints.audio) {
  850. // if it is good enough for hangouts...
  851. constraints.audio.optional.push(
  852. {googEchoCancellation: true},
  853. {googAutoGainControl: true},
  854. {googNoiseSupression: true},
  855. {googHighpassFilter: true},
  856. {googNoisesuppression2: true},
  857. {googEchoCancellation2: true},
  858. {googAutoGainControl2: true}
  859. );
  860. }
  861. if (constraints.video) {
  862. constraints.video.optional.push(
  863. {googNoiseReduction: false} // chrome 37 workaround for issue 3807, reenable in M38
  864. );
  865. if (um.indexOf('video') >= 0) {
  866. constraints.video.optional.push(
  867. {googLeakyBucket: true}
  868. );
  869. }
  870. }
  871. if (um.indexOf('video') >= 0) {
  872. setResolutionConstraints(constraints, resolution, isAndroid);
  873. }
  874. if (bandwidth) { // doesn't work currently, see webrtc issue 1846
  875. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};//same behaviour as true
  876. constraints.video.optional.push({bandwidth: bandwidth});
  877. }
  878. if (fps) { // for some cameras it might be necessary to request 30fps
  879. // so they choose 30fps mjpg over 10fps yuy2
  880. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};// same behaviour as true;
  881. constraints.video.mandatory.minFrameRate = fps;
  882. }
  883. return constraints;
  884. }
  885. function RTCUtils(RTCService)
  886. {
  887. this.service = RTCService;
  888. if (navigator.mozGetUserMedia) {
  889. console.log('This appears to be Firefox');
  890. var version = parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  891. if (version >= 22) {
  892. this.peerconnection = mozRTCPeerConnection;
  893. this.browser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  894. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  895. this.pc_constraints = {};
  896. this.attachMediaStream = function (element, stream) {
  897. element[0].mozSrcObject = stream;
  898. element[0].play();
  899. };
  900. this.getStreamID = function (stream) {
  901. var tracks = stream.getVideoTracks();
  902. if(!tracks || tracks.length == 0)
  903. {
  904. tracks = stream.getAudioTracks();
  905. }
  906. return tracks[0].id.replace(/[\{,\}]/g,"");
  907. };
  908. this.getVideoSrc = function (element) {
  909. return element.mozSrcObject;
  910. };
  911. this.setVideoSrc = function (element, src) {
  912. element.mozSrcObject = src;
  913. };
  914. RTCSessionDescription = mozRTCSessionDescription;
  915. RTCIceCandidate = mozRTCIceCandidate;
  916. }
  917. } else if (navigator.webkitGetUserMedia) {
  918. console.log('This appears to be Chrome');
  919. this.peerconnection = webkitRTCPeerConnection;
  920. this.browser = RTCBrowserType.RTC_BROWSER_CHROME;
  921. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  922. this.attachMediaStream = function (element, stream) {
  923. element.attr('src', webkitURL.createObjectURL(stream));
  924. };
  925. this.getStreamID = function (stream) {
  926. // streams from FF endpoints have the characters '{' and '}'
  927. // that make jQuery choke.
  928. return stream.id.replace(/[\{,\}]/g,"");
  929. };
  930. this.getVideoSrc = function (element) {
  931. return element.getAttribute("src");
  932. };
  933. this.setVideoSrc = function (element, src) {
  934. element.setAttribute("src", src);
  935. };
  936. // DTLS should now be enabled by default but..
  937. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  938. if (navigator.userAgent.indexOf('Android') != -1) {
  939. this.pc_constraints = {}; // disable DTLS on Android
  940. }
  941. if (!webkitMediaStream.prototype.getVideoTracks) {
  942. webkitMediaStream.prototype.getVideoTracks = function () {
  943. return this.videoTracks;
  944. };
  945. }
  946. if (!webkitMediaStream.prototype.getAudioTracks) {
  947. webkitMediaStream.prototype.getAudioTracks = function () {
  948. return this.audioTracks;
  949. };
  950. }
  951. }
  952. else
  953. {
  954. try { console.log('Browser does not appear to be WebRTC-capable'); } catch (e) { }
  955. window.location.href = 'unsupported_browser.html';
  956. return;
  957. }
  958. if (this.browser !== RTCBrowserType.RTC_BROWSER_CHROME &&
  959. config.enableFirefoxSupport !== true) {
  960. window.location.href = 'unsupported_browser.html';
  961. return;
  962. }
  963. }
  964. RTCUtils.prototype.getUserMediaWithConstraints = function(
  965. um, success_callback, failure_callback, resolution,bandwidth, fps,
  966. desktopStream)
  967. {
  968. currentResolution = resolution;
  969. // Check if we are running on Android device
  970. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  971. var constraints = getConstraints(
  972. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  973. var isFF = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
  974. try {
  975. if (config.enableSimulcast
  976. && constraints.video
  977. && constraints.video.chromeMediaSource !== 'screen'
  978. && constraints.video.chromeMediaSource !== 'desktop'
  979. && !isAndroid
  980. // We currently do not support FF, as it doesn't have multistream support.
  981. && !isFF) {
  982. APP.simulcast.getUserMedia(constraints, function (stream) {
  983. console.log('onUserMediaSuccess');
  984. success_callback(stream);
  985. },
  986. function (error) {
  987. console.warn('Failed to get access to local media. Error ', error);
  988. if (failure_callback) {
  989. failure_callback(error);
  990. }
  991. });
  992. } else {
  993. this.getUserMedia(constraints,
  994. function (stream) {
  995. console.log('onUserMediaSuccess');
  996. success_callback(stream);
  997. },
  998. function (error) {
  999. console.warn('Failed to get access to local media. Error ',
  1000. error, constraints);
  1001. if (failure_callback) {
  1002. failure_callback(error);
  1003. }
  1004. });
  1005. }
  1006. } catch (e) {
  1007. console.error('GUM failed: ', e);
  1008. if(failure_callback) {
  1009. failure_callback(e);
  1010. }
  1011. }
  1012. };
  1013. /**
  1014. * We ask for audio and video combined stream in order to get permissions and
  1015. * not to ask twice.
  1016. */
  1017. RTCUtils.prototype.obtainAudioAndVideoPermissions = function() {
  1018. var self = this;
  1019. // Get AV
  1020. this.getUserMediaWithConstraints(
  1021. ['audio', 'video'],
  1022. function (stream) {
  1023. self.successCallback(stream);
  1024. },
  1025. function (error) {
  1026. self.errorCallback(error);
  1027. },
  1028. config.resolution || '360');
  1029. }
  1030. RTCUtils.prototype.successCallback = function (stream) {
  1031. console.log('got', stream, stream.getAudioTracks().length,
  1032. stream.getVideoTracks().length);
  1033. this.handleLocalStream(stream);
  1034. };
  1035. RTCUtils.prototype.errorCallback = function (error) {
  1036. var self = this;
  1037. console.error('failed to obtain audio/video stream - trying audio only', error);
  1038. var resolution = getPreviousResolution(currentResolution);
  1039. if(typeof error == "object" && error.constraintName && error.name
  1040. && (error.name == "ConstraintNotSatisfiedError" ||
  1041. error.name == "OverconstrainedError") &&
  1042. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1043. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1044. && resolution != null)
  1045. {
  1046. self.getUserMediaWithConstraints(['audio', 'video'],
  1047. function (stream) {
  1048. return self.successCallback(stream);
  1049. }, function (error) {
  1050. return self.errorCallback(error);
  1051. }, resolution);
  1052. }
  1053. else
  1054. {
  1055. self.getUserMediaWithConstraints(
  1056. ['audio'],
  1057. function (stream) {
  1058. return self.successCallback(stream);
  1059. },
  1060. function (error) {
  1061. console.error('failed to obtain audio/video stream - stop',
  1062. error);
  1063. APP.UI.messageHandler.showError("dialog.error",
  1064. "dialog.failedpermissions");
  1065. }
  1066. );
  1067. }
  1068. }
  1069. RTCUtils.prototype.handleLocalStream = function(stream)
  1070. {
  1071. if(window.webkitMediaStream)
  1072. {
  1073. var audioStream = new webkitMediaStream();
  1074. var videoStream = new webkitMediaStream();
  1075. var audioTracks = stream.getAudioTracks();
  1076. var videoTracks = stream.getVideoTracks();
  1077. for (var i = 0; i < audioTracks.length; i++) {
  1078. audioStream.addTrack(audioTracks[i]);
  1079. }
  1080. this.service.createLocalStream(audioStream, "audio");
  1081. for (i = 0; i < videoTracks.length; i++) {
  1082. videoStream.addTrack(videoTracks[i]);
  1083. }
  1084. this.service.createLocalStream(videoStream, "video");
  1085. }
  1086. else
  1087. {//firefox
  1088. this.service.createLocalStream(stream, "stream");
  1089. }
  1090. };
  1091. module.exports = RTCUtils;
  1092. },{"../../service/RTC/RTCBrowserType.js":79,"../../service/RTC/Resolutions":81}],8:[function(require,module,exports){
  1093. var UI = {};
  1094. var VideoLayout = require("./videolayout/VideoLayout.js");
  1095. var AudioLevels = require("./audio_levels/AudioLevels.js");
  1096. var Prezi = require("./prezi/Prezi.js");
  1097. var Etherpad = require("./etherpad/Etherpad.js");
  1098. var Chat = require("./side_pannels/chat/Chat.js");
  1099. var Toolbar = require("./toolbars/Toolbar");
  1100. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  1101. var BottomToolbar = require("./toolbars/BottomToolbar");
  1102. var ContactList = require("./side_pannels/contactlist/ContactList");
  1103. var Avatar = require("./avatar/Avatar");
  1104. var EventEmitter = require("events");
  1105. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  1106. var Settings = require("./../settings/Settings");
  1107. var PanelToggler = require("./side_pannels/SidePanelToggler");
  1108. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  1109. UI.messageHandler = require("./util/MessageHandler");
  1110. var messageHandler = UI.messageHandler;
  1111. var Authentication = require("./authentication/Authentication");
  1112. var UIUtil = require("./util/UIUtil");
  1113. var NicknameHandler = require("./util/NicknameHandler");
  1114. var CQEvents = require("../../service/connectionquality/CQEvents");
  1115. var DesktopSharingEventTypes
  1116. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1117. var RTCEvents = require("../../service/RTC/RTCEvents");
  1118. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  1119. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  1120. var eventEmitter = new EventEmitter();
  1121. var roomName = null;
  1122. function setupPrezi()
  1123. {
  1124. $("#reloadPresentationLink").click(function()
  1125. {
  1126. Prezi.reloadPresentation();
  1127. });
  1128. }
  1129. function setupChat()
  1130. {
  1131. Chat.init();
  1132. $("#toggle_smileys").click(function() {
  1133. Chat.toggleSmileys();
  1134. });
  1135. }
  1136. function setupToolbars() {
  1137. Toolbar.init(UI);
  1138. Toolbar.setupButtonsFromConfig();
  1139. BottomToolbar.init();
  1140. }
  1141. function streamHandler(stream) {
  1142. switch (stream.type)
  1143. {
  1144. case "audio":
  1145. VideoLayout.changeLocalAudio(stream);
  1146. break;
  1147. case "video":
  1148. VideoLayout.changeLocalVideo(stream);
  1149. break;
  1150. case "stream":
  1151. VideoLayout.changeLocalStream(stream);
  1152. break;
  1153. }
  1154. }
  1155. function onDisposeConference(unload) {
  1156. Toolbar.showAuthenticateButton(false);
  1157. };
  1158. function onDisplayNameChanged(jid, displayName) {
  1159. ContactList.onDisplayNameChange(jid, displayName);
  1160. SettingsMenu.onDisplayNameChange(jid, displayName);
  1161. VideoLayout.onDisplayNameChanged(jid, displayName);
  1162. }
  1163. function registerListeners() {
  1164. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  1165. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  1166. APP.RTC.addStreamListener(function (stream) {
  1167. VideoLayout.onRemoteStreamAdded(stream);
  1168. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  1169. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  1170. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (resourceJid) {
  1171. VideoLayout.onDominantSpeakerChanged(resourceJid);
  1172. });
  1173. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1174. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  1175. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  1176. endpointsEnteringLastN, stream);
  1177. });
  1178. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  1179. function (endpointSimulcastLayers) {
  1180. VideoLayout.onSimulcastLayersChanged(endpointSimulcastLayers);
  1181. });
  1182. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGING,
  1183. function (endpointSimulcastLayers) {
  1184. VideoLayout.onSimulcastLayersChanging(endpointSimulcastLayers);
  1185. });
  1186. APP.statistics.addAudioLevelListener(function(jid, audioLevel)
  1187. {
  1188. var resourceJid;
  1189. if(jid === APP.statistics.LOCAL_JID)
  1190. {
  1191. resourceJid = AudioLevels.LOCAL_LEVEL;
  1192. if(APP.RTC.localAudio.isMuted())
  1193. {
  1194. audioLevel = 0;
  1195. }
  1196. }
  1197. else
  1198. {
  1199. resourceJid = Strophe.getResourceFromJid(jid);
  1200. }
  1201. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  1202. UI.getLargeVideoState().userResourceJid);
  1203. });
  1204. APP.desktopsharing.addListener(function () {
  1205. ToolbarToggler.showDesktopSharingButton();
  1206. }, DesktopSharingEventTypes.INIT);
  1207. APP.desktopsharing.addListener(
  1208. Toolbar.changeDesktopSharingButtonState,
  1209. DesktopSharingEventTypes.SWITCHING_DONE);
  1210. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  1211. VideoLayout.updateLocalConnectionStats);
  1212. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  1213. VideoLayout.updateConnectionStats);
  1214. APP.connectionquality.addListener(CQEvents.STOP,
  1215. VideoLayout.onStatsStop);
  1216. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  1217. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  1218. messageHandler.openMessageDialog(
  1219. 'dialog.serviceUnavailable',
  1220. 'dialog.gracefulShutdown'
  1221. );
  1222. });
  1223. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  1224. var title = APP.translation.generateTranslatonHTML(
  1225. "dialog.reservationError");
  1226. var message = APP.translation.generateTranslatonHTML(
  1227. "dialog.reservationErrorMsg", {code: code, msg: msg});
  1228. messageHandler.openDialog(
  1229. title,
  1230. message,
  1231. true, {},
  1232. function (event, value, message, formVals)
  1233. {
  1234. return false;
  1235. }
  1236. );
  1237. });
  1238. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  1239. messageHandler.openMessageDialog("dialog.sessTerminated",
  1240. "dialog.kickMessage");
  1241. });
  1242. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  1243. //FIXME: use Session Terminated from translation, but
  1244. // 'reason' text comes from XMPP packet and is not translated
  1245. var title = APP.translation.generateTranslatonHTML("dialog.sessTerminated");
  1246. messageHandler.openDialog(
  1247. title, reason, true, {},
  1248. function (event, value, message, formVals)
  1249. {
  1250. return false;
  1251. }
  1252. );
  1253. });
  1254. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  1255. messageHandler.showError("dialog.error",
  1256. "dialog.bridgeUnavailable");
  1257. });
  1258. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  1259. Avatar.setUserAvatar(from, id);
  1260. });
  1261. APP.xmpp.addListener(XMPPEvents.CHANGED_STREAMS, function (jid, changedStreams) {
  1262. for(stream in changedStreams)
  1263. {
  1264. // might need to update the direction if participant just went from sendrecv to recvonly
  1265. if (stream.type === 'video' || stream.type === 'screen') {
  1266. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  1267. switch (stream.direction) {
  1268. case 'sendrecv':
  1269. el.show();
  1270. break;
  1271. case 'recvonly':
  1272. el.hide();
  1273. // FIXME: Check if we have to change large video
  1274. //VideoLayout.updateLargeVideo(el);
  1275. break;
  1276. }
  1277. }
  1278. }
  1279. });
  1280. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  1281. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  1282. APP.xmpp.addListener(XMPPEvents.LOCALROLE_CHANGED, onLocalRoleChange);
  1283. APP.xmpp.addListener(XMPPEvents.MUC_ENTER, onMucEntered);
  1284. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  1285. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  1286. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  1287. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  1288. APP.xmpp.addListener(XMPPEvents.MUC_LEFT, onMucLeft);
  1289. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordReqiured);
  1290. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  1291. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  1292. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED, onAuthenticationRequired);
  1293. }
  1294. /**
  1295. * Mutes/unmutes the local video.
  1296. *
  1297. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  1298. * @param options an object which specifies optional arguments such as the
  1299. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  1300. * specifies whether the method was initiated in response to a user command (in
  1301. * contrast to an automatic decision taken by the application logic)
  1302. */
  1303. function setVideoMute(mute, options) {
  1304. APP.xmpp.setVideoMute(
  1305. mute,
  1306. function (mute) {
  1307. var video = $('#video');
  1308. var communicativeClass = "icon-camera";
  1309. var muteClass = "icon-camera icon-camera-disabled";
  1310. if (mute) {
  1311. video.removeClass(communicativeClass);
  1312. video.addClass(muteClass);
  1313. } else {
  1314. video.removeClass(muteClass);
  1315. video.addClass(communicativeClass);
  1316. }
  1317. },
  1318. options);
  1319. }
  1320. function bindEvents()
  1321. {
  1322. /**
  1323. * Resizes and repositions videos in full screen mode.
  1324. */
  1325. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1326. function () {
  1327. VideoLayout.resizeLargeVideoContainer();
  1328. VideoLayout.positionLarge();
  1329. }
  1330. );
  1331. $(window).resize(function () {
  1332. VideoLayout.resizeLargeVideoContainer();
  1333. VideoLayout.positionLarge();
  1334. });
  1335. }
  1336. UI.start = function (init) {
  1337. document.title = interfaceConfig.APP_NAME;
  1338. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1339. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1340. {
  1341. $("#videoconference_page").hide();
  1342. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1343. setupWelcomePage();
  1344. return;
  1345. }
  1346. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  1347. var leftWatermarkDiv
  1348. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  1349. leftWatermarkDiv.css({display: 'block'});
  1350. leftWatermarkDiv.parent().get(0).href
  1351. = interfaceConfig.JITSI_WATERMARK_LINK;
  1352. }
  1353. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1354. var rightWatermarkDiv
  1355. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  1356. rightWatermarkDiv.css({display: 'block'});
  1357. rightWatermarkDiv.parent().get(0).href
  1358. = interfaceConfig.BRAND_WATERMARK_LINK;
  1359. rightWatermarkDiv.get(0).style.backgroundImage
  1360. = "url(images/rightwatermark.png)";
  1361. }
  1362. if (interfaceConfig.SHOW_POWERED_BY) {
  1363. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  1364. }
  1365. $("#welcome_page").hide();
  1366. VideoLayout.resizeLargeVideoContainer();
  1367. $("#videospace").mousemove(function () {
  1368. return ToolbarToggler.showToolbar();
  1369. });
  1370. // Set the defaults for prompt dialogs.
  1371. jQuery.prompt.setDefaults({persistent: false});
  1372. VideoLayout.init(eventEmitter);
  1373. AudioLevels.init();
  1374. NicknameHandler.init(eventEmitter);
  1375. registerListeners();
  1376. bindEvents();
  1377. setupPrezi();
  1378. setupToolbars();
  1379. setupChat();
  1380. document.title = interfaceConfig.APP_NAME;
  1381. $("#downloadlog").click(function (event) {
  1382. dump(event.target);
  1383. });
  1384. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1385. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1386. {
  1387. $("#videoconference_page").hide();
  1388. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1389. setupWelcomePage();
  1390. return;
  1391. }
  1392. $("#welcome_page").hide();
  1393. document.getElementById('largeVideo').volume = 0;
  1394. if (!$('#settings').is(':visible')) {
  1395. console.log('init');
  1396. init();
  1397. } else {
  1398. loginInfo.onsubmit = function (e) {
  1399. if (e.preventDefault) e.preventDefault();
  1400. $('#settings').hide();
  1401. init();
  1402. };
  1403. }
  1404. toastr.options = {
  1405. "closeButton": true,
  1406. "debug": false,
  1407. "positionClass": "notification-bottom-right",
  1408. "onclick": null,
  1409. "showDuration": "300",
  1410. "hideDuration": "1000",
  1411. "timeOut": "2000",
  1412. "extendedTimeOut": "1000",
  1413. "showEasing": "swing",
  1414. "hideEasing": "linear",
  1415. "showMethod": "fadeIn",
  1416. "hideMethod": "fadeOut",
  1417. "reposition": function() {
  1418. if(PanelToggler.isVisible()) {
  1419. $("#toast-container").addClass("notification-bottom-right-center");
  1420. } else {
  1421. $("#toast-container").removeClass("notification-bottom-right-center");
  1422. }
  1423. },
  1424. "newestOnTop": false
  1425. };
  1426. SettingsMenu.init();
  1427. };
  1428. function chatAddError(errorMessage, originalText)
  1429. {
  1430. return Chat.chatAddError(errorMessage, originalText);
  1431. };
  1432. function chatSetSubject(text)
  1433. {
  1434. return Chat.chatSetSubject(text);
  1435. };
  1436. function updateChatConversation(from, displayName, message) {
  1437. return Chat.updateChatConversation(from, displayName, message);
  1438. };
  1439. function onMucJoined(jid, info) {
  1440. Toolbar.updateRoomUrl(window.location.href);
  1441. document.getElementById('localNick').appendChild(
  1442. document.createTextNode(Strophe.getResourceFromJid(jid) + ' (me)')
  1443. );
  1444. var settings = Settings.getSettings();
  1445. // Add myself to the contact list.
  1446. ContactList.addContact(jid, settings.email || settings.uid);
  1447. // Once we've joined the muc show the toolbar
  1448. ToolbarToggler.showToolbar();
  1449. var displayName = !config.displayJids
  1450. ? info.displayName : Strophe.getResourceFromJid(jid);
  1451. if (displayName)
  1452. onDisplayNameChanged('localVideoContainer', displayName + ' (me)');
  1453. }
  1454. function initEtherpad(name) {
  1455. Etherpad.init(name);
  1456. };
  1457. function onMucLeft(jid) {
  1458. console.log('left.muc', jid);
  1459. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  1460. '>.displayname').html();
  1461. messageHandler.notify(displayName,'notify.somebody',
  1462. 'disconnected',
  1463. 'notify.disconnected');
  1464. // Need to call this with a slight delay, otherwise the element couldn't be
  1465. // found for some reason.
  1466. // XXX(gp) it works fine without the timeout for me (with Chrome 38).
  1467. window.setTimeout(function () {
  1468. var container = document.getElementById(
  1469. 'participant_' + Strophe.getResourceFromJid(jid));
  1470. if (container) {
  1471. ContactList.removeContact(jid);
  1472. VideoLayout.removeConnectionIndicator(jid);
  1473. // hide here, wait for video to close before removing
  1474. $(container).hide();
  1475. VideoLayout.resizeThumbnails();
  1476. }
  1477. }, 10);
  1478. VideoLayout.participantLeft(jid);
  1479. };
  1480. function onLocalRoleChange(jid, info, pres, isModerator)
  1481. {
  1482. console.info("My role changed, new role: " + info.role);
  1483. onModeratorStatusChanged(isModerator);
  1484. VideoLayout.showModeratorIndicator();
  1485. if (isModerator) {
  1486. Authentication.closeAuthenticationWindow();
  1487. messageHandler.notify(null, "notify.me",
  1488. 'connected', "notify.moderator");
  1489. }
  1490. }
  1491. function onModeratorStatusChanged(isModerator) {
  1492. Toolbar.showSipCallButton(isModerator);
  1493. Toolbar.showRecordingButton(
  1494. isModerator); //&&
  1495. // FIXME:
  1496. // Recording visible if
  1497. // there are at least 2(+ 1 focus) participants
  1498. //Object.keys(connection.emuc.members).length >= 3);
  1499. if (isModerator && config.etherpad_base) {
  1500. Etherpad.init();
  1501. }
  1502. };
  1503. function onPasswordReqiured(callback) {
  1504. // password is required
  1505. Toolbar.lockLockButton();
  1506. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1507. message += APP.translation.translateString(
  1508. "dialog.passwordRequired");
  1509. message += '</h2>' +
  1510. '<input id="lockKey" type="text" placeholder="password" autofocus>';
  1511. messageHandler.openTwoButtonDialog(null, null, null, message,
  1512. true,
  1513. "dialog.Ok",
  1514. function (e, v, m, f) {},
  1515. function (event) {
  1516. document.getElementById('lockKey').focus();
  1517. },
  1518. function (e, v, m, f) {
  1519. if (v) {
  1520. var lockKey = document.getElementById('lockKey');
  1521. if (lockKey.value !== null) {
  1522. Toolbar.setSharedKey(lockKey.value);
  1523. callback(lockKey.value);
  1524. }
  1525. }
  1526. }
  1527. );
  1528. }
  1529. function onMucEntered(jid, id, displayName) {
  1530. messageHandler.notify(displayName,'notify.somebody',
  1531. 'connected',
  1532. 'notify.connected');
  1533. // Add Peer's container
  1534. VideoLayout.ensurePeerContainerExists(jid,id);
  1535. }
  1536. function onMucPresenceStatus( jid, info) {
  1537. VideoLayout.setPresenceStatus(
  1538. 'participant_' + Strophe.getResourceFromJid(jid), info.status);
  1539. }
  1540. function onMucRoleChanged(role, displayName) {
  1541. VideoLayout.showModeratorIndicator();
  1542. if (role === 'moderator') {
  1543. var messageKey, messageOptions = {};
  1544. if (!displayName) {
  1545. messageKey = "notify.grantedToUnknown";
  1546. }
  1547. else
  1548. {
  1549. messageKey = "notify.grantedTo";
  1550. messageOptions = {to: displayName};
  1551. }
  1552. messageHandler.notify(
  1553. displayName,'notify.somebody',
  1554. 'connected', messageKey,
  1555. messageOptions);
  1556. }
  1557. }
  1558. function onAuthenticationRequired(intervalCallback) {
  1559. Authentication.openAuthenticationDialog(
  1560. roomName, intervalCallback, function () {
  1561. Toolbar.authenticateClicked();
  1562. });
  1563. };
  1564. function onLastNChanged(oldValue, newValue) {
  1565. if (config.muteLocalVideoIfNotInLastN) {
  1566. setVideoMute(!newValue, { 'byUser': false });
  1567. }
  1568. }
  1569. UI.toggleSmileys = function () {
  1570. Chat.toggleSmileys();
  1571. };
  1572. UI.getSettings = function () {
  1573. return Settings.getSettings();
  1574. };
  1575. UI.toggleFilmStrip = function () {
  1576. return BottomToolbar.toggleFilmStrip();
  1577. };
  1578. UI.toggleChat = function () {
  1579. return BottomToolbar.toggleChat();
  1580. };
  1581. UI.toggleContactList = function () {
  1582. return BottomToolbar.toggleContactList();
  1583. };
  1584. UI.inputDisplayNameHandler = function (value) {
  1585. VideoLayout.inputDisplayNameHandler(value);
  1586. };
  1587. UI.getLargeVideoState = function()
  1588. {
  1589. return VideoLayout.getLargeVideoState();
  1590. };
  1591. UI.generateRoomName = function() {
  1592. if(roomName)
  1593. return roomName;
  1594. var roomnode = null;
  1595. var path = window.location.pathname;
  1596. // determinde the room node from the url
  1597. // TODO: just the roomnode or the whole bare jid?
  1598. if (config.getroomnode && typeof config.getroomnode === 'function') {
  1599. // custom function might be responsible for doing the pushstate
  1600. roomnode = config.getroomnode(path);
  1601. } else {
  1602. /* fall back to default strategy
  1603. * this is making assumptions about how the URL->room mapping happens.
  1604. * It currently assumes deployment at root, with a rewrite like the
  1605. * following one (for nginx):
  1606. location ~ ^/([a-zA-Z0-9]+)$ {
  1607. rewrite ^/(.*)$ / break;
  1608. }
  1609. */
  1610. if (path.length > 1) {
  1611. roomnode = path.substr(1).toLowerCase();
  1612. } else {
  1613. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  1614. roomnode = word.toLowerCase();
  1615. window.history.pushState('VideoChat',
  1616. 'Room: ' + word, window.location.pathname + word);
  1617. }
  1618. }
  1619. roomName = roomnode + '@' + config.hosts.muc;
  1620. return roomName;
  1621. };
  1622. UI.connectionIndicatorShowMore = function(id)
  1623. {
  1624. return VideoLayout.connectionIndicators[id].showMore();
  1625. };
  1626. UI.getCredentials = function () {
  1627. var settings = this.getSettings();
  1628. return {
  1629. bosh: document.getElementById('boshURL').value,
  1630. password: document.getElementById('password').value,
  1631. jid: document.getElementById('jid').value,
  1632. email: settings.email,
  1633. displayName: settings.displayName,
  1634. uid: settings.uid
  1635. };
  1636. };
  1637. UI.disableConnect = function () {
  1638. document.getElementById('connect').disabled = true;
  1639. };
  1640. UI.showLoginPopup = function(callback)
  1641. {
  1642. console.log('password is required');
  1643. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1644. message += APP.translation.translateString(
  1645. "dialog.passwordRequired");
  1646. message += '</h2>' +
  1647. '<input id="passwordrequired.username" type="text" ' +
  1648. 'placeholder="user@domain.net" autofocus>' +
  1649. '<input id="passwordrequired.password" ' +
  1650. 'type="password" placeholder="user password">';
  1651. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  1652. true,
  1653. "dialog.Ok",
  1654. function (e, v, m, f) {
  1655. if (v) {
  1656. var username = document.getElementById('passwordrequired.username');
  1657. var password = document.getElementById('passwordrequired.password');
  1658. if (username.value !== null && password.value != null) {
  1659. callback(username.value, password.value);
  1660. }
  1661. }
  1662. },
  1663. function (event) {
  1664. document.getElementById('passwordrequired.username').focus();
  1665. }
  1666. );
  1667. }
  1668. UI.checkForNicknameAndJoin = function () {
  1669. Authentication.closeAuthenticationDialog();
  1670. Authentication.stopInterval();
  1671. var nick = null;
  1672. if (config.useNicks) {
  1673. nick = window.prompt('Your nickname (optional)');
  1674. }
  1675. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  1676. };
  1677. function dump(elem, filename) {
  1678. elem = elem.parentNode;
  1679. elem.download = filename || 'meetlog.json';
  1680. elem.href = 'data:application/json;charset=utf-8,\n';
  1681. var data = APP.xmpp.populateData();
  1682. var metadata = {};
  1683. metadata.time = new Date();
  1684. metadata.url = window.location.href;
  1685. metadata.ua = navigator.userAgent;
  1686. var log = APP.xmpp.getLogger();
  1687. if (log) {
  1688. metadata.xmpp = log;
  1689. }
  1690. data.metadata = metadata;
  1691. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  1692. return false;
  1693. }
  1694. UI.getRoomName = function () {
  1695. return roomName;
  1696. };
  1697. /**
  1698. * Mutes/unmutes the local video.
  1699. */
  1700. UI.toggleVideo = function () {
  1701. UIUtil.buttonClick("#video", "icon-camera icon-camera-disabled");
  1702. setVideoMute(!APP.RTC.localVideo.isMuted());
  1703. };
  1704. /**
  1705. * Mutes / unmutes audio for the local participant.
  1706. */
  1707. UI.toggleAudio = function() {
  1708. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  1709. };
  1710. /**
  1711. * Sets muted audio state for the local participant.
  1712. */
  1713. UI.setAudioMuted = function (mute) {
  1714. if(!APP.xmpp.setAudioMute(mute, function () {
  1715. VideoLayout.showLocalAudioIndicator(mute);
  1716. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1717. }))
  1718. {
  1719. // We still click the button.
  1720. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1721. return;
  1722. }
  1723. }
  1724. UI.addListener = function (type, listener) {
  1725. eventEmitter.on(type, listener);
  1726. }
  1727. UI.clickOnVideo = function (videoNumber) {
  1728. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  1729. if (remoteVideos.length > videoNumber) {
  1730. remoteVideos[videoNumber].click();
  1731. }
  1732. }
  1733. //Used by torture
  1734. UI.showToolbar = function () {
  1735. return ToolbarToggler.showToolbar();
  1736. }
  1737. //Used by torture
  1738. UI.dockToolbar = function (isDock) {
  1739. return ToolbarToggler.dockToolbar(isDock);
  1740. }
  1741. module.exports = UI;
  1742. },{"../../service/RTC/RTCEvents":80,"../../service/RTC/StreamEventTypes":82,"../../service/connectionquality/CQEvents":85,"../../service/desktopsharing/DesktopSharingEventTypes":86,"../../service/xmpp/XMPPEvents":88,"./../settings/Settings":37,"./audio_levels/AudioLevels.js":9,"./authentication/Authentication":11,"./avatar/Avatar":12,"./etherpad/Etherpad.js":13,"./prezi/Prezi.js":14,"./side_pannels/SidePanelToggler":16,"./side_pannels/chat/Chat.js":17,"./side_pannels/contactlist/ContactList":21,"./side_pannels/settings/SettingsMenu":22,"./toolbars/BottomToolbar":23,"./toolbars/Toolbar":24,"./toolbars/ToolbarToggler":25,"./util/MessageHandler":27,"./util/NicknameHandler":28,"./util/UIUtil":29,"./videolayout/VideoLayout.js":31,"./welcome_page/RoomnameGenerator":32,"./welcome_page/WelcomePage":33,"events":89}],9:[function(require,module,exports){
  1743. var CanvasUtil = require("./CanvasUtils");
  1744. var ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  1745. function initActiveSpeakerAudioLevels() {
  1746. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  1747. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  1748. // Draw a circle.
  1749. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  1750. // Add a shadow around the circle
  1751. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  1752. ASDrawContext.shadowOffsetX = 0;
  1753. ASDrawContext.shadowOffsetY = 0;
  1754. }
  1755. /**
  1756. * The audio Levels plugin.
  1757. */
  1758. var AudioLevels = (function(my) {
  1759. var audioLevelCanvasCache = {};
  1760. my.LOCAL_LEVEL = 'local';
  1761. my.init = function () {
  1762. initActiveSpeakerAudioLevels();
  1763. }
  1764. /**
  1765. * Updates the audio level canvas for the given peerJid. If the canvas
  1766. * didn't exist we create it.
  1767. */
  1768. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  1769. var resourceJid = null;
  1770. var videoSpanId = null;
  1771. if (!peerJid)
  1772. videoSpanId = 'localVideoContainer';
  1773. else {
  1774. resourceJid = Strophe.getResourceFromJid(peerJid);
  1775. videoSpanId = 'participant_' + resourceJid;
  1776. }
  1777. var videoSpan = document.getElementById(videoSpanId);
  1778. if (!videoSpan) {
  1779. if (resourceJid)
  1780. console.error("No video element for jid", resourceJid);
  1781. else
  1782. console.error("No video element for local video.");
  1783. return;
  1784. }
  1785. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  1786. var videoSpaceWidth = $('#remoteVideos').width();
  1787. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  1788. var thumbnailWidth = thumbnailSize[0];
  1789. var thumbnailHeight = thumbnailSize[1];
  1790. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  1791. audioLevelCanvas = document.createElement('canvas');
  1792. audioLevelCanvas.className = "audiolevel";
  1793. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  1794. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  1795. resizeAudioLevelCanvas( audioLevelCanvas,
  1796. thumbnailWidth,
  1797. thumbnailHeight);
  1798. videoSpan.appendChild(audioLevelCanvas);
  1799. } else {
  1800. audioLevelCanvas = audioLevelCanvas.get(0);
  1801. resizeAudioLevelCanvas( audioLevelCanvas,
  1802. thumbnailWidth,
  1803. thumbnailHeight);
  1804. }
  1805. };
  1806. /**
  1807. * Updates the audio level UI for the given resourceJid.
  1808. *
  1809. * @param resourceJid the resource jid indicating the video element for
  1810. * which we draw the audio level
  1811. * @param audioLevel the newAudio level to render
  1812. */
  1813. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  1814. drawAudioLevelCanvas(resourceJid, audioLevel);
  1815. var videoSpanId = getVideoSpanId(resourceJid);
  1816. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  1817. if (!audioLevelCanvas)
  1818. return;
  1819. var drawContext = audioLevelCanvas.getContext('2d');
  1820. var canvasCache = audioLevelCanvasCache[resourceJid];
  1821. drawContext.clearRect (0, 0,
  1822. audioLevelCanvas.width, audioLevelCanvas.height);
  1823. drawContext.drawImage(canvasCache, 0, 0);
  1824. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  1825. if(!APP.xmpp.myJid()) {
  1826. return;
  1827. }
  1828. resourceJid = APP.xmpp.myResource();
  1829. }
  1830. if(resourceJid === largeVideoResourceJid) {
  1831. window.requestAnimationFrame(function () {
  1832. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  1833. });
  1834. }
  1835. };
  1836. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  1837. if($("#activeSpeaker").css("visibility") == "hidden")
  1838. return;
  1839. ASDrawContext.clearRect(0, 0, 300, 300);
  1840. if(audioLevel == 0)
  1841. return;
  1842. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  1843. // Fill the shape.
  1844. ASDrawContext.fill();
  1845. };
  1846. /**
  1847. * Resizes the given audio level canvas to match the given thumbnail size.
  1848. */
  1849. function resizeAudioLevelCanvas(audioLevelCanvas,
  1850. thumbnailWidth,
  1851. thumbnailHeight) {
  1852. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  1853. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  1854. }
  1855. /**
  1856. * Draws the audio level canvas into the cached canvas object.
  1857. *
  1858. * @param resourceJid the resource jid indicating the video element for
  1859. * which we draw the audio level
  1860. * @param audioLevel the newAudio level to render
  1861. */
  1862. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  1863. if (!audioLevelCanvasCache[resourceJid]) {
  1864. var videoSpanId = getVideoSpanId(resourceJid);
  1865. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  1866. /*
  1867. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  1868. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  1869. * error. Since audio levels are frequently updated, the errors have
  1870. * been observed to pile into the console, strain the CPU.
  1871. */
  1872. if (audioLevelCanvasOrig)
  1873. {
  1874. audioLevelCanvasCache[resourceJid]
  1875. = CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  1876. }
  1877. }
  1878. var canvas = audioLevelCanvasCache[resourceJid];
  1879. if (!canvas)
  1880. return;
  1881. var drawContext = canvas.getContext('2d');
  1882. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  1883. var shadowLevel = getShadowLevel(audioLevel);
  1884. if (shadowLevel > 0)
  1885. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  1886. CanvasUtil.drawRoundRectGlow( drawContext,
  1887. interfaceConfig.CANVAS_EXTRA/2, interfaceConfig.CANVAS_EXTRA/2,
  1888. canvas.width - interfaceConfig.CANVAS_EXTRA,
  1889. canvas.height - interfaceConfig.CANVAS_EXTRA,
  1890. interfaceConfig.CANVAS_RADIUS,
  1891. interfaceConfig.SHADOW_COLOR,
  1892. shadowLevel);
  1893. }
  1894. /**
  1895. * Returns the shadow/glow level for the given audio level.
  1896. *
  1897. * @param audioLevel the audio level from which we determine the shadow
  1898. * level
  1899. */
  1900. function getShadowLevel (audioLevel) {
  1901. var shadowLevel = 0;
  1902. if (audioLevel <= 0.3) {
  1903. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  1904. }
  1905. else if (audioLevel <= 0.6) {
  1906. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  1907. }
  1908. else {
  1909. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  1910. }
  1911. return shadowLevel;
  1912. }
  1913. /**
  1914. * Returns the video span id corresponding to the given resourceJid or local
  1915. * user.
  1916. */
  1917. function getVideoSpanId(resourceJid) {
  1918. var videoSpanId = null;
  1919. if (resourceJid === AudioLevels.LOCAL_LEVEL
  1920. || (APP.xmpp.myResource() && resourceJid
  1921. === APP.xmpp.myResource()))
  1922. videoSpanId = 'localVideoContainer';
  1923. else
  1924. videoSpanId = 'participant_' + resourceJid;
  1925. return videoSpanId;
  1926. }
  1927. /**
  1928. * Indicates that the remote video has been resized.
  1929. */
  1930. $(document).bind('remotevideo.resized', function (event, width, height) {
  1931. var resized = false;
  1932. $('#remoteVideos>span>canvas').each(function() {
  1933. var canvas = $(this).get(0);
  1934. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  1935. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  1936. resized = true;
  1937. }
  1938. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  1939. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  1940. resized = true;
  1941. }
  1942. });
  1943. if (resized)
  1944. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  1945. audioLevelCanvasCache[resourceJid].width
  1946. = width + interfaceConfig.CANVAS_EXTRA;
  1947. audioLevelCanvasCache[resourceJid].height
  1948. = height + interfaceConfig.CANVAS_EXTRA;
  1949. });
  1950. });
  1951. return my;
  1952. })(AudioLevels || {});
  1953. module.exports = AudioLevels;
  1954. },{"./CanvasUtils":10}],10:[function(require,module,exports){
  1955. /**
  1956. * Utility class for drawing canvas shapes.
  1957. */
  1958. var CanvasUtil = (function(my) {
  1959. /**
  1960. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  1961. * of the glow.
  1962. *
  1963. * @param drawContext the context of the canvas to draw to
  1964. * @param x the x coordinate of the round rectangle
  1965. * @param y the y coordinate of the round rectangle
  1966. * @param w the width of the round rectangle
  1967. * @param h the height of the round rectangle
  1968. * @param glowColor the color of the glow
  1969. * @param glowWidth the width of the glow
  1970. */
  1971. my.drawRoundRectGlow
  1972. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  1973. // Save the previous state of the context.
  1974. drawContext.save();
  1975. if (w < 2 * r) r = w / 2;
  1976. if (h < 2 * r) r = h / 2;
  1977. // Draw a round rectangle.
  1978. drawContext.beginPath();
  1979. drawContext.moveTo(x+r, y);
  1980. drawContext.arcTo(x+w, y, x+w, y+h, r);
  1981. drawContext.arcTo(x+w, y+h, x, y+h, r);
  1982. drawContext.arcTo(x, y+h, x, y, r);
  1983. drawContext.arcTo(x, y, x+w, y, r);
  1984. drawContext.closePath();
  1985. // Add a shadow around the rectangle
  1986. drawContext.shadowColor = glowColor;
  1987. drawContext.shadowBlur = glowWidth;
  1988. drawContext.shadowOffsetX = 0;
  1989. drawContext.shadowOffsetY = 0;
  1990. // Fill the shape.
  1991. drawContext.fill();
  1992. drawContext.save();
  1993. drawContext.restore();
  1994. // 1) Uncomment this line to use Composite Operation, which is doing the
  1995. // same as the clip function below and is also antialiasing the round
  1996. // border, but is said to be less fast performance wise.
  1997. // drawContext.globalCompositeOperation='destination-out';
  1998. drawContext.beginPath();
  1999. drawContext.moveTo(x+r, y);
  2000. drawContext.arcTo(x+w, y, x+w, y+h, r);
  2001. drawContext.arcTo(x+w, y+h, x, y+h, r);
  2002. drawContext.arcTo(x, y+h, x, y, r);
  2003. drawContext.arcTo(x, y, x+w, y, r);
  2004. drawContext.closePath();
  2005. // 2) Uncomment this line to use Composite Operation, which is doing the
  2006. // same as the clip function below and is also antialiasing the round
  2007. // border, but is said to be less fast performance wise.
  2008. // drawContext.fill();
  2009. // Comment these two lines if choosing to do the same with composite
  2010. // operation above 1 and 2.
  2011. drawContext.clip();
  2012. drawContext.clearRect(0, 0, 277, 200);
  2013. // Restore the previous context state.
  2014. drawContext.restore();
  2015. };
  2016. /**
  2017. * Clones the given canvas.
  2018. *
  2019. * @return the new cloned canvas.
  2020. */
  2021. my.cloneCanvas = function (oldCanvas) {
  2022. /*
  2023. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  2024. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  2025. * levels are frequently updated, the errors have been observed to pile
  2026. * into the console, strain the CPU.
  2027. */
  2028. if (!oldCanvas)
  2029. return oldCanvas;
  2030. //create a new canvas
  2031. var newCanvas = document.createElement('canvas');
  2032. var context = newCanvas.getContext('2d');
  2033. //set dimensions
  2034. newCanvas.width = oldCanvas.width;
  2035. newCanvas.height = oldCanvas.height;
  2036. //apply the old canvas to the new one
  2037. context.drawImage(oldCanvas, 0, 0);
  2038. //return the new canvas
  2039. return newCanvas;
  2040. };
  2041. return my;
  2042. })(CanvasUtil || {});
  2043. module.exports = CanvasUtil;
  2044. },{}],11:[function(require,module,exports){
  2045. /* Initial "authentication required" dialog */
  2046. var authDialog = null;
  2047. /* Loop retry ID that wits for other user to create the room */
  2048. var authRetryId = null;
  2049. var authenticationWindow = null;
  2050. var Authentication = {
  2051. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  2052. // This is the loop that will wait for the room to be created by
  2053. // someone else. 'auth_required.moderator' will bring us back here.
  2054. authRetryId = window.setTimeout(intervalCallback , 5000);
  2055. // Show prompt only if it's not open
  2056. if (authDialog !== null) {
  2057. return;
  2058. }
  2059. // extract room name from 'room@muc.server.net'
  2060. var room = roomName.substr(0, roomName.indexOf('@'));
  2061. var title = APP.translation.generateTranslatonHTML("dialog.Stop");
  2062. var msg = APP.translation.generateTranslatonHTML("dialog.AuthMsg",
  2063. {room: room});
  2064. var button = APP.translation.generateTranslatonHTML(
  2065. "dialog.Authenticate");
  2066. var buttons = {};
  2067. buttons.authenticate = {title: button, value: "authNow"};
  2068. authDialog = APP.UI.messageHandler.openDialog(
  2069. title,
  2070. msg,
  2071. true,
  2072. buttons,
  2073. function (onSubmitEvent, submitValue) {
  2074. // Do not close the dialog yet
  2075. onSubmitEvent.preventDefault();
  2076. // Open login popup
  2077. if (submitValue === 'authNow') {
  2078. callback();
  2079. }
  2080. }
  2081. );
  2082. },
  2083. closeAuthenticationWindow:function () {
  2084. if (authenticationWindow) {
  2085. authenticationWindow.close();
  2086. authenticationWindow = null;
  2087. }
  2088. },
  2089. focusAuthenticationWindow: function () {
  2090. // If auth window exists just bring it to the front
  2091. if (authenticationWindow) {
  2092. authenticationWindow.focus();
  2093. return;
  2094. }
  2095. },
  2096. closeAuthenticationDialog: function () {
  2097. // Close authentication dialog if opened
  2098. if (authDialog) {
  2099. APP.UI.messageHandler.closeDialog();
  2100. authDialog = null;
  2101. }
  2102. },
  2103. createAuthenticationWindow: function (callback, url) {
  2104. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  2105. url, 910, 660,
  2106. // On closed
  2107. function () {
  2108. // Close authentication dialog if opened
  2109. if (authDialog) {
  2110. messageHandler.closeDialog();
  2111. authDialog = null;
  2112. }
  2113. callback();
  2114. authenticationWindow = null;
  2115. });
  2116. return authenticationWindow;
  2117. },
  2118. stopInterval: function () {
  2119. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  2120. if (authRetryId) {
  2121. window.clearTimeout(authRetryId);
  2122. authRetryId = null;
  2123. }
  2124. }
  2125. };
  2126. module.exports = Authentication;
  2127. },{}],12:[function(require,module,exports){
  2128. var Settings = require("../../settings/Settings");
  2129. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  2130. var users = {};
  2131. var activeSpeakerJid;
  2132. function setVisibility(selector, show) {
  2133. if (selector && selector.length > 0) {
  2134. selector.css("visibility", show ? "visible" : "hidden");
  2135. }
  2136. }
  2137. function isUserMuted(jid) {
  2138. // XXX(gp) we may want to rename this method to something like
  2139. // isUserStreaming, for example.
  2140. if (jid && jid != APP.xmpp.myJid()) {
  2141. var resource = Strophe.getResourceFromJid(jid);
  2142. if (!require("../videolayout/VideoLayout").isInLastN(resource)) {
  2143. return true;
  2144. }
  2145. }
  2146. if (!APP.RTC.remoteStreams[jid] || !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  2147. return null;
  2148. }
  2149. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  2150. }
  2151. function getGravatarUrl(id, size) {
  2152. if(id === APP.xmpp.myJid() || !id) {
  2153. id = Settings.getSettings().uid;
  2154. }
  2155. return 'https://www.gravatar.com/avatar/' +
  2156. MD5.hexdigest(id.trim().toLowerCase()) +
  2157. "?d=wavatar&size=" + (size || "30");
  2158. }
  2159. var Avatar = {
  2160. /**
  2161. * Sets the user's avatar in the settings menu(if local user), contact list
  2162. * and thumbnail
  2163. * @param jid jid of the user
  2164. * @param id email or userID to be used as a hash
  2165. */
  2166. setUserAvatar: function (jid, id) {
  2167. if (id) {
  2168. if (users[jid] === id) {
  2169. return;
  2170. }
  2171. users[jid] = id;
  2172. }
  2173. var thumbUrl = getGravatarUrl(users[jid] || jid, 100);
  2174. var contactListUrl = getGravatarUrl(users[jid] || jid);
  2175. var resourceJid = Strophe.getResourceFromJid(jid);
  2176. var thumbnail = $('#participant_' + resourceJid);
  2177. var avatar = $('#avatar_' + resourceJid);
  2178. // set the avatar in the settings menu if it is local user and get the
  2179. // local video container
  2180. if (jid === APP.xmpp.myJid()) {
  2181. $('#avatar').get(0).src = thumbUrl;
  2182. thumbnail = $('#localVideoContainer');
  2183. }
  2184. // set the avatar in the contact list
  2185. var contact = $('#' + resourceJid + '>img');
  2186. if (contact && contact.length > 0) {
  2187. contact.get(0).src = contactListUrl;
  2188. }
  2189. // set the avatar in the thumbnail
  2190. if (avatar && avatar.length > 0) {
  2191. avatar[0].src = thumbUrl;
  2192. } else {
  2193. if (thumbnail && thumbnail.length > 0) {
  2194. avatar = document.createElement('img');
  2195. avatar.id = 'avatar_' + resourceJid;
  2196. avatar.className = 'userAvatar';
  2197. avatar.src = thumbUrl;
  2198. thumbnail.append(avatar);
  2199. }
  2200. }
  2201. //if the user is the current active speaker - update the active speaker
  2202. // avatar
  2203. if (jid === activeSpeakerJid) {
  2204. this.updateActiveSpeakerAvatarSrc(jid);
  2205. }
  2206. },
  2207. /**
  2208. * Hides or shows the user's avatar
  2209. * @param jid jid of the user
  2210. * @param show whether we should show the avatar or not
  2211. * video because there is no dominant speaker and no focused speaker
  2212. */
  2213. showUserAvatar: function (jid, show) {
  2214. if (users[jid]) {
  2215. var resourceJid = Strophe.getResourceFromJid(jid);
  2216. var video = $('#participant_' + resourceJid + '>video');
  2217. var avatar = $('#avatar_' + resourceJid);
  2218. if (jid === APP.xmpp.myJid()) {
  2219. video = $('#localVideoWrapper>video');
  2220. }
  2221. if (show === undefined || show === null) {
  2222. show = isUserMuted(jid);
  2223. }
  2224. //if the user is the currently focused, the dominant speaker or if
  2225. //there is no focused and no dominant speaker and the large video is
  2226. //currently shown
  2227. if (activeSpeakerJid === jid && require("../videolayout/VideoLayout").isLargeVideoOnTop()) {
  2228. setVisibility($("#largeVideo"), !show);
  2229. setVisibility($('#activeSpeaker'), show);
  2230. setVisibility(avatar, false);
  2231. setVisibility(video, false);
  2232. } else {
  2233. if (video && video.length > 0) {
  2234. setVisibility(video, !show);
  2235. setVisibility(avatar, show);
  2236. }
  2237. }
  2238. }
  2239. },
  2240. /**
  2241. * Updates the src of the active speaker avatar
  2242. * @param jid of the current active speaker
  2243. */
  2244. updateActiveSpeakerAvatarSrc: function (jid) {
  2245. if (!jid) {
  2246. jid = APP.xmpp.findJidFromResource(
  2247. require("../videolayout/VideoLayout").getLargeVideoState().userResourceJid);
  2248. }
  2249. var avatar = $("#activeSpeakerAvatar")[0];
  2250. var url = getGravatarUrl(users[jid],
  2251. interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE);
  2252. if (jid === activeSpeakerJid && avatar.src === url) {
  2253. return;
  2254. }
  2255. activeSpeakerJid = jid;
  2256. var isMuted = isUserMuted(jid);
  2257. if (jid && isMuted !== null) {
  2258. avatar.src = url;
  2259. setVisibility($("#largeVideo"), !isMuted);
  2260. Avatar.showUserAvatar(jid, isMuted);
  2261. }
  2262. }
  2263. };
  2264. module.exports = Avatar;
  2265. },{"../../../service/RTC/MediaStreamTypes":78,"../../settings/Settings":37,"../videolayout/VideoLayout":31}],13:[function(require,module,exports){
  2266. /* global $, config,
  2267. setLargeVideoVisible, Util */
  2268. var VideoLayout = require("../videolayout/VideoLayout");
  2269. var Prezi = require("../prezi/Prezi");
  2270. var UIUtil = require("../util/UIUtil");
  2271. var etherpadName = null;
  2272. var etherpadIFrame = null;
  2273. var domain = null;
  2274. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  2275. /**
  2276. * Resizes the etherpad.
  2277. */
  2278. function resize() {
  2279. if ($('#etherpad>iframe').length) {
  2280. var remoteVideos = $('#remoteVideos');
  2281. var availableHeight
  2282. = window.innerHeight - remoteVideos.outerHeight();
  2283. var availableWidth = UIUtil.getAvailableVideoWidth();
  2284. $('#etherpad>iframe').width(availableWidth);
  2285. $('#etherpad>iframe').height(availableHeight);
  2286. }
  2287. }
  2288. /**
  2289. * Shares the Etherpad name with other participants.
  2290. */
  2291. function shareEtherpad() {
  2292. APP.xmpp.addToPresence("etherpad", etherpadName);
  2293. }
  2294. /**
  2295. * Creates the Etherpad button and adds it to the toolbar.
  2296. */
  2297. function enableEtherpadButton() {
  2298. if (!$('#etherpadButton').is(":visible"))
  2299. $('#etherpadButton').css({display: 'inline-block'});
  2300. }
  2301. /**
  2302. * Creates the IFrame for the etherpad.
  2303. */
  2304. function createIFrame() {
  2305. etherpadIFrame = document.createElement('iframe');
  2306. etherpadIFrame.src = domain + etherpadName + options;
  2307. etherpadIFrame.frameBorder = 0;
  2308. etherpadIFrame.scrolling = "no";
  2309. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  2310. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  2311. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  2312. document.getElementById('etherpad').appendChild(etherpadIFrame);
  2313. etherpadIFrame.onload = function() {
  2314. document.domain = document.domain;
  2315. bubbleIframeMouseMove(etherpadIFrame);
  2316. setTimeout(function() {
  2317. // the iframes inside of the etherpad are
  2318. // not yet loaded when the etherpad iframe is loaded
  2319. var outer = etherpadIFrame.
  2320. contentDocument.getElementsByName("ace_outer")[0];
  2321. bubbleIframeMouseMove(outer);
  2322. var inner = outer.
  2323. contentDocument.getElementsByName("ace_inner")[0];
  2324. bubbleIframeMouseMove(inner);
  2325. }, 2000);
  2326. };
  2327. }
  2328. function bubbleIframeMouseMove(iframe){
  2329. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  2330. iframe.contentWindow.onmousemove = function(e){
  2331. if(existingOnMouseMove) existingOnMouseMove(e);
  2332. var evt = document.createEvent("MouseEvents");
  2333. var boundingClientRect = iframe.getBoundingClientRect();
  2334. evt.initMouseEvent(
  2335. "mousemove",
  2336. true, // bubbles
  2337. false, // not cancelable
  2338. window,
  2339. e.detail,
  2340. e.screenX,
  2341. e.screenY,
  2342. e.clientX + boundingClientRect.left,
  2343. e.clientY + boundingClientRect.top,
  2344. e.ctrlKey,
  2345. e.altKey,
  2346. e.shiftKey,
  2347. e.metaKey,
  2348. e.button,
  2349. null // no related element
  2350. );
  2351. iframe.dispatchEvent(evt);
  2352. };
  2353. }
  2354. /**
  2355. * On video selected event.
  2356. */
  2357. $(document).bind('video.selected', function (event, isPresentation) {
  2358. if (config.etherpad_base && etherpadIFrame && etherpadIFrame.style.visibility !== 'hidden')
  2359. Etherpad.toggleEtherpad(isPresentation);
  2360. });
  2361. var Etherpad = {
  2362. /**
  2363. * Initializes the etherpad.
  2364. */
  2365. init: function (name) {
  2366. if (config.etherpad_base && !etherpadName) {
  2367. domain = config.etherpad_base;
  2368. if (!name) {
  2369. // In case we're the focus we generate the name.
  2370. etherpadName = Math.random().toString(36).substring(7) +
  2371. '_' + (new Date().getTime()).toString();
  2372. shareEtherpad();
  2373. }
  2374. else
  2375. etherpadName = name;
  2376. enableEtherpadButton();
  2377. /**
  2378. * Resizes the etherpad, when the window is resized.
  2379. */
  2380. $(window).resize(function () {
  2381. resize();
  2382. });
  2383. }
  2384. },
  2385. /**
  2386. * Opens/hides the Etherpad.
  2387. */
  2388. toggleEtherpad: function (isPresentation) {
  2389. if (!etherpadIFrame)
  2390. createIFrame();
  2391. var largeVideo = null;
  2392. if (Prezi.isPresentationVisible())
  2393. largeVideo = $('#presentation>iframe');
  2394. else
  2395. largeVideo = $('#largeVideo');
  2396. if ($('#etherpad>iframe').css('visibility') === 'hidden') {
  2397. $('#activeSpeaker').css('visibility', 'hidden');
  2398. largeVideo.fadeOut(300, function () {
  2399. if (Prezi.isPresentationVisible()) {
  2400. largeVideo.css({opacity: '0'});
  2401. } else {
  2402. VideoLayout.setLargeVideoVisible(false);
  2403. }
  2404. });
  2405. $('#etherpad>iframe').fadeIn(300, function () {
  2406. document.body.style.background = '#eeeeee';
  2407. $('#etherpad>iframe').css({visibility: 'visible'});
  2408. $('#etherpad').css({zIndex: 2});
  2409. });
  2410. }
  2411. else if ($('#etherpad>iframe')) {
  2412. $('#etherpad>iframe').fadeOut(300, function () {
  2413. $('#etherpad>iframe').css({visibility: 'hidden'});
  2414. $('#etherpad').css({zIndex: 0});
  2415. document.body.style.background = 'black';
  2416. });
  2417. if (!isPresentation) {
  2418. $('#largeVideo').fadeIn(300, function () {
  2419. VideoLayout.setLargeVideoVisible(true);
  2420. });
  2421. }
  2422. }
  2423. resize();
  2424. },
  2425. isVisible: function() {
  2426. var etherpadIframe = $('#etherpad>iframe');
  2427. return etherpadIframe && etherpadIframe.is(':visible');
  2428. }
  2429. };
  2430. module.exports = Etherpad;
  2431. },{"../prezi/Prezi":14,"../util/UIUtil":29,"../videolayout/VideoLayout":31}],14:[function(require,module,exports){
  2432. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  2433. var UIUtil = require("../util/UIUtil");
  2434. var VideoLayout = require("../videolayout/VideoLayout");
  2435. var messageHandler = require("../util/MessageHandler");
  2436. var PreziPlayer = require("./PreziPlayer");
  2437. var preziPlayer = null;
  2438. var Prezi = {
  2439. /**
  2440. * Reloads the current presentation.
  2441. */
  2442. reloadPresentation: function() {
  2443. var iframe = document.getElementById(preziPlayer.options.preziId);
  2444. iframe.src = iframe.src;
  2445. },
  2446. /**
  2447. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  2448. * otherwise.
  2449. */
  2450. isPresentationVisible: function () {
  2451. return ($('#presentation>iframe') != null
  2452. && $('#presentation>iframe').css('opacity') == 1);
  2453. },
  2454. /**
  2455. * Opens the Prezi dialog, from which the user could choose a presentation
  2456. * to load.
  2457. */
  2458. openPreziDialog: function() {
  2459. var myprezi = APP.xmpp.getPrezi();
  2460. if (myprezi) {
  2461. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  2462. null,
  2463. "dialog.removePreziMsg",
  2464. null,
  2465. false,
  2466. "dialog.Remove",
  2467. function(e,v,m,f) {
  2468. if(v) {
  2469. APP.xmpp.removePreziFromPresence();
  2470. }
  2471. }
  2472. );
  2473. }
  2474. else if (preziPlayer != null) {
  2475. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  2476. null, "dialog.sharePreziMsg",
  2477. null,
  2478. false,
  2479. "dialog.Ok",
  2480. function(e,v,m,f) {
  2481. $.prompt.close();
  2482. }
  2483. );
  2484. }
  2485. else {
  2486. var html = APP.translation.generateTranslatonHTML(
  2487. "dialog.sharePreziTitle");
  2488. var cancelButton = APP.translation.generateTranslatonHTML(
  2489. "dialog.Cancel");
  2490. var shareButton = APP.translation.generateTranslatonHTML(
  2491. "dialog.Share");
  2492. var backButton = APP.translation.generateTranslatonHTML(
  2493. "dialog.Back");
  2494. var buttons = {};
  2495. var buttons1 = {};
  2496. buttons1.button1 = buttons.button1 = {title: cancelButton, value: false};
  2497. buttons.button2 = {title: shareButton, value: true};
  2498. buttons1.button2 = {title: backButton, value: true};
  2499. var linkError = APP.translation.generateTranslatonHTML(
  2500. "dialog.preziLinkError");
  2501. var openPreziState = {
  2502. state0: {
  2503. html: '<h2>' + html + '</h2>' +
  2504. '<input id="preziUrl" type="text" ' +
  2505. 'placeholder="e.g. ' +
  2506. 'http://prezi.com/wz7vhjycl7e6/my-prezi" autofocus>',
  2507. persistent: false,
  2508. buttons: buttons,
  2509. defaultButton: 1,
  2510. submit: function(e,v,m,f){
  2511. e.preventDefault();
  2512. if(v)
  2513. {
  2514. var preziUrl = document.getElementById('preziUrl');
  2515. if (preziUrl.value)
  2516. {
  2517. var urlValue
  2518. = encodeURI(UIUtil.escapeHtml(preziUrl.value));
  2519. if (urlValue.indexOf('http://prezi.com/') != 0
  2520. && urlValue.indexOf('https://prezi.com/') != 0)
  2521. {
  2522. $.prompt.goToState('state1');
  2523. return false;
  2524. }
  2525. else {
  2526. var presIdTmp = urlValue.substring(
  2527. urlValue.indexOf("prezi.com/") + 10);
  2528. if (!isAlphanumeric(presIdTmp)
  2529. || presIdTmp.indexOf('/') < 2) {
  2530. $.prompt.goToState('state1');
  2531. return false;
  2532. }
  2533. else {
  2534. APP.xmpp.addToPresence("prezi", urlValue);
  2535. $.prompt.close();
  2536. }
  2537. }
  2538. }
  2539. }
  2540. else
  2541. $.prompt.close();
  2542. }
  2543. },
  2544. state1: {
  2545. html: '<h2>' + html + '</h2>' +
  2546. linkError,
  2547. persistent: false,
  2548. buttons: buttons1,
  2549. defaultButton: 1,
  2550. submit:function(e,v,m,f) {
  2551. e.preventDefault();
  2552. if(v==0)
  2553. $.prompt.close();
  2554. else
  2555. $.prompt.goToState('state0');
  2556. }
  2557. }
  2558. };
  2559. var focusPreziUrl = function(e) {
  2560. document.getElementById('preziUrl').focus();
  2561. };
  2562. messageHandler.openDialogWithStates(openPreziState, focusPreziUrl, focusPreziUrl);
  2563. }
  2564. }
  2565. };
  2566. /**
  2567. * A new presentation has been added.
  2568. *
  2569. * @param event the event indicating the add of a presentation
  2570. * @param jid the jid from which the presentation was added
  2571. * @param presUrl url of the presentation
  2572. * @param currentSlide the current slide to which we should move
  2573. */
  2574. function presentationAdded(event, jid, presUrl, currentSlide) {
  2575. console.log("presentation added", presUrl);
  2576. var presId = getPresentationId(presUrl);
  2577. var elementId = 'participant_'
  2578. + Strophe.getResourceFromJid(jid)
  2579. + '_' + presId;
  2580. // We explicitly don't specify the peer jid here, because we don't want
  2581. // this video to be dealt with as a peer related one (for example we
  2582. // don't want to show a mute/kick menu for this one, etc.).
  2583. VideoLayout.addRemoteVideoContainer(null, elementId);
  2584. VideoLayout.resizeThumbnails();
  2585. var controlsEnabled = false;
  2586. if (jid === APP.xmpp.myJid())
  2587. controlsEnabled = true;
  2588. setPresentationVisible(true);
  2589. $('#largeVideoContainer').hover(
  2590. function (event) {
  2591. if (Prezi.isPresentationVisible()) {
  2592. var reloadButtonRight = window.innerWidth
  2593. - $('#presentation>iframe').offset().left
  2594. - $('#presentation>iframe').width();
  2595. $('#reloadPresentation').css({ right: reloadButtonRight,
  2596. display:'inline-block'});
  2597. }
  2598. },
  2599. function (event) {
  2600. if (!Prezi.isPresentationVisible())
  2601. $('#reloadPresentation').css({display:'none'});
  2602. else {
  2603. var e = event.toElement || event.relatedTarget;
  2604. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  2605. $('#reloadPresentation').css({display:'none'});
  2606. }
  2607. });
  2608. preziPlayer = new PreziPlayer(
  2609. 'presentation',
  2610. {preziId: presId,
  2611. width: getPresentationWidth(),
  2612. height: getPresentationHeihgt(),
  2613. controls: controlsEnabled,
  2614. debug: true
  2615. });
  2616. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  2617. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  2618. console.log("prezi status", event.value);
  2619. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  2620. if (jid != APP.xmpp.myJid())
  2621. preziPlayer.flyToStep(currentSlide);
  2622. }
  2623. });
  2624. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  2625. console.log("event value", event.value);
  2626. APP.xmpp.addToPresence("preziSlide", event.value);
  2627. });
  2628. $("#" + elementId).css( 'background-image',
  2629. 'url(../images/avatarprezi.png)');
  2630. $("#" + elementId).click(
  2631. function () {
  2632. setPresentationVisible(true);
  2633. }
  2634. );
  2635. };
  2636. /**
  2637. * A presentation has been removed.
  2638. *
  2639. * @param event the event indicating the remove of a presentation
  2640. * @param jid the jid for which the presentation was removed
  2641. * @param the url of the presentation
  2642. */
  2643. function presentationRemoved(event, jid, presUrl) {
  2644. console.log('presentation removed', presUrl);
  2645. var presId = getPresentationId(presUrl);
  2646. setPresentationVisible(false);
  2647. $('#participant_'
  2648. + Strophe.getResourceFromJid(jid)
  2649. + '_' + presId).remove();
  2650. $('#presentation>iframe').remove();
  2651. if (preziPlayer != null) {
  2652. preziPlayer.destroy();
  2653. preziPlayer = null;
  2654. }
  2655. };
  2656. /**
  2657. * Indicates if the given string is an alphanumeric string.
  2658. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  2659. * purpose of checking URIs.
  2660. */
  2661. function isAlphanumeric(unsafeText) {
  2662. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  2663. return regex.test(unsafeText);
  2664. }
  2665. /**
  2666. * Returns the presentation id from the given url.
  2667. */
  2668. function getPresentationId (presUrl) {
  2669. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  2670. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  2671. }
  2672. /**
  2673. * Returns the presentation width.
  2674. */
  2675. function getPresentationWidth() {
  2676. var availableWidth = UIUtil.getAvailableVideoWidth();
  2677. var availableHeight = getPresentationHeihgt();
  2678. var aspectRatio = 16.0 / 9.0;
  2679. if (availableHeight < availableWidth / aspectRatio) {
  2680. availableWidth = Math.floor(availableHeight * aspectRatio);
  2681. }
  2682. return availableWidth;
  2683. }
  2684. /**
  2685. * Returns the presentation height.
  2686. */
  2687. function getPresentationHeihgt() {
  2688. var remoteVideos = $('#remoteVideos');
  2689. return window.innerHeight - remoteVideos.outerHeight();
  2690. }
  2691. /**
  2692. * Resizes the presentation iframe.
  2693. */
  2694. function resize() {
  2695. if ($('#presentation>iframe')) {
  2696. $('#presentation>iframe').width(getPresentationWidth());
  2697. $('#presentation>iframe').height(getPresentationHeihgt());
  2698. }
  2699. }
  2700. /**
  2701. * Shows/hides a presentation.
  2702. */
  2703. function setPresentationVisible(visible) {
  2704. var prezi = $('#presentation>iframe');
  2705. if (visible) {
  2706. // Trigger the video.selected event to indicate a change in the
  2707. // large video.
  2708. $(document).trigger("video.selected", [true]);
  2709. $('#largeVideo').fadeOut(300);
  2710. prezi.fadeIn(300, function() {
  2711. prezi.css({opacity:'1'});
  2712. ToolbarToggler.dockToolbar(true);
  2713. VideoLayout.setLargeVideoVisible(false);
  2714. });
  2715. $('#activeSpeaker').css('visibility', 'hidden');
  2716. }
  2717. else {
  2718. if (prezi.css('opacity') == '1') {
  2719. prezi.fadeOut(300, function () {
  2720. prezi.css({opacity:'0'});
  2721. $('#reloadPresentation').css({display:'none'});
  2722. $('#largeVideo').fadeIn(300, function() {
  2723. VideoLayout.setLargeVideoVisible(true);
  2724. ToolbarToggler.dockToolbar(false);
  2725. });
  2726. });
  2727. }
  2728. }
  2729. }
  2730. /**
  2731. * Presentation has been removed.
  2732. */
  2733. $(document).bind('presentationremoved.muc', presentationRemoved);
  2734. /**
  2735. * Presentation has been added.
  2736. */
  2737. $(document).bind('presentationadded.muc', presentationAdded);
  2738. /*
  2739. * Indicates presentation slide change.
  2740. */
  2741. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  2742. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  2743. preziPlayer.flyToStep(current);
  2744. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  2745. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  2746. preziPlayer.flyToStep(current, i);
  2747. }
  2748. }
  2749. });
  2750. /**
  2751. * On video selected event.
  2752. */
  2753. $(document).bind('video.selected', function (event, isPresentation) {
  2754. if (!isPresentation && $('#presentation>iframe')) {
  2755. setPresentationVisible(false);
  2756. }
  2757. });
  2758. $(window).resize(function () {
  2759. resize();
  2760. });
  2761. module.exports = Prezi;
  2762. },{"../toolbars/ToolbarToggler":25,"../util/MessageHandler":27,"../util/UIUtil":29,"../videolayout/VideoLayout":31,"./PreziPlayer":15}],15:[function(require,module,exports){
  2763. (function() {
  2764. "use strict";
  2765. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  2766. window.PreziPlayer = (function() {
  2767. PreziPlayer.API_VERSION = 1;
  2768. PreziPlayer.CURRENT_STEP = 'currentStep';
  2769. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  2770. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  2771. PreziPlayer.STATUS_LOADING = 'loading';
  2772. PreziPlayer.STATUS_READY = 'ready';
  2773. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  2774. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  2775. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  2776. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  2777. PreziPlayer.EVENT_STATUS = "statusChange";
  2778. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  2779. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  2780. PreziPlayer.domain = "https://prezi.com";
  2781. PreziPlayer.path = "/player/";
  2782. PreziPlayer.players = {};
  2783. PreziPlayer.binded_methods = ['changesHandler'];
  2784. PreziPlayer.createMultiplePlayers = function(optionArray){
  2785. for(var i=0; i<optionArray.length; i++) {
  2786. var optionSet = optionArray[i];
  2787. new PreziPlayer(optionSet.id, optionSet);
  2788. };
  2789. };
  2790. PreziPlayer.messageReceived = function(event){
  2791. var message, item, player;
  2792. try {
  2793. message = JSON.parse(event.data);
  2794. if (message.id && (player = PreziPlayer.players[message.id])) {
  2795. if (player.options.debug === true) {
  2796. if (console && console.log)
  2797. console.log('received', message);
  2798. }
  2799. if (message.type === "changes") {
  2800. player.changesHandler(message);
  2801. }
  2802. for (var i = 0; i < player.callbacks.length; i++) {
  2803. item = player.callbacks[i];
  2804. if (item && message.type === item.event) {
  2805. item.callback(message);
  2806. }
  2807. }
  2808. }
  2809. } catch (e) { }
  2810. };
  2811. function PreziPlayer(id, options) {
  2812. var params, paramString = "", _this = this;
  2813. if (PreziPlayer.players[id]){
  2814. PreziPlayer.players[id].destroy();
  2815. }
  2816. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  2817. var method_name = PreziPlayer.binded_methods[i];
  2818. _this[method_name] = __bind(_this[method_name], _this);
  2819. };
  2820. options = options || {};
  2821. this.options = options;
  2822. this.values = {'status': PreziPlayer.STATUS_LOADING};
  2823. this.values[PreziPlayer.CURRENT_STEP] = 0;
  2824. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  2825. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  2826. this.callbacks = [];
  2827. this.id = id;
  2828. this.embedTo = document.getElementById(id);
  2829. if (!this.embedTo) {
  2830. throw "The element id is not available.";
  2831. }
  2832. this.iframe = document.createElement('iframe');
  2833. params = [
  2834. { name: 'oid', value: options.preziId },
  2835. { name: 'explorable', value: options.explorable ? 1 : 0 },
  2836. { name: 'controls', value: options.controls ? 1 : 0 }
  2837. ];
  2838. for(var i=0; i<params.length; i++) {
  2839. var param = params[i];
  2840. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  2841. };
  2842. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  2843. this.iframe.frameBorder = 0;
  2844. this.iframe.scrolling = "no";
  2845. this.iframe.width = options.width || 640;
  2846. this.iframe.height = options.height || 480;
  2847. this.embedTo.innerHTML = '';
  2848. // JITSI: IN CASE SOMETHING GOES WRONG.
  2849. try {
  2850. this.embedTo.appendChild(this.iframe);
  2851. }
  2852. catch (err) {
  2853. console.log("CATCH ERROR");
  2854. }
  2855. // JITSI: Increase interval from 200 to 500, which fixes prezi
  2856. // crashes for us.
  2857. this.initPollInterval = setInterval(function(){
  2858. _this.sendMessage({'action': 'init'});
  2859. }, 500);
  2860. PreziPlayer.players[id] = this;
  2861. }
  2862. PreziPlayer.prototype.changesHandler = function(message) {
  2863. var key, value, j, item;
  2864. if (this.initPollInterval) {
  2865. clearInterval(this.initPollInterval);
  2866. this.initPollInterval = false;
  2867. }
  2868. for (key in message.data) {
  2869. if (message.data.hasOwnProperty(key)){
  2870. value = message.data[key];
  2871. this.values[key] = value;
  2872. for (j=0; j<this.callbacks.length; j++) {
  2873. item = this.callbacks[j];
  2874. if (item && item.event === key + "Change"){
  2875. item.callback({type: item.event, value: value});
  2876. }
  2877. }
  2878. }
  2879. }
  2880. };
  2881. PreziPlayer.prototype.destroy = function() {
  2882. if (this.initPollInterval) {
  2883. clearInterval(this.initPollInterval);
  2884. this.initPollInterval = false;
  2885. }
  2886. this.embedTo.innerHTML = '';
  2887. };
  2888. PreziPlayer.prototype.sendMessage = function(message) {
  2889. if (this.options.debug === true) {
  2890. if (console && console.log) console.log('sent', message);
  2891. }
  2892. message.version = PreziPlayer.API_VERSION;
  2893. message.id = this.id;
  2894. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  2895. };
  2896. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  2897. PreziPlayer.prototype.flyToNextStep = function() {
  2898. return this.sendMessage({
  2899. 'action': 'present',
  2900. 'data': ['moveToNextStep']
  2901. });
  2902. };
  2903. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  2904. PreziPlayer.prototype.flyToPreviousStep = function() {
  2905. return this.sendMessage({
  2906. 'action': 'present',
  2907. 'data': ['moveToPrevStep']
  2908. });
  2909. };
  2910. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  2911. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  2912. var obj = this;
  2913. // check animation_step
  2914. if (animation_step > 0 &&
  2915. obj.values.animationCountOnSteps &&
  2916. obj.values.animationCountOnSteps[step] <= animation_step) {
  2917. animation_step = obj.values.animationCountOnSteps[step];
  2918. }
  2919. // jump to animation steps by calling flyToNextStep()
  2920. function doAnimationSteps() {
  2921. if (obj.values.isMoving == true) {
  2922. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  2923. return;
  2924. }
  2925. while (animation_step-- > 0) {
  2926. obj.flyToNextStep(); // do the animation steps
  2927. }
  2928. }
  2929. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  2930. // jump to the step
  2931. return this.sendMessage({
  2932. 'action': 'present',
  2933. 'data': ['moveToStep', step]
  2934. });
  2935. };
  2936. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  2937. PreziPlayer.prototype.flyToObject = function(objectId) {
  2938. return this.sendMessage({
  2939. 'action': 'present',
  2940. 'data': ['moveToObject', objectId]
  2941. });
  2942. };
  2943. PreziPlayer.prototype.play = function(defaultDelay) {
  2944. return this.sendMessage({
  2945. 'action': 'present',
  2946. 'data': ['startAutoPlay', defaultDelay]
  2947. });
  2948. };
  2949. PreziPlayer.prototype.stop = function() {
  2950. return this.sendMessage({
  2951. 'action': 'present',
  2952. 'data': ['stopAutoPlay']
  2953. });
  2954. };
  2955. PreziPlayer.prototype.pause = function(defaultDelay) {
  2956. return this.sendMessage({
  2957. 'action': 'present',
  2958. 'data': ['pauseAutoPlay', defaultDelay]
  2959. });
  2960. };
  2961. PreziPlayer.prototype.getCurrentStep = function() {
  2962. return this.values.currentStep;
  2963. };
  2964. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  2965. return this.values.currentAnimationStep;
  2966. };
  2967. PreziPlayer.prototype.getCurrentObject = function() {
  2968. return this.values.currentObject;
  2969. };
  2970. PreziPlayer.prototype.getStatus = function() {
  2971. return this.values.status;
  2972. };
  2973. PreziPlayer.prototype.isPlaying = function() {
  2974. return this.values.isAutoPlaying;
  2975. };
  2976. PreziPlayer.prototype.getStepCount = function() {
  2977. return this.values.stepCount;
  2978. };
  2979. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  2980. return this.values.animationCountOnSteps;
  2981. };
  2982. PreziPlayer.prototype.getTitle = function() {
  2983. return this.values.title;
  2984. };
  2985. PreziPlayer.prototype.setDimensions = function(dims) {
  2986. for (var parameter in dims) {
  2987. this.iframe[parameter] = dims[parameter];
  2988. }
  2989. }
  2990. PreziPlayer.prototype.getDimensions = function() {
  2991. return {
  2992. width: parseInt(this.iframe.width, 10),
  2993. height: parseInt(this.iframe.height, 10)
  2994. }
  2995. }
  2996. PreziPlayer.prototype.on = function(event, callback) {
  2997. this.callbacks.push({
  2998. event: event,
  2999. callback: callback
  3000. });
  3001. };
  3002. PreziPlayer.prototype.off = function(event, callback) {
  3003. var j, item;
  3004. if (event === undefined) {
  3005. this.callbacks = [];
  3006. }
  3007. j = this.callbacks.length;
  3008. while (j--) {
  3009. item = this.callbacks[j];
  3010. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  3011. this.callbacks.splice(j, 1);
  3012. }
  3013. }
  3014. };
  3015. if (window.addEventListener) {
  3016. window.addEventListener('message', PreziPlayer.messageReceived, false);
  3017. } else {
  3018. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  3019. }
  3020. return PreziPlayer;
  3021. })();
  3022. })();
  3023. module.exports = PreziPlayer;
  3024. },{}],16:[function(require,module,exports){
  3025. var Chat = require("./chat/Chat");
  3026. var ContactList = require("./contactlist/ContactList");
  3027. var Settings = require("./../../settings/Settings");
  3028. var SettingsMenu = require("./settings/SettingsMenu");
  3029. var VideoLayout = require("../videolayout/VideoLayout");
  3030. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  3031. var UIUtil = require("../util/UIUtil");
  3032. /**
  3033. * Toggler for the chat, contact list, settings menu, etc..
  3034. */
  3035. var PanelToggler = (function(my) {
  3036. var currentlyOpen = null;
  3037. var buttons = {
  3038. '#chatspace': '#chatBottomButton',
  3039. '#contactlist': '#contactListButton',
  3040. '#settingsmenu': '#settingsButton'
  3041. };
  3042. /**
  3043. * Resizes the video area
  3044. * @param isClosing whether the side panel is going to be closed or is going to open / remain opened
  3045. * @param completeFunction a function to be called when the video space is resized
  3046. */
  3047. var resizeVideoArea = function(isClosing, completeFunction) {
  3048. var videospace = $('#videospace');
  3049. var panelSize = isClosing ? [0, 0] : PanelToggler.getPanelSize();
  3050. var videospaceWidth = window.innerWidth - panelSize[0];
  3051. var videospaceHeight = window.innerHeight;
  3052. var videoSize
  3053. = VideoLayout.getVideoSize(null, null, videospaceWidth, videospaceHeight);
  3054. var videoWidth = videoSize[0];
  3055. var videoHeight = videoSize[1];
  3056. var videoPosition = VideoLayout.getVideoPosition(videoWidth,
  3057. videoHeight,
  3058. videospaceWidth,
  3059. videospaceHeight);
  3060. var horizontalIndent = videoPosition[0];
  3061. var verticalIndent = videoPosition[1];
  3062. var thumbnailSize = VideoLayout.calculateThumbnailSize(videospaceWidth);
  3063. var thumbnailsWidth = thumbnailSize[0];
  3064. var thumbnailsHeight = thumbnailSize[1];
  3065. //for chat
  3066. videospace.animate({
  3067. right: panelSize[0],
  3068. width: videospaceWidth,
  3069. height: videospaceHeight
  3070. },
  3071. {
  3072. queue: false,
  3073. duration: 500,
  3074. complete: completeFunction
  3075. });
  3076. $('#remoteVideos').animate({
  3077. height: thumbnailsHeight
  3078. },
  3079. {
  3080. queue: false,
  3081. duration: 500
  3082. });
  3083. $('#remoteVideos>span').animate({
  3084. height: thumbnailsHeight,
  3085. width: thumbnailsWidth
  3086. },
  3087. {
  3088. queue: false,
  3089. duration: 500,
  3090. complete: function () {
  3091. $(document).trigger(
  3092. "remotevideo.resized",
  3093. [thumbnailsWidth,
  3094. thumbnailsHeight]);
  3095. }
  3096. });
  3097. $('#largeVideoContainer').animate({
  3098. width: videospaceWidth,
  3099. height: videospaceHeight
  3100. },
  3101. {
  3102. queue: false,
  3103. duration: 500
  3104. });
  3105. $('#largeVideo').animate({
  3106. width: videoWidth,
  3107. height: videoHeight,
  3108. top: verticalIndent,
  3109. bottom: verticalIndent,
  3110. left: horizontalIndent,
  3111. right: horizontalIndent
  3112. },
  3113. {
  3114. queue: false,
  3115. duration: 500
  3116. });
  3117. };
  3118. /**
  3119. * Toggles the windows in the side panel
  3120. * @param object the window that should be shown
  3121. * @param selector the selector for the element containing the panel
  3122. * @param onOpenComplete function to be called when the panel is opened
  3123. * @param onOpen function to be called if the window is going to be opened
  3124. * @param onClose function to be called if the window is going to be closed
  3125. */
  3126. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  3127. UIUtil.buttonClick(buttons[selector], "active");
  3128. if (object.isVisible()) {
  3129. $("#toast-container").animate({
  3130. right: '5px'
  3131. },
  3132. {
  3133. queue: false,
  3134. duration: 500
  3135. });
  3136. $(selector).hide("slide", {
  3137. direction: "right",
  3138. queue: false,
  3139. duration: 500
  3140. });
  3141. if(typeof onClose === "function") {
  3142. onClose();
  3143. }
  3144. currentlyOpen = null;
  3145. }
  3146. else {
  3147. // Undock the toolbar when the chat is shown and if we're in a
  3148. // video mode.
  3149. if (VideoLayout.isLargeVideoVisible()) {
  3150. ToolbarToggler.dockToolbar(false);
  3151. }
  3152. if(currentlyOpen) {
  3153. var current = $(currentlyOpen);
  3154. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  3155. current.css('z-index', 4);
  3156. setTimeout(function () {
  3157. current.css('display', 'none');
  3158. current.css('z-index', 5);
  3159. }, 500);
  3160. }
  3161. $("#toast-container").animate({
  3162. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  3163. },
  3164. {
  3165. queue: false,
  3166. duration: 500
  3167. });
  3168. $(selector).show("slide", {
  3169. direction: "right",
  3170. queue: false,
  3171. duration: 500,
  3172. complete: onOpenComplete
  3173. });
  3174. if(typeof onOpen === "function") {
  3175. onOpen();
  3176. }
  3177. currentlyOpen = selector;
  3178. }
  3179. };
  3180. /**
  3181. * Opens / closes the chat area.
  3182. */
  3183. my.toggleChat = function() {
  3184. var chatCompleteFunction = Chat.isVisible() ?
  3185. function() {} : function () {
  3186. Chat.scrollChatToBottom();
  3187. $('#chatspace').trigger('shown');
  3188. };
  3189. resizeVideoArea(Chat.isVisible(), chatCompleteFunction);
  3190. toggle(Chat,
  3191. '#chatspace',
  3192. function () {
  3193. // Request the focus in the nickname field or the chat input field.
  3194. if ($('#nickname').css('visibility') === 'visible') {
  3195. $('#nickinput').focus();
  3196. } else {
  3197. $('#usermsg').focus();
  3198. }
  3199. },
  3200. null,
  3201. Chat.resizeChat,
  3202. null);
  3203. };
  3204. /**
  3205. * Opens / closes the contact list area.
  3206. */
  3207. my.toggleContactList = function () {
  3208. var completeFunction = ContactList.isVisible() ?
  3209. function() {} : function () { $('#contactlist').trigger('shown');};
  3210. resizeVideoArea(ContactList.isVisible(), completeFunction);
  3211. toggle(ContactList,
  3212. '#contactlist',
  3213. null,
  3214. function() {
  3215. ContactList.setVisualNotification(false);
  3216. },
  3217. null);
  3218. };
  3219. /**
  3220. * Opens / closes the settings menu
  3221. */
  3222. my.toggleSettingsMenu = function() {
  3223. resizeVideoArea(SettingsMenu.isVisible(), function (){});
  3224. toggle(SettingsMenu,
  3225. '#settingsmenu',
  3226. null,
  3227. function() {
  3228. var settings = Settings.getSettings();
  3229. $('#setDisplayName').get(0).value = settings.displayName;
  3230. $('#setEmail').get(0).value = settings.email;
  3231. },
  3232. null);
  3233. };
  3234. /**
  3235. * Returns the size of the side panel.
  3236. */
  3237. my.getPanelSize = function () {
  3238. var availableHeight = window.innerHeight;
  3239. var availableWidth = window.innerWidth;
  3240. var panelWidth = 200;
  3241. if (availableWidth * 0.2 < 200) {
  3242. panelWidth = availableWidth * 0.2;
  3243. }
  3244. return [panelWidth, availableHeight];
  3245. };
  3246. my.isVisible = function() {
  3247. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  3248. };
  3249. return my;
  3250. }(PanelToggler || {}));
  3251. module.exports = PanelToggler;
  3252. },{"../toolbars/ToolbarToggler":25,"../util/UIUtil":29,"../videolayout/VideoLayout":31,"./../../settings/Settings":37,"./chat/Chat":17,"./contactlist/ContactList":21,"./settings/SettingsMenu":22}],17:[function(require,module,exports){
  3253. /* global $, Util, nickname:true */
  3254. var Replacement = require("./Replacement");
  3255. var CommandsProcessor = require("./Commands");
  3256. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  3257. var smileys = require("./smileys.json").smileys;
  3258. var NicknameHandler = require("../../util/NicknameHandler");
  3259. var UIUtil = require("../../util/UIUtil");
  3260. var UIEvents = require("../../../../service/UI/UIEvents");
  3261. var notificationInterval = false;
  3262. var unreadMessages = 0;
  3263. /**
  3264. * Shows/hides a visual notification, indicating that a message has arrived.
  3265. */
  3266. function setVisualNotification(show) {
  3267. var unreadMsgElement = document.getElementById('unreadMessages');
  3268. var unreadMsgBottomElement
  3269. = document.getElementById('bottomUnreadMessages');
  3270. var glower = $('#chatButton');
  3271. var bottomGlower = $('#chatBottomButton');
  3272. if (unreadMessages) {
  3273. unreadMsgElement.innerHTML = unreadMessages.toString();
  3274. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  3275. ToolbarToggler.dockToolbar(true);
  3276. var chatButtonElement
  3277. = document.getElementById('chatButton').parentNode;
  3278. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  3279. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  3280. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  3281. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  3282. unreadMsgElement.setAttribute(
  3283. 'style',
  3284. 'top:' + topIndent +
  3285. '; left:' + leftIndent + ';');
  3286. var chatBottomButtonElement
  3287. = document.getElementById('chatBottomButton').parentNode;
  3288. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  3289. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  3290. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  3291. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  3292. unreadMsgBottomElement.setAttribute(
  3293. 'style',
  3294. 'top:' + bottomTopIndent +
  3295. '; left:' + bottomLeftIndent + ';');
  3296. if (!glower.hasClass('icon-chat-simple')) {
  3297. glower.removeClass('icon-chat');
  3298. glower.addClass('icon-chat-simple');
  3299. }
  3300. }
  3301. else {
  3302. unreadMsgElement.innerHTML = '';
  3303. unreadMsgBottomElement.innerHTML = '';
  3304. glower.removeClass('icon-chat-simple');
  3305. glower.addClass('icon-chat');
  3306. }
  3307. if (show && !notificationInterval) {
  3308. notificationInterval = window.setInterval(function () {
  3309. glower.toggleClass('active');
  3310. bottomGlower.toggleClass('active glowing');
  3311. }, 800);
  3312. }
  3313. else if (!show && notificationInterval) {
  3314. window.clearInterval(notificationInterval);
  3315. notificationInterval = false;
  3316. glower.removeClass('active');
  3317. bottomGlower.removeClass('glowing');
  3318. bottomGlower.addClass('active');
  3319. }
  3320. }
  3321. /**
  3322. * Returns the current time in the format it is shown to the user
  3323. * @returns {string}
  3324. */
  3325. function getCurrentTime() {
  3326. var now = new Date();
  3327. var hour = now.getHours();
  3328. var minute = now.getMinutes();
  3329. var second = now.getSeconds();
  3330. if(hour.toString().length === 1) {
  3331. hour = '0'+hour;
  3332. }
  3333. if(minute.toString().length === 1) {
  3334. minute = '0'+minute;
  3335. }
  3336. if(second.toString().length === 1) {
  3337. second = '0'+second;
  3338. }
  3339. return hour+':'+minute+':'+second;
  3340. }
  3341. function toggleSmileys()
  3342. {
  3343. var smileys = $('#smileysContainer');
  3344. if(!smileys.is(':visible')) {
  3345. smileys.show("slide", { direction: "down", duration: 300});
  3346. } else {
  3347. smileys.hide("slide", { direction: "down", duration: 300});
  3348. }
  3349. $('#usermsg').focus();
  3350. }
  3351. function addClickFunction(smiley, number) {
  3352. smiley.onclick = function addSmileyToMessage() {
  3353. var usermsg = $('#usermsg');
  3354. var message = usermsg.val();
  3355. message += smileys['smiley' + number];
  3356. usermsg.val(message);
  3357. usermsg.get(0).setSelectionRange(message.length, message.length);
  3358. toggleSmileys();
  3359. usermsg.focus();
  3360. };
  3361. }
  3362. /**
  3363. * Adds the smileys container to the chat
  3364. */
  3365. function addSmileys() {
  3366. var smileysContainer = document.createElement('div');
  3367. smileysContainer.id = 'smileysContainer';
  3368. for(var i = 1; i <= 21; i++) {
  3369. var smileyContainer = document.createElement('div');
  3370. smileyContainer.id = 'smiley' + i;
  3371. smileyContainer.className = 'smileyContainer';
  3372. var smiley = document.createElement('img');
  3373. smiley.src = 'images/smileys/smiley' + i + '.svg';
  3374. smiley.className = 'smiley';
  3375. addClickFunction(smiley, i);
  3376. smileyContainer.appendChild(smiley);
  3377. smileysContainer.appendChild(smileyContainer);
  3378. }
  3379. $("#chatspace").append(smileysContainer);
  3380. }
  3381. /**
  3382. * Resizes the chat conversation.
  3383. */
  3384. function resizeChatConversation() {
  3385. var msgareaHeight = $('#usermsg').outerHeight();
  3386. var chatspace = $('#chatspace');
  3387. var width = chatspace.width();
  3388. var chat = $('#chatconversation');
  3389. var smileys = $('#smileysarea');
  3390. smileys.height(msgareaHeight);
  3391. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  3392. $('#smileysContainer').css('bottom', msgareaHeight);
  3393. chat.width(width - 10);
  3394. chat.height(window.innerHeight - 15 - msgareaHeight);
  3395. }
  3396. /**
  3397. * Chat related user interface.
  3398. */
  3399. var Chat = (function (my) {
  3400. /**
  3401. * Initializes chat related interface.
  3402. */
  3403. my.init = function () {
  3404. if(NicknameHandler.getNickname())
  3405. Chat.setChatConversationMode(true);
  3406. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  3407. function (nickname) {
  3408. Chat.setChatConversationMode(true);
  3409. });
  3410. $('#nickinput').keydown(function (event) {
  3411. if (event.keyCode === 13) {
  3412. event.preventDefault();
  3413. var val = UIUtil.escapeHtml(this.value);
  3414. this.value = '';
  3415. if (!NicknameHandler.getNickname()) {
  3416. NicknameHandler.setNickname(val);
  3417. return;
  3418. }
  3419. }
  3420. });
  3421. $('#usermsg').keydown(function (event) {
  3422. if (event.keyCode === 13) {
  3423. event.preventDefault();
  3424. var value = this.value;
  3425. $('#usermsg').val('').trigger('autosize.resize');
  3426. this.focus();
  3427. var command = new CommandsProcessor(value);
  3428. if(command.isCommand())
  3429. {
  3430. command.processCommand();
  3431. }
  3432. else
  3433. {
  3434. var message = UIUtil.escapeHtml(value);
  3435. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  3436. }
  3437. }
  3438. });
  3439. var onTextAreaResize = function () {
  3440. resizeChatConversation();
  3441. Chat.scrollChatToBottom();
  3442. };
  3443. $('#usermsg').autosize({callback: onTextAreaResize});
  3444. $("#chatspace").bind("shown",
  3445. function () {
  3446. unreadMessages = 0;
  3447. setVisualNotification(false);
  3448. });
  3449. addSmileys();
  3450. };
  3451. /**
  3452. * Appends the given message to the chat conversation.
  3453. */
  3454. my.updateChatConversation = function (from, displayName, message) {
  3455. var divClassName = '';
  3456. if (APP.xmpp.myJid() === from) {
  3457. divClassName = "localuser";
  3458. }
  3459. else {
  3460. divClassName = "remoteuser";
  3461. if (!Chat.isVisible()) {
  3462. unreadMessages++;
  3463. UIUtil.playSoundNotification('chatNotification');
  3464. setVisualNotification(true);
  3465. }
  3466. }
  3467. // replace links and smileys
  3468. // Strophe already escapes special symbols on sending,
  3469. // so we escape here only tags to avoid double &amp;
  3470. var escMessage = message.replace(/</g, '&lt;').
  3471. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  3472. var escDisplayName = UIUtil.escapeHtml(displayName);
  3473. message = Replacement.processReplacements(escMessage);
  3474. var messageContainer =
  3475. '<div class="chatmessage">'+
  3476. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  3477. '<div class="username ' + divClassName +'">' + escDisplayName +
  3478. '</div>' + '<div class="timestamp">' + getCurrentTime() +
  3479. '</div>' + '<div class="usermessage">' + message + '</div>' +
  3480. '</div>';
  3481. $('#chatconversation').append(messageContainer);
  3482. $('#chatconversation').animate(
  3483. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3484. };
  3485. /**
  3486. * Appends error message to the conversation
  3487. * @param errorMessage the received error message.
  3488. * @param originalText the original message.
  3489. */
  3490. my.chatAddError = function(errorMessage, originalText)
  3491. {
  3492. errorMessage = UIUtil.escapeHtml(errorMessage);
  3493. originalText = UIUtil.escapeHtml(originalText);
  3494. $('#chatconversation').append(
  3495. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  3496. (originalText? (' \"'+ originalText + '\"') : "") +
  3497. ' was not sent.' +
  3498. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  3499. $('#chatconversation').animate(
  3500. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3501. };
  3502. /**
  3503. * Sets the subject to the UI
  3504. * @param subject the subject
  3505. */
  3506. my.chatSetSubject = function(subject)
  3507. {
  3508. if(subject)
  3509. subject = subject.trim();
  3510. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  3511. if(subject === "")
  3512. {
  3513. $("#subject").css({display: "none"});
  3514. }
  3515. else
  3516. {
  3517. $("#subject").css({display: "block"});
  3518. }
  3519. };
  3520. /**
  3521. * Sets the chat conversation mode.
  3522. */
  3523. my.setChatConversationMode = function (isConversationMode) {
  3524. if (isConversationMode) {
  3525. $('#nickname').css({visibility: 'hidden'});
  3526. $('#chatconversation').css({visibility: 'visible'});
  3527. $('#usermsg').css({visibility: 'visible'});
  3528. $('#smileysarea').css({visibility: 'visible'});
  3529. $('#usermsg').focus();
  3530. }
  3531. };
  3532. /**
  3533. * Resizes the chat area.
  3534. */
  3535. my.resizeChat = function () {
  3536. var chatSize = require("../SidePanelToggler").getPanelSize();
  3537. $('#chatspace').width(chatSize[0]);
  3538. $('#chatspace').height(chatSize[1]);
  3539. resizeChatConversation();
  3540. };
  3541. /**
  3542. * Indicates if the chat is currently visible.
  3543. */
  3544. my.isVisible = function () {
  3545. return $('#chatspace').is(":visible");
  3546. };
  3547. /**
  3548. * Shows and hides the window with the smileys
  3549. */
  3550. my.toggleSmileys = toggleSmileys;
  3551. /**
  3552. * Scrolls chat to the bottom.
  3553. */
  3554. my.scrollChatToBottom = function() {
  3555. setTimeout(function () {
  3556. $('#chatconversation').scrollTop(
  3557. $('#chatconversation')[0].scrollHeight);
  3558. }, 5);
  3559. };
  3560. return my;
  3561. }(Chat || {}));
  3562. module.exports = Chat;
  3563. },{"../../../../service/UI/UIEvents":83,"../../toolbars/ToolbarToggler":25,"../../util/NicknameHandler":28,"../../util/UIUtil":29,"../SidePanelToggler":16,"./Commands":18,"./Replacement":19,"./smileys.json":20}],18:[function(require,module,exports){
  3564. var UIUtil = require("../../util/UIUtil");
  3565. /**
  3566. * List with supported commands. The keys are the names of the commands and
  3567. * the value is the function that processes the message.
  3568. * @type {{String: function}}
  3569. */
  3570. var commands = {
  3571. "topic" : processTopic
  3572. };
  3573. /**
  3574. * Extracts the command from the message.
  3575. * @param message the received message
  3576. * @returns {string} the command
  3577. */
  3578. function getCommand(message)
  3579. {
  3580. if(message)
  3581. {
  3582. for(var command in commands)
  3583. {
  3584. if(message.indexOf("/" + command) == 0)
  3585. return command;
  3586. }
  3587. }
  3588. return "";
  3589. };
  3590. /**
  3591. * Processes the data for topic command.
  3592. * @param commandArguments the arguments of the topic command.
  3593. */
  3594. function processTopic(commandArguments)
  3595. {
  3596. var topic = UIUtil.escapeHtml(commandArguments);
  3597. APP.xmpp.setSubject(topic);
  3598. }
  3599. /**
  3600. * Constructs new CommandProccessor instance from a message that
  3601. * handles commands received via chat messages.
  3602. * @param message the message
  3603. * @constructor
  3604. */
  3605. function CommandsProcessor(message)
  3606. {
  3607. var command = getCommand(message);
  3608. /**
  3609. * Returns the name of the command.
  3610. * @returns {String} the command
  3611. */
  3612. this.getCommand = function()
  3613. {
  3614. return command;
  3615. };
  3616. var messageArgument = message.substr(command.length + 2);
  3617. /**
  3618. * Returns the arguments of the command.
  3619. * @returns {string}
  3620. */
  3621. this.getArgument = function()
  3622. {
  3623. return messageArgument;
  3624. };
  3625. }
  3626. /**
  3627. * Checks whether this instance is valid command or not.
  3628. * @returns {boolean}
  3629. */
  3630. CommandsProcessor.prototype.isCommand = function()
  3631. {
  3632. if(this.getCommand())
  3633. return true;
  3634. return false;
  3635. };
  3636. /**
  3637. * Processes the command.
  3638. */
  3639. CommandsProcessor.prototype.processCommand = function()
  3640. {
  3641. if(!this.isCommand())
  3642. return;
  3643. commands[this.getCommand()](this.getArgument());
  3644. };
  3645. module.exports = CommandsProcessor;
  3646. },{"../../util/UIUtil":29}],19:[function(require,module,exports){
  3647. var Smileys = require("./smileys.json");
  3648. /**
  3649. * Processes links and smileys in "body"
  3650. */
  3651. function processReplacements(body)
  3652. {
  3653. //make links clickable
  3654. body = linkify(body);
  3655. //add smileys
  3656. body = smilify(body);
  3657. return body;
  3658. }
  3659. /**
  3660. * Finds and replaces all links in the links in "body"
  3661. * with their <a href=""></a>
  3662. */
  3663. function linkify(inputText)
  3664. {
  3665. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  3666. //URLs starting with http://, https://, or ftp://
  3667. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  3668. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  3669. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  3670. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  3671. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  3672. //Change email addresses to mailto:: links.
  3673. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  3674. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  3675. return replacedText;
  3676. }
  3677. /**
  3678. * Replaces common smiley strings with images
  3679. */
  3680. function smilify(body)
  3681. {
  3682. if(!body) {
  3683. return body;
  3684. }
  3685. var regexs = Smileys["regexs"];
  3686. for(var smiley in regexs) {
  3687. if(regexs.hasOwnProperty(smiley)) {
  3688. body = body.replace(regexs[smiley],
  3689. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  3690. }
  3691. }
  3692. return body;
  3693. }
  3694. module.exports = {
  3695. processReplacements: processReplacements,
  3696. linkify: linkify
  3697. };
  3698. },{"./smileys.json":20}],20:[function(require,module,exports){
  3699. module.exports={
  3700. "smileys": {
  3701. "smiley1": ":)",
  3702. "smiley2": ":(",
  3703. "smiley3": ":D",
  3704. "smiley4": "(y)",
  3705. "smiley5": " :P",
  3706. "smiley6": "(wave)",
  3707. "smiley7": "(blush)",
  3708. "smiley8": "(chuckle)",
  3709. "smiley9": "(shocked)",
  3710. "smiley10": ":*",
  3711. "smiley11": "(n)",
  3712. "smiley12": "(search)",
  3713. "smiley13": " <3",
  3714. "smiley14": "(oops)",
  3715. "smiley15": "(angry)",
  3716. "smiley16": "(angel)",
  3717. "smiley17": "(sick)",
  3718. "smiley18": ";(",
  3719. "smiley19": "(bomb)",
  3720. "smiley20": "(clap)",
  3721. "smiley21": " ;)"
  3722. },
  3723. "regexs": {
  3724. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  3725. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  3726. "smiley1": /(:-\)|:\))/gi,
  3727. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  3728. "smiley5": /(:-P|:P|:-p|:p)/gi,
  3729. "smiley6": /(\(wave\))/gi,
  3730. "smiley7": /(\(blush\))/gi,
  3731. "smiley8": /(\(chuckle\))/gi,
  3732. "smiley9": /(:-0|\(shocked\))/gi,
  3733. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  3734. "smiley11": /(\(n\))/gi,
  3735. "smiley12": /(\(search\))/g,
  3736. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  3737. "smiley14": /(\(oops\))/gi,
  3738. "smiley15": /(\(angry\))/gi,
  3739. "smiley16": /(\(angel\))/gi,
  3740. "smiley17": /(\(sick\))/gi,
  3741. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  3742. "smiley19": /(\(bomb\))/gi,
  3743. "smiley20": /(\(clap\))/gi,
  3744. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  3745. }
  3746. }
  3747. },{}],21:[function(require,module,exports){
  3748. var numberOfContacts = 0;
  3749. var notificationInterval;
  3750. /**
  3751. * Updates the number of participants in the contact list button and sets
  3752. * the glow
  3753. * @param delta indicates whether a new user has joined (1) or someone has
  3754. * left(-1)
  3755. */
  3756. function updateNumberOfParticipants(delta) {
  3757. //when the user is alone we don't show the number of participants
  3758. if(numberOfContacts === 0) {
  3759. $("#numberOfParticipants").text('');
  3760. numberOfContacts += delta;
  3761. } else if(numberOfContacts !== 0 && !ContactList.isVisible()) {
  3762. ContactList.setVisualNotification(true);
  3763. numberOfContacts += delta;
  3764. $("#numberOfParticipants").text(numberOfContacts);
  3765. }
  3766. }
  3767. /**
  3768. * Creates the avatar element.
  3769. *
  3770. * @return the newly created avatar element
  3771. */
  3772. function createAvatar(id) {
  3773. var avatar = document.createElement('img');
  3774. avatar.className = "icon-avatar avatar";
  3775. avatar.src = "https://www.gravatar.com/avatar/" + id + "?d=wavatar&size=30";
  3776. return avatar;
  3777. }
  3778. /**
  3779. * Creates the display name paragraph.
  3780. *
  3781. * @param displayName the display name to set
  3782. */
  3783. function createDisplayNameParagraph(displayName) {
  3784. var p = document.createElement('p');
  3785. p.innerText = displayName;
  3786. return p;
  3787. }
  3788. function stopGlowing(glower) {
  3789. window.clearInterval(notificationInterval);
  3790. notificationInterval = false;
  3791. glower.removeClass('glowing');
  3792. if (!ContactList.isVisible()) {
  3793. glower.removeClass('active');
  3794. }
  3795. }
  3796. /**
  3797. * Contact list.
  3798. */
  3799. var ContactList = {
  3800. /**
  3801. * Indicates if the chat is currently visible.
  3802. *
  3803. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  3804. * otherwise
  3805. */
  3806. isVisible: function () {
  3807. return $('#contactlist').is(":visible");
  3808. },
  3809. /**
  3810. * Adds a contact for the given peerJid if such doesn't yet exist.
  3811. *
  3812. * @param peerJid the peerJid corresponding to the contact
  3813. * @param id the user's email or userId used to get the user's avatar
  3814. */
  3815. ensureAddContact: function (peerJid, id) {
  3816. var resourceJid = Strophe.getResourceFromJid(peerJid);
  3817. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  3818. if (!contact || contact.length <= 0)
  3819. ContactList.addContact(peerJid, id);
  3820. },
  3821. /**
  3822. * Adds a contact for the given peer jid.
  3823. *
  3824. * @param peerJid the jid of the contact to add
  3825. * @param id the email or userId of the user
  3826. */
  3827. addContact: function (peerJid, id) {
  3828. var resourceJid = Strophe.getResourceFromJid(peerJid);
  3829. var contactlist = $('#contactlist>ul');
  3830. var newContact = document.createElement('li');
  3831. newContact.id = resourceJid;
  3832. newContact.className = "clickable";
  3833. newContact.onclick = function (event) {
  3834. if (event.currentTarget.className === "clickable") {
  3835. $(ContactList).trigger('contactclicked', [peerJid]);
  3836. }
  3837. };
  3838. newContact.appendChild(createAvatar(id));
  3839. newContact.appendChild(createDisplayNameParagraph("Participant"));
  3840. var clElement = contactlist.get(0);
  3841. if (resourceJid === APP.xmpp.myResource()
  3842. && $('#contactlist>ul .title')[0].nextSibling.nextSibling) {
  3843. clElement.insertBefore(newContact,
  3844. $('#contactlist>ul .title')[0].nextSibling.nextSibling);
  3845. }
  3846. else {
  3847. clElement.appendChild(newContact);
  3848. }
  3849. updateNumberOfParticipants(1);
  3850. },
  3851. /**
  3852. * Removes a contact for the given peer jid.
  3853. *
  3854. * @param peerJid the peerJid corresponding to the contact to remove
  3855. */
  3856. removeContact: function (peerJid) {
  3857. var resourceJid = Strophe.getResourceFromJid(peerJid);
  3858. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  3859. if (contact && contact.length > 0) {
  3860. var contactlist = $('#contactlist>ul');
  3861. contactlist.get(0).removeChild(contact.get(0));
  3862. updateNumberOfParticipants(-1);
  3863. }
  3864. },
  3865. setVisualNotification: function (show, stopGlowingIn) {
  3866. var glower = $('#contactListButton');
  3867. if (show && !notificationInterval) {
  3868. notificationInterval = window.setInterval(function () {
  3869. glower.toggleClass('active glowing');
  3870. }, 800);
  3871. }
  3872. else if (!show && notificationInterval) {
  3873. stopGlowing(glower);
  3874. }
  3875. if (stopGlowingIn) {
  3876. setTimeout(function () {
  3877. stopGlowing(glower);
  3878. }, stopGlowingIn);
  3879. }
  3880. },
  3881. setClickable: function (resourceJid, isClickable) {
  3882. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  3883. if (isClickable) {
  3884. contact.addClass('clickable');
  3885. } else {
  3886. contact.removeClass('clickable');
  3887. }
  3888. },
  3889. onDisplayNameChange: function (peerJid, displayName) {
  3890. if (peerJid === 'localVideoContainer')
  3891. peerJid = APP.xmpp.myJid();
  3892. var resourceJid = Strophe.getResourceFromJid(peerJid);
  3893. var contactName = $('#contactlist #' + resourceJid + '>p');
  3894. if (contactName && displayName && displayName.length > 0)
  3895. contactName.html(displayName);
  3896. }
  3897. };
  3898. module.exports = ContactList;
  3899. },{}],22:[function(require,module,exports){
  3900. var Avatar = require("../../avatar/Avatar");
  3901. var Settings = require("./../../../settings/Settings");
  3902. var UIUtil = require("../../util/UIUtil");
  3903. var languages = require("../../../../service/translation/languages");
  3904. function generateLanguagesSelectBox()
  3905. {
  3906. var currentLang = APP.translation.getCurrentLanguage();
  3907. var html = "<select id=\"languages_selectbox\">";
  3908. var langArray = languages.getLanguages();
  3909. for(var i = 0; i < langArray.length; i++)
  3910. {
  3911. var lang = langArray[i];
  3912. html += "<option ";
  3913. if(lang === currentLang)
  3914. html += "selected ";
  3915. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  3916. html += "</option>";
  3917. }
  3918. return html + "</select>";
  3919. }
  3920. var SettingsMenu = {
  3921. init: function () {
  3922. $("#updateSettings").before(generateLanguagesSelectBox());
  3923. APP.translation.translateElement($("#languages_selectbox"));
  3924. $('#settingsmenu>input').keyup(function(event){
  3925. if(event.keyCode === 13) {//enter
  3926. SettingsMenu.update();
  3927. }
  3928. });
  3929. $("#updateSettings").click(function () {
  3930. SettingsMenu.update();
  3931. });
  3932. },
  3933. update: function() {
  3934. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  3935. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  3936. if(newDisplayName) {
  3937. var displayName = Settings.setDisplayName(newDisplayName);
  3938. APP.xmpp.addToPresence("displayName", displayName, true);
  3939. }
  3940. var language = $("#languages_selectbox").val();
  3941. APP.translation.setLanguage(language);
  3942. Settings.setLanguage(language);
  3943. APP.xmpp.addToPresence("email", newEmail);
  3944. var email = Settings.setEmail(newEmail);
  3945. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  3946. },
  3947. isVisible: function() {
  3948. return $('#settingsmenu').is(':visible');
  3949. },
  3950. setDisplayName: function(newDisplayName) {
  3951. var displayName = Settings.setDisplayName(newDisplayName);
  3952. $('#setDisplayName').get(0).value = displayName;
  3953. },
  3954. onDisplayNameChange: function(peerJid, newDisplayName) {
  3955. if(peerJid === 'localVideoContainer' ||
  3956. peerJid === APP.xmpp.myJid()) {
  3957. this.setDisplayName(newDisplayName);
  3958. }
  3959. }
  3960. };
  3961. module.exports = SettingsMenu;
  3962. },{"../../../../service/translation/languages":87,"../../avatar/Avatar":12,"../../util/UIUtil":29,"./../../../settings/Settings":37}],23:[function(require,module,exports){
  3963. var PanelToggler = require("../side_pannels/SidePanelToggler");
  3964. var buttonHandlers = {
  3965. "bottom_toolbar_contact_list": function () {
  3966. BottomToolbar.toggleContactList();
  3967. },
  3968. "bottom_toolbar_film_strip": function () {
  3969. BottomToolbar.toggleFilmStrip();
  3970. },
  3971. "bottom_toolbar_chat": function () {
  3972. BottomToolbar.toggleChat();
  3973. }
  3974. };
  3975. var BottomToolbar = (function (my) {
  3976. my.init = function () {
  3977. for(var k in buttonHandlers)
  3978. $("#" + k).click(buttonHandlers[k]);
  3979. };
  3980. my.toggleChat = function() {
  3981. PanelToggler.toggleChat();
  3982. };
  3983. my.toggleContactList = function() {
  3984. PanelToggler.toggleContactList();
  3985. };
  3986. my.toggleFilmStrip = function() {
  3987. var filmstrip = $("#remoteVideos");
  3988. filmstrip.toggleClass("hidden");
  3989. };
  3990. $(document).bind("remotevideo.resized", function (event, width, height) {
  3991. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  3992. $('#bottomToolbar').css({bottom: bottom + 'px'});
  3993. });
  3994. return my;
  3995. }(BottomToolbar || {}));
  3996. module.exports = BottomToolbar;
  3997. },{"../side_pannels/SidePanelToggler":16}],24:[function(require,module,exports){
  3998. /* global APP,$, buttonClick, config, lockRoom,
  3999. setSharedKey, Util */
  4000. var messageHandler = require("../util/MessageHandler");
  4001. var BottomToolbar = require("./BottomToolbar");
  4002. var Prezi = require("../prezi/Prezi");
  4003. var Etherpad = require("../etherpad/Etherpad");
  4004. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4005. var Authentication = require("../authentication/Authentication");
  4006. var UIUtil = require("../util/UIUtil");
  4007. var AuthenticationEvents
  4008. = require("../../../service/authentication/AuthenticationEvents");
  4009. var roomUrl = null;
  4010. var sharedKey = '';
  4011. var UI = null;
  4012. var buttonHandlers =
  4013. {
  4014. "toolbar_button_mute": function () {
  4015. return APP.UI.toggleAudio();
  4016. },
  4017. "toolbar_button_camera": function () {
  4018. return APP.UI.toggleVideo();
  4019. },
  4020. /*"toolbar_button_authentication": function () {
  4021. return Toolbar.authenticateClicked();
  4022. },*/
  4023. "toolbar_button_record": function () {
  4024. return toggleRecording();
  4025. },
  4026. "toolbar_button_security": function () {
  4027. return Toolbar.openLockDialog();
  4028. },
  4029. "toolbar_button_link": function () {
  4030. return Toolbar.openLinkDialog();
  4031. },
  4032. "toolbar_button_chat": function () {
  4033. return BottomToolbar.toggleChat();
  4034. },
  4035. "toolbar_button_prezi": function () {
  4036. return Prezi.openPreziDialog();
  4037. },
  4038. "toolbar_button_etherpad": function () {
  4039. return Etherpad.toggleEtherpad(0);
  4040. },
  4041. "toolbar_button_desktopsharing": function () {
  4042. return APP.desktopsharing.toggleScreenSharing();
  4043. },
  4044. "toolbar_button_fullScreen": function()
  4045. {
  4046. UIUtil.buttonClick("#fullScreen", "icon-full-screen icon-exit-full-screen");
  4047. return Toolbar.toggleFullScreen();
  4048. },
  4049. "toolbar_button_sip": function () {
  4050. return callSipButtonClicked();
  4051. },
  4052. "toolbar_button_settings": function () {
  4053. PanelToggler.toggleSettingsMenu();
  4054. },
  4055. "toolbar_button_hangup": function () {
  4056. return hangup();
  4057. },
  4058. "toolbar_button_login": function () {
  4059. Toolbar.authenticateClicked();
  4060. },
  4061. "toolbar_button_logout": function () {
  4062. // Ask for confirmation
  4063. messageHandler.openTwoButtonDialog(
  4064. "dialog.logoutTitle",
  4065. null,
  4066. "dialog.logoutQuestion",
  4067. null,
  4068. false,
  4069. "dialog.Yes",
  4070. function (evt, yes) {
  4071. if (yes) {
  4072. APP.xmpp.logout(function (url) {
  4073. if (url) {
  4074. window.location.href = url;
  4075. } else {
  4076. hangup();
  4077. }
  4078. });
  4079. }
  4080. });
  4081. }
  4082. };
  4083. function hangup() {
  4084. APP.xmpp.disposeConference();
  4085. if(config.enableWelcomePage)
  4086. {
  4087. setTimeout(function()
  4088. {
  4089. window.localStorage.welcomePageDisabled = false;
  4090. window.location.pathname = "/";
  4091. }, 10000);
  4092. }
  4093. var title = APP.translation.generateTranslatonHTML(
  4094. "dialog.sessTerminated");
  4095. var msg = APP.translation.generateTranslatonHTML(
  4096. "dialog.hungUp");
  4097. var button = APP.translation.generateTranslatonHTML(
  4098. "dialog.joinAgain");
  4099. var buttons = {};
  4100. buttons.joinAgain = {title: button, value: true};
  4101. UI.messageHandler.openDialog(
  4102. title,
  4103. msg,
  4104. true,
  4105. buttons,
  4106. function(event, value, message, formVals)
  4107. {
  4108. window.location.reload();
  4109. return false;
  4110. }
  4111. );
  4112. }
  4113. /**
  4114. * Starts or stops the recording for the conference.
  4115. */
  4116. function toggleRecording() {
  4117. APP.xmpp.toggleRecording(function (callback) {
  4118. var msg = APP.translation.generateTranslatonHTML(
  4119. "dialog.recordingToken");
  4120. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  4121. '<h2>' + msg + '</h2>' +
  4122. '<input id="recordingToken" type="text" ' +
  4123. 'placeholder="token" autofocus>',
  4124. false,
  4125. "dialog.Save",
  4126. function (e, v, m, f) {
  4127. if (v) {
  4128. var token = document.getElementById('recordingToken');
  4129. if (token.value) {
  4130. callback(UIUtil.escapeHtml(token.value));
  4131. }
  4132. }
  4133. },
  4134. function (event) {
  4135. document.getElementById('recordingToken').focus();
  4136. },
  4137. function () {
  4138. }
  4139. );
  4140. }, Toolbar.setRecordingButtonState, Toolbar.setRecordingButtonState);
  4141. }
  4142. /**
  4143. * Locks / unlocks the room.
  4144. */
  4145. function lockRoom(lock) {
  4146. var currentSharedKey = '';
  4147. if (lock)
  4148. currentSharedKey = sharedKey;
  4149. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  4150. // password is required
  4151. if (sharedKey)
  4152. {
  4153. console.log('set room password');
  4154. Toolbar.lockLockButton();
  4155. }
  4156. else
  4157. {
  4158. console.log('removed room password');
  4159. Toolbar.unlockLockButton();
  4160. }
  4161. }, function (err) {
  4162. console.warn('setting password failed', err);
  4163. messageHandler.showError("dialog.lockTitle",
  4164. "dialog.lockMessage");
  4165. Toolbar.setSharedKey('');
  4166. }, function () {
  4167. console.warn('room passwords not supported');
  4168. messageHandler.showError("dialog.warning",
  4169. "dialog.passwordNotSupported");
  4170. Toolbar.setSharedKey('');
  4171. });
  4172. };
  4173. /**
  4174. * Invite participants to conference.
  4175. */
  4176. function inviteParticipants() {
  4177. if (roomUrl === null)
  4178. return;
  4179. var sharedKeyText = "";
  4180. if (sharedKey && sharedKey.length > 0) {
  4181. sharedKeyText =
  4182. "This conference is password protected. Please use the " +
  4183. "following pin when joining:%0D%0A%0D%0A" +
  4184. sharedKey + "%0D%0A%0D%0A";
  4185. }
  4186. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  4187. var subject = "Invitation to a " + interfaceConfig.APP_NAME + " (" + conferenceName + ")";
  4188. var body = "Hey there, I%27d like to invite you to a " + interfaceConfig.APP_NAME +
  4189. " conference I%27ve just set up.%0D%0A%0D%0A" +
  4190. "Please click on the following link in order" +
  4191. " to join the conference.%0D%0A%0D%0A" +
  4192. roomUrl +
  4193. "%0D%0A%0D%0A" +
  4194. sharedKeyText +
  4195. "Note that " + interfaceConfig.APP_NAME + " is currently" +
  4196. " only supported by Chromium," +
  4197. " Google Chrome and Opera, so you need" +
  4198. " to be using one of these browsers.%0D%0A%0D%0A" +
  4199. "Talk to you in a sec!";
  4200. if (window.localStorage.displayname) {
  4201. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  4202. }
  4203. if (interfaceConfig.INVITATION_POWERED_BY) {
  4204. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  4205. }
  4206. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  4207. }
  4208. function callSipButtonClicked()
  4209. {
  4210. var defaultNumber
  4211. = config.defaultSipNumber ? config.defaultSipNumber : '';
  4212. var sipMsg = APP.translation.generateTranslatonHTML(
  4213. "dialog.sipMsg");
  4214. messageHandler.openTwoButtonDialog(null, null, null,
  4215. '<h2>' + sipMsg + '</h2>' +
  4216. '<input id="sipNumber" type="text"' +
  4217. ' value="' + defaultNumber + '" autofocus>',
  4218. false,
  4219. "dialog.Dial",
  4220. function (e, v, m, f) {
  4221. if (v) {
  4222. var numberInput = document.getElementById('sipNumber');
  4223. if (numberInput.value) {
  4224. APP.xmpp.dial(numberInput.value, 'fromnumber',
  4225. UI.getRoomName(), sharedKey);
  4226. }
  4227. }
  4228. },
  4229. function (event) {
  4230. document.getElementById('sipNumber').focus();
  4231. }
  4232. );
  4233. }
  4234. var Toolbar = (function (my) {
  4235. my.init = function (ui) {
  4236. for(var k in buttonHandlers)
  4237. $("#" + k).click(buttonHandlers[k]);
  4238. UI = ui;
  4239. // Update login info
  4240. APP.xmpp.addListener(
  4241. AuthenticationEvents.IDENTITY_UPDATED,
  4242. function (authenticationEnabled, userIdentity) {
  4243. var loggedIn = false;
  4244. if (userIdentity) {
  4245. loggedIn = true;
  4246. }
  4247. //FIXME: XMPP authentication need improvements for "live" login
  4248. if (!APP.xmpp.isExternalAuthEnabled() && !loggedIn)
  4249. {
  4250. authenticationEnabled = false;
  4251. }
  4252. Toolbar.showAuthenticateButton(authenticationEnabled);
  4253. if (authenticationEnabled) {
  4254. Toolbar.setAuthenticatedIdentity(userIdentity);
  4255. Toolbar.showLoginButton(!loggedIn);
  4256. Toolbar.showLogoutButton(loggedIn);
  4257. }
  4258. }
  4259. );
  4260. },
  4261. /**
  4262. * Sets shared key
  4263. * @param sKey the shared key
  4264. */
  4265. my.setSharedKey = function (sKey) {
  4266. sharedKey = sKey;
  4267. };
  4268. my.authenticateClicked = function () {
  4269. Authentication.focusAuthenticationWindow();
  4270. // Get authentication URL
  4271. if (!APP.xmpp.getMUCJoined()) {
  4272. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  4273. // If conference has not been started yet - redirect to login page
  4274. window.location.href = url;
  4275. });
  4276. } else {
  4277. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  4278. // Otherwise - open popup with authentication URL
  4279. var authenticationWindow = Authentication.createAuthenticationWindow(
  4280. function () {
  4281. // On popup closed - retry room allocation
  4282. APP.xmpp.allocateConferenceFocus(
  4283. APP.UI.getRoomName(),
  4284. function () { console.info("AUTH DONE"); }
  4285. );
  4286. }, url);
  4287. if (!authenticationWindow) {
  4288. messageHandler.openMessageDialog(
  4289. null, "dialog.popupError");
  4290. }
  4291. });
  4292. }
  4293. };
  4294. /**
  4295. * Updates the room invite url.
  4296. */
  4297. my.updateRoomUrl = function (newRoomUrl) {
  4298. roomUrl = newRoomUrl;
  4299. // If the invite dialog has been already opened we update the information.
  4300. var inviteLink = document.getElementById('inviteLinkRef');
  4301. if (inviteLink) {
  4302. inviteLink.value = roomUrl;
  4303. inviteLink.select();
  4304. document.getElementById('jqi_state0_buttonInvite').disabled = false;
  4305. }
  4306. };
  4307. /**
  4308. * Disables and enables some of the buttons.
  4309. */
  4310. my.setupButtonsFromConfig = function () {
  4311. if (config.disablePrezi)
  4312. {
  4313. $("#prezi_button").css({display: "none"});
  4314. }
  4315. };
  4316. /**
  4317. * Opens the lock room dialog.
  4318. */
  4319. my.openLockDialog = function () {
  4320. // Only the focus is able to set a shared key.
  4321. if (!APP.xmpp.isModerator()) {
  4322. if (sharedKey) {
  4323. messageHandler.openMessageDialog(null,
  4324. "dialog.passwordError");
  4325. } else {
  4326. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  4327. }
  4328. } else {
  4329. if (sharedKey) {
  4330. messageHandler.openTwoButtonDialog(null, null,
  4331. "dialog.passwordCheck",
  4332. null,
  4333. false,
  4334. "dialog.Remove",
  4335. function (e, v) {
  4336. if (v) {
  4337. Toolbar.setSharedKey('');
  4338. lockRoom(false);
  4339. }
  4340. });
  4341. } else {
  4342. var msg = APP.translation.generateTranslatonHTML(
  4343. "dialog.passwordMsg");
  4344. var yourPassword = APP.translation.translateString(
  4345. "dialog.yourPassword");
  4346. messageHandler.openTwoButtonDialog(null, null, null,
  4347. '<h2>' + msg + '</h2>' +
  4348. '<input id="lockKey" type="text"' +
  4349. 'placeholder="' + yourPassword + '" autofocus>',
  4350. false,
  4351. "dialog.Save",
  4352. function (e, v) {
  4353. if (v) {
  4354. var lockKey = document.getElementById('lockKey');
  4355. if (lockKey.value) {
  4356. Toolbar.setSharedKey(UIUtil.escapeHtml(lockKey.value));
  4357. lockRoom(true);
  4358. }
  4359. }
  4360. },
  4361. function () {
  4362. document.getElementById('lockKey').focus();
  4363. }
  4364. );
  4365. }
  4366. }
  4367. };
  4368. /**
  4369. * Opens the invite link dialog.
  4370. */
  4371. my.openLinkDialog = function () {
  4372. var inviteLink;
  4373. if (roomUrl === null) {
  4374. inviteLink = "Your conference is currently being created...";
  4375. } else {
  4376. inviteLink = encodeURI(roomUrl);
  4377. }
  4378. messageHandler.openTwoButtonDialog("dialog.shareLink",
  4379. null, null,
  4380. '<input id="inviteLinkRef" type="text" value="' +
  4381. inviteLink + '" onclick="this.select();" readonly>',
  4382. false,
  4383. "dialog.Invite",
  4384. function (e, v) {
  4385. if (v) {
  4386. if (roomUrl) {
  4387. inviteParticipants();
  4388. }
  4389. }
  4390. },
  4391. function () {
  4392. if (roomUrl) {
  4393. document.getElementById('inviteLinkRef').select();
  4394. } else {
  4395. document.getElementById('jqi_state0_buttonInvite')
  4396. .disabled = true;
  4397. }
  4398. }
  4399. );
  4400. };
  4401. /**
  4402. * Opens the settings dialog.
  4403. */
  4404. my.openSettingsDialog = function () {
  4405. var settings1 = APP.translation.generateTranslatonHTML(
  4406. "dialog.settings1");
  4407. var settings2 = APP.translation.generateTranslatonHTML(
  4408. "dialog.settings2");
  4409. var settings3 = APP.translation.generateTranslatonHTML(
  4410. "dialog.settings3");
  4411. var yourPassword = APP.translation.translateString(
  4412. "dialog.yourPassword");
  4413. messageHandler.openTwoButtonDialog(null,
  4414. '<h2>' + settings1 + '</h2>' +
  4415. '<input type="checkbox" id="initMuted">' +
  4416. settings2 + '<br/>' +
  4417. '<input type="checkbox" id="requireNicknames">' +
  4418. settings3 +
  4419. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  4420. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  4421. null,
  4422. null,
  4423. false,
  4424. "dialog.Save",
  4425. function () {
  4426. document.getElementById('lockKey').focus();
  4427. },
  4428. function (e, v) {
  4429. if (v) {
  4430. if ($('#initMuted').is(":checked")) {
  4431. // it is checked
  4432. }
  4433. if ($('#requireNicknames').is(":checked")) {
  4434. // it is checked
  4435. }
  4436. /*
  4437. var lockKey = document.getElementById('lockKey');
  4438. if (lockKey.value) {
  4439. setSharedKey(lockKey.value);
  4440. lockRoom(true);
  4441. }
  4442. */
  4443. }
  4444. }
  4445. );
  4446. };
  4447. /**
  4448. * Toggles the application in and out of full screen mode
  4449. * (a.k.a. presentation mode in Chrome).
  4450. */
  4451. my.toggleFullScreen = function () {
  4452. var fsElement = document.documentElement;
  4453. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  4454. //Enter Full Screen
  4455. if (fsElement.mozRequestFullScreen) {
  4456. fsElement.mozRequestFullScreen();
  4457. }
  4458. else {
  4459. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  4460. }
  4461. } else {
  4462. //Exit Full Screen
  4463. if (document.mozCancelFullScreen) {
  4464. document.mozCancelFullScreen();
  4465. } else {
  4466. document.webkitCancelFullScreen();
  4467. }
  4468. }
  4469. };
  4470. /**
  4471. * Unlocks the lock button state.
  4472. */
  4473. my.unlockLockButton = function () {
  4474. if ($("#lockIcon").hasClass("icon-security-locked"))
  4475. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  4476. };
  4477. /**
  4478. * Updates the lock button state to locked.
  4479. */
  4480. my.lockLockButton = function () {
  4481. if ($("#lockIcon").hasClass("icon-security"))
  4482. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  4483. };
  4484. /**
  4485. * Shows or hides authentication button
  4486. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  4487. */
  4488. my.showAuthenticateButton = function (show) {
  4489. if (show) {
  4490. $('#authentication').css({display: "inline"});
  4491. }
  4492. else {
  4493. $('#authentication').css({display: "none"});
  4494. }
  4495. };
  4496. // Shows or hides the 'recording' button.
  4497. my.showRecordingButton = function (show) {
  4498. if (!config.enableRecording) {
  4499. return;
  4500. }
  4501. if (show) {
  4502. $('#recording').css({display: "inline"});
  4503. }
  4504. else {
  4505. $('#recording').css({display: "none"});
  4506. }
  4507. };
  4508. // Sets the state of the recording button
  4509. my.setRecordingButtonState = function (isRecording) {
  4510. if (isRecording) {
  4511. $('#recordButton').removeClass("icon-recEnable");
  4512. $('#recordButton').addClass("icon-recEnable active");
  4513. } else {
  4514. $('#recordButton').removeClass("icon-recEnable active");
  4515. $('#recordButton').addClass("icon-recEnable");
  4516. }
  4517. };
  4518. // Shows or hides SIP calls button
  4519. my.showSipCallButton = function (show) {
  4520. if (APP.xmpp.isSipGatewayEnabled() && show) {
  4521. $('#sipCallButton').css({display: "inline-block"});
  4522. } else {
  4523. $('#sipCallButton').css({display: "none"});
  4524. }
  4525. };
  4526. /**
  4527. * Displays user authenticated identity name(login).
  4528. * @param authIdentity identity name to be displayed.
  4529. */
  4530. my.setAuthenticatedIdentity = function (authIdentity) {
  4531. if (authIdentity) {
  4532. $('#toolbar_auth_identity').css({display: "list-item"});
  4533. $('#toolbar_auth_identity').text(authIdentity);
  4534. } else {
  4535. $('#toolbar_auth_identity').css({display: "none"});
  4536. }
  4537. };
  4538. /**
  4539. * Shows/hides login button.
  4540. * @param show <tt>true</tt> to show
  4541. */
  4542. my.showLoginButton = function (show) {
  4543. if (show) {
  4544. $('#toolbar_button_login').css({display: "list-item"});
  4545. } else {
  4546. $('#toolbar_button_login').css({display: "none"});
  4547. }
  4548. };
  4549. /**
  4550. * Shows/hides logout button.
  4551. * @param show <tt>true</tt> to show
  4552. */
  4553. my.showLogoutButton = function (show) {
  4554. if (show) {
  4555. $('#toolbar_button_logout').css({display: "list-item"});
  4556. } else {
  4557. $('#toolbar_button_logout').css({display: "none"});
  4558. }
  4559. };
  4560. /**
  4561. * Sets the state of the button. The button has blue glow if desktop
  4562. * streaming is active.
  4563. * @param active the state of the desktop streaming.
  4564. */
  4565. my.changeDesktopSharingButtonState = function (active) {
  4566. var button = $("#desktopsharing > a");
  4567. if (active)
  4568. {
  4569. button.addClass("glow");
  4570. }
  4571. else
  4572. {
  4573. button.removeClass("glow");
  4574. }
  4575. };
  4576. return my;
  4577. }(Toolbar || {}));
  4578. module.exports = Toolbar;
  4579. },{"../../../service/authentication/AuthenticationEvents":84,"../authentication/Authentication":11,"../etherpad/Etherpad":13,"../prezi/Prezi":14,"../side_pannels/SidePanelToggler":16,"../util/MessageHandler":27,"../util/UIUtil":29,"./BottomToolbar":23}],25:[function(require,module,exports){
  4580. /* global $, interfaceConfig, Moderator, DesktopStreaming.showDesktopSharingButton */
  4581. var toolbarTimeoutObject,
  4582. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  4583. function showDesktopSharingButton() {
  4584. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  4585. $('#desktopsharing').css({display: "inline"});
  4586. } else {
  4587. $('#desktopsharing').css({display: "none"});
  4588. }
  4589. }
  4590. /**
  4591. * Hides the toolbar.
  4592. */
  4593. function hideToolbar() {
  4594. var header = $("#header"),
  4595. bottomToolbar = $("#bottomToolbar");
  4596. var isToolbarHover = false;
  4597. header.find('*').each(function () {
  4598. var id = $(this).attr('id');
  4599. if ($("#" + id + ":hover").length > 0) {
  4600. isToolbarHover = true;
  4601. }
  4602. });
  4603. if ($("#bottomToolbar:hover").length > 0) {
  4604. isToolbarHover = true;
  4605. }
  4606. clearTimeout(toolbarTimeoutObject);
  4607. toolbarTimeoutObject = null;
  4608. if (!isToolbarHover) {
  4609. header.hide("slide", { direction: "up", duration: 300});
  4610. $('#subject').animate({top: "-=40"}, 300);
  4611. if ($("#remoteVideos").hasClass("hidden")) {
  4612. bottomToolbar.hide(
  4613. "slide", {direction: "right", duration: 300});
  4614. }
  4615. }
  4616. else {
  4617. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4618. }
  4619. }
  4620. var ToolbarToggler = {
  4621. /**
  4622. * Shows the main toolbar.
  4623. */
  4624. showToolbar: function () {
  4625. var header = $("#header"),
  4626. bottomToolbar = $("#bottomToolbar");
  4627. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  4628. header.show("slide", { direction: "up", duration: 300});
  4629. $('#subject').animate({top: "+=40"}, 300);
  4630. if (!bottomToolbar.is(":visible")) {
  4631. bottomToolbar.show(
  4632. "slide", {direction: "right", duration: 300});
  4633. }
  4634. if (toolbarTimeoutObject) {
  4635. clearTimeout(toolbarTimeoutObject);
  4636. toolbarTimeoutObject = null;
  4637. }
  4638. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4639. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  4640. }
  4641. if (APP.xmpp.isModerator())
  4642. {
  4643. // TODO: Enable settings functionality.
  4644. // Need to uncomment the settings button in index.html.
  4645. // $('#settingsButton').css({visibility:"visible"});
  4646. }
  4647. // Show/hide desktop sharing button
  4648. showDesktopSharingButton();
  4649. },
  4650. /**
  4651. * Docks/undocks the toolbar.
  4652. *
  4653. * @param isDock indicates what operation to perform
  4654. */
  4655. dockToolbar: function (isDock) {
  4656. if (isDock) {
  4657. // First make sure the toolbar is shown.
  4658. if (!$('#header').is(':visible')) {
  4659. this.showToolbar();
  4660. }
  4661. // Then clear the time out, to dock the toolbar.
  4662. if (toolbarTimeoutObject) {
  4663. clearTimeout(toolbarTimeoutObject);
  4664. toolbarTimeoutObject = null;
  4665. }
  4666. }
  4667. else {
  4668. if (!$('#header').is(':visible')) {
  4669. this.showToolbar();
  4670. }
  4671. else {
  4672. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4673. }
  4674. }
  4675. },
  4676. showDesktopSharingButton: showDesktopSharingButton
  4677. };
  4678. module.exports = ToolbarToggler;
  4679. },{}],26:[function(require,module,exports){
  4680. var JitsiPopover = (function () {
  4681. /**
  4682. * Constructs new JitsiPopover and attaches it to the element
  4683. * @param element jquery selector
  4684. * @param options the options for the popover.
  4685. * @constructor
  4686. */
  4687. function JitsiPopover(element, options)
  4688. {
  4689. this.options = {
  4690. skin: "white",
  4691. content: ""
  4692. };
  4693. if(options)
  4694. {
  4695. if(options.skin)
  4696. this.options.skin = options.skin;
  4697. if(options.content)
  4698. this.options.content = options.content;
  4699. }
  4700. this.elementIsHovered = false;
  4701. this.popoverIsHovered = false;
  4702. this.popoverShown = false;
  4703. element.data("jitsi_popover", this);
  4704. this.element = element;
  4705. this.template = ' <div class="jitsipopover ' + this.options.skin +
  4706. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  4707. '<div class="jitsiPopupmenuPadding"></div></div>';
  4708. var self = this;
  4709. this.element.on("mouseenter", function () {
  4710. self.elementIsHovered = true;
  4711. self.show();
  4712. }).on("mouseleave", function () {
  4713. self.elementIsHovered = false;
  4714. setTimeout(function () {
  4715. self.hide();
  4716. }, 10);
  4717. });
  4718. }
  4719. /**
  4720. * Shows the popover
  4721. */
  4722. JitsiPopover.prototype.show = function () {
  4723. this.createPopover();
  4724. this.popoverShown = true;
  4725. };
  4726. /**
  4727. * Hides the popover
  4728. */
  4729. JitsiPopover.prototype.hide = function () {
  4730. if(!this.elementIsHovered && !this.popoverIsHovered && this.popoverShown)
  4731. {
  4732. this.forceHide();
  4733. }
  4734. };
  4735. /**
  4736. * Hides the popover
  4737. */
  4738. JitsiPopover.prototype.forceHide = function () {
  4739. $(".jitsipopover").remove();
  4740. this.popoverShown = false;
  4741. };
  4742. /**
  4743. * Creates the popover html
  4744. */
  4745. JitsiPopover.prototype.createPopover = function () {
  4746. $("body").append(this.template);
  4747. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  4748. var self = this;
  4749. $(".jitsipopover").on("mouseenter", function () {
  4750. self.popoverIsHovered = true;
  4751. }).on("mouseleave", function () {
  4752. self.popoverIsHovered = false;
  4753. self.hide();
  4754. });
  4755. this.refreshPosition();
  4756. };
  4757. /**
  4758. * Refreshes the position of the popover
  4759. */
  4760. JitsiPopover.prototype.refreshPosition = function () {
  4761. $(".jitsipopover").position({
  4762. my: "bottom",
  4763. at: "top",
  4764. collision: "fit",
  4765. of: this.element,
  4766. using: function (position, elements) {
  4767. var calcLeft = elements.target.left - elements.element.left + elements.target.width/2;
  4768. $(".jitsipopover").css({top: position.top, left: position.left, display: "table"});
  4769. $(".jitsipopover > .arrow").css({left: calcLeft});
  4770. $(".jitsipopover > .jitsiPopupmenuPadding").css({left: calcLeft - 50});
  4771. }
  4772. });
  4773. };
  4774. /**
  4775. * Updates the content of popover.
  4776. * @param content new content
  4777. */
  4778. JitsiPopover.prototype.updateContent = function (content) {
  4779. this.options.content = content;
  4780. if(!this.popoverShown)
  4781. return;
  4782. $(".jitsipopover").remove();
  4783. this.createPopover();
  4784. };
  4785. return JitsiPopover;
  4786. })();
  4787. module.exports = JitsiPopover;
  4788. },{}],27:[function(require,module,exports){
  4789. /* global $, jQuery */
  4790. var messageHandler = (function(my) {
  4791. /**
  4792. * Shows a message to the user.
  4793. *
  4794. * @param titleString the title of the message
  4795. * @param messageString the text of the message
  4796. */
  4797. my.openMessageDialog = function(titleKey, messageKey) {
  4798. var title = null;
  4799. if(titleKey)
  4800. {
  4801. title = APP.translation.generateTranslatonHTML(titleKey);
  4802. }
  4803. var message = APP.translation.generateTranslatonHTML(messageKey);
  4804. $.prompt(message,
  4805. {
  4806. title: title,
  4807. persistent: false
  4808. }
  4809. );
  4810. };
  4811. /**
  4812. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  4813. *
  4814. * @param titleString the title of the message
  4815. * @param msgString the text of the message
  4816. * @param persistent boolean value which determines whether the message is persistent or not
  4817. * @param leftButton the fist button's text
  4818. * @param submitFunction function to be called on submit
  4819. * @param loadedFunction function to be called after the prompt is fully loaded
  4820. * @param closeFunction function to be called after the prompt is closed
  4821. */
  4822. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  4823. persistent, leftButtonKey, submitFunction, loadedFunction,
  4824. closeFunction)
  4825. {
  4826. var leftButton = APP.translation.generateTranslatonHTML(leftButtonKey);
  4827. var buttons = {};
  4828. buttons.button1 = {title: leftButton, value: true};
  4829. var cancelButton = APP.translation.generateTranslatonHTML("dialog.Cancel");
  4830. buttons.button2 = {title: cancelButton, value: false};
  4831. var message = msgString, title = titleString;
  4832. if(titleKey)
  4833. {
  4834. title = APP.translation.generateTranslatonHTML(titleKey);
  4835. }
  4836. if(msgKey) {
  4837. message = APP.translation.generateTranslatonHTML(msgKey);
  4838. }
  4839. $.prompt(message, {
  4840. title: title,
  4841. persistent: false,
  4842. buttons: buttons,
  4843. defaultButton: 1,
  4844. loaded: loadedFunction,
  4845. submit: submitFunction,
  4846. close: closeFunction
  4847. });
  4848. };
  4849. /**
  4850. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  4851. *
  4852. * @param titleString the title of the message
  4853. * @param msgString the text of the message
  4854. * @param persistent boolean value which determines whether the message is persistent or not
  4855. * @param buttons object with the buttons. The keys must be the name of the button and value is the value
  4856. * that will be passed to submitFunction
  4857. * @param submitFunction function to be called on submit
  4858. * @param loadedFunction function to be called after the prompt is fully loaded
  4859. */
  4860. my.openDialog = function (titleString, msgString, persistent, buttons,
  4861. submitFunction, loadedFunction) {
  4862. var args = {
  4863. title: titleString,
  4864. persistent: persistent,
  4865. buttons: buttons,
  4866. defaultButton: 1,
  4867. loaded: loadedFunction,
  4868. submit: submitFunction
  4869. };
  4870. if (persistent) {
  4871. args.closeText = '';
  4872. }
  4873. return $.prompt(msgString, args);
  4874. };
  4875. /**
  4876. * Closes currently opened dialog.
  4877. */
  4878. my.closeDialog = function () {
  4879. $.prompt.close();
  4880. };
  4881. /**
  4882. * Shows a dialog with different states to the user.
  4883. *
  4884. * @param statesObject object containing all the states of the dialog
  4885. * @param loadedFunction function to be called after the prompt is fully loaded
  4886. * @param stateChangedFunction function to be called when the state of the dialog is changed
  4887. */
  4888. my.openDialogWithStates = function(statesObject, loadedFunction, stateChangedFunction) {
  4889. var myPrompt = $.prompt(statesObject);
  4890. myPrompt.on('impromptu:loaded', loadedFunction);
  4891. myPrompt.on('impromptu:statechanged', stateChangedFunction);
  4892. };
  4893. /**
  4894. * Opens new popup window for given <tt>url</tt> centered over current
  4895. * window.
  4896. *
  4897. * @param url the URL to be displayed in the popup window
  4898. * @param w the width of the popup window
  4899. * @param h the height of the popup window
  4900. * @param onPopupClosed optional callback function called when popup window
  4901. * has been closed.
  4902. *
  4903. * @returns popup window object if opened successfully or undefined
  4904. * in case we failed to open it(popup blocked)
  4905. */
  4906. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  4907. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  4908. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  4909. var popup = window.open(
  4910. url, '_blank',
  4911. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  4912. if (popup && onPopupClosed) {
  4913. var pollTimer = window.setInterval(function () {
  4914. if (popup.closed !== false) {
  4915. window.clearInterval(pollTimer);
  4916. onPopupClosed();
  4917. }
  4918. }, 200);
  4919. }
  4920. return popup;
  4921. };
  4922. /**
  4923. * Shows a dialog prompting the user to send an error report.
  4924. *
  4925. * @param titleString the title of the message
  4926. * @param msgString the text of the message
  4927. * @param error the error that is being reported
  4928. */
  4929. my.openReportDialog = function(titleKey, msgKey, error) {
  4930. my.openMessageDialog(titleKey, msgKey);
  4931. console.log(error);
  4932. //FIXME send the error to the server
  4933. };
  4934. /**
  4935. * Shows an error dialog to the user.
  4936. * @param title the title of the message
  4937. * @param message the text of the messafe
  4938. */
  4939. my.showError = function(titleKey, msgKey) {
  4940. if(!titleKey) {
  4941. titleKey = "dialog.oops";
  4942. }
  4943. if(!msgKey)
  4944. {
  4945. msgKey = "dialog.defaultError";
  4946. }
  4947. messageHandler.openMessageDialog(titleKey, msgKey);
  4948. };
  4949. my.notify = function(displayName, displayNameKey,
  4950. cls, messageKey, messageArguments) {
  4951. var displayNameSpan = '<span class="nickname" ';
  4952. if(displayName)
  4953. {
  4954. displayNameSpan += ">" + displayName;
  4955. }
  4956. else
  4957. {
  4958. displayNameSpan += "data-i18n='" + displayNameKey +
  4959. "'>" + APP.translation.translateString(displayNameKey);
  4960. }
  4961. displayNameSpan += "</span>";
  4962. toastr.info(
  4963. displayNameSpan + '<br>' +
  4964. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  4965. (messageArguments?
  4966. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  4967. : "") + ">" +
  4968. APP.translation.translateString(messageKey,
  4969. messageArguments) +
  4970. '</span>');
  4971. };
  4972. return my;
  4973. }(messageHandler || {}));
  4974. module.exports = messageHandler;
  4975. },{}],28:[function(require,module,exports){
  4976. var UIEvents = require("../../../service/UI/UIEvents");
  4977. var nickname = null;
  4978. var eventEmitter = null;
  4979. var NickanameHandler = {
  4980. init: function (emitter) {
  4981. eventEmitter = emitter;
  4982. var storedDisplayName = window.localStorage.displayname;
  4983. if (storedDisplayName) {
  4984. nickname = storedDisplayName;
  4985. }
  4986. },
  4987. setNickname: function (newNickname) {
  4988. if (!newNickname || nickname === newNickname)
  4989. return;
  4990. nickname = newNickname;
  4991. window.localStorage.displayname = nickname;
  4992. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  4993. },
  4994. getNickname: function () {
  4995. return nickname;
  4996. },
  4997. addListener: function (type, listener) {
  4998. eventEmitter.on(type, listener);
  4999. }
  5000. };
  5001. module.exports = NickanameHandler;
  5002. },{"../../../service/UI/UIEvents":83}],29:[function(require,module,exports){
  5003. /**
  5004. * Created by hristo on 12/22/14.
  5005. */
  5006. module.exports = {
  5007. /**
  5008. * Returns the available video width.
  5009. */
  5010. getAvailableVideoWidth: function () {
  5011. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5012. var rightPanelWidth
  5013. = PanelToggler.isVisible() ? PanelToggler.getPanelSize()[0] : 0;
  5014. return window.innerWidth - rightPanelWidth;
  5015. },
  5016. /**
  5017. * Changes the style class of the element given by id.
  5018. */
  5019. buttonClick: function(id, classname) {
  5020. $(id).toggleClass(classname); // add the class to the clicked element
  5021. },
  5022. /**
  5023. * Returns the text width for the given element.
  5024. *
  5025. * @param el the element
  5026. */
  5027. getTextWidth: function (el) {
  5028. return (el.clientWidth + 1);
  5029. },
  5030. /**
  5031. * Returns the text height for the given element.
  5032. *
  5033. * @param el the element
  5034. */
  5035. getTextHeight: function (el) {
  5036. return (el.clientHeight + 1);
  5037. },
  5038. /**
  5039. * Plays the sound given by id.
  5040. *
  5041. * @param id the identifier of the audio element.
  5042. */
  5043. playSoundNotification: function (id) {
  5044. document.getElementById(id).play();
  5045. },
  5046. /**
  5047. * Escapes the given text.
  5048. */
  5049. escapeHtml: function (unsafeText) {
  5050. return $('<div/>').text(unsafeText).html();
  5051. },
  5052. imageToGrayScale: function (canvas) {
  5053. var context = canvas.getContext('2d');
  5054. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  5055. var pixels = imgData.data;
  5056. for (var i = 0, n = pixels.length; i < n; i += 4) {
  5057. var grayscale
  5058. = pixels[i] * .3 + pixels[i+1] * .59 + pixels[i+2] * .11;
  5059. pixels[i ] = grayscale; // red
  5060. pixels[i+1] = grayscale; // green
  5061. pixels[i+2] = grayscale; // blue
  5062. // pixels[i+3] is alpha
  5063. }
  5064. // redraw the image in black & white
  5065. context.putImageData(imgData, 0, 0);
  5066. },
  5067. setTooltip: function (element, key, position) {
  5068. element.setAttribute("data-i18n", "[data-content]" + key);
  5069. element.setAttribute("data-toggle", "popover");
  5070. element.setAttribute("data-placement", position);
  5071. element.setAttribute("data-html", true);
  5072. element.setAttribute("data-container", "body");
  5073. }
  5074. };
  5075. },{"../side_pannels/SidePanelToggler":16}],30:[function(require,module,exports){
  5076. var JitsiPopover = require("../util/JitsiPopover");
  5077. /**
  5078. * Constructs new connection indicator.
  5079. * @param videoContainer the video container associated with the indicator.
  5080. * @constructor
  5081. */
  5082. function ConnectionIndicator(videoContainer, jid, VideoLayout)
  5083. {
  5084. this.videoContainer = videoContainer;
  5085. this.bandwidth = null;
  5086. this.packetLoss = null;
  5087. this.bitrate = null;
  5088. this.showMoreValue = false;
  5089. this.resolution = null;
  5090. this.transport = [];
  5091. this.popover = null;
  5092. this.jid = jid;
  5093. this.create();
  5094. this.videoLayout = VideoLayout;
  5095. }
  5096. /**
  5097. * Values for the connection quality
  5098. * @type {{98: string,
  5099. * 81: string,
  5100. * 64: string,
  5101. * 47: string,
  5102. * 30: string,
  5103. * 0: string}}
  5104. */
  5105. ConnectionIndicator.connectionQualityValues = {
  5106. 98: "18px", //full
  5107. 81: "15px",//4 bars
  5108. 64: "11px",//3 bars
  5109. 47: "7px",//2 bars
  5110. 30: "3px",//1 bar
  5111. 0: "0px"//empty
  5112. };
  5113. ConnectionIndicator.getIP = function(value)
  5114. {
  5115. return value.substring(0, value.lastIndexOf(":"));
  5116. };
  5117. ConnectionIndicator.getPort = function(value)
  5118. {
  5119. return value.substring(value.lastIndexOf(":") + 1, value.length);
  5120. };
  5121. ConnectionIndicator.getStringFromArray = function (array) {
  5122. var res = "";
  5123. for(var i = 0; i < array.length; i++)
  5124. {
  5125. res += (i === 0? "" : ", ") + array[i];
  5126. }
  5127. return res;
  5128. };
  5129. /**
  5130. * Generates the html content.
  5131. * @returns {string} the html content.
  5132. */
  5133. ConnectionIndicator.prototype.generateText = function () {
  5134. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  5135. var translate = APP.translation.translateString;
  5136. if(this.bitrate === null)
  5137. {
  5138. downloadBitrate = "N/A";
  5139. uploadBitrate = "N/A";
  5140. }
  5141. else
  5142. {
  5143. downloadBitrate =
  5144. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  5145. uploadBitrate =
  5146. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  5147. }
  5148. if(this.packetLoss === null)
  5149. {
  5150. packetLoss = "N/A";
  5151. }
  5152. else
  5153. {
  5154. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  5155. (this.packetLoss.download !== null? this.packetLoss.download : "N/A") +
  5156. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  5157. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") + "%";
  5158. }
  5159. var resolutionValue = null;
  5160. if(this.resolution && this.jid != null)
  5161. {
  5162. var keys = Object.keys(this.resolution);
  5163. if(keys.length == 1)
  5164. {
  5165. for(var ssrc in this.resolution)
  5166. {
  5167. resolutionValue = this.resolution[ssrc];
  5168. }
  5169. }
  5170. else if(keys.length > 1)
  5171. {
  5172. var displayedSsrc = APP.simulcast.getReceivingSSRC(this.jid);
  5173. resolutionValue = this.resolution[displayedSsrc];
  5174. }
  5175. }
  5176. if(this.jid === null)
  5177. {
  5178. resolution = "";
  5179. if(this.resolution === null || !Object.keys(this.resolution) ||
  5180. Object.keys(this.resolution).length === 0)
  5181. {
  5182. resolution = "N/A";
  5183. }
  5184. else
  5185. for(i in this.resolution)
  5186. {
  5187. resolutionValue = this.resolution[i];
  5188. if(resolutionValue)
  5189. {
  5190. if(resolutionValue.height &&
  5191. resolutionValue.width)
  5192. {
  5193. resolution += (resolution === ""? "" : ", ") +
  5194. resolutionValue.width + "x" +
  5195. resolutionValue.height;
  5196. }
  5197. }
  5198. }
  5199. }
  5200. else if(!resolutionValue ||
  5201. !resolutionValue.height ||
  5202. !resolutionValue.width)
  5203. {
  5204. resolution = "N/A";
  5205. }
  5206. else
  5207. {
  5208. resolution = resolutionValue.width + "x" + resolutionValue.height;
  5209. }
  5210. var result = "<table style='width:100%'>" +
  5211. "<tr>" +
  5212. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  5213. translate("connectionindicator.bitrate") + "</span></td>" +
  5214. "<td><span class='jitsipopover_green'>&darr;</span>" +
  5215. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  5216. uploadBitrate + "</td>" +
  5217. "</tr><tr>" +
  5218. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  5219. translate("connectionindicator.packetloss") + "</span></td>" +
  5220. "<td>" + packetLoss + "</td>" +
  5221. "</tr><tr>" +
  5222. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  5223. translate("connectionindicator.resolution") + "</span></td>" +
  5224. "<td>" + resolution + "</td></tr></table>";
  5225. if(this.videoContainer.id == "localVideoContainer") {
  5226. result += "<div class=\"jitsipopover_showmore\" " +
  5227. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  5228. this.videoContainer.id + "')\" data-i18n='connectionindicator." +
  5229. (this.showMoreValue ? "less" : "more") + "'>" +
  5230. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  5231. "</div><br />";
  5232. }
  5233. if(this.showMoreValue)
  5234. {
  5235. var downloadBandwidth, uploadBandwidth, transport;
  5236. if(this.bandwidth === null)
  5237. {
  5238. downloadBandwidth = "N/A";
  5239. uploadBandwidth = "N/A";
  5240. }
  5241. else
  5242. {
  5243. downloadBandwidth = this.bandwidth.download?
  5244. this.bandwidth.download + " Kbps" :
  5245. "N/A";
  5246. uploadBandwidth = this.bandwidth.upload?
  5247. this.bandwidth.upload + " Kbps" :
  5248. "N/A";
  5249. }
  5250. if(!this.transport || this.transport.length === 0)
  5251. {
  5252. transport = "<tr>" +
  5253. "<td><span class='jitsipopover_blue' " +
  5254. "data-i18n='connectionindicator.address'>" +
  5255. translate("connectionindicator.address") + "</span></td>" +
  5256. "<td> N/A</td></tr>";
  5257. }
  5258. else
  5259. {
  5260. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  5261. for(i = 0; i < this.transport.length; i++)
  5262. {
  5263. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  5264. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  5265. var localIP =
  5266. ConnectionIndicator.getIP(this.transport[i].localip);
  5267. var localPort =
  5268. ConnectionIndicator.getPort(this.transport[i].localip);
  5269. if(data.remoteIP.indexOf(ip) == -1)
  5270. {
  5271. data.remoteIP.push(ip);
  5272. }
  5273. if(data.remotePort.indexOf(port) == -1)
  5274. {
  5275. data.remotePort.push(port);
  5276. }
  5277. if(data.localIP.indexOf(localIP) == -1)
  5278. {
  5279. data.localIP.push(localIP);
  5280. }
  5281. if(data.localPort.indexOf(localPort) == -1)
  5282. {
  5283. data.localPort.push(localPort);
  5284. }
  5285. }
  5286. var local_address_key = "connectionindicator." +
  5287. (data.localIP.length > 1? "localaddresses" : "localaddress");
  5288. var remote_address_key = "connectionindicator." +
  5289. (data.remoteIP.length > 1? "remoteaddresses" : "remoteaddress");
  5290. var localTransport =
  5291. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5292. local_address_key +"'>" +
  5293. translate(local_address_key) + "</span></td><td> " +
  5294. ConnectionIndicator.getStringFromArray(data.localIP) +
  5295. "</td></tr>";
  5296. transport =
  5297. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5298. remote_address_key + "'>" +
  5299. translate(remote_address_key) + "</span></td><td> " +
  5300. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  5301. "</td></tr>";
  5302. var key_remote = "connectionindicator.",
  5303. key_local = "connectionindicator.";
  5304. if(this.transport.length > 1)
  5305. {
  5306. key_remote += "remoteports";
  5307. key_local += "localports";
  5308. }
  5309. else
  5310. {
  5311. key_remote += "remoteport";
  5312. key_local += "localport";
  5313. }
  5314. transport += "<tr>" +
  5315. "<td>" +
  5316. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  5317. "'>" +
  5318. translate(key_remote) + "</span></td><td>";
  5319. localTransport += "<tr>" +
  5320. "<td>" +
  5321. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  5322. "'>" +
  5323. translate(key_local) + "</span></td><td>";
  5324. transport +=
  5325. ConnectionIndicator.getStringFromArray(data.remotePort);
  5326. localTransport +=
  5327. ConnectionIndicator.getStringFromArray(data.localPort);
  5328. transport += "</td></tr>";
  5329. transport += localTransport + "</td></tr>";
  5330. transport +="<tr>" +
  5331. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  5332. translate("connectionindicator.transport") + "</span></td>" +
  5333. "<td>" + this.transport[0].type + "</td></tr>";
  5334. }
  5335. result += "<table style='width:100%'>" +
  5336. "<tr>" +
  5337. "<td>" +
  5338. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  5339. translate("connectionindicator.bandwidth") + "</span>" +
  5340. "</td><td>" +
  5341. "<span class='jitsipopover_green'>&darr;</span>" +
  5342. downloadBandwidth +
  5343. " <span class='jitsipopover_orange'>&uarr;</span>" +
  5344. uploadBandwidth + "</td></tr>";
  5345. result += transport + "</table>";
  5346. }
  5347. return result;
  5348. };
  5349. /**
  5350. * Shows or hide the additional information.
  5351. */
  5352. ConnectionIndicator.prototype.showMore = function () {
  5353. this.showMoreValue = !this.showMoreValue;
  5354. this.updatePopoverData();
  5355. };
  5356. function createIcon(classes)
  5357. {
  5358. var icon = document.createElement("span");
  5359. for(var i in classes)
  5360. {
  5361. icon.classList.add(classes[i]);
  5362. }
  5363. icon.appendChild(
  5364. document.createElement("i")).classList.add("icon-connection");
  5365. return icon;
  5366. }
  5367. /**
  5368. * Creates the indicator
  5369. */
  5370. ConnectionIndicator.prototype.create = function () {
  5371. this.connectionIndicatorContainer = document.createElement("div");
  5372. this.connectionIndicatorContainer.className = "connectionindicator";
  5373. this.connectionIndicatorContainer.style.display = "none";
  5374. this.videoContainer.appendChild(this.connectionIndicatorContainer);
  5375. this.popover = new JitsiPopover(
  5376. $("#" + this.videoContainer.id + " > .connectionindicator"),
  5377. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  5378. APP.translation.translateString("connectionindicator.na") + "</div>",
  5379. skin: "black"});
  5380. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  5381. createIcon(["connection", "connection_empty"]));
  5382. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  5383. createIcon(["connection", "connection_full"]));
  5384. };
  5385. /**
  5386. * Removes the indicator
  5387. */
  5388. ConnectionIndicator.prototype.remove = function()
  5389. {
  5390. this.connectionIndicatorContainer.remove();
  5391. this.popover.forceHide();
  5392. };
  5393. /**
  5394. * Updates the data of the indicator
  5395. * @param percent the percent of connection quality
  5396. * @param object the statistics data.
  5397. */
  5398. ConnectionIndicator.prototype.updateConnectionQuality =
  5399. function (percent, object) {
  5400. if(percent === null)
  5401. {
  5402. this.connectionIndicatorContainer.style.display = "none";
  5403. this.popover.forceHide();
  5404. return;
  5405. }
  5406. else
  5407. {
  5408. if(this.connectionIndicatorContainer.style.display == "none") {
  5409. this.connectionIndicatorContainer.style.display = "block";
  5410. this.videoLayout.updateMutePosition(this.videoContainer.id);
  5411. }
  5412. }
  5413. this.bandwidth = object.bandwidth;
  5414. this.bitrate = object.bitrate;
  5415. this.packetLoss = object.packetLoss;
  5416. this.transport = object.transport;
  5417. if(object.resolution)
  5418. {
  5419. this.resolution = object.resolution;
  5420. }
  5421. for(var quality in ConnectionIndicator.connectionQualityValues)
  5422. {
  5423. if(percent >= quality)
  5424. {
  5425. this.fullIcon.style.width =
  5426. ConnectionIndicator.connectionQualityValues[quality];
  5427. }
  5428. }
  5429. this.updatePopoverData();
  5430. };
  5431. /**
  5432. * Updates the resolution
  5433. * @param resolution the new resolution
  5434. */
  5435. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  5436. this.resolution = resolution;
  5437. this.updatePopoverData();
  5438. };
  5439. /**
  5440. * Updates the content of the popover
  5441. */
  5442. ConnectionIndicator.prototype.updatePopoverData = function () {
  5443. this.popover.updateContent(
  5444. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  5445. APP.translation.translateElement($(".connection_info"));
  5446. };
  5447. /**
  5448. * Hides the popover
  5449. */
  5450. ConnectionIndicator.prototype.hide = function () {
  5451. this.popover.forceHide();
  5452. };
  5453. /**
  5454. * Hides the indicator
  5455. */
  5456. ConnectionIndicator.prototype.hideIndicator = function () {
  5457. this.connectionIndicatorContainer.style.display = "none";
  5458. if(this.popover)
  5459. this.popover.forceHide();
  5460. };
  5461. module.exports = ConnectionIndicator;
  5462. },{"../util/JitsiPopover":26}],31:[function(require,module,exports){
  5463. var AudioLevels = require("../audio_levels/AudioLevels");
  5464. var Avatar = require("../avatar/Avatar");
  5465. var Chat = require("../side_pannels/chat/Chat");
  5466. var ContactList = require("../side_pannels/contactlist/ContactList");
  5467. var UIUtil = require("../util/UIUtil");
  5468. var ConnectionIndicator = require("./ConnectionIndicator");
  5469. var NicknameHandler = require("../util/NicknameHandler");
  5470. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  5471. var UIEvents = require("../../../service/UI/UIEvents");
  5472. var currentDominantSpeaker = null;
  5473. var lastNCount = config.channelLastN;
  5474. var localLastNCount = config.channelLastN;
  5475. var localLastNSet = [];
  5476. var lastNEndpointsCache = [];
  5477. var lastNPickupJid = null;
  5478. var largeVideoState = {
  5479. updateInProgress: false,
  5480. newSrc: ''
  5481. };
  5482. var eventEmitter = null;
  5483. /**
  5484. * Currently focused video "src"(displayed in large video).
  5485. * @type {String}
  5486. */
  5487. var focusedVideoInfo = null;
  5488. /**
  5489. * Indicates if we have muted our audio before the conference has started.
  5490. * @type {boolean}
  5491. */
  5492. var preMuted = false;
  5493. var mutedAudios = {};
  5494. var flipXLocalVideo = true;
  5495. var currentVideoWidth = null;
  5496. var currentVideoHeight = null;
  5497. var localVideoSrc = null;
  5498. function videoactive( videoelem) {
  5499. if (videoelem.attr('id').indexOf('mixedmslabel') === -1) {
  5500. // ignore mixedmslabela0 and v0
  5501. videoelem.show();
  5502. VideoLayout.resizeThumbnails();
  5503. var videoParent = videoelem.parent();
  5504. var parentResourceJid = null;
  5505. if (videoParent)
  5506. parentResourceJid
  5507. = VideoLayout.getPeerContainerResourceJid(videoParent[0]);
  5508. // Update the large video to the last added video only if there's no
  5509. // current dominant, focused speaker or prezi playing or update it to
  5510. // the current dominant speaker.
  5511. if ((!focusedVideoInfo &&
  5512. !VideoLayout.getDominantSpeakerResourceJid() &&
  5513. !require("../prezi/Prezi").isPresentationVisible()) ||
  5514. (parentResourceJid &&
  5515. VideoLayout.getDominantSpeakerResourceJid() === parentResourceJid)) {
  5516. VideoLayout.updateLargeVideo(
  5517. APP.RTC.getVideoSrc(videoelem[0]),
  5518. 1,
  5519. parentResourceJid);
  5520. }
  5521. VideoLayout.showModeratorIndicator();
  5522. }
  5523. }
  5524. function waitForRemoteVideo(selector, ssrc, stream, jid) {
  5525. // XXX(gp) so, every call to this function is *always* preceded by a call
  5526. // to the RTC.attachMediaStream() function but that call is *not* followed
  5527. // by an update to the videoSrcToSsrc map!
  5528. //
  5529. // The above way of doing things results in video SRCs that don't correspond
  5530. // to any SSRC for a short period of time (to be more precise, for as long
  5531. // the waitForRemoteVideo takes to complete). This causes problems (see
  5532. // bellow).
  5533. //
  5534. // I'm wondering why we need to do that; i.e. why call RTC.attachMediaStream()
  5535. // a second time in here and only then update the videoSrcToSsrc map? Why
  5536. // not simply update the videoSrcToSsrc map when the RTC.attachMediaStream()
  5537. // is called the first time? I actually do that in the lastN changed event
  5538. // handler because the "orphan" video SRC is causing troubles there. The
  5539. // purpose of this method would then be to fire the "videoactive.jingle".
  5540. //
  5541. // Food for though I guess :-)
  5542. if (selector.removed || !selector.parent().is(":visible")) {
  5543. console.warn("Media removed before had started", selector);
  5544. return;
  5545. }
  5546. if (stream.id === 'mixedmslabel') return;
  5547. if (selector[0].currentTime > 0) {
  5548. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  5549. APP.RTC.attachMediaStream(selector, videoStream); // FIXME: why do i have to do this for FF?
  5550. videoactive(selector);
  5551. } else {
  5552. setTimeout(function () {
  5553. waitForRemoteVideo(selector, ssrc, stream, jid);
  5554. }, 250);
  5555. }
  5556. }
  5557. /**
  5558. * Returns an array of the video horizontal and vertical indents,
  5559. * so that if fits its parent.
  5560. *
  5561. * @return an array with 2 elements, the horizontal indent and the vertical
  5562. * indent
  5563. */
  5564. function getCameraVideoPosition(videoWidth,
  5565. videoHeight,
  5566. videoSpaceWidth,
  5567. videoSpaceHeight) {
  5568. // Parent height isn't completely calculated when we position the video in
  5569. // full screen mode and this is why we use the screen height in this case.
  5570. // Need to think it further at some point and implement it properly.
  5571. var isFullScreen = document.fullScreen ||
  5572. document.mozFullScreen ||
  5573. document.webkitIsFullScreen;
  5574. if (isFullScreen)
  5575. videoSpaceHeight = window.innerHeight;
  5576. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  5577. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  5578. return [horizontalIndent, verticalIndent];
  5579. }
  5580. /**
  5581. * Returns an array of the video horizontal and vertical indents.
  5582. * Centers horizontally and top aligns vertically.
  5583. *
  5584. * @return an array with 2 elements, the horizontal indent and the vertical
  5585. * indent
  5586. */
  5587. function getDesktopVideoPosition(videoWidth,
  5588. videoHeight,
  5589. videoSpaceWidth,
  5590. videoSpaceHeight) {
  5591. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  5592. var verticalIndent = 0;// Top aligned
  5593. return [horizontalIndent, verticalIndent];
  5594. }
  5595. /**
  5596. * Returns an array of the video dimensions, so that it covers the screen.
  5597. * It leaves no empty areas, but some parts of the video might not be visible.
  5598. *
  5599. * @return an array with 2 elements, the video width and the video height
  5600. */
  5601. function getCameraVideoSize(videoWidth,
  5602. videoHeight,
  5603. videoSpaceWidth,
  5604. videoSpaceHeight) {
  5605. if (!videoWidth)
  5606. videoWidth = currentVideoWidth;
  5607. if (!videoHeight)
  5608. videoHeight = currentVideoHeight;
  5609. var aspectRatio = videoWidth / videoHeight;
  5610. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  5611. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  5612. if (availableWidth / aspectRatio < videoSpaceHeight) {
  5613. availableHeight = videoSpaceHeight;
  5614. availableWidth = availableHeight * aspectRatio;
  5615. }
  5616. if (availableHeight * aspectRatio < videoSpaceWidth) {
  5617. availableWidth = videoSpaceWidth;
  5618. availableHeight = availableWidth / aspectRatio;
  5619. }
  5620. return [availableWidth, availableHeight];
  5621. }
  5622. /**
  5623. * Sets the display name for the given video span id.
  5624. */
  5625. function setDisplayName(videoSpanId, displayName) {
  5626. var nameSpan = $('#' + videoSpanId + '>span.displayname');
  5627. var defaultLocalDisplayName = interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME;
  5628. // If we already have a display name for this video.
  5629. if (nameSpan.length > 0) {
  5630. var nameSpanElement = nameSpan.get(0);
  5631. if (nameSpanElement.id === 'localDisplayName' &&
  5632. $('#localDisplayName').text() !== displayName) {
  5633. if (displayName && displayName.length > 0)
  5634. $('#localDisplayName').html(displayName + ' (me)');
  5635. else
  5636. $('#localDisplayName').text(defaultLocalDisplayName);
  5637. } else {
  5638. if (displayName && displayName.length > 0)
  5639. $('#' + videoSpanId + '_name').html(displayName);
  5640. else
  5641. $('#' + videoSpanId + '_name').text(interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  5642. }
  5643. } else {
  5644. var editButton = null;
  5645. nameSpan = document.createElement('span');
  5646. nameSpan.className = 'displayname';
  5647. $('#' + videoSpanId)[0].appendChild(nameSpan);
  5648. if (videoSpanId === 'localVideoContainer') {
  5649. editButton = createEditDisplayNameButton();
  5650. nameSpan.innerText = defaultLocalDisplayName;
  5651. }
  5652. else {
  5653. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  5654. }
  5655. if (displayName && displayName.length > 0) {
  5656. nameSpan.innerText = displayName;
  5657. }
  5658. if (!editButton) {
  5659. nameSpan.id = videoSpanId + '_name';
  5660. } else {
  5661. nameSpan.id = 'localDisplayName';
  5662. $('#' + videoSpanId)[0].appendChild(editButton);
  5663. //translates popover of edit button
  5664. APP.translation.translateElement($("a.displayname"));
  5665. var editableText = document.createElement('input');
  5666. editableText.className = 'displayname';
  5667. editableText.type = 'text';
  5668. editableText.id = 'editDisplayName';
  5669. if (displayName && displayName.length) {
  5670. editableText.value
  5671. = displayName.substring(0, displayName.indexOf(' (me)'));
  5672. }
  5673. editableText.setAttribute('style', 'display:none;');
  5674. editableText.setAttribute('placeholder', 'ex. Jane Pink');
  5675. $('#' + videoSpanId)[0].appendChild(editableText);
  5676. $('#localVideoContainer .displayname')
  5677. .bind("click", function (e) {
  5678. e.preventDefault();
  5679. e.stopPropagation();
  5680. $('#localDisplayName').hide();
  5681. $('#editDisplayName').show();
  5682. $('#editDisplayName').focus();
  5683. $('#editDisplayName').select();
  5684. $('#editDisplayName').one("focusout", function (e) {
  5685. VideoLayout.inputDisplayNameHandler(this.value);
  5686. });
  5687. $('#editDisplayName').on('keydown', function (e) {
  5688. if (e.keyCode === 13) {
  5689. e.preventDefault();
  5690. VideoLayout.inputDisplayNameHandler(this.value);
  5691. }
  5692. });
  5693. });
  5694. }
  5695. }
  5696. }
  5697. /**
  5698. * Gets the selector of video thumbnail container for the user identified by
  5699. * given <tt>userJid</tt>
  5700. * @param resourceJid user's Jid for whom we want to get the video container.
  5701. */
  5702. function getParticipantContainer(resourceJid)
  5703. {
  5704. if (!resourceJid)
  5705. return null;
  5706. if (resourceJid === APP.xmpp.myResource())
  5707. return $("#localVideoContainer");
  5708. else
  5709. return $("#participant_" + resourceJid);
  5710. }
  5711. /**
  5712. * Sets the size and position of the given video element.
  5713. *
  5714. * @param video the video element to position
  5715. * @param width the desired video width
  5716. * @param height the desired video height
  5717. * @param horizontalIndent the left and right indent
  5718. * @param verticalIndent the top and bottom indent
  5719. */
  5720. function positionVideo(video,
  5721. width,
  5722. height,
  5723. horizontalIndent,
  5724. verticalIndent) {
  5725. video.width(width);
  5726. video.height(height);
  5727. video.css({ top: verticalIndent + 'px',
  5728. bottom: verticalIndent + 'px',
  5729. left: horizontalIndent + 'px',
  5730. right: horizontalIndent + 'px'});
  5731. }
  5732. /**
  5733. * Adds the remote video menu element for the given <tt>jid</tt> in the
  5734. * given <tt>parentElement</tt>.
  5735. *
  5736. * @param jid the jid indicating the video for which we're adding a menu.
  5737. * @param parentElement the parent element where this menu will be added
  5738. */
  5739. function addRemoteVideoMenu(jid, parentElement) {
  5740. var spanElement = document.createElement('span');
  5741. spanElement.className = 'remotevideomenu';
  5742. parentElement.appendChild(spanElement);
  5743. var menuElement = document.createElement('i');
  5744. menuElement.className = 'fa fa-angle-down';
  5745. menuElement.title = 'Remote user controls';
  5746. spanElement.appendChild(menuElement);
  5747. // <ul class="popupmenu">
  5748. // <li><a href="#">Mute</a></li>
  5749. // <li><a href="#">Eject</a></li>
  5750. // </ul>
  5751. var popupmenuElement = document.createElement('ul');
  5752. popupmenuElement.className = 'popupmenu';
  5753. popupmenuElement.id
  5754. = 'remote_popupmenu_' + Strophe.getResourceFromJid(jid);
  5755. spanElement.appendChild(popupmenuElement);
  5756. var muteMenuItem = document.createElement('li');
  5757. var muteLinkItem = document.createElement('a');
  5758. var mutedIndicator = "<i style='float:left;' class='icon-mic-disabled'></i>";
  5759. if (!mutedAudios[jid]) {
  5760. muteLinkItem.innerHTML = mutedIndicator +
  5761. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  5762. muteLinkItem.className = 'mutelink';
  5763. }
  5764. else {
  5765. muteLinkItem.innerHTML = mutedIndicator +
  5766. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  5767. muteLinkItem.className = 'mutelink disabled';
  5768. }
  5769. muteLinkItem.onclick = function(){
  5770. if ($(this).attr('disabled') != undefined) {
  5771. event.preventDefault();
  5772. }
  5773. var isMute = mutedAudios[jid] == true;
  5774. APP.xmpp.setMute(jid, !isMute);
  5775. popupmenuElement.setAttribute('style', 'display:none;');
  5776. if (isMute) {
  5777. this.innerHTML = mutedIndicator +
  5778. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  5779. this.className = 'mutelink disabled';
  5780. }
  5781. else {
  5782. this.innerHTML = mutedIndicator +
  5783. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  5784. this.className = 'mutelink';
  5785. }
  5786. };
  5787. muteMenuItem.appendChild(muteLinkItem);
  5788. popupmenuElement.appendChild(muteMenuItem);
  5789. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  5790. var ejectMenuItem = document.createElement('li');
  5791. var ejectLinkItem = document.createElement('a');
  5792. var ejectText = "<div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.kick'>&nbsp;</div>";
  5793. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  5794. ejectLinkItem.onclick = function(){
  5795. APP.xmpp.eject(jid);
  5796. popupmenuElement.setAttribute('style', 'display:none;');
  5797. };
  5798. ejectMenuItem.appendChild(ejectLinkItem);
  5799. popupmenuElement.appendChild(ejectMenuItem);
  5800. var paddingSpan = document.createElement('span');
  5801. paddingSpan.className = 'popupmenuPadding';
  5802. popupmenuElement.appendChild(paddingSpan);
  5803. APP.translation.translateElement($("#" + popupmenuElement.id + " > li > a > div"));
  5804. }
  5805. /**
  5806. * Removes remote video menu element from video element identified by
  5807. * given <tt>videoElementId</tt>.
  5808. *
  5809. * @param videoElementId the id of local or remote video element.
  5810. */
  5811. function removeRemoteVideoMenu(videoElementId) {
  5812. var menuSpan = $('#' + videoElementId + '>span.remotevideomenu');
  5813. if (menuSpan.length) {
  5814. menuSpan.remove();
  5815. }
  5816. }
  5817. /**
  5818. * Updates the data for the indicator
  5819. * @param id the id of the indicator
  5820. * @param percent the percent for connection quality
  5821. * @param object the data
  5822. */
  5823. function updateStatsIndicator(id, percent, object) {
  5824. if(VideoLayout.connectionIndicators[id])
  5825. VideoLayout.connectionIndicators[id].updateConnectionQuality(percent, object);
  5826. }
  5827. /**
  5828. * Returns an array of the video dimensions, so that it keeps it's aspect
  5829. * ratio and fits available area with it's larger dimension. This method
  5830. * ensures that whole video will be visible and can leave empty areas.
  5831. *
  5832. * @return an array with 2 elements, the video width and the video height
  5833. */
  5834. function getDesktopVideoSize(videoWidth,
  5835. videoHeight,
  5836. videoSpaceWidth,
  5837. videoSpaceHeight) {
  5838. if (!videoWidth)
  5839. videoWidth = currentVideoWidth;
  5840. if (!videoHeight)
  5841. videoHeight = currentVideoHeight;
  5842. var aspectRatio = videoWidth / videoHeight;
  5843. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  5844. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  5845. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  5846. if (availableWidth / aspectRatio >= videoSpaceHeight)
  5847. {
  5848. availableHeight = videoSpaceHeight;
  5849. availableWidth = availableHeight * aspectRatio;
  5850. }
  5851. if (availableHeight * aspectRatio >= videoSpaceWidth)
  5852. {
  5853. availableWidth = videoSpaceWidth;
  5854. availableHeight = availableWidth / aspectRatio;
  5855. }
  5856. return [availableWidth, availableHeight];
  5857. }
  5858. /**
  5859. * Creates the edit display name button.
  5860. *
  5861. * @returns the edit button
  5862. */
  5863. function createEditDisplayNameButton() {
  5864. var editButton = document.createElement('a');
  5865. editButton.className = 'displayname';
  5866. UIUtil.setTooltip(editButton,
  5867. "videothumbnail.editnickname",
  5868. "top");
  5869. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  5870. return editButton;
  5871. }
  5872. /**
  5873. * Creates the element indicating the moderator(owner) of the conference.
  5874. *
  5875. * @param parentElement the parent element where the owner indicator will
  5876. * be added
  5877. */
  5878. function createModeratorIndicatorElement(parentElement) {
  5879. var moderatorIndicator = document.createElement('i');
  5880. moderatorIndicator.className = 'fa fa-star';
  5881. parentElement.appendChild(moderatorIndicator);
  5882. UIUtil.setTooltip(parentElement,
  5883. "videothumbnail.moderator",
  5884. "top");
  5885. }
  5886. var VideoLayout = (function (my) {
  5887. my.connectionIndicators = {};
  5888. // By default we use camera
  5889. my.getVideoSize = getCameraVideoSize;
  5890. my.getVideoPosition = getCameraVideoPosition;
  5891. my.init = function (emitter) {
  5892. // Listen for large video size updates
  5893. document.getElementById('largeVideo')
  5894. .addEventListener('loadedmetadata', function (e) {
  5895. currentVideoWidth = this.videoWidth;
  5896. currentVideoHeight = this.videoHeight;
  5897. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  5898. });
  5899. eventEmitter = emitter;
  5900. };
  5901. my.isInLastN = function(resource) {
  5902. return lastNCount < 0 // lastN is disabled, return true
  5903. || (lastNCount > 0 && lastNEndpointsCache.length == 0) // lastNEndpoints cache not built yet, return true
  5904. || (lastNEndpointsCache && lastNEndpointsCache.indexOf(resource) !== -1);
  5905. };
  5906. my.changeLocalStream = function (stream) {
  5907. VideoLayout.changeLocalVideo(stream);
  5908. };
  5909. my.changeLocalAudio = function(stream) {
  5910. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  5911. document.getElementById('localAudio').autoplay = true;
  5912. document.getElementById('localAudio').volume = 0;
  5913. if (preMuted) {
  5914. if(!APP.UI.setAudioMuted(true))
  5915. {
  5916. preMuted = mute;
  5917. }
  5918. preMuted = false;
  5919. }
  5920. };
  5921. my.changeLocalVideo = function(stream) {
  5922. var flipX = true;
  5923. if(stream.videoType == "screen")
  5924. flipX = false;
  5925. var localVideo = document.createElement('video');
  5926. localVideo.id = 'localVideo_' +
  5927. APP.RTC.getStreamID(stream.getOriginalStream());
  5928. localVideo.autoplay = true;
  5929. localVideo.volume = 0; // is it required if audio is separated ?
  5930. localVideo.oncontextmenu = function () { return false; };
  5931. var localVideoContainer = document.getElementById('localVideoWrapper');
  5932. localVideoContainer.appendChild(localVideo);
  5933. // Set default display name.
  5934. setDisplayName('localVideoContainer');
  5935. if(!VideoLayout.connectionIndicators["localVideoContainer"]) {
  5936. VideoLayout.connectionIndicators["localVideoContainer"]
  5937. = new ConnectionIndicator($("#localVideoContainer")[0], null, VideoLayout);
  5938. }
  5939. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  5940. var localVideoSelector = $('#' + localVideo.id);
  5941. function localVideoClick(event) {
  5942. event.stopPropagation();
  5943. VideoLayout.handleVideoThumbClicked(
  5944. APP.RTC.getVideoSrc(localVideo),
  5945. false,
  5946. APP.xmpp.myResource());
  5947. }
  5948. // Add click handler to both video and video wrapper elements in case
  5949. // there's no video.
  5950. localVideoSelector.click(localVideoClick);
  5951. $('#localVideoContainer').click(localVideoClick);
  5952. // Add hover handler
  5953. $('#localVideoContainer').hover(
  5954. function() {
  5955. VideoLayout.showDisplayName('localVideoContainer', true);
  5956. },
  5957. function() {
  5958. if (!VideoLayout.isLargeVideoVisible()
  5959. || APP.RTC.getVideoSrc(localVideo) !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  5960. VideoLayout.showDisplayName('localVideoContainer', false);
  5961. }
  5962. );
  5963. // Add stream ended handler
  5964. stream.getOriginalStream().onended = function () {
  5965. localVideoContainer.removeChild(localVideo);
  5966. VideoLayout.updateRemovedVideo(APP.RTC.getVideoSrc(localVideo));
  5967. };
  5968. // Flip video x axis if needed
  5969. flipXLocalVideo = flipX;
  5970. if (flipX) {
  5971. localVideoSelector.addClass("flipVideoX");
  5972. }
  5973. // Attach WebRTC stream
  5974. var videoStream = APP.simulcast.getLocalVideoStream();
  5975. APP.RTC.attachMediaStream(localVideoSelector, videoStream);
  5976. localVideoSrc = APP.RTC.getVideoSrc(localVideo);
  5977. var myResourceJid = APP.xmpp.myResource();
  5978. VideoLayout.updateLargeVideo(localVideoSrc, 0,
  5979. myResourceJid);
  5980. };
  5981. /**
  5982. * Checks if removed video is currently displayed and tries to display
  5983. * another one instead.
  5984. * @param removedVideoSrc src stream identifier of the video.
  5985. */
  5986. my.updateRemovedVideo = function(removedVideoSrc) {
  5987. if (removedVideoSrc === APP.RTC.getVideoSrc($('#largeVideo')[0])) {
  5988. // this is currently displayed as large
  5989. // pick the last visible video in the row
  5990. // if nobody else is left, this picks the local video
  5991. var pick
  5992. = $('#remoteVideos>span[id!="mixedstream"]:visible:last>video')
  5993. .get(0);
  5994. if (!pick) {
  5995. console.info("Last visible video no longer exists");
  5996. pick = $('#remoteVideos>span[id!="mixedstream"]>video').get(0);
  5997. if (!pick || !APP.RTC.getVideoSrc(pick)) {
  5998. // Try local video
  5999. console.info("Fallback to local video...");
  6000. pick = $('#remoteVideos>span>span>video').get(0);
  6001. }
  6002. }
  6003. // mute if localvideo
  6004. if (pick) {
  6005. var container = pick.parentNode;
  6006. var jid = null;
  6007. if(container)
  6008. {
  6009. if(container.id == "localVideoWrapper")
  6010. {
  6011. jid = APP.xmpp.myResource();
  6012. }
  6013. else
  6014. {
  6015. jid = VideoLayout.getPeerContainerResourceJid(container);
  6016. }
  6017. }
  6018. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(pick), pick.volume, jid);
  6019. } else {
  6020. console.warn("Failed to elect large video");
  6021. }
  6022. }
  6023. };
  6024. my.onRemoteStreamAdded = function (stream) {
  6025. var container;
  6026. var remotes = document.getElementById('remoteVideos');
  6027. if (stream.peerjid) {
  6028. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  6029. container = document.getElementById(
  6030. 'participant_' + Strophe.getResourceFromJid(stream.peerjid));
  6031. } else {
  6032. var id = stream.getOriginalStream().id;
  6033. if (id !== 'mixedmslabel'
  6034. // FIXME: default stream is added always with new focus
  6035. // (to be investigated)
  6036. && id !== 'default') {
  6037. console.error('can not associate stream',
  6038. id,
  6039. 'with a participant');
  6040. // We don't want to add it here since it will cause troubles
  6041. return;
  6042. }
  6043. // FIXME: for the mixed ms we dont need a video -- currently
  6044. container = document.createElement('span');
  6045. container.id = 'mixedstream';
  6046. container.className = 'videocontainer';
  6047. remotes.appendChild(container);
  6048. UIUtil.playSoundNotification('userJoined');
  6049. }
  6050. if (container) {
  6051. VideoLayout.addRemoteStreamElement( container,
  6052. stream.sid,
  6053. stream.getOriginalStream(),
  6054. stream.peerjid,
  6055. stream.ssrc);
  6056. }
  6057. }
  6058. my.getLargeVideoState = function () {
  6059. return largeVideoState;
  6060. };
  6061. /**
  6062. * Updates the large video with the given new video source.
  6063. */
  6064. my.updateLargeVideo = function(newSrc, vol, resourceJid) {
  6065. console.log('hover in', newSrc);
  6066. if (APP.RTC.getVideoSrc($('#largeVideo')[0]) !== newSrc) {
  6067. $('#activeSpeaker').css('visibility', 'hidden');
  6068. // Due to the simulcast the localVideoSrc may have changed when the
  6069. // fadeOut event triggers. In that case the getJidFromVideoSrc and
  6070. // isVideoSrcDesktop methods will not function correctly.
  6071. //
  6072. // Also, again due to the simulcast, the updateLargeVideo method can
  6073. // be called multiple times almost simultaneously. Therefore, we
  6074. // store the state here and update only once.
  6075. largeVideoState.newSrc = newSrc;
  6076. largeVideoState.isVisible = $('#largeVideo').is(':visible');
  6077. largeVideoState.isDesktop = APP.RTC.isVideoSrcDesktop(resourceJid);
  6078. if(largeVideoState.userResourceJid) {
  6079. largeVideoState.oldResourceJid = largeVideoState.userResourceJid;
  6080. } else {
  6081. largeVideoState.oldResourceJid = null;
  6082. }
  6083. largeVideoState.userResourceJid = resourceJid;
  6084. // Screen stream is already rotated
  6085. largeVideoState.flipX = (newSrc === localVideoSrc) && flipXLocalVideo;
  6086. var userChanged = false;
  6087. if (largeVideoState.oldResourceJid !== largeVideoState.userResourceJid) {
  6088. userChanged = true;
  6089. // we want the notification to trigger even if userJid is undefined,
  6090. // or null.
  6091. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT,
  6092. largeVideoState.userResourceJid);
  6093. }
  6094. if (!largeVideoState.updateInProgress) {
  6095. largeVideoState.updateInProgress = true;
  6096. var doUpdate = function () {
  6097. Avatar.updateActiveSpeakerAvatarSrc(
  6098. APP.xmpp.findJidFromResource(
  6099. largeVideoState.userResourceJid));
  6100. if (!userChanged && largeVideoState.preload &&
  6101. largeVideoState.preload !== null &&
  6102. APP.RTC.getVideoSrc($(largeVideoState.preload)[0]) === newSrc)
  6103. {
  6104. console.info('Switching to preloaded video');
  6105. var attributes = $('#largeVideo').prop("attributes");
  6106. // loop through largeVideo attributes and apply them on
  6107. // preload.
  6108. $.each(attributes, function () {
  6109. if (this.name !== 'id' && this.name !== 'src') {
  6110. largeVideoState.preload.attr(this.name, this.value);
  6111. }
  6112. });
  6113. largeVideoState.preload.appendTo($('#largeVideoContainer'));
  6114. $('#largeVideo').attr('id', 'previousLargeVideo');
  6115. largeVideoState.preload.attr('id', 'largeVideo');
  6116. $('#previousLargeVideo').remove();
  6117. largeVideoState.preload.on('loadedmetadata', function (e) {
  6118. currentVideoWidth = this.videoWidth;
  6119. currentVideoHeight = this.videoHeight;
  6120. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  6121. });
  6122. largeVideoState.preload = null;
  6123. largeVideoState.preload_ssrc = 0;
  6124. } else {
  6125. APP.RTC.setVideoSrc($('#largeVideo')[0], largeVideoState.newSrc);
  6126. }
  6127. var videoTransform = document.getElementById('largeVideo')
  6128. .style.webkitTransform;
  6129. if (largeVideoState.flipX && videoTransform !== 'scaleX(-1)') {
  6130. document.getElementById('largeVideo').style.webkitTransform
  6131. = "scaleX(-1)";
  6132. }
  6133. else if (!largeVideoState.flipX && videoTransform === 'scaleX(-1)') {
  6134. document.getElementById('largeVideo').style.webkitTransform
  6135. = "none";
  6136. }
  6137. // Change the way we'll be measuring and positioning large video
  6138. VideoLayout.getVideoSize = largeVideoState.isDesktop
  6139. ? getDesktopVideoSize
  6140. : getCameraVideoSize;
  6141. VideoLayout.getVideoPosition = largeVideoState.isDesktop
  6142. ? getDesktopVideoPosition
  6143. : getCameraVideoPosition;
  6144. // Only if the large video is currently visible.
  6145. // Disable previous dominant speaker video.
  6146. if (largeVideoState.oldResourceJid) {
  6147. VideoLayout.enableDominantSpeaker(
  6148. largeVideoState.oldResourceJid,
  6149. false);
  6150. }
  6151. // Enable new dominant speaker in the remote videos section.
  6152. if (largeVideoState.userResourceJid) {
  6153. VideoLayout.enableDominantSpeaker(
  6154. largeVideoState.userResourceJid,
  6155. true);
  6156. }
  6157. if (userChanged && largeVideoState.isVisible) {
  6158. // using "this" should be ok because we're called
  6159. // from within the fadeOut event.
  6160. $(this).fadeIn(300);
  6161. }
  6162. if(userChanged) {
  6163. Avatar.showUserAvatar(
  6164. APP.xmpp.findJidFromResource(
  6165. largeVideoState.oldResourceJid));
  6166. }
  6167. largeVideoState.updateInProgress = false;
  6168. };
  6169. if (userChanged) {
  6170. $('#largeVideo').fadeOut(300, doUpdate);
  6171. } else {
  6172. doUpdate();
  6173. }
  6174. }
  6175. } else {
  6176. Avatar.showUserAvatar(
  6177. APP.xmpp.findJidFromResource(
  6178. largeVideoState.userResourceJid));
  6179. }
  6180. };
  6181. my.handleVideoThumbClicked = function(videoSrc,
  6182. noPinnedEndpointChangedEvent,
  6183. resourceJid) {
  6184. // Restore style for previously focused video
  6185. var oldContainer = null;
  6186. if(focusedVideoInfo) {
  6187. var focusResourceJid = focusedVideoInfo.resourceJid;
  6188. oldContainer = getParticipantContainer(focusResourceJid);
  6189. }
  6190. if (oldContainer) {
  6191. oldContainer.removeClass("videoContainerFocused");
  6192. }
  6193. // Unlock current focused.
  6194. if (focusedVideoInfo && focusedVideoInfo.src === videoSrc)
  6195. {
  6196. focusedVideoInfo = null;
  6197. var dominantSpeakerVideo = null;
  6198. // Enable the currently set dominant speaker.
  6199. if (currentDominantSpeaker) {
  6200. dominantSpeakerVideo
  6201. = $('#participant_' + currentDominantSpeaker + '>video')
  6202. .get(0);
  6203. if (dominantSpeakerVideo) {
  6204. VideoLayout.updateLargeVideo(
  6205. APP.RTC.getVideoSrc(dominantSpeakerVideo),
  6206. 1,
  6207. currentDominantSpeaker);
  6208. }
  6209. }
  6210. if (!noPinnedEndpointChangedEvent) {
  6211. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  6212. }
  6213. return;
  6214. }
  6215. // Lock new video
  6216. focusedVideoInfo = {
  6217. src: videoSrc,
  6218. resourceJid: resourceJid
  6219. };
  6220. // Update focused/pinned interface.
  6221. if (resourceJid)
  6222. {
  6223. var container = getParticipantContainer(resourceJid);
  6224. container.addClass("videoContainerFocused");
  6225. if (!noPinnedEndpointChangedEvent) {
  6226. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  6227. }
  6228. }
  6229. if ($('#largeVideo').attr('src') === videoSrc &&
  6230. VideoLayout.isLargeVideoOnTop()) {
  6231. return;
  6232. }
  6233. // Triggers a "video.selected" event. The "false" parameter indicates
  6234. // this isn't a prezi.
  6235. $(document).trigger("video.selected", [false]);
  6236. VideoLayout.updateLargeVideo(videoSrc, 1, resourceJid);
  6237. $('audio').each(function (idx, el) {
  6238. if (el.id.indexOf('mixedmslabel') !== -1) {
  6239. el.volume = 0;
  6240. el.volume = 1;
  6241. }
  6242. });
  6243. };
  6244. /**
  6245. * Positions the large video.
  6246. *
  6247. * @param videoWidth the stream video width
  6248. * @param videoHeight the stream video height
  6249. */
  6250. my.positionLarge = function (videoWidth, videoHeight) {
  6251. var videoSpaceWidth = $('#videospace').width();
  6252. var videoSpaceHeight = window.innerHeight;
  6253. var videoSize = VideoLayout.getVideoSize(videoWidth,
  6254. videoHeight,
  6255. videoSpaceWidth,
  6256. videoSpaceHeight);
  6257. var largeVideoWidth = videoSize[0];
  6258. var largeVideoHeight = videoSize[1];
  6259. var videoPosition = VideoLayout.getVideoPosition(largeVideoWidth,
  6260. largeVideoHeight,
  6261. videoSpaceWidth,
  6262. videoSpaceHeight);
  6263. var horizontalIndent = videoPosition[0];
  6264. var verticalIndent = videoPosition[1];
  6265. positionVideo($('#largeVideo'),
  6266. largeVideoWidth,
  6267. largeVideoHeight,
  6268. horizontalIndent, verticalIndent);
  6269. };
  6270. /**
  6271. * Shows/hides the large video.
  6272. */
  6273. my.setLargeVideoVisible = function(isVisible) {
  6274. var resourceJid = largeVideoState.userResourceJid;
  6275. if (isVisible) {
  6276. $('#largeVideo').css({visibility: 'visible'});
  6277. $('.watermark').css({visibility: 'visible'});
  6278. VideoLayout.enableDominantSpeaker(resourceJid, true);
  6279. }
  6280. else {
  6281. $('#largeVideo').css({visibility: 'hidden'});
  6282. $('#activeSpeaker').css('visibility', 'hidden');
  6283. $('.watermark').css({visibility: 'hidden'});
  6284. VideoLayout.enableDominantSpeaker(resourceJid, false);
  6285. if(focusedVideoInfo) {
  6286. var focusResourceJid = focusedVideoInfo.resourceJid;
  6287. var oldContainer = getParticipantContainer(focusResourceJid);
  6288. if (oldContainer && oldContainer.length > 0) {
  6289. oldContainer.removeClass("videoContainerFocused");
  6290. }
  6291. focusedVideoInfo = null;
  6292. if(focusResourceJid) {
  6293. Avatar.showUserAvatar(
  6294. APP.xmpp.findJidFromResource(focusResourceJid));
  6295. }
  6296. }
  6297. }
  6298. };
  6299. /**
  6300. * Indicates if the large video is currently visible.
  6301. *
  6302. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  6303. */
  6304. my.isLargeVideoVisible = function() {
  6305. return $('#largeVideo').is(':visible');
  6306. };
  6307. my.isLargeVideoOnTop = function () {
  6308. var Etherpad = require("../etherpad/Etherpad");
  6309. var Prezi = require("../prezi/Prezi");
  6310. return !Prezi.isPresentationVisible() && !Etherpad.isVisible();
  6311. };
  6312. /**
  6313. * Checks if container for participant identified by given peerJid exists
  6314. * in the document and creates it eventually.
  6315. *
  6316. * @param peerJid peer Jid to check.
  6317. * @param userId user email or id for setting the avatar
  6318. *
  6319. * @return Returns <tt>true</tt> if the peer container exists,
  6320. * <tt>false</tt> - otherwise
  6321. */
  6322. my.ensurePeerContainerExists = function(peerJid, userId) {
  6323. ContactList.ensureAddContact(peerJid, userId);
  6324. var resourceJid = Strophe.getResourceFromJid(peerJid);
  6325. var videoSpanId = 'participant_' + resourceJid;
  6326. if (!$('#' + videoSpanId).length) {
  6327. var container =
  6328. VideoLayout.addRemoteVideoContainer(peerJid, videoSpanId, userId);
  6329. Avatar.setUserAvatar(peerJid, userId);
  6330. // Set default display name.
  6331. setDisplayName(videoSpanId);
  6332. VideoLayout.connectionIndicators[videoSpanId] =
  6333. new ConnectionIndicator(container, peerJid, VideoLayout);
  6334. var nickfield = document.createElement('span');
  6335. nickfield.className = "nick";
  6336. nickfield.appendChild(document.createTextNode(resourceJid));
  6337. container.appendChild(nickfield);
  6338. // In case this is not currently in the last n we don't show it.
  6339. if (localLastNCount
  6340. && localLastNCount > 0
  6341. && $('#remoteVideos>span').length >= localLastNCount + 2) {
  6342. showPeerContainer(resourceJid, 'hide');
  6343. }
  6344. else
  6345. VideoLayout.resizeThumbnails();
  6346. }
  6347. };
  6348. my.addRemoteVideoContainer = function(peerJid, spanId) {
  6349. var container = document.createElement('span');
  6350. container.id = spanId;
  6351. container.className = 'videocontainer';
  6352. var remotes = document.getElementById('remoteVideos');
  6353. remotes.appendChild(container);
  6354. // If the peerJid is null then this video span couldn't be directly
  6355. // associated with a participant (this could happen in the case of prezi).
  6356. if (APP.xmpp.isModerator() && peerJid !== null)
  6357. addRemoteVideoMenu(peerJid, container);
  6358. AudioLevels.updateAudioLevelCanvas(peerJid, VideoLayout);
  6359. return container;
  6360. };
  6361. /**
  6362. * Creates an audio or video stream element.
  6363. */
  6364. my.createStreamElement = function (sid, stream) {
  6365. var isVideo = stream.getVideoTracks().length > 0;
  6366. var element = isVideo
  6367. ? document.createElement('video')
  6368. : document.createElement('audio');
  6369. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_')
  6370. + sid + '_' + APP.RTC.getStreamID(stream);
  6371. element.id = id;
  6372. element.autoplay = true;
  6373. element.oncontextmenu = function () { return false; };
  6374. return element;
  6375. };
  6376. my.addRemoteStreamElement
  6377. = function (container, sid, stream, peerJid, thessrc) {
  6378. var newElementId = null;
  6379. var isVideo = stream.getVideoTracks().length > 0;
  6380. if (container) {
  6381. var streamElement = VideoLayout.createStreamElement(sid, stream);
  6382. newElementId = streamElement.id;
  6383. container.appendChild(streamElement);
  6384. var sel = $('#' + newElementId);
  6385. sel.hide();
  6386. // If the container is currently visible we attach the stream.
  6387. if (!isVideo
  6388. || (container.offsetParent !== null && isVideo)) {
  6389. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  6390. APP.RTC.attachMediaStream(sel, videoStream);
  6391. if (isVideo)
  6392. waitForRemoteVideo(sel, thessrc, stream, peerJid);
  6393. }
  6394. stream.onended = function () {
  6395. console.log('stream ended', this);
  6396. VideoLayout.removeRemoteStreamElement(
  6397. stream, isVideo, container);
  6398. // NOTE(gp) it seems that under certain circumstances, the
  6399. // onended event is not fired and thus the contact list is not
  6400. // updated.
  6401. //
  6402. // The onended event of a stream should be fired when the SSRCs
  6403. // corresponding to that stream are removed from the SDP; but
  6404. // this doesn't seem to always be the case, resulting in ghost
  6405. // contacts.
  6406. //
  6407. // In an attempt to fix the ghost contacts problem, I'm moving
  6408. // the removeContact() method call in app.js, inside the
  6409. // 'muc.left' event handler.
  6410. //if (peerJid)
  6411. // ContactList.removeContact(peerJid);
  6412. };
  6413. // Add click handler.
  6414. container.onclick = function (event) {
  6415. /*
  6416. * FIXME It turns out that videoThumb may not exist (if there is
  6417. * no actual video).
  6418. */
  6419. var videoThumb = $('#' + container.id + '>video').get(0);
  6420. if (videoThumb) {
  6421. VideoLayout.handleVideoThumbClicked(
  6422. APP.RTC.getVideoSrc(videoThumb),
  6423. false,
  6424. Strophe.getResourceFromJid(peerJid));
  6425. }
  6426. event.stopPropagation();
  6427. event.preventDefault();
  6428. return false;
  6429. };
  6430. // Add hover handler
  6431. $(container).hover(
  6432. function() {
  6433. VideoLayout.showDisplayName(container.id, true);
  6434. },
  6435. function() {
  6436. var videoSrc = null;
  6437. if ($('#' + container.id + '>video')
  6438. && $('#' + container.id + '>video').length > 0) {
  6439. videoSrc = APP.RTC.getVideoSrc($('#' + container.id + '>video').get(0));
  6440. }
  6441. // If the video has been "pinned" by the user we want to
  6442. // keep the display name on place.
  6443. if (!VideoLayout.isLargeVideoVisible()
  6444. || videoSrc !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  6445. VideoLayout.showDisplayName(container.id, false);
  6446. }
  6447. );
  6448. }
  6449. return newElementId;
  6450. };
  6451. /**
  6452. * Removes the remote stream element corresponding to the given stream and
  6453. * parent container.
  6454. *
  6455. * @param stream the stream
  6456. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  6457. * @param container
  6458. */
  6459. my.removeRemoteStreamElement = function (stream, isVideo, container) {
  6460. if (!container)
  6461. return;
  6462. var select = null;
  6463. var removedVideoSrc = null;
  6464. if (isVideo) {
  6465. select = $('#' + container.id + '>video');
  6466. removedVideoSrc = APP.RTC.getVideoSrc(select.get(0));
  6467. }
  6468. else
  6469. select = $('#' + container.id + '>audio');
  6470. // Mark video as removed to cancel waiting loop(if video is removed
  6471. // before has started)
  6472. select.removed = true;
  6473. select.remove();
  6474. var audioCount = $('#' + container.id + '>audio').length;
  6475. var videoCount = $('#' + container.id + '>video').length;
  6476. if (!audioCount && !videoCount) {
  6477. console.log("Remove whole user", container.id);
  6478. if(VideoLayout.connectionIndicators[container.id])
  6479. VideoLayout.connectionIndicators[container.id].remove();
  6480. // Remove whole container
  6481. container.remove();
  6482. UIUtil.playSoundNotification('userLeft');
  6483. VideoLayout.resizeThumbnails();
  6484. }
  6485. if (removedVideoSrc)
  6486. VideoLayout.updateRemovedVideo(removedVideoSrc);
  6487. };
  6488. /**
  6489. * Show/hide peer container for the given resourceJid.
  6490. */
  6491. function showPeerContainer(resourceJid, state) {
  6492. var peerContainer = $('#participant_' + resourceJid);
  6493. if (!peerContainer)
  6494. return;
  6495. var isHide = state === 'hide';
  6496. var resizeThumbnails = false;
  6497. if (!isHide) {
  6498. if (!peerContainer.is(':visible')) {
  6499. resizeThumbnails = true;
  6500. peerContainer.show();
  6501. }
  6502. var jid = APP.xmpp.findJidFromResource(resourceJid);
  6503. if (state == 'show')
  6504. {
  6505. // peerContainer.css('-webkit-filter', '');
  6506. Avatar.showUserAvatar(jid, false);
  6507. }
  6508. else // if (state == 'avatar')
  6509. {
  6510. // peerContainer.css('-webkit-filter', 'grayscale(100%)');
  6511. Avatar.showUserAvatar(jid, true);
  6512. }
  6513. }
  6514. else if (peerContainer.is(':visible') && isHide)
  6515. {
  6516. resizeThumbnails = true;
  6517. peerContainer.hide();
  6518. if(VideoLayout.connectionIndicators['participant_' + resourceJid])
  6519. VideoLayout.connectionIndicators['participant_' + resourceJid].hide();
  6520. }
  6521. if (resizeThumbnails) {
  6522. VideoLayout.resizeThumbnails();
  6523. }
  6524. // We want to be able to pin a participant from the contact list, even
  6525. // if he's not in the lastN set!
  6526. // ContactList.setClickable(resourceJid, !isHide);
  6527. };
  6528. my.inputDisplayNameHandler = function (name) {
  6529. NicknameHandler.setNickname(name);
  6530. if (!$('#localDisplayName').is(":visible")) {
  6531. if (NicknameHandler.getNickname())
  6532. $('#localDisplayName').text(NicknameHandler.getNickname() + " (me)");
  6533. else
  6534. $('#localDisplayName')
  6535. .text(interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  6536. $('#localDisplayName').show();
  6537. }
  6538. $('#editDisplayName').hide();
  6539. };
  6540. /**
  6541. * Shows/hides the display name on the remote video.
  6542. * @param videoSpanId the identifier of the video span element
  6543. * @param isShow indicates if the display name should be shown or hidden
  6544. */
  6545. my.showDisplayName = function(videoSpanId, isShow) {
  6546. var nameSpan = $('#' + videoSpanId + '>span.displayname').get(0);
  6547. if (isShow) {
  6548. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  6549. nameSpan.setAttribute("style", "display:inline-block;");
  6550. }
  6551. else {
  6552. if (nameSpan)
  6553. nameSpan.setAttribute("style", "display:none;");
  6554. }
  6555. };
  6556. /**
  6557. * Shows the presence status message for the given video.
  6558. */
  6559. my.setPresenceStatus = function (videoSpanId, statusMsg) {
  6560. if (!$('#' + videoSpanId).length) {
  6561. // No container
  6562. return;
  6563. }
  6564. var statusSpan = $('#' + videoSpanId + '>span.status');
  6565. if (!statusSpan.length) {
  6566. //Add status span
  6567. statusSpan = document.createElement('span');
  6568. statusSpan.className = 'status';
  6569. statusSpan.id = videoSpanId + '_status';
  6570. $('#' + videoSpanId)[0].appendChild(statusSpan);
  6571. statusSpan = $('#' + videoSpanId + '>span.status');
  6572. }
  6573. // Display status
  6574. if (statusMsg && statusMsg.length) {
  6575. $('#' + videoSpanId + '_status').text(statusMsg);
  6576. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  6577. }
  6578. else {
  6579. // Hide
  6580. statusSpan.get(0).setAttribute("style", "display:none;");
  6581. }
  6582. };
  6583. /**
  6584. * Shows a visual indicator for the moderator of the conference.
  6585. */
  6586. my.showModeratorIndicator = function () {
  6587. var isModerator = APP.xmpp.isModerator();
  6588. if (isModerator) {
  6589. var indicatorSpan = $('#localVideoContainer .focusindicator');
  6590. if (indicatorSpan.children().length === 0)
  6591. {
  6592. createModeratorIndicatorElement(indicatorSpan[0]);
  6593. //translates text in focus indicator
  6594. APP.translation.translateElement($('#localVideoContainer .focusindicator'));
  6595. }
  6596. }
  6597. var members = APP.xmpp.getMembers();
  6598. Object.keys(members).forEach(function (jid) {
  6599. if (Strophe.getResourceFromJid(jid) === 'focus') {
  6600. // Skip server side focus
  6601. return;
  6602. }
  6603. var resourceJid = Strophe.getResourceFromJid(jid);
  6604. var videoSpanId = 'participant_' + resourceJid;
  6605. var videoContainer = document.getElementById(videoSpanId);
  6606. if (!videoContainer) {
  6607. console.error("No video container for " + jid);
  6608. return;
  6609. }
  6610. var member = members[jid];
  6611. if (member.role === 'moderator') {
  6612. // Remove menu if peer is moderator
  6613. var menuSpan = $('#' + videoSpanId + '>span.remotevideomenu');
  6614. if (menuSpan.length) {
  6615. removeRemoteVideoMenu(videoSpanId);
  6616. }
  6617. // Show moderator indicator
  6618. var indicatorSpan
  6619. = $('#' + videoSpanId + ' .focusindicator');
  6620. if (!indicatorSpan || indicatorSpan.length === 0) {
  6621. indicatorSpan = document.createElement('span');
  6622. indicatorSpan.className = 'focusindicator';
  6623. videoContainer.appendChild(indicatorSpan);
  6624. createModeratorIndicatorElement(indicatorSpan);
  6625. //translates text in focus indicators
  6626. APP.translation.translateElement($('#' + videoSpanId + ' .focusindicator'));
  6627. }
  6628. } else if (isModerator) {
  6629. // We are moderator, but user is not - add menu
  6630. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  6631. addRemoteVideoMenu(
  6632. jid,
  6633. document.getElementById('participant_' + resourceJid));
  6634. }
  6635. }
  6636. });
  6637. };
  6638. /**
  6639. * Shows video muted indicator over small videos.
  6640. */
  6641. my.showVideoIndicator = function(videoSpanId, isMuted) {
  6642. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  6643. if (isMuted === 'false') {
  6644. if (videoMutedSpan.length > 0) {
  6645. videoMutedSpan.remove();
  6646. }
  6647. }
  6648. else {
  6649. if(videoMutedSpan.length == 0) {
  6650. videoMutedSpan = document.createElement('span');
  6651. videoMutedSpan.className = 'videoMuted';
  6652. $('#' + videoSpanId)[0].appendChild(videoMutedSpan);
  6653. var mutedIndicator = document.createElement('i');
  6654. mutedIndicator.className = 'icon-camera-disabled';
  6655. UIUtil.setTooltip(mutedIndicator,
  6656. "videothumbnail.videomute",
  6657. "top");
  6658. videoMutedSpan.appendChild(mutedIndicator);
  6659. //translate texts for muted indicator
  6660. APP.translation.translateElement($('#' + videoSpanId + " > span > i"));
  6661. }
  6662. VideoLayout.updateMutePosition(videoSpanId);
  6663. }
  6664. };
  6665. my.updateMutePosition = function (videoSpanId) {
  6666. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  6667. var connectionIndicator = $('#' + videoSpanId + '>div.connectionindicator');
  6668. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  6669. if(connectionIndicator.length > 0
  6670. && connectionIndicator[0].style.display != "none") {
  6671. audioMutedSpan.css({right: "23px"});
  6672. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  6673. }
  6674. else
  6675. {
  6676. audioMutedSpan.css({right: "0px"});
  6677. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  6678. }
  6679. }
  6680. /**
  6681. * Shows audio muted indicator over small videos.
  6682. * @param {string} isMuted
  6683. */
  6684. my.showAudioIndicator = function(videoSpanId, isMuted) {
  6685. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  6686. if (isMuted === 'false') {
  6687. if (audioMutedSpan.length > 0) {
  6688. audioMutedSpan.popover('hide');
  6689. audioMutedSpan.remove();
  6690. }
  6691. }
  6692. else {
  6693. if(audioMutedSpan.length == 0 ) {
  6694. audioMutedSpan = document.createElement('span');
  6695. audioMutedSpan.className = 'audioMuted';
  6696. UIUtil.setTooltip(audioMutedSpan,
  6697. "videothumbnail.mute",
  6698. "top");
  6699. $('#' + videoSpanId)[0].appendChild(audioMutedSpan);
  6700. APP.translation.translateElement($('#' + videoSpanId + " > span"));
  6701. var mutedIndicator = document.createElement('i');
  6702. mutedIndicator.className = 'icon-mic-disabled';
  6703. audioMutedSpan.appendChild(mutedIndicator);
  6704. }
  6705. VideoLayout.updateMutePosition(videoSpanId);
  6706. }
  6707. };
  6708. /*
  6709. * Shows or hides the audio muted indicator over the local thumbnail video.
  6710. * @param {boolean} isMuted
  6711. */
  6712. my.showLocalAudioIndicator = function(isMuted) {
  6713. VideoLayout.showAudioIndicator('localVideoContainer', isMuted.toString());
  6714. };
  6715. /**
  6716. * Resizes the large video container.
  6717. */
  6718. my.resizeLargeVideoContainer = function () {
  6719. Chat.resizeChat();
  6720. var availableHeight = window.innerHeight;
  6721. var availableWidth = UIUtil.getAvailableVideoWidth();
  6722. if (availableWidth < 0 || availableHeight < 0) return;
  6723. $('#videospace').width(availableWidth);
  6724. $('#videospace').height(availableHeight);
  6725. $('#largeVideoContainer').width(availableWidth);
  6726. $('#largeVideoContainer').height(availableHeight);
  6727. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  6728. var top = availableHeight / 2 - avatarSize / 4 * 3;
  6729. $('#activeSpeaker').css('top', top);
  6730. VideoLayout.resizeThumbnails();
  6731. };
  6732. /**
  6733. * Resizes thumbnails.
  6734. */
  6735. my.resizeThumbnails = function() {
  6736. var videoSpaceWidth = $('#remoteVideos').width();
  6737. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  6738. var width = thumbnailSize[0];
  6739. var height = thumbnailSize[1];
  6740. // size videos so that while keeping AR and max height, we have a
  6741. // nice fit
  6742. $('#remoteVideos').height(height);
  6743. $('#remoteVideos>span').width(width);
  6744. $('#remoteVideos>span').height(height);
  6745. $('.userAvatar').css('left', (width - height) / 2);
  6746. $(document).trigger("remotevideo.resized", [width, height]);
  6747. };
  6748. /**
  6749. * Enables the dominant speaker UI.
  6750. *
  6751. * @param resourceJid the jid indicating the video element to
  6752. * activate/deactivate
  6753. * @param isEnable indicates if the dominant speaker should be enabled or
  6754. * disabled
  6755. */
  6756. my.enableDominantSpeaker = function(resourceJid, isEnable) {
  6757. var videoSpanId = null;
  6758. var videoContainerId = null;
  6759. if (resourceJid
  6760. === APP.xmpp.myResource()) {
  6761. videoSpanId = 'localVideoWrapper';
  6762. videoContainerId = 'localVideoContainer';
  6763. }
  6764. else {
  6765. videoSpanId = 'participant_' + resourceJid;
  6766. videoContainerId = videoSpanId;
  6767. }
  6768. var displayName = resourceJid;
  6769. var nameSpan = $('#' + videoContainerId + '>span.displayname');
  6770. if (nameSpan.length > 0)
  6771. displayName = nameSpan.html();
  6772. console.log("UI enable dominant speaker",
  6773. displayName,
  6774. resourceJid,
  6775. isEnable);
  6776. videoSpan = document.getElementById(videoContainerId);
  6777. if (!videoSpan) {
  6778. return;
  6779. }
  6780. var video = $('#' + videoSpanId + '>video');
  6781. if (video && video.length > 0) {
  6782. if (isEnable) {
  6783. var isLargeVideoVisible = VideoLayout.isLargeVideoOnTop();
  6784. VideoLayout.showDisplayName(videoContainerId, isLargeVideoVisible);
  6785. if (!videoSpan.classList.contains("dominantspeaker"))
  6786. videoSpan.classList.add("dominantspeaker");
  6787. }
  6788. else {
  6789. VideoLayout.showDisplayName(videoContainerId, false);
  6790. if (videoSpan.classList.contains("dominantspeaker"))
  6791. videoSpan.classList.remove("dominantspeaker");
  6792. }
  6793. Avatar.showUserAvatar(
  6794. APP.xmpp.findJidFromResource(resourceJid));
  6795. }
  6796. };
  6797. /**
  6798. * Calculates the thumbnail size.
  6799. *
  6800. * @param videoSpaceWidth the width of the video space
  6801. */
  6802. my.calculateThumbnailSize = function (videoSpaceWidth) {
  6803. // Calculate the available height, which is the inner window height minus
  6804. // 39px for the header minus 2px for the delimiter lines on the top and
  6805. // bottom of the large video, minus the 36px space inside the remoteVideos
  6806. // container used for highlighting shadow.
  6807. var availableHeight = 100;
  6808. var numvids = $('#remoteVideos>span:visible').length;
  6809. if (localLastNCount && localLastNCount > 0) {
  6810. numvids = Math.min(localLastNCount + 1, numvids);
  6811. }
  6812. // Remove the 3px borders arround videos and border around the remote
  6813. // videos area and the 4 pixels between the local video and the others
  6814. //TODO: Find out where the 4 pixels come from and remove them
  6815. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  6816. var availableWidth = availableWinWidth / numvids;
  6817. var aspectRatio = 16.0 / 9.0;
  6818. var maxHeight = Math.min(160, availableHeight);
  6819. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  6820. if (availableHeight < availableWidth / aspectRatio) {
  6821. availableWidth = Math.floor(availableHeight * aspectRatio);
  6822. }
  6823. return [availableWidth, availableHeight];
  6824. };
  6825. /**
  6826. * Updates the remote video menu.
  6827. *
  6828. * @param jid the jid indicating the video for which we're adding a menu.
  6829. * @param isMuted indicates the current mute state
  6830. */
  6831. my.updateRemoteVideoMenu = function(jid, isMuted) {
  6832. var muteMenuItem
  6833. = $('#remote_popupmenu_'
  6834. + Strophe.getResourceFromJid(jid)
  6835. + '>li>a.mutelink');
  6836. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  6837. if (muteMenuItem.length) {
  6838. var muteLink = muteMenuItem.get(0);
  6839. if (isMuted === 'true') {
  6840. muteLink.innerHTML = mutedIndicator + ' Muted';
  6841. muteLink.className = 'mutelink disabled';
  6842. }
  6843. else {
  6844. muteLink.innerHTML = mutedIndicator + ' Mute';
  6845. muteLink.className = 'mutelink';
  6846. }
  6847. }
  6848. };
  6849. /**
  6850. * Returns the current dominant speaker resource jid.
  6851. */
  6852. my.getDominantSpeakerResourceJid = function () {
  6853. return currentDominantSpeaker;
  6854. };
  6855. /**
  6856. * Returns the corresponding resource jid to the given peer container
  6857. * DOM element.
  6858. *
  6859. * @return the corresponding resource jid to the given peer container
  6860. * DOM element
  6861. */
  6862. my.getPeerContainerResourceJid = function (containerElement) {
  6863. var i = containerElement.id.indexOf('participant_');
  6864. if (i >= 0)
  6865. return containerElement.id.substring(i + 12);
  6866. };
  6867. /**
  6868. * On contact list item clicked.
  6869. */
  6870. $(ContactList).bind('contactclicked', function(event, jid) {
  6871. if (!jid) {
  6872. return;
  6873. }
  6874. var resource = Strophe.getResourceFromJid(jid);
  6875. var videoContainer = $("#participant_" + resource);
  6876. if (videoContainer.length > 0) {
  6877. var videoThumb = $('video', videoContainer).get(0);
  6878. // It is not always the case that a videoThumb exists (if there is
  6879. // no actual video).
  6880. if (videoThumb) {
  6881. if (videoThumb.src && videoThumb.src != '') {
  6882. // We have a video src, great! Let's update the large video
  6883. // now.
  6884. VideoLayout.handleVideoThumbClicked(
  6885. videoThumb.src,
  6886. false,
  6887. Strophe.getResourceFromJid(jid));
  6888. } else {
  6889. // If we don't have a video src for jid, there's absolutely
  6890. // no point in calling handleVideoThumbClicked; Quite
  6891. // simply, it won't work because it needs an src to attach
  6892. // to the large video.
  6893. //
  6894. // Instead, we trigger the pinned endpoint changed event to
  6895. // let the bridge adjust its lastN set for myjid and store
  6896. // the pinned user in the lastNPickupJid variable to be
  6897. // picked up later by the lastN changed event handler.
  6898. lastNPickupJid = jid;
  6899. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  6900. Strophe.getResourceFromJid(jid));
  6901. }
  6902. } else if (jid == APP.xmpp.myJid()) {
  6903. $("#localVideoContainer").click();
  6904. }
  6905. }
  6906. });
  6907. /**
  6908. * On audio muted event.
  6909. */
  6910. $(document).bind('audiomuted.muc', function (event, jid, isMuted) {
  6911. /*
  6912. // FIXME: but focus can not mute in this case ? - check
  6913. if (jid === xmpp.myJid()) {
  6914. // The local mute indicator is controlled locally
  6915. return;
  6916. }*/
  6917. var videoSpanId = null;
  6918. if (jid === APP.xmpp.myJid()) {
  6919. videoSpanId = 'localVideoContainer';
  6920. } else {
  6921. VideoLayout.ensurePeerContainerExists(jid);
  6922. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  6923. }
  6924. mutedAudios[jid] = isMuted;
  6925. if (APP.xmpp.isModerator()) {
  6926. VideoLayout.updateRemoteVideoMenu(jid, isMuted);
  6927. }
  6928. if (videoSpanId)
  6929. VideoLayout.showAudioIndicator(videoSpanId, isMuted);
  6930. });
  6931. /**
  6932. * On video muted event.
  6933. */
  6934. $(document).bind('videomuted.muc', function (event, jid, value) {
  6935. var isMuted = (value === "true");
  6936. if(!APP.RTC.muteRemoteVideoStream(jid, isMuted))
  6937. return;
  6938. Avatar.showUserAvatar(jid, isMuted);
  6939. var videoSpanId = null;
  6940. if (jid === APP.xmpp.myJid()) {
  6941. videoSpanId = 'localVideoContainer';
  6942. } else {
  6943. VideoLayout.ensurePeerContainerExists(jid);
  6944. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  6945. }
  6946. if (videoSpanId)
  6947. VideoLayout.showVideoIndicator(videoSpanId, value);
  6948. });
  6949. /**
  6950. * Display name changed.
  6951. */
  6952. my.onDisplayNameChanged =
  6953. function (jid, displayName, status) {
  6954. if (jid === 'localVideoContainer'
  6955. || jid === APP.xmpp.myJid()) {
  6956. setDisplayName('localVideoContainer',
  6957. displayName);
  6958. } else {
  6959. VideoLayout.ensurePeerContainerExists(jid);
  6960. setDisplayName(
  6961. 'participant_' + Strophe.getResourceFromJid(jid),
  6962. displayName,
  6963. status);
  6964. }
  6965. };
  6966. /**
  6967. * On dominant speaker changed event.
  6968. */
  6969. my.onDominantSpeakerChanged = function (resourceJid) {
  6970. // We ignore local user events.
  6971. if (resourceJid
  6972. === APP.xmpp.myResource())
  6973. return;
  6974. // Update the current dominant speaker.
  6975. if (resourceJid !== currentDominantSpeaker) {
  6976. var oldSpeakerVideoSpanId = "participant_" + currentDominantSpeaker,
  6977. newSpeakerVideoSpanId = "participant_" + resourceJid;
  6978. if($("#" + oldSpeakerVideoSpanId + ">span.displayname").text() ===
  6979. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME) {
  6980. setDisplayName(oldSpeakerVideoSpanId, null);
  6981. }
  6982. if($("#" + newSpeakerVideoSpanId + ">span.displayname").text() ===
  6983. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME) {
  6984. setDisplayName(newSpeakerVideoSpanId,
  6985. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  6986. }
  6987. currentDominantSpeaker = resourceJid;
  6988. } else {
  6989. return;
  6990. }
  6991. // Obtain container for new dominant speaker.
  6992. var container = document.getElementById(
  6993. 'participant_' + resourceJid);
  6994. // Local video will not have container found, but that's ok
  6995. // since we don't want to switch to local video.
  6996. if (container && !focusedVideoInfo)
  6997. {
  6998. var video = container.getElementsByTagName("video");
  6999. // Update the large video if the video source is already available,
  7000. // otherwise wait for the "videoactive.jingle" event.
  7001. if (video.length && video[0].currentTime > 0)
  7002. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(video[0]), resourceJid);
  7003. }
  7004. };
  7005. /**
  7006. * On last N change event.
  7007. *
  7008. * @param lastNEndpoints the list of last N endpoints
  7009. * @param endpointsEnteringLastN the list currently entering last N
  7010. * endpoints
  7011. */
  7012. my.onLastNEndpointsChanged = function ( lastNEndpoints,
  7013. endpointsEnteringLastN,
  7014. stream) {
  7015. if (lastNCount !== lastNEndpoints.length)
  7016. lastNCount = lastNEndpoints.length;
  7017. lastNEndpointsCache = lastNEndpoints;
  7018. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  7019. //
  7020. // If LastN drops to, say, 2, because of adaptivity, then E should see
  7021. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  7022. // so E sees them. C is only in E's local LastN set.
  7023. //
  7024. // If F starts talking and LastN = 3, then E should see thumbnails for
  7025. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  7026. // enters E's local LastN ejecting C.
  7027. // Increase the local LastN set size, if necessary.
  7028. if (lastNCount > localLastNCount) {
  7029. localLastNCount = lastNCount;
  7030. }
  7031. // Update the local LastN set preserving the order in which the
  7032. // endpoints appeared in the LastN/local LastN set.
  7033. var nextLocalLastNSet = lastNEndpoints.slice(0);
  7034. for (var i = 0; i < localLastNSet.length; i++) {
  7035. if (nextLocalLastNSet.length >= localLastNCount) {
  7036. break;
  7037. }
  7038. var resourceJid = localLastNSet[i];
  7039. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  7040. nextLocalLastNSet.push(resourceJid);
  7041. }
  7042. }
  7043. localLastNSet = nextLocalLastNSet;
  7044. var updateLargeVideo = false;
  7045. // Handle LastN/local LastN changes.
  7046. $('#remoteVideos>span').each(function( index, element ) {
  7047. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  7048. var isReceived = true;
  7049. if (resourceJid
  7050. && lastNEndpoints.indexOf(resourceJid) < 0
  7051. && localLastNSet.indexOf(resourceJid) < 0) {
  7052. console.log("Remove from last N", resourceJid);
  7053. showPeerContainer(resourceJid, 'hide');
  7054. isReceived = false;
  7055. } else if (resourceJid
  7056. && $('#participant_' + resourceJid).is(':visible')
  7057. && lastNEndpoints.indexOf(resourceJid) < 0
  7058. && localLastNSet.indexOf(resourceJid) >= 0) {
  7059. showPeerContainer(resourceJid, 'avatar');
  7060. isReceived = false;
  7061. }
  7062. if (!isReceived) {
  7063. // resourceJid has dropped out of the server side lastN set, so
  7064. // it is no longer being received. If resourceJid was being
  7065. // displayed in the large video we have to switch to another
  7066. // user.
  7067. var largeVideoResource = largeVideoState.userResourceJid;
  7068. if (!updateLargeVideo && resourceJid === largeVideoResource) {
  7069. updateLargeVideo = true;
  7070. }
  7071. }
  7072. });
  7073. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  7074. endpointsEnteringLastN = lastNEndpoints;
  7075. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  7076. endpointsEnteringLastN.forEach(function (resourceJid) {
  7077. var isVisible = $('#participant_' + resourceJid).is(':visible');
  7078. showPeerContainer(resourceJid, 'show');
  7079. if (!isVisible) {
  7080. console.log("Add to last N", resourceJid);
  7081. var jid = APP.xmpp.findJidFromResource(resourceJid);
  7082. var mediaStream = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  7083. var sel = $('#participant_' + resourceJid + '>video');
  7084. var videoStream = APP.simulcast.getReceivingVideoStream(
  7085. mediaStream.stream);
  7086. APP.RTC.attachMediaStream(sel, videoStream);
  7087. if (lastNPickupJid == mediaStream.peerjid) {
  7088. // Clean up the lastN pickup jid.
  7089. lastNPickupJid = null;
  7090. // Don't fire the events again, they've already
  7091. // been fired in the contact list click handler.
  7092. VideoLayout.handleVideoThumbClicked(
  7093. $(sel).attr('src'),
  7094. false,
  7095. Strophe.getResourceFromJid(mediaStream.peerjid));
  7096. updateLargeVideo = false;
  7097. }
  7098. waitForRemoteVideo(sel, mediaStream.ssrc, mediaStream.stream, resourceJid);
  7099. }
  7100. })
  7101. }
  7102. // The endpoint that was being shown in the large video has dropped out
  7103. // of the lastN set and there was no lastN pickup jid. We need to update
  7104. // the large video now.
  7105. if (updateLargeVideo) {
  7106. var resource, container, src;
  7107. var myResource
  7108. = APP.xmpp.myResource();
  7109. // Find out which endpoint to show in the large video.
  7110. for (var i = 0; i < lastNEndpoints.length; i++) {
  7111. resource = lastNEndpoints[i];
  7112. if (!resource || resource === myResource)
  7113. continue;
  7114. container = $("#participant_" + resource);
  7115. if (container.length == 0)
  7116. continue;
  7117. src = $('video', container).attr('src');
  7118. if (!src)
  7119. continue;
  7120. // videoSrcToSsrc needs to be update for this call to succeed.
  7121. VideoLayout.updateLargeVideo(src);
  7122. break;
  7123. }
  7124. }
  7125. };
  7126. my.onSimulcastLayersChanging = function (endpointSimulcastLayers) {
  7127. endpointSimulcastLayers.forEach(function (esl) {
  7128. var resource = esl.endpoint;
  7129. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7130. // then ignore the event (= do not preload anything).
  7131. //
  7132. // The bridge could probably stop sending this message if it's for
  7133. // an endpoint that's not in lastN.
  7134. if (lastNCount != -1
  7135. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7136. return;
  7137. }
  7138. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7139. // Get session and stream from primary ssrc.
  7140. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7141. var sid = res.sid;
  7142. var electedStream = res.stream;
  7143. if (sid && electedStream) {
  7144. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7145. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7146. var preload = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC)) == largeVideoState.userResourceJid);
  7147. if (preload) {
  7148. if (largeVideoState.preload)
  7149. {
  7150. $(largeVideoState.preload).remove();
  7151. }
  7152. console.info('Preloading remote video');
  7153. largeVideoState.preload = $('<video autoplay></video>');
  7154. // ssrcs are unique in an rtp session
  7155. largeVideoState.preload_ssrc = primarySSRC;
  7156. APP.RTC.attachMediaStream(largeVideoState.preload, electedStream)
  7157. }
  7158. } else {
  7159. console.error('Could not find a stream or a session.', sid, electedStream);
  7160. }
  7161. });
  7162. };
  7163. /**
  7164. * On simulcast layers changed event.
  7165. */
  7166. my.onSimulcastLayersChanged = function (endpointSimulcastLayers) {
  7167. endpointSimulcastLayers.forEach(function (esl) {
  7168. var resource = esl.endpoint;
  7169. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7170. // then ignore the event (= do not change large video/thumbnail
  7171. // SRCs).
  7172. //
  7173. // Note that even if we ignore the "changed" event in this event
  7174. // handler, the bridge must continue sending these events because
  7175. // the simulcast code in simulcast.js uses it to know what's going
  7176. // to be streamed by the bridge when/if the endpoint gets back into
  7177. // the lastN set.
  7178. if (lastNCount != -1
  7179. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7180. return;
  7181. }
  7182. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7183. // Get session and stream from primary ssrc.
  7184. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7185. var sid = res.sid;
  7186. var electedStream = res.stream;
  7187. if (sid && electedStream) {
  7188. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7189. console.info('Switching simulcast substream.');
  7190. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7191. var msidParts = msid.split(' ');
  7192. var selRemoteVideo = $(['#', 'remoteVideo_', sid, '_', msidParts[0]].join(''));
  7193. var updateLargeVideo = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC))
  7194. == largeVideoState.userResourceJid);
  7195. var updateFocusedVideoSrc = (focusedVideoInfo && focusedVideoInfo.src && focusedVideoInfo.src != '' &&
  7196. (APP.RTC.getVideoSrc(selRemoteVideo[0]) == focusedVideoInfo.src));
  7197. var electedStreamUrl;
  7198. if (largeVideoState.preload_ssrc == primarySSRC)
  7199. {
  7200. APP.RTC.setVideoSrc(selRemoteVideo[0], APP.RTC.getVideoSrc(largeVideoState.preload[0]));
  7201. }
  7202. else
  7203. {
  7204. if (largeVideoState.preload
  7205. && largeVideoState.preload != null) {
  7206. $(largeVideoState.preload).remove();
  7207. }
  7208. largeVideoState.preload_ssrc = 0;
  7209. APP.RTC.attachMediaStream(selRemoteVideo, electedStream);
  7210. }
  7211. var jid = APP.xmpp.getJidFromSSRC(primarySSRC);
  7212. if (updateLargeVideo) {
  7213. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(selRemoteVideo[0]), null,
  7214. Strophe.getResourceFromJid(jid));
  7215. }
  7216. if (updateFocusedVideoSrc) {
  7217. focusedVideoInfo.src = APP.RTC.getVideoSrc(selRemoteVideo[0]);
  7218. }
  7219. var videoId;
  7220. if(resource == APP.xmpp.myResource())
  7221. {
  7222. videoId = "localVideoContainer";
  7223. }
  7224. else
  7225. {
  7226. videoId = "participant_" + resource;
  7227. }
  7228. var connectionIndicator = VideoLayout.connectionIndicators[videoId];
  7229. if(connectionIndicator)
  7230. connectionIndicator.updatePopoverData();
  7231. } else {
  7232. console.error('Could not find a stream or a sid.', sid, electedStream);
  7233. }
  7234. });
  7235. };
  7236. /**
  7237. * Updates local stats
  7238. * @param percent
  7239. * @param object
  7240. */
  7241. my.updateLocalConnectionStats = function (percent, object) {
  7242. var resolution = null;
  7243. if(object.resolution !== null)
  7244. {
  7245. resolution = object.resolution;
  7246. object.resolution = resolution[APP.xmpp.myJid()];
  7247. delete resolution[APP.xmpp.myJid()];
  7248. }
  7249. updateStatsIndicator("localVideoContainer", percent, object);
  7250. for(var jid in resolution)
  7251. {
  7252. if(resolution[jid] === null)
  7253. continue;
  7254. var id = 'participant_' + Strophe.getResourceFromJid(jid);
  7255. if(VideoLayout.connectionIndicators[id])
  7256. {
  7257. VideoLayout.connectionIndicators[id].updateResolution(resolution[jid]);
  7258. }
  7259. }
  7260. };
  7261. /**
  7262. * Updates remote stats.
  7263. * @param jid the jid associated with the stats
  7264. * @param percent the connection quality percent
  7265. * @param object the stats data
  7266. */
  7267. my.updateConnectionStats = function (jid, percent, object) {
  7268. var resourceJid = Strophe.getResourceFromJid(jid);
  7269. var videoSpanId = 'participant_' + resourceJid;
  7270. updateStatsIndicator(videoSpanId, percent, object);
  7271. };
  7272. /**
  7273. * Removes the connection
  7274. * @param jid
  7275. */
  7276. my.removeConnectionIndicator = function (jid) {
  7277. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7278. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].remove();
  7279. };
  7280. /**
  7281. * Hides the connection indicator
  7282. * @param jid
  7283. */
  7284. my.hideConnectionIndicator = function (jid) {
  7285. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7286. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].hide();
  7287. };
  7288. /**
  7289. * Hides all the indicators
  7290. */
  7291. my.onStatsStop = function () {
  7292. for(var indicator in VideoLayout.connectionIndicators)
  7293. {
  7294. VideoLayout.connectionIndicators[indicator].hideIndicator();
  7295. }
  7296. };
  7297. my.participantLeft = function (jid) {
  7298. // Unlock large video
  7299. if (focusedVideoInfo && focusedVideoInfo.jid === jid)
  7300. {
  7301. console.info("Focused video owner has left the conference");
  7302. focusedVideoInfo = null;
  7303. }
  7304. }
  7305. return my;
  7306. }(VideoLayout || {}));
  7307. module.exports = VideoLayout;
  7308. },{"../../../service/RTC/MediaStreamTypes":78,"../../../service/UI/UIEvents":83,"../audio_levels/AudioLevels":9,"../avatar/Avatar":12,"../etherpad/Etherpad":13,"../prezi/Prezi":14,"../side_pannels/chat/Chat":17,"../side_pannels/contactlist/ContactList":21,"../util/NicknameHandler":28,"../util/UIUtil":29,"./ConnectionIndicator":30}],32:[function(require,module,exports){
  7309. //var nouns = [
  7310. //];
  7311. var pluralNouns = [
  7312. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  7313. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  7314. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  7315. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  7316. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  7317. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  7318. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  7319. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  7320. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  7321. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  7322. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  7323. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  7324. ];
  7325. //var places = [
  7326. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  7327. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  7328. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  7329. // "Bridge"
  7330. //];
  7331. var verbs = [
  7332. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  7333. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  7334. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  7335. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  7336. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  7337. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  7338. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  7339. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  7340. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  7341. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  7342. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  7343. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  7344. ];
  7345. var adverbs = [
  7346. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  7347. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  7348. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  7349. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  7350. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  7351. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  7352. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  7353. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  7354. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  7355. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  7356. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  7357. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  7358. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  7359. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  7360. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly", "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  7361. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  7362. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  7363. ];
  7364. var adjectives = [
  7365. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  7366. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  7367. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  7368. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  7369. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  7370. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  7371. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  7372. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  7373. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  7374. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  7375. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  7376. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  7377. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  7378. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  7379. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  7380. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  7381. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  7382. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  7383. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  7384. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  7385. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  7386. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  7387. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  7388. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  7389. "Zealous"
  7390. ];
  7391. //var pronouns = [
  7392. //];
  7393. //var conjunctions = [
  7394. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  7395. //];
  7396. /*
  7397. * Maps a string (category name) to the array of words from that category.
  7398. */
  7399. var CATEGORIES =
  7400. {
  7401. //"_NOUN_": nouns,
  7402. "_PLURALNOUN_": pluralNouns,
  7403. //"_PLACE_": places,
  7404. "_VERB_": verbs,
  7405. "_ADVERB_": adverbs,
  7406. "_ADJECTIVE_": adjectives
  7407. //"_PRONOUN_": pronouns,
  7408. //"_CONJUNCTION_": conjunctions,
  7409. };
  7410. var PATTERNS = [
  7411. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  7412. // BeautifulFungiOrSpaghetti
  7413. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  7414. // AmazinglyScaryToy
  7415. //"_ADVERB__ADJECTIVE__NOUN_",
  7416. // NeitherTrashNorRifle
  7417. //"Neither_NOUN_Nor_NOUN_",
  7418. //"Either_NOUN_Or_NOUN_",
  7419. // EitherCopulateOrInvestigate
  7420. //"Either_VERB_Or_VERB_",
  7421. //"Neither_VERB_Nor_VERB_",
  7422. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  7423. //"The_ADVERB__ADJECTIVE__NOUN_",
  7424. //"The_ADVERB__ADJECTIVE__NOUN_s",
  7425. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  7426. // WolvesComputeBadly
  7427. //"_PLURALNOUN__VERB__ADVERB_",
  7428. // UniteFacilitateAndMerge
  7429. //"_VERB__VERB_And_VERB_",
  7430. //NastyWitchesAtThePub
  7431. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  7432. ];
  7433. /*
  7434. * Returns a random element from the array 'arr'
  7435. */
  7436. function randomElement(arr)
  7437. {
  7438. return arr[Math.floor(Math.random() * arr.length)];
  7439. }
  7440. /*
  7441. * Returns true if the string 's' contains one of the
  7442. * template strings.
  7443. */
  7444. function hasTemplate(s)
  7445. {
  7446. for (var template in CATEGORIES){
  7447. if (s.indexOf(template) >= 0){
  7448. return true;
  7449. }
  7450. }
  7451. }
  7452. /**
  7453. * Generates new room name.
  7454. */
  7455. var RoomNameGenerator = {
  7456. generateRoomWithoutSeparator: function()
  7457. {
  7458. // Note that if more than one pattern is available, the choice of 'name' won't be random (names from patterns
  7459. // with fewer options will have higher probability of being chosen that names from patterns with more options).
  7460. var name = randomElement(PATTERNS);
  7461. var word;
  7462. while (hasTemplate(name)){
  7463. for (var template in CATEGORIES){
  7464. word = randomElement(CATEGORIES[template]);
  7465. name = name.replace(template, word);
  7466. }
  7467. }
  7468. return name;
  7469. }
  7470. }
  7471. module.exports = RoomNameGenerator;
  7472. },{}],33:[function(require,module,exports){
  7473. var animateTimeout, updateTimeout;
  7474. var RoomNameGenerator = require("./RoomnameGenerator");
  7475. function enter_room()
  7476. {
  7477. var val = $("#enter_room_field").val();
  7478. if(!val) {
  7479. val = $("#enter_room_field").attr("room_name");
  7480. }
  7481. if (val) {
  7482. window.location.pathname = "/" + val;
  7483. }
  7484. }
  7485. function animate(word) {
  7486. var currentVal = $("#enter_room_field").attr("placeholder");
  7487. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  7488. animateTimeout = setTimeout(function() {
  7489. animate(word.substring(1, word.length))
  7490. }, 70);
  7491. }
  7492. function update_roomname()
  7493. {
  7494. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  7495. $("#enter_room_field").attr("room_name", word);
  7496. $("#enter_room_field").attr("placeholder", "");
  7497. clearTimeout(animateTimeout);
  7498. animate(word);
  7499. updateTimeout = setTimeout(update_roomname, 10000);
  7500. }
  7501. function setupWelcomePage()
  7502. {
  7503. $("#videoconference_page").hide();
  7504. $("#domain_name").text(
  7505. window.location.protocol + "//" + window.location.host + "/");
  7506. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  7507. var leftWatermarkDiv
  7508. = $("#welcome_page_header div[class='watermark leftwatermark']");
  7509. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  7510. {
  7511. leftWatermarkDiv.css({display: 'block'});
  7512. leftWatermarkDiv.parent().get(0).href
  7513. = interfaceConfig.JITSI_WATERMARK_LINK;
  7514. }
  7515. }
  7516. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  7517. var rightWatermarkDiv
  7518. = $("#welcome_page_header div[class='watermark rightwatermark']");
  7519. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  7520. rightWatermarkDiv.css({display: 'block'});
  7521. rightWatermarkDiv.parent().get(0).href
  7522. = interfaceConfig.BRAND_WATERMARK_LINK;
  7523. rightWatermarkDiv.get(0).style.backgroundImage
  7524. = "url(images/rightwatermark.png)";
  7525. }
  7526. }
  7527. if (interfaceConfig.SHOW_POWERED_BY) {
  7528. $("#welcome_page_header>a[class='poweredby']")
  7529. .css({display: 'block'});
  7530. }
  7531. $("#enter_room_button").click(function()
  7532. {
  7533. enter_room();
  7534. });
  7535. $("#enter_room_field").keydown(function (event) {
  7536. if (event.keyCode === 13 /* enter */) {
  7537. enter_room();
  7538. }
  7539. });
  7540. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  7541. var updateTimeout;
  7542. var animateTimeout;
  7543. $("#reload_roomname").click(function () {
  7544. clearTimeout(updateTimeout);
  7545. clearTimeout(animateTimeout);
  7546. update_roomname();
  7547. });
  7548. $("#reload_roomname").show();
  7549. update_roomname();
  7550. }
  7551. $("#disable_welcome").click(function () {
  7552. window.localStorage.welcomePageDisabled
  7553. = $("#disable_welcome").is(":checked");
  7554. });
  7555. }
  7556. module.exports = setupWelcomePage;
  7557. },{"./RoomnameGenerator":32}],34:[function(require,module,exports){
  7558. var EventEmitter = require("events");
  7559. var eventEmitter = new EventEmitter();
  7560. var CQEvents = require("../../service/connectionquality/CQEvents");
  7561. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7562. /**
  7563. * local stats
  7564. * @type {{}}
  7565. */
  7566. var stats = {};
  7567. /**
  7568. * remote stats
  7569. * @type {{}}
  7570. */
  7571. var remoteStats = {};
  7572. /**
  7573. * Interval for sending statistics to other participants
  7574. * @type {null}
  7575. */
  7576. var sendIntervalId = null;
  7577. /**
  7578. * Start statistics sending.
  7579. */
  7580. function startSendingStats() {
  7581. sendStats();
  7582. sendIntervalId = setInterval(sendStats, 10000);
  7583. }
  7584. /**
  7585. * Sends statistics to other participants
  7586. */
  7587. function sendStats() {
  7588. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  7589. }
  7590. /**
  7591. * Converts statistics to format for sending through XMPP
  7592. * @param stats the statistics
  7593. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  7594. */
  7595. function convertToMUCStats(stats) {
  7596. return {
  7597. "bitrate_download": stats.bitrate.download,
  7598. "bitrate_upload": stats.bitrate.upload,
  7599. "packetLoss_total": stats.packetLoss.total,
  7600. "packetLoss_download": stats.packetLoss.download,
  7601. "packetLoss_upload": stats.packetLoss.upload
  7602. };
  7603. }
  7604. /**
  7605. * Converts statitistics to format used by VideoLayout
  7606. * @param stats
  7607. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  7608. */
  7609. function parseMUCStats(stats) {
  7610. return {
  7611. bitrate: {
  7612. download: stats.bitrate_download,
  7613. upload: stats.bitrate_upload
  7614. },
  7615. packetLoss: {
  7616. total: stats.packetLoss_total,
  7617. download: stats.packetLoss_download,
  7618. upload: stats.packetLoss_upload
  7619. }
  7620. };
  7621. }
  7622. var ConnectionQuality = {
  7623. init: function () {
  7624. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  7625. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  7626. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  7627. },
  7628. /**
  7629. * Updates the local statistics
  7630. * @param data new statistics
  7631. */
  7632. updateLocalStats: function (data) {
  7633. stats = data;
  7634. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  7635. if (sendIntervalId == null) {
  7636. startSendingStats();
  7637. }
  7638. },
  7639. /**
  7640. * Updates remote statistics
  7641. * @param jid the jid associated with the statistics
  7642. * @param data the statistics
  7643. */
  7644. updateRemoteStats: function (jid, data) {
  7645. if (data == null || data.packetLoss_total == null) {
  7646. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  7647. return;
  7648. }
  7649. remoteStats[jid] = parseMUCStats(data);
  7650. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  7651. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  7652. },
  7653. /**
  7654. * Stops statistics sending.
  7655. */
  7656. stopSendingStats: function () {
  7657. clearInterval(sendIntervalId);
  7658. sendIntervalId = null;
  7659. //notify UI about stopping statistics gathering
  7660. eventEmitter.emit(CQEvents.STOP);
  7661. },
  7662. /**
  7663. * Returns the local statistics.
  7664. */
  7665. getStats: function () {
  7666. return stats;
  7667. },
  7668. addListener: function (type, listener) {
  7669. eventEmitter.on(type, listener);
  7670. }
  7671. };
  7672. module.exports = ConnectionQuality;
  7673. },{"../../service/connectionquality/CQEvents":85,"../../service/xmpp/XMPPEvents":88,"events":89}],35:[function(require,module,exports){
  7674. /* global $, alert, changeLocalVideo, chrome, config, getConferenceHandler, getUserMediaWithConstraints */
  7675. /**
  7676. * Indicates that desktop stream is currently in use(for toggle purpose).
  7677. * @type {boolean}
  7678. */
  7679. var isUsingScreenStream = false;
  7680. /**
  7681. * Indicates that switch stream operation is in progress and prevent from triggering new events.
  7682. * @type {boolean}
  7683. */
  7684. var switchInProgress = false;
  7685. /**
  7686. * Method used to get screen sharing stream.
  7687. *
  7688. * @type {function (stream_callback, failure_callback}
  7689. */
  7690. var obtainDesktopStream = null;
  7691. /**
  7692. * Flag used to cache desktop sharing enabled state. Do not use directly as it can be <tt>null</tt>.
  7693. * @type {null|boolean}
  7694. */
  7695. var _desktopSharingEnabled = null;
  7696. var EventEmitter = require("events");
  7697. var eventEmitter = new EventEmitter();
  7698. var DesktopSharingEventTypes = require("../../service/desktopsharing/DesktopSharingEventTypes");
  7699. /**
  7700. * Method obtains desktop stream from WebRTC 'screen' source.
  7701. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  7702. */
  7703. function obtainWebRTCScreen(streamCallback, failCallback) {
  7704. APP.RTC.getUserMediaWithConstraints(
  7705. ['screen'],
  7706. streamCallback,
  7707. failCallback
  7708. );
  7709. }
  7710. /**
  7711. * Constructs inline install URL for Chrome desktop streaming extension.
  7712. * The 'chromeExtensionId' must be defined in config.js.
  7713. * @returns {string}
  7714. */
  7715. function getWebStoreInstallUrl()
  7716. {
  7717. return "https://chrome.google.com/webstore/detail/" + config.chromeExtensionId;
  7718. }
  7719. /**
  7720. * Checks whether extension update is required.
  7721. * @param minVersion minimal required version
  7722. * @param extVersion current extension version
  7723. * @returns {boolean}
  7724. */
  7725. function isUpdateRequired(minVersion, extVersion)
  7726. {
  7727. try
  7728. {
  7729. var s1 = minVersion.split('.');
  7730. var s2 = extVersion.split('.');
  7731. var len = Math.max(s1.length, s2.length);
  7732. for (var i = 0; i < len; i++)
  7733. {
  7734. var n1 = 0,
  7735. n2 = 0;
  7736. if (i < s1.length)
  7737. n1 = parseInt(s1[i]);
  7738. if (i < s2.length)
  7739. n2 = parseInt(s2[i]);
  7740. if (isNaN(n1) || isNaN(n2))
  7741. {
  7742. return true;
  7743. }
  7744. else if (n1 !== n2)
  7745. {
  7746. return n1 > n2;
  7747. }
  7748. }
  7749. // will happen if boths version has identical numbers in
  7750. // their components (even if one of them is longer, has more components)
  7751. return false;
  7752. }
  7753. catch (e)
  7754. {
  7755. console.error("Failed to parse extension version", e);
  7756. APP.UI.messageHandler.showError("dialog.error",
  7757. "dialog.detectext");
  7758. return true;
  7759. }
  7760. }
  7761. function checkExtInstalled(isInstalledCallback) {
  7762. if (!chrome.runtime) {
  7763. // No API, so no extension for sure
  7764. isInstalledCallback(false);
  7765. return;
  7766. }
  7767. chrome.runtime.sendMessage(
  7768. config.chromeExtensionId,
  7769. { getVersion: true },
  7770. function (response) {
  7771. if (!response || !response.version) {
  7772. // Communication failure - assume that no endpoint exists
  7773. console.warn("Extension not installed?: " + chrome.runtime.lastError);
  7774. isInstalledCallback(false);
  7775. } else {
  7776. // Check installed extension version
  7777. var extVersion = response.version;
  7778. console.log('Extension version is: ' + extVersion);
  7779. var updateRequired = isUpdateRequired(config.minChromeExtVersion, extVersion);
  7780. if (updateRequired) {
  7781. alert(
  7782. 'Jitsi Desktop Streamer requires update. ' +
  7783. 'Changes will take effect after next Chrome restart.');
  7784. }
  7785. isInstalledCallback(!updateRequired);
  7786. }
  7787. }
  7788. );
  7789. }
  7790. function doGetStreamFromExtension(streamCallback, failCallback) {
  7791. // Sends 'getStream' msg to the extension. Extension id must be defined in the config.
  7792. chrome.runtime.sendMessage(
  7793. config.chromeExtensionId,
  7794. { getStream: true, sources: config.desktopSharingSources },
  7795. function (response) {
  7796. if (!response) {
  7797. failCallback(chrome.runtime.lastError);
  7798. return;
  7799. }
  7800. console.log("Response from extension: " + response);
  7801. if (response.streamId) {
  7802. APP.RTC.getUserMediaWithConstraints(
  7803. ['desktop'],
  7804. function (stream) {
  7805. streamCallback(stream);
  7806. },
  7807. failCallback,
  7808. null, null, null,
  7809. response.streamId);
  7810. } else {
  7811. failCallback("Extension failed to get the stream");
  7812. }
  7813. }
  7814. );
  7815. }
  7816. /**
  7817. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop' stream for returned stream token.
  7818. */
  7819. function obtainScreenFromExtension(streamCallback, failCallback) {
  7820. checkExtInstalled(
  7821. function (isInstalled) {
  7822. if (isInstalled) {
  7823. doGetStreamFromExtension(streamCallback, failCallback);
  7824. } else {
  7825. chrome.webstore.install(
  7826. getWebStoreInstallUrl(),
  7827. function (arg) {
  7828. console.log("Extension installed successfully", arg);
  7829. // We need to reload the page in order to get the access to chrome.runtime
  7830. window.location.reload(false);
  7831. },
  7832. function (arg) {
  7833. console.log("Failed to install the extension", arg);
  7834. failCallback(arg);
  7835. APP.UI.messageHandler.showError("dialog.error",
  7836. "dialog.failtoinstall");
  7837. }
  7838. );
  7839. }
  7840. }
  7841. );
  7842. }
  7843. /**
  7844. * Call this method to toggle desktop sharing feature.
  7845. * @param method pass "ext" to use chrome extension for desktop capture(chrome extension required),
  7846. * pass "webrtc" to use WebRTC "screen" desktop source('chrome://flags/#enable-usermedia-screen-capture'
  7847. * must be enabled), pass any other string or nothing in order to disable this feature completely.
  7848. */
  7849. function setDesktopSharing(method) {
  7850. // Check if we are running chrome
  7851. if (!navigator.webkitGetUserMedia) {
  7852. obtainDesktopStream = null;
  7853. console.info("Desktop sharing disabled");
  7854. } else if (method == "ext") {
  7855. obtainDesktopStream = obtainScreenFromExtension;
  7856. console.info("Using Chrome extension for desktop sharing");
  7857. } else if (method == "webrtc") {
  7858. obtainDesktopStream = obtainWebRTCScreen;
  7859. console.info("Using Chrome WebRTC for desktop sharing");
  7860. }
  7861. // Reset enabled cache
  7862. _desktopSharingEnabled = null;
  7863. }
  7864. /**
  7865. * Initializes <link rel=chrome-webstore-item /> with extension id set in config.js to support inline installs.
  7866. * Host site must be selected as main website of published extension.
  7867. */
  7868. function initInlineInstalls()
  7869. {
  7870. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  7871. }
  7872. function getSwitchStreamFailed(error) {
  7873. console.error("Failed to obtain the stream to switch to", error);
  7874. switchInProgress = false;
  7875. }
  7876. function streamSwitchDone() {
  7877. switchInProgress = false;
  7878. eventEmitter.emit(
  7879. DesktopSharingEventTypes.SWITCHING_DONE,
  7880. isUsingScreenStream);
  7881. }
  7882. function newStreamCreated(stream)
  7883. {
  7884. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  7885. stream, isUsingScreenStream, streamSwitchDone);
  7886. }
  7887. module.exports = {
  7888. isUsingScreenStream: function () {
  7889. return isUsingScreenStream;
  7890. },
  7891. /**
  7892. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available and enabled.
  7893. */
  7894. isDesktopSharingEnabled: function () {
  7895. if (_desktopSharingEnabled === null) {
  7896. if (obtainDesktopStream === obtainScreenFromExtension) {
  7897. // Parse chrome version
  7898. var userAgent = navigator.userAgent.toLowerCase();
  7899. // We can assume that user agent is chrome, because it's enforced when 'ext' streaming method is set
  7900. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  7901. console.log("Chrome version" + userAgent, ver);
  7902. _desktopSharingEnabled = ver >= 34;
  7903. } else {
  7904. _desktopSharingEnabled = obtainDesktopStream === obtainWebRTCScreen;
  7905. }
  7906. }
  7907. return _desktopSharingEnabled;
  7908. },
  7909. init: function () {
  7910. setDesktopSharing(config.desktopSharing);
  7911. // Initialize Chrome extension inline installs
  7912. if (config.chromeExtensionId) {
  7913. initInlineInstalls();
  7914. }
  7915. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  7916. },
  7917. addListener: function(listener, type)
  7918. {
  7919. eventEmitter.on(type, listener);
  7920. },
  7921. removeListener: function (listener,type) {
  7922. eventEmitter.removeListener(type, listener);
  7923. },
  7924. /*
  7925. * Toggles screen sharing.
  7926. */
  7927. toggleScreenSharing: function () {
  7928. if (switchInProgress || !obtainDesktopStream) {
  7929. console.warn("Switch in progress or no method defined");
  7930. return;
  7931. }
  7932. switchInProgress = true;
  7933. if (!isUsingScreenStream)
  7934. {
  7935. // Switch to desktop stream
  7936. obtainDesktopStream(
  7937. function (stream) {
  7938. // We now use screen stream
  7939. isUsingScreenStream = true;
  7940. // Hook 'ended' event to restore camera when screen stream stops
  7941. stream.addEventListener('ended',
  7942. function (e) {
  7943. if (!switchInProgress && isUsingScreenStream) {
  7944. toggleScreenSharing();
  7945. }
  7946. }
  7947. );
  7948. newStreamCreated(stream);
  7949. },
  7950. getSwitchStreamFailed);
  7951. } else {
  7952. // Disable screen stream
  7953. APP.RTC.getUserMediaWithConstraints(
  7954. ['video'],
  7955. function (stream) {
  7956. // We are now using camera stream
  7957. isUsingScreenStream = false;
  7958. newStreamCreated(stream);
  7959. },
  7960. getSwitchStreamFailed, config.resolution || '360'
  7961. );
  7962. }
  7963. }
  7964. };
  7965. },{"../../service/desktopsharing/DesktopSharingEventTypes":86,"events":89}],36:[function(require,module,exports){
  7966. //maps keycode to character, id of popover for given function and function
  7967. var shortcuts = {
  7968. 67: {
  7969. character: "C",
  7970. id: "toggleChatPopover",
  7971. function: APP.UI.toggleChat
  7972. },
  7973. 70: {
  7974. character: "F",
  7975. id: "filmstripPopover",
  7976. function: APP.UI.toggleFilmStrip
  7977. },
  7978. 77: {
  7979. character: "M",
  7980. id: "mutePopover",
  7981. function: APP.UI.toggleAudio
  7982. },
  7983. 84: {
  7984. character: "T",
  7985. function: function() {
  7986. if(!APP.RTC.localAudio.isMuted()) {
  7987. APP.UI.toggleAudio();
  7988. }
  7989. }
  7990. },
  7991. 86: {
  7992. character: "V",
  7993. id: "toggleVideoPopover",
  7994. function: APP.UI.toggleVideo
  7995. }
  7996. };
  7997. var KeyboardShortcut = {
  7998. init: function () {
  7999. window.onkeyup = function(e) {
  8000. var keycode = e.which;
  8001. if(!($(":focus").is("input[type=text]") ||
  8002. $(":focus").is("input[type=password]") ||
  8003. $(":focus").is("textarea"))) {
  8004. if (typeof shortcuts[keycode] === "object") {
  8005. shortcuts[keycode].function();
  8006. }
  8007. else if (keycode >= "0".charCodeAt(0) &&
  8008. keycode <= "9".charCodeAt(0)) {
  8009. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  8010. }
  8011. //esc while the smileys are visible hides them
  8012. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  8013. APP.UI.toggleSmileys();
  8014. }
  8015. };
  8016. window.onkeydown = function(e) {
  8017. if(!($(":focus").is("input[type=text]") ||
  8018. $(":focus").is("input[type=password]") ||
  8019. $(":focus").is("textarea"))) {
  8020. if(e.which === "T".charCodeAt(0)) {
  8021. if(APP.RTC.localAudio.isMuted()) {
  8022. APP.UI.toggleAudio();
  8023. }
  8024. }
  8025. }
  8026. };
  8027. var self = this;
  8028. $('body').popover({ selector: '[data-toggle=popover]',
  8029. trigger: 'click hover',
  8030. content: function() {
  8031. return this.getAttribute("content") +
  8032. self.getShortcut(this.getAttribute("shortcut"));
  8033. }
  8034. });
  8035. },
  8036. /**
  8037. *
  8038. * @param id indicates the popover associated with the shortcut
  8039. * @returns {string} the keyboard shortcut used for the id given
  8040. */
  8041. getShortcut: function (id) {
  8042. for (var keycode in shortcuts) {
  8043. if (shortcuts.hasOwnProperty(keycode)) {
  8044. if (shortcuts[keycode].id === id) {
  8045. return " (" + shortcuts[keycode].character + ")";
  8046. }
  8047. }
  8048. }
  8049. return "";
  8050. }
  8051. };
  8052. module.exports = KeyboardShortcut;
  8053. },{}],37:[function(require,module,exports){
  8054. var email = '';
  8055. var displayName = '';
  8056. var userId;
  8057. var language = null;
  8058. function supportsLocalStorage() {
  8059. try {
  8060. return 'localStorage' in window && window.localStorage !== null;
  8061. } catch (e) {
  8062. console.log("localstorage is not supported");
  8063. return false;
  8064. }
  8065. }
  8066. function generateUniqueId() {
  8067. function _p8() {
  8068. return (Math.random().toString(16) + "000000000").substr(2, 8);
  8069. }
  8070. return _p8() + _p8() + _p8() + _p8();
  8071. }
  8072. if (supportsLocalStorage()) {
  8073. if (!window.localStorage.jitsiMeetId) {
  8074. window.localStorage.jitsiMeetId = generateUniqueId();
  8075. console.log("generated id", window.localStorage.jitsiMeetId);
  8076. }
  8077. userId = window.localStorage.jitsiMeetId || '';
  8078. email = window.localStorage.email || '';
  8079. displayName = window.localStorage.displayname || '';
  8080. language = window.localStorage.language;
  8081. } else {
  8082. console.log("local storage is not supported");
  8083. userId = generateUniqueId();
  8084. }
  8085. var Settings =
  8086. {
  8087. setDisplayName: function (newDisplayName) {
  8088. displayName = newDisplayName;
  8089. window.localStorage.displayname = displayName;
  8090. return displayName;
  8091. },
  8092. setEmail: function (newEmail)
  8093. {
  8094. email = newEmail;
  8095. window.localStorage.email = newEmail;
  8096. return email;
  8097. },
  8098. getSettings: function () {
  8099. return {
  8100. email: email,
  8101. displayName: displayName,
  8102. uid: userId,
  8103. language: language
  8104. };
  8105. },
  8106. setLanguage: function (lang) {
  8107. language = lang;
  8108. window.localStorage.language = lang;
  8109. }
  8110. };
  8111. module.exports = Settings;
  8112. },{}],38:[function(require,module,exports){
  8113. /**
  8114. *
  8115. * @constructor
  8116. */
  8117. function SimulcastLogger(name, lvl) {
  8118. this.name = name;
  8119. this.lvl = lvl;
  8120. }
  8121. SimulcastLogger.prototype.log = function (text) {
  8122. if (this.lvl) {
  8123. console.log(text);
  8124. }
  8125. };
  8126. SimulcastLogger.prototype.info = function (text) {
  8127. if (this.lvl > 1) {
  8128. console.info(text);
  8129. }
  8130. };
  8131. SimulcastLogger.prototype.fine = function (text) {
  8132. if (this.lvl > 2) {
  8133. console.log(text);
  8134. }
  8135. };
  8136. SimulcastLogger.prototype.error = function (text) {
  8137. console.error(text);
  8138. };
  8139. module.exports = SimulcastLogger;
  8140. },{}],39:[function(require,module,exports){
  8141. var SimulcastLogger = require("./SimulcastLogger");
  8142. var SimulcastUtils = require("./SimulcastUtils");
  8143. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  8144. function SimulcastReceiver() {
  8145. this.simulcastUtils = new SimulcastUtils();
  8146. this.logger = new SimulcastLogger('SimulcastReceiver', 1);
  8147. }
  8148. SimulcastReceiver.prototype._remoteVideoSourceCache = '';
  8149. SimulcastReceiver.prototype._remoteMaps = {
  8150. msid2Quality: {},
  8151. ssrc2Msid: {},
  8152. msid2ssrc: {},
  8153. receivingVideoStreams: {}
  8154. };
  8155. SimulcastReceiver.prototype._cacheRemoteVideoSources = function (lines) {
  8156. this._remoteVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  8157. };
  8158. SimulcastReceiver.prototype._restoreRemoteVideoSources = function (lines) {
  8159. this.simulcastUtils._replaceVideoSources(lines, this._remoteVideoSourceCache);
  8160. };
  8161. SimulcastReceiver.prototype._ensureGoogConference = function (lines) {
  8162. var sb;
  8163. this.logger.info('Ensuring x-google-conference flag...')
  8164. if (this.simulcastUtils._indexOfArray('a=x-google-flag:conference', lines) === this.simulcastUtils._emptyCompoundIndex) {
  8165. // TODO(gp) do that for the audio as well as suggested by fippo.
  8166. // Add the google conference flag
  8167. sb = this.simulcastUtils._getVideoSources(lines);
  8168. sb = ['a=x-google-flag:conference'].concat(sb);
  8169. this.simulcastUtils._replaceVideoSources(lines, sb);
  8170. }
  8171. };
  8172. SimulcastReceiver.prototype._restoreSimulcastGroups = function (sb) {
  8173. this._restoreRemoteVideoSources(sb);
  8174. };
  8175. /**
  8176. * Restores the simulcast groups of the remote description. In
  8177. * transformRemoteDescription we remove those in order for the set remote
  8178. * description to succeed. The focus needs the signal the groups to new
  8179. * participants.
  8180. *
  8181. * @param desc
  8182. * @returns {*}
  8183. */
  8184. SimulcastReceiver.prototype.reverseTransformRemoteDescription = function (desc) {
  8185. var sb;
  8186. if (!this.simulcastUtils.isValidDescription(desc)) {
  8187. return desc;
  8188. }
  8189. if (config.enableSimulcast) {
  8190. sb = desc.sdp.split('\r\n');
  8191. this._restoreSimulcastGroups(sb);
  8192. desc = new RTCSessionDescription({
  8193. type: desc.type,
  8194. sdp: sb.join('\r\n')
  8195. });
  8196. }
  8197. return desc;
  8198. };
  8199. SimulcastUtils.prototype._ensureOrder = function (lines) {
  8200. var videoSources, sb;
  8201. videoSources = this.parseMedia(lines, ['video'])[0];
  8202. sb = this._compileVideoSources(videoSources);
  8203. this._replaceVideoSources(lines, sb);
  8204. };
  8205. SimulcastReceiver.prototype._updateRemoteMaps = function (lines) {
  8206. var remoteVideoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0],
  8207. videoSource, quality;
  8208. // (re) initialize the remote maps.
  8209. this._remoteMaps.msid2Quality = {};
  8210. this._remoteMaps.ssrc2Msid = {};
  8211. this._remoteMaps.msid2ssrc = {};
  8212. var self = this;
  8213. if (remoteVideoSources.groups && remoteVideoSources.groups.length !== 0) {
  8214. remoteVideoSources.groups.forEach(function (group) {
  8215. if (group.semantics === 'SIM' && group.ssrcs && group.ssrcs.length !== 0) {
  8216. quality = 0;
  8217. group.ssrcs.forEach(function (ssrc) {
  8218. videoSource = remoteVideoSources.sources[ssrc];
  8219. self._remoteMaps.msid2Quality[videoSource.msid] = quality++;
  8220. self._remoteMaps.ssrc2Msid[videoSource.ssrc] = videoSource.msid;
  8221. self._remoteMaps.msid2ssrc[videoSource.msid] = videoSource.ssrc;
  8222. });
  8223. }
  8224. });
  8225. }
  8226. };
  8227. SimulcastReceiver.prototype._setReceivingVideoStream = function (resource, ssrc) {
  8228. this._remoteMaps.receivingVideoStreams[resource] = ssrc;
  8229. };
  8230. /**
  8231. * Returns a stream with single video track, the one currently being
  8232. * received by this endpoint.
  8233. *
  8234. * @param stream the remote simulcast stream.
  8235. * @returns {webkitMediaStream}
  8236. */
  8237. SimulcastReceiver.prototype.getReceivingVideoStream = function (stream) {
  8238. var tracks, i, electedTrack, msid, quality = 0, receivingTrackId;
  8239. var self = this;
  8240. if (config.enableSimulcast) {
  8241. stream.getVideoTracks().some(function (track) {
  8242. return Object.keys(self._remoteMaps.receivingVideoStreams).some(function (resource) {
  8243. var ssrc = self._remoteMaps.receivingVideoStreams[resource];
  8244. var msid = self._remoteMaps.ssrc2Msid[ssrc];
  8245. if (msid == [stream.id, track.id].join(' ')) {
  8246. electedTrack = track;
  8247. return true;
  8248. }
  8249. });
  8250. });
  8251. if (!electedTrack) {
  8252. // we don't have an elected track, choose by initial quality.
  8253. tracks = stream.getVideoTracks();
  8254. for (i = 0; i < tracks.length; i++) {
  8255. msid = [stream.id, tracks[i].id].join(' ');
  8256. if (this._remoteMaps.msid2Quality[msid] === quality) {
  8257. electedTrack = tracks[i];
  8258. break;
  8259. }
  8260. }
  8261. // TODO(gp) if the initialQuality could not be satisfied, lower
  8262. // the requirement and try again.
  8263. }
  8264. }
  8265. return (electedTrack)
  8266. ? new webkitMediaStream([electedTrack])
  8267. : stream;
  8268. };
  8269. SimulcastReceiver.prototype.getReceivingSSRC = function (jid) {
  8270. var resource = Strophe.getResourceFromJid(jid);
  8271. var ssrc = this._remoteMaps.receivingVideoStreams[resource];
  8272. // If we haven't receiving a "changed" event yet, then we must be receiving
  8273. // low quality (that the sender always streams).
  8274. if(!ssrc)
  8275. {
  8276. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  8277. var remoteStream = remoteStreamObject.getOriginalStream();
  8278. var tracks = remoteStream.getVideoTracks();
  8279. if (tracks) {
  8280. for (var k = 0; k < tracks.length; k++) {
  8281. var track = tracks[k];
  8282. var msid = [remoteStream.id, track.id].join(' ');
  8283. var _ssrc = this._remoteMaps.msid2ssrc[msid];
  8284. var quality = this._remoteMaps.msid2Quality[msid];
  8285. if (quality == 0) {
  8286. ssrc = _ssrc;
  8287. }
  8288. }
  8289. }
  8290. }
  8291. return ssrc;
  8292. };
  8293. SimulcastReceiver.prototype.getReceivingVideoStreamBySSRC = function (ssrc)
  8294. {
  8295. var sid, electedStream;
  8296. var i, j, k;
  8297. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  8298. if(jid && APP.RTC.remoteStreams[jid])
  8299. {
  8300. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  8301. var remoteStream = remoteStreamObject.getOriginalStream();
  8302. var tracks = remoteStream.getVideoTracks();
  8303. if (tracks) {
  8304. for (k = 0; k < tracks.length; k++) {
  8305. var track = tracks[k];
  8306. var msid = [remoteStream.id, track.id].join(' ');
  8307. var tmp = this._remoteMaps.msid2ssrc[msid];
  8308. if (tmp == ssrc) {
  8309. electedStream = new webkitMediaStream([track]);
  8310. sid = remoteStreamObject.sid;
  8311. // stream found, stop.
  8312. break;
  8313. }
  8314. }
  8315. }
  8316. }
  8317. else
  8318. {
  8319. console.debug(APP.RTC.remoteStreams, jid, ssrc);
  8320. }
  8321. return {
  8322. sid: sid,
  8323. stream: electedStream
  8324. };
  8325. };
  8326. /**
  8327. * Gets the fully qualified msid (stream.id + track.id) associated to the
  8328. * SSRC.
  8329. *
  8330. * @param ssrc
  8331. * @returns {*}
  8332. */
  8333. SimulcastReceiver.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  8334. return this._remoteMaps.ssrc2Msid[ssrc];
  8335. };
  8336. /**
  8337. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  8338. * either gets confused and thinks this is an FID group or, if an FID group
  8339. * is already present, it fails to set the remote description.
  8340. *
  8341. * @param desc
  8342. * @returns {*}
  8343. */
  8344. SimulcastReceiver.prototype.transformRemoteDescription = function (desc) {
  8345. if (desc && desc.sdp) {
  8346. var sb = desc.sdp.split('\r\n');
  8347. this._updateRemoteMaps(sb);
  8348. this._cacheRemoteVideoSources(sb);
  8349. // NOTE(gp) this needs to be called after updateRemoteMaps because we
  8350. // need the simulcast group in the _updateRemoteMaps() method.
  8351. this.simulcastUtils._removeSimulcastGroup(sb);
  8352. if (desc.sdp.indexOf('a=ssrc-group:SIM') !== -1) {
  8353. // We don't need the goog conference flag if we're not doing
  8354. // simulcast.
  8355. this._ensureGoogConference(sb);
  8356. }
  8357. desc = new RTCSessionDescription({
  8358. type: desc.type,
  8359. sdp: sb.join('\r\n')
  8360. });
  8361. this.logger.fine(['Transformed remote description', desc.sdp].join(' '));
  8362. }
  8363. return desc;
  8364. };
  8365. module.exports = SimulcastReceiver;
  8366. },{"../../service/RTC/MediaStreamTypes":78,"./SimulcastLogger":38,"./SimulcastUtils":41}],40:[function(require,module,exports){
  8367. var SimulcastLogger = require("./SimulcastLogger");
  8368. var SimulcastUtils = require("./SimulcastUtils");
  8369. function SimulcastSender() {
  8370. this.simulcastUtils = new SimulcastUtils();
  8371. this.logger = new SimulcastLogger('SimulcastSender', 1);
  8372. }
  8373. SimulcastSender.prototype.displayedLocalVideoStream = null;
  8374. SimulcastSender.prototype._generateGuid = (function () {
  8375. function s4() {
  8376. return Math.floor((1 + Math.random()) * 0x10000)
  8377. .toString(16)
  8378. .substring(1);
  8379. }
  8380. return function () {
  8381. return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
  8382. s4() + '-' + s4() + s4() + s4();
  8383. };
  8384. }());
  8385. // Returns a random integer between min (included) and max (excluded)
  8386. // Using Math.round() gives a non-uniform distribution!
  8387. SimulcastSender.prototype._generateRandomSSRC = function () {
  8388. var min = 0, max = 0xffffffff;
  8389. return Math.floor(Math.random() * (max - min)) + min;
  8390. };
  8391. SimulcastSender.prototype.getLocalVideoStream = function () {
  8392. return (this.displayedLocalVideoStream != null)
  8393. ? this.displayedLocalVideoStream
  8394. // in case we have no simulcast at all, i.e. we didn't perform the GUM
  8395. : APP.RTC.localVideo.getOriginalStream();
  8396. };
  8397. function NativeSimulcastSender() {
  8398. SimulcastSender.call(this); // call the super constructor.
  8399. }
  8400. NativeSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8401. NativeSimulcastSender.prototype._localExplosionMap = {};
  8402. NativeSimulcastSender.prototype._isUsingScreenStream = false;
  8403. NativeSimulcastSender.prototype._localVideoSourceCache = '';
  8404. NativeSimulcastSender.prototype.reset = function () {
  8405. this._localExplosionMap = {};
  8406. this._isUsingScreenStream = APP.desktopsharing.isUsingScreenStream();
  8407. };
  8408. NativeSimulcastSender.prototype._cacheLocalVideoSources = function (lines) {
  8409. this._localVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  8410. };
  8411. NativeSimulcastSender.prototype._restoreLocalVideoSources = function (lines) {
  8412. this.simulcastUtils._replaceVideoSources(lines, this._localVideoSourceCache);
  8413. };
  8414. NativeSimulcastSender.prototype._appendSimulcastGroup = function (lines) {
  8415. var videoSources, ssrcGroup, simSSRC, numOfSubs = 2, i, sb, msid;
  8416. this.logger.info('Appending simulcast group...');
  8417. // Get the primary SSRC information.
  8418. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8419. // Start building the SIM SSRC group.
  8420. ssrcGroup = ['a=ssrc-group:SIM'];
  8421. // The video source buffer.
  8422. sb = [];
  8423. // Create the simulcast sub-streams.
  8424. for (i = 0; i < numOfSubs; i++) {
  8425. // TODO(gp) prevent SSRC collision.
  8426. simSSRC = this._generateRandomSSRC();
  8427. ssrcGroup.push(simSSRC);
  8428. if (videoSources.base) {
  8429. sb.splice.apply(sb, [sb.length, 0].concat(
  8430. [["a=ssrc:", simSSRC, " cname:", videoSources.base.cname].join(''),
  8431. ["a=ssrc:", simSSRC, " msid:", videoSources.base.msid].join('')]
  8432. ));
  8433. }
  8434. this.logger.info(['Generated substream ', i, ' with SSRC ', simSSRC, '.'].join(''));
  8435. }
  8436. // Add the group sim layers.
  8437. sb.splice(0, 0, ssrcGroup.join(' '))
  8438. this.simulcastUtils._replaceVideoSources(lines, sb);
  8439. };
  8440. // Does the actual patching.
  8441. NativeSimulcastSender.prototype._ensureSimulcastGroup = function (lines) {
  8442. this.logger.info('Ensuring simulcast group...');
  8443. if (this.simulcastUtils._indexOfArray('a=ssrc-group:SIM', lines) === this.simulcastUtils._emptyCompoundIndex) {
  8444. this._appendSimulcastGroup(lines);
  8445. this._cacheLocalVideoSources(lines);
  8446. } else {
  8447. // verify that the ssrcs participating in the SIM group are present
  8448. // in the SDP (needed for presence).
  8449. this._restoreLocalVideoSources(lines);
  8450. }
  8451. };
  8452. /**
  8453. * Produces a single stream with multiple tracks for local video sources.
  8454. *
  8455. * @param lines
  8456. * @private
  8457. */
  8458. NativeSimulcastSender.prototype._explodeSimulcastSenderSources = function (lines) {
  8459. var sb, msid, sid, tid, videoSources, self;
  8460. this.logger.info('Exploding local video sources...');
  8461. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8462. self = this;
  8463. if (videoSources.groups && videoSources.groups.length !== 0) {
  8464. videoSources.groups.forEach(function (group) {
  8465. if (group.semantics === 'SIM') {
  8466. group.ssrcs.forEach(function (ssrc) {
  8467. // Get the msid for this ssrc..
  8468. if (self._localExplosionMap[ssrc]) {
  8469. // .. either from the explosion map..
  8470. msid = self._localExplosionMap[ssrc];
  8471. } else {
  8472. // .. or generate a new one (msid).
  8473. sid = videoSources.sources[ssrc].msid
  8474. .substring(0, videoSources.sources[ssrc].msid.indexOf(' '));
  8475. tid = self._generateGuid();
  8476. msid = [sid, tid].join(' ');
  8477. self._localExplosionMap[ssrc] = msid;
  8478. }
  8479. // Assign it to the source object.
  8480. videoSources.sources[ssrc].msid = msid;
  8481. // TODO(gp) Change the msid of associated sources.
  8482. });
  8483. }
  8484. });
  8485. }
  8486. sb = this.simulcastUtils._compileVideoSources(videoSources);
  8487. this.simulcastUtils._replaceVideoSources(lines, sb);
  8488. };
  8489. /**
  8490. * GUM for simulcast.
  8491. *
  8492. * @param constraints
  8493. * @param success
  8494. * @param err
  8495. */
  8496. NativeSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8497. // There's nothing special to do for native simulcast, so just do a normal GUM.
  8498. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8499. success(hqStream);
  8500. }, err);
  8501. };
  8502. /**
  8503. * Prepares the local description for public usage (i.e. to be signaled
  8504. * through Jingle to the focus).
  8505. *
  8506. * @param desc
  8507. * @returns {RTCSessionDescription}
  8508. */
  8509. NativeSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8510. var sb;
  8511. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  8512. return desc;
  8513. }
  8514. sb = desc.sdp.split('\r\n');
  8515. this._explodeSimulcastSenderSources(sb);
  8516. desc = new RTCSessionDescription({
  8517. type: desc.type,
  8518. sdp: sb.join('\r\n')
  8519. });
  8520. this.logger.fine(['Exploded local video sources', desc.sdp].join(' '));
  8521. return desc;
  8522. };
  8523. /**
  8524. * Ensures that the simulcast group is present in the answer, _if_ native
  8525. * simulcast is enabled,
  8526. *
  8527. * @param desc
  8528. * @returns {*}
  8529. */
  8530. NativeSimulcastSender.prototype.transformAnswer = function (desc) {
  8531. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  8532. return desc;
  8533. }
  8534. var sb = desc.sdp.split('\r\n');
  8535. // Even if we have enabled native simulcasting previously
  8536. // (with a call to SLD with an appropriate SDP, for example),
  8537. // createAnswer seems to consistently generate incomplete SDP
  8538. // with missing SSRCS.
  8539. //
  8540. // So, subsequent calls to SLD will have missing SSRCS and presence
  8541. // won't have the complete list of SRCs.
  8542. this._ensureSimulcastGroup(sb);
  8543. desc = new RTCSessionDescription({
  8544. type: desc.type,
  8545. sdp: sb.join('\r\n')
  8546. });
  8547. this.logger.fine(['Transformed answer', desc.sdp].join(' '));
  8548. return desc;
  8549. };
  8550. /**
  8551. *
  8552. *
  8553. * @param desc
  8554. * @returns {*}
  8555. */
  8556. NativeSimulcastSender.prototype.transformLocalDescription = function (desc) {
  8557. return desc;
  8558. };
  8559. NativeSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  8560. // Nothing to do here, native simulcast does that auto-magically.
  8561. };
  8562. NativeSimulcastSender.prototype.constructor = NativeSimulcastSender;
  8563. function SimpleSimulcastSender() {
  8564. SimulcastSender.call(this);
  8565. }
  8566. SimpleSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8567. SimpleSimulcastSender.prototype.localStream = null;
  8568. SimpleSimulcastSender.prototype._localMaps = {
  8569. msids: [],
  8570. msid2ssrc: {}
  8571. };
  8572. /**
  8573. * Groups local video sources together in the ssrc-group:SIM group.
  8574. *
  8575. * @param lines
  8576. * @private
  8577. */
  8578. SimpleSimulcastSender.prototype._groupLocalVideoSources = function (lines) {
  8579. var sb, videoSources, ssrcs = [], ssrc;
  8580. this.logger.info('Grouping local video sources...');
  8581. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8582. for (ssrc in videoSources.sources) {
  8583. // jitsi-meet destroys/creates streams at various places causing
  8584. // the original local stream ids to change. The only thing that
  8585. // remains unchanged is the trackid.
  8586. this._localMaps.msid2ssrc[videoSources.sources[ssrc].msid.split(' ')[1]] = ssrc;
  8587. }
  8588. var self = this;
  8589. // TODO(gp) add only "free" sources.
  8590. this._localMaps.msids.forEach(function (msid) {
  8591. ssrcs.push(self._localMaps.msid2ssrc[msid]);
  8592. });
  8593. if (!videoSources.groups) {
  8594. videoSources.groups = [];
  8595. }
  8596. videoSources.groups.push({
  8597. 'semantics': 'SIM',
  8598. 'ssrcs': ssrcs
  8599. });
  8600. sb = this.simulcastUtils._compileVideoSources(videoSources);
  8601. this.simulcastUtils._replaceVideoSources(lines, sb);
  8602. };
  8603. /**
  8604. * GUM for simulcast.
  8605. *
  8606. * @param constraints
  8607. * @param success
  8608. * @param err
  8609. */
  8610. SimpleSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8611. // TODO(gp) what if we request a resolution not supported by the hardware?
  8612. // TODO(gp) make the lq stream configurable; although this wouldn't work with native simulcast
  8613. var lqConstraints = {
  8614. audio: false,
  8615. video: {
  8616. mandatory: {
  8617. maxWidth: 320,
  8618. maxHeight: 180,
  8619. maxFrameRate: 15
  8620. }
  8621. }
  8622. };
  8623. this.logger.info('HQ constraints: ', constraints);
  8624. this.logger.info('LQ constraints: ', lqConstraints);
  8625. // NOTE(gp) if we request the lq stream first webkitGetUserMedia
  8626. // fails randomly. Tested with Chrome 37. As fippo suggested, the
  8627. // reason appears to be that Chrome only acquires the cam once and
  8628. // then downscales the picture (https://code.google.com/p/chromium/issues/detail?id=346616#c11)
  8629. var self = this;
  8630. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8631. self.localStream = hqStream;
  8632. // reset local maps.
  8633. self._localMaps.msids = [];
  8634. self._localMaps.msid2ssrc = {};
  8635. // add hq trackid to local map
  8636. self._localMaps.msids.push(hqStream.getVideoTracks()[0].id);
  8637. navigator.webkitGetUserMedia(lqConstraints, function (lqStream) {
  8638. self.displayedLocalVideoStream = lqStream;
  8639. // NOTE(gp) The specification says Array.forEach() will visit
  8640. // the array elements in numeric order, and that it doesn't
  8641. // visit elements that don't exist.
  8642. // add lq trackid to local map
  8643. self._localMaps.msids.splice(0, 0, lqStream.getVideoTracks()[0].id);
  8644. self.localStream.addTrack(lqStream.getVideoTracks()[0]);
  8645. success(self.localStream);
  8646. }, err);
  8647. }, err);
  8648. };
  8649. /**
  8650. * Prepares the local description for public usage (i.e. to be signaled
  8651. * through Jingle to the focus).
  8652. *
  8653. * @param desc
  8654. * @returns {RTCSessionDescription}
  8655. */
  8656. SimpleSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8657. var sb;
  8658. if (!this.simulcastUtils.isValidDescription(desc)) {
  8659. return desc;
  8660. }
  8661. sb = desc.sdp.split('\r\n');
  8662. this._groupLocalVideoSources(sb);
  8663. desc = new RTCSessionDescription({
  8664. type: desc.type,
  8665. sdp: sb.join('\r\n')
  8666. });
  8667. this.logger.fine('Grouped local video sources');
  8668. this.logger.fine(desc.sdp);
  8669. return desc;
  8670. };
  8671. /**
  8672. * Ensures that the simulcast group is present in the answer, _if_ native
  8673. * simulcast is enabled,
  8674. *
  8675. * @param desc
  8676. * @returns {*}
  8677. */
  8678. SimpleSimulcastSender.prototype.transformAnswer = function (desc) {
  8679. return desc;
  8680. };
  8681. /**
  8682. *
  8683. *
  8684. * @param desc
  8685. * @returns {*}
  8686. */
  8687. SimpleSimulcastSender.prototype.transformLocalDescription = function (desc) {
  8688. var sb = desc.sdp.split('\r\n');
  8689. this.simulcastUtils._removeSimulcastGroup(sb);
  8690. desc = new RTCSessionDescription({
  8691. type: desc.type,
  8692. sdp: sb.join('\r\n')
  8693. });
  8694. this.logger.fine('Transformed local description');
  8695. this.logger.fine(desc.sdp);
  8696. return desc;
  8697. };
  8698. SimpleSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  8699. var trackid;
  8700. var self = this;
  8701. this.logger.log(['Requested to', enabled ? 'enable' : 'disable', ssrc].join(' '));
  8702. if (Object.keys(this._localMaps.msid2ssrc).some(function (tid) {
  8703. // Search for the track id that corresponds to the ssrc
  8704. if (self._localMaps.msid2ssrc[tid] == ssrc) {
  8705. trackid = tid;
  8706. return true;
  8707. }
  8708. }) && self.localStream.getVideoTracks().some(function (track) {
  8709. // Start/stop the track that corresponds to the track id
  8710. if (track.id === trackid) {
  8711. track.enabled = enabled;
  8712. return true;
  8713. }
  8714. })) {
  8715. this.logger.log([trackid, enabled ? 'enabled' : 'disabled'].join(' '));
  8716. $(document).trigger(enabled
  8717. ? 'simulcastlayerstarted'
  8718. : 'simulcastlayerstopped');
  8719. } else {
  8720. this.logger.error("I don't have a local stream with SSRC " + ssrc);
  8721. }
  8722. };
  8723. SimpleSimulcastSender.prototype.constructor = SimpleSimulcastSender;
  8724. function NoSimulcastSender() {
  8725. SimulcastSender.call(this);
  8726. }
  8727. NoSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8728. /**
  8729. * GUM for simulcast.
  8730. *
  8731. * @param constraints
  8732. * @param success
  8733. * @param err
  8734. */
  8735. NoSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8736. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8737. success(hqStream);
  8738. }, err);
  8739. };
  8740. /**
  8741. * Prepares the local description for public usage (i.e. to be signaled
  8742. * through Jingle to the focus).
  8743. *
  8744. * @param desc
  8745. * @returns {RTCSessionDescription}
  8746. */
  8747. NoSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8748. return desc;
  8749. };
  8750. /**
  8751. * Ensures that the simulcast group is present in the answer, _if_ native
  8752. * simulcast is enabled,
  8753. *
  8754. * @param desc
  8755. * @returns {*}
  8756. */
  8757. NoSimulcastSender.prototype.transformAnswer = function (desc) {
  8758. return desc;
  8759. };
  8760. /**
  8761. *
  8762. *
  8763. * @param desc
  8764. * @returns {*}
  8765. */
  8766. NoSimulcastSender.prototype.transformLocalDescription = function (desc) {
  8767. return desc;
  8768. };
  8769. NoSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  8770. };
  8771. NoSimulcastSender.prototype.constructor = NoSimulcastSender;
  8772. module.exports = {
  8773. "native": NativeSimulcastSender,
  8774. "no": NoSimulcastSender
  8775. }
  8776. },{"./SimulcastLogger":38,"./SimulcastUtils":41}],41:[function(require,module,exports){
  8777. var SimulcastLogger = require("./SimulcastLogger");
  8778. /**
  8779. *
  8780. * @constructor
  8781. */
  8782. function SimulcastUtils() {
  8783. this.logger = new SimulcastLogger("SimulcastUtils", 1);
  8784. }
  8785. /**
  8786. *
  8787. * @type {{}}
  8788. * @private
  8789. */
  8790. SimulcastUtils.prototype._emptyCompoundIndex = {};
  8791. /**
  8792. *
  8793. * @param lines
  8794. * @param videoSources
  8795. * @private
  8796. */
  8797. SimulcastUtils.prototype._replaceVideoSources = function (lines, videoSources) {
  8798. var i, inVideo = false, index = -1, howMany = 0;
  8799. this.logger.info('Replacing video sources...');
  8800. for (i = 0; i < lines.length; i++) {
  8801. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  8802. // Out of video.
  8803. break;
  8804. }
  8805. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  8806. // In video.
  8807. inVideo = true;
  8808. }
  8809. if (inVideo && (lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:'
  8810. || lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:')) {
  8811. if (index === -1) {
  8812. index = i;
  8813. }
  8814. howMany++;
  8815. }
  8816. }
  8817. // efficiency baby ;)
  8818. lines.splice.apply(lines,
  8819. [index, howMany].concat(videoSources));
  8820. };
  8821. SimulcastUtils.prototype.isValidDescription = function (desc)
  8822. {
  8823. return desc && desc != null
  8824. && desc.type && desc.type != ''
  8825. && desc.sdp && desc.sdp != '';
  8826. };
  8827. SimulcastUtils.prototype._getVideoSources = function (lines) {
  8828. var i, inVideo = false, sb = [];
  8829. this.logger.info('Getting video sources...');
  8830. for (i = 0; i < lines.length; i++) {
  8831. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  8832. // Out of video.
  8833. break;
  8834. }
  8835. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  8836. // In video.
  8837. inVideo = true;
  8838. }
  8839. if (inVideo && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  8840. // In SSRC.
  8841. sb.push(lines[i]);
  8842. }
  8843. if (inVideo && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  8844. sb.push(lines[i]);
  8845. }
  8846. }
  8847. return sb;
  8848. };
  8849. SimulcastUtils.prototype.parseMedia = function (lines, mediatypes) {
  8850. var i, res = [], type, cur_media, idx, ssrcs, cur_ssrc, ssrc,
  8851. ssrc_attribute, group, semantics, skip = true;
  8852. this.logger.info('Parsing media sources...');
  8853. for (i = 0; i < lines.length; i++) {
  8854. if (lines[i].substring(0, 'm='.length) === 'm=') {
  8855. type = lines[i]
  8856. .substr('m='.length, lines[i].indexOf(' ') - 'm='.length);
  8857. skip = mediatypes !== undefined && mediatypes.indexOf(type) === -1;
  8858. if (!skip) {
  8859. cur_media = {
  8860. 'type': type,
  8861. 'sources': {},
  8862. 'groups': []
  8863. };
  8864. res.push(cur_media);
  8865. }
  8866. } else if (!skip && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  8867. idx = lines[i].indexOf(' ');
  8868. ssrc = lines[i].substring('a=ssrc:'.length, idx);
  8869. if (cur_media.sources[ssrc] === undefined) {
  8870. cur_ssrc = {'ssrc': ssrc};
  8871. cur_media.sources[ssrc] = cur_ssrc;
  8872. }
  8873. ssrc_attribute = lines[i].substr(idx + 1).split(':', 2)[0];
  8874. cur_ssrc[ssrc_attribute] = lines[i].substr(idx + 1).split(':', 2)[1];
  8875. if (cur_media.base === undefined) {
  8876. cur_media.base = cur_ssrc;
  8877. }
  8878. } else if (!skip && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  8879. idx = lines[i].indexOf(' ');
  8880. semantics = lines[i].substr(0, idx).substr('a=ssrc-group:'.length);
  8881. ssrcs = lines[i].substr(idx).trim().split(' ');
  8882. group = {
  8883. 'semantics': semantics,
  8884. 'ssrcs': ssrcs
  8885. };
  8886. cur_media.groups.push(group);
  8887. } else if (!skip && (lines[i].substring(0, 'a=sendrecv'.length) === 'a=sendrecv' ||
  8888. lines[i].substring(0, 'a=recvonly'.length) === 'a=recvonly' ||
  8889. lines[i].substring(0, 'a=sendonly'.length) === 'a=sendonly' ||
  8890. lines[i].substring(0, 'a=inactive'.length) === 'a=inactive')) {
  8891. cur_media.direction = lines[i].substring('a='.length);
  8892. }
  8893. }
  8894. return res;
  8895. };
  8896. /**
  8897. * The _indexOfArray() method returns the first a CompoundIndex at which a
  8898. * given element can be found in the array, or _emptyCompoundIndex if it is
  8899. * not present.
  8900. *
  8901. * Example:
  8902. *
  8903. * _indexOfArray('3', [ 'this is line 1', 'this is line 2', 'this is line 3' ])
  8904. *
  8905. * returns {row: 2, column: 14}
  8906. *
  8907. * @param needle
  8908. * @param haystack
  8909. * @param start
  8910. * @returns {}
  8911. * @private
  8912. */
  8913. SimulcastUtils.prototype._indexOfArray = function (needle, haystack, start) {
  8914. var length = haystack.length, idx, i;
  8915. if (!start) {
  8916. start = 0;
  8917. }
  8918. for (i = start; i < length; i++) {
  8919. idx = haystack[i].indexOf(needle);
  8920. if (idx !== -1) {
  8921. return {row: i, column: idx};
  8922. }
  8923. }
  8924. return this._emptyCompoundIndex;
  8925. };
  8926. SimulcastUtils.prototype._removeSimulcastGroup = function (lines) {
  8927. var i;
  8928. for (i = lines.length - 1; i >= 0; i--) {
  8929. if (lines[i].indexOf('a=ssrc-group:SIM') !== -1) {
  8930. lines.splice(i, 1);
  8931. }
  8932. }
  8933. };
  8934. SimulcastUtils.prototype._compileVideoSources = function (videoSources) {
  8935. var sb = [], ssrc, addedSSRCs = [];
  8936. this.logger.info('Compiling video sources...');
  8937. // Add the groups
  8938. if (videoSources.groups && videoSources.groups.length !== 0) {
  8939. videoSources.groups.forEach(function (group) {
  8940. if (group.ssrcs && group.ssrcs.length !== 0) {
  8941. sb.push([['a=ssrc-group:', group.semantics].join(''), group.ssrcs.join(' ')].join(' '));
  8942. // if (group.semantics !== 'SIM') {
  8943. group.ssrcs.forEach(function (ssrc) {
  8944. addedSSRCs.push(ssrc);
  8945. sb.splice.apply(sb, [sb.length, 0].concat([
  8946. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  8947. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  8948. });
  8949. //}
  8950. }
  8951. });
  8952. }
  8953. // Then add any free sources.
  8954. if (videoSources.sources) {
  8955. for (ssrc in videoSources.sources) {
  8956. if (addedSSRCs.indexOf(ssrc) === -1) {
  8957. sb.splice.apply(sb, [sb.length, 0].concat([
  8958. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  8959. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  8960. }
  8961. }
  8962. }
  8963. return sb;
  8964. };
  8965. module.exports = SimulcastUtils;
  8966. },{"./SimulcastLogger":38}],42:[function(require,module,exports){
  8967. /*jslint plusplus: true */
  8968. /*jslint nomen: true*/
  8969. var SimulcastSender = require("./SimulcastSender");
  8970. var NoSimulcastSender = SimulcastSender["no"];
  8971. var NativeSimulcastSender = SimulcastSender["native"];
  8972. var SimulcastReceiver = require("./SimulcastReceiver");
  8973. var SimulcastUtils = require("./SimulcastUtils");
  8974. var RTCEvents = require("../../service/RTC/RTCEvents");
  8975. /**
  8976. *
  8977. * @constructor
  8978. */
  8979. function SimulcastManager() {
  8980. // Create the simulcast utilities.
  8981. this.simulcastUtils = new SimulcastUtils();
  8982. // Create remote simulcast.
  8983. this.simulcastReceiver = new SimulcastReceiver();
  8984. // Initialize local simulcast.
  8985. // TODO(gp) move into SimulcastManager.prototype.getUserMedia and take into
  8986. // account constraints.
  8987. if (!config.enableSimulcast) {
  8988. this.simulcastSender = new NoSimulcastSender();
  8989. } else {
  8990. var isChromium = window.chrome,
  8991. vendorName = window.navigator.vendor;
  8992. if(isChromium !== null && isChromium !== undefined
  8993. /* skip opera */
  8994. && vendorName === "Google Inc."
  8995. /* skip Chromium as suggested by fippo */
  8996. && !window.navigator.appVersion.match(/Chromium\//) ) {
  8997. var ver = parseInt(window.navigator.appVersion.match(/Chrome\/(\d+)\./)[1], 10);
  8998. if (ver > 37) {
  8999. this.simulcastSender = new NativeSimulcastSender();
  9000. } else {
  9001. this.simulcastSender = new NoSimulcastSender();
  9002. }
  9003. } else {
  9004. this.simulcastSender = new NoSimulcastSender();
  9005. }
  9006. }
  9007. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  9008. function (endpointSimulcastLayers) {
  9009. endpointSimulcastLayers.forEach(function (esl) {
  9010. var ssrc = esl.simulcastLayer.primarySSRC;
  9011. simulcast._setReceivingVideoStream(esl.endpoint, ssrc);
  9012. });
  9013. });
  9014. APP.RTC.addListener(RTCEvents.SIMULCAST_START, function (simulcastLayer) {
  9015. var ssrc = simulcastLayer.primarySSRC;
  9016. simulcast._setLocalVideoStreamEnabled(ssrc, true);
  9017. });
  9018. APP.RTC.addListener(RTCEvents.SIMULCAST_STOP, function (simulcastLayer) {
  9019. var ssrc = simulcastLayer.primarySSRC;
  9020. simulcast._setLocalVideoStreamEnabled(ssrc, false);
  9021. });
  9022. }
  9023. /**
  9024. * Restores the simulcast groups of the remote description. In
  9025. * transformRemoteDescription we remove those in order for the set remote
  9026. * description to succeed. The focus needs the signal the groups to new
  9027. * participants.
  9028. *
  9029. * @param desc
  9030. * @returns {*}
  9031. */
  9032. SimulcastManager.prototype.reverseTransformRemoteDescription = function (desc) {
  9033. return this.simulcastReceiver.reverseTransformRemoteDescription(desc);
  9034. };
  9035. /**
  9036. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  9037. * either gets confused and thinks this is an FID group or, if an FID group
  9038. * is already present, it fails to set the remote description.
  9039. *
  9040. * @param desc
  9041. * @returns {*}
  9042. */
  9043. SimulcastManager.prototype.transformRemoteDescription = function (desc) {
  9044. return this.simulcastReceiver.transformRemoteDescription(desc);
  9045. };
  9046. /**
  9047. * Gets the fully qualified msid (stream.id + track.id) associated to the
  9048. * SSRC.
  9049. *
  9050. * @param ssrc
  9051. * @returns {*}
  9052. */
  9053. SimulcastManager.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  9054. return this.simulcastReceiver.getRemoteVideoStreamIdBySSRC(ssrc);
  9055. };
  9056. /**
  9057. * Returns a stream with single video track, the one currently being
  9058. * received by this endpoint.
  9059. *
  9060. * @param stream the remote simulcast stream.
  9061. * @returns {webkitMediaStream}
  9062. */
  9063. SimulcastManager.prototype.getReceivingVideoStream = function (stream) {
  9064. return this.simulcastReceiver.getReceivingVideoStream(stream);
  9065. };
  9066. /**
  9067. *
  9068. *
  9069. * @param desc
  9070. * @returns {*}
  9071. */
  9072. SimulcastManager.prototype.transformLocalDescription = function (desc) {
  9073. return this.simulcastSender.transformLocalDescription(desc);
  9074. };
  9075. /**
  9076. *
  9077. * @returns {*}
  9078. */
  9079. SimulcastManager.prototype.getLocalVideoStream = function() {
  9080. return this.simulcastSender.getLocalVideoStream();
  9081. };
  9082. /**
  9083. * GUM for simulcast.
  9084. *
  9085. * @param constraints
  9086. * @param success
  9087. * @param err
  9088. */
  9089. SimulcastManager.prototype.getUserMedia = function (constraints, success, err) {
  9090. this.simulcastSender.getUserMedia(constraints, success, err);
  9091. };
  9092. /**
  9093. * Prepares the local description for public usage (i.e. to be signaled
  9094. * through Jingle to the focus).
  9095. *
  9096. * @param desc
  9097. * @returns {RTCSessionDescription}
  9098. */
  9099. SimulcastManager.prototype.reverseTransformLocalDescription = function (desc) {
  9100. return this.simulcastSender.reverseTransformLocalDescription(desc);
  9101. };
  9102. /**
  9103. * Ensures that the simulcast group is present in the answer, _if_ native
  9104. * simulcast is enabled,
  9105. *
  9106. * @param desc
  9107. * @returns {*}
  9108. */
  9109. SimulcastManager.prototype.transformAnswer = function (desc) {
  9110. return this.simulcastSender.transformAnswer(desc);
  9111. };
  9112. SimulcastManager.prototype.getReceivingSSRC = function (jid) {
  9113. return this.simulcastReceiver.getReceivingSSRC(jid);
  9114. };
  9115. SimulcastManager.prototype.getReceivingVideoStreamBySSRC = function (msid) {
  9116. return this.simulcastReceiver.getReceivingVideoStreamBySSRC(msid);
  9117. };
  9118. /**
  9119. *
  9120. * @param lines
  9121. * @param mediatypes
  9122. * @returns {*}
  9123. */
  9124. SimulcastManager.prototype.parseMedia = function(lines, mediatypes) {
  9125. var sb = lines.sdp.split('\r\n');
  9126. return this.simulcastUtils.parseMedia(sb, mediatypes);
  9127. };
  9128. SimulcastManager.prototype._setReceivingVideoStream = function(resource, ssrc) {
  9129. this.simulcastReceiver._setReceivingVideoStream(resource, ssrc);
  9130. };
  9131. SimulcastManager.prototype._setLocalVideoStreamEnabled = function(ssrc, enabled) {
  9132. this.simulcastSender._setLocalVideoStreamEnabled(ssrc, enabled);
  9133. };
  9134. SimulcastManager.prototype.resetSender = function() {
  9135. if (typeof this.simulcastSender.reset === 'function'){
  9136. this.simulcastSender.reset();
  9137. }
  9138. };
  9139. var simulcast = new SimulcastManager();
  9140. module.exports = simulcast;
  9141. },{"../../service/RTC/RTCEvents":80,"./SimulcastReceiver":39,"./SimulcastSender":40,"./SimulcastUtils":41}],43:[function(require,module,exports){
  9142. /**
  9143. * Provides statistics for the local stream.
  9144. */
  9145. /**
  9146. * Size of the webaudio analizer buffer.
  9147. * @type {number}
  9148. */
  9149. var WEBAUDIO_ANALIZER_FFT_SIZE = 2048;
  9150. /**
  9151. * Value of the webaudio analizer smoothing time parameter.
  9152. * @type {number}
  9153. */
  9154. var WEBAUDIO_ANALIZER_SMOOTING_TIME = 0.8;
  9155. /**
  9156. * Converts time domain data array to audio level.
  9157. * @param array the time domain data array.
  9158. * @returns {number} the audio level
  9159. */
  9160. function timeDomainDataToAudioLevel(samples) {
  9161. var maxVolume = 0;
  9162. var length = samples.length;
  9163. for (var i = 0; i < length; i++) {
  9164. if (maxVolume < samples[i])
  9165. maxVolume = samples[i];
  9166. }
  9167. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  9168. };
  9169. /**
  9170. * Animates audio level change
  9171. * @param newLevel the new audio level
  9172. * @param lastLevel the last audio level
  9173. * @returns {Number} the audio level to be set
  9174. */
  9175. function animateLevel(newLevel, lastLevel)
  9176. {
  9177. var value = 0;
  9178. var diff = lastLevel - newLevel;
  9179. if(diff > 0.2)
  9180. {
  9181. value = lastLevel - 0.2;
  9182. }
  9183. else if(diff < -0.4)
  9184. {
  9185. value = lastLevel + 0.4;
  9186. }
  9187. else
  9188. {
  9189. value = newLevel;
  9190. }
  9191. return parseFloat(value.toFixed(3));
  9192. }
  9193. /**
  9194. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  9195. *
  9196. * @param stream the local stream
  9197. * @param interval stats refresh interval given in ms.
  9198. * @param {function(LocalStatsCollector)} updateCallback the callback called on stats
  9199. * update.
  9200. * @constructor
  9201. */
  9202. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  9203. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  9204. this.stream = stream;
  9205. this.intervalId = null;
  9206. this.intervalMilis = interval;
  9207. this.eventEmitter = eventEmitter;
  9208. this.audioLevel = 0;
  9209. this.statisticsService = statisticsService;
  9210. }
  9211. /**
  9212. * Starts the collecting the statistics.
  9213. */
  9214. LocalStatsCollector.prototype.start = function () {
  9215. if (config.disableAudioLevels || !window.AudioContext)
  9216. return;
  9217. var context = new AudioContext();
  9218. var analyser = context.createAnalyser();
  9219. analyser.smoothingTimeConstant = WEBAUDIO_ANALIZER_SMOOTING_TIME;
  9220. analyser.fftSize = WEBAUDIO_ANALIZER_FFT_SIZE;
  9221. var source = context.createMediaStreamSource(this.stream);
  9222. source.connect(analyser);
  9223. var self = this;
  9224. this.intervalId = setInterval(
  9225. function () {
  9226. var array = new Uint8Array(analyser.frequencyBinCount);
  9227. analyser.getByteTimeDomainData(array);
  9228. var audioLevel = timeDomainDataToAudioLevel(array);
  9229. if(audioLevel != self.audioLevel) {
  9230. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  9231. self.eventEmitter.emit(
  9232. "statistics.audioLevel",
  9233. self.statisticsService.LOCAL_JID,
  9234. self.audioLevel);
  9235. }
  9236. },
  9237. this.intervalMilis
  9238. );
  9239. };
  9240. /**
  9241. * Stops collecting the statistics.
  9242. */
  9243. LocalStatsCollector.prototype.stop = function () {
  9244. if (this.intervalId) {
  9245. clearInterval(this.intervalId);
  9246. this.intervalId = null;
  9247. }
  9248. };
  9249. module.exports = LocalStatsCollector;
  9250. },{}],44:[function(require,module,exports){
  9251. /* global ssrc2jid */
  9252. /* jshint -W117 */
  9253. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  9254. /**
  9255. * Calculates packet lost percent using the number of lost packets and the
  9256. * number of all packet.
  9257. * @param lostPackets the number of lost packets
  9258. * @param totalPackets the number of all packets.
  9259. * @returns {number} packet loss percent
  9260. */
  9261. function calculatePacketLoss(lostPackets, totalPackets) {
  9262. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  9263. return 0;
  9264. return Math.round((lostPackets/totalPackets)*100);
  9265. }
  9266. function getStatValue(item, name) {
  9267. if(!keyMap[APP.RTC.getBrowserType()][name])
  9268. throw "The property isn't supported!";
  9269. var key = keyMap[APP.RTC.getBrowserType()][name];
  9270. return APP.RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_CHROME? item.stat(key) : item[key];
  9271. }
  9272. /**
  9273. * Peer statistics data holder.
  9274. * @constructor
  9275. */
  9276. function PeerStats()
  9277. {
  9278. this.ssrc2Loss = {};
  9279. this.ssrc2AudioLevel = {};
  9280. this.ssrc2bitrate = {};
  9281. this.ssrc2resolution = {};
  9282. }
  9283. /**
  9284. * The bandwidth
  9285. * @type {{}}
  9286. */
  9287. PeerStats.bandwidth = {};
  9288. /**
  9289. * The bit rate
  9290. * @type {{}}
  9291. */
  9292. PeerStats.bitrate = {};
  9293. /**
  9294. * The packet loss rate
  9295. * @type {{}}
  9296. */
  9297. PeerStats.packetLoss = null;
  9298. /**
  9299. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  9300. * represented by this instance.
  9301. * @param ssrc audio or video RTP stream SSRC.
  9302. * @param lossRate new packet loss rate value to be set.
  9303. */
  9304. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  9305. {
  9306. this.ssrc2Loss[ssrc] = lossRate;
  9307. };
  9308. /**
  9309. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  9310. * represented by this instance.
  9311. * @param ssrc audio or video RTP stream SSRC.
  9312. * @param resolution new resolution value to be set.
  9313. */
  9314. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  9315. {
  9316. if(resolution === null && this.ssrc2resolution[ssrc])
  9317. {
  9318. delete this.ssrc2resolution[ssrc];
  9319. }
  9320. else if(resolution !== null)
  9321. this.ssrc2resolution[ssrc] = resolution;
  9322. };
  9323. /**
  9324. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  9325. * represented by this instance.
  9326. * @param ssrc audio or video RTP stream SSRC.
  9327. * @param bitrate new bitrate value to be set.
  9328. */
  9329. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  9330. {
  9331. if(this.ssrc2bitrate[ssrc])
  9332. {
  9333. this.ssrc2bitrate[ssrc].download += bitrate.download;
  9334. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  9335. }
  9336. else {
  9337. this.ssrc2bitrate[ssrc] = bitrate;
  9338. }
  9339. };
  9340. /**
  9341. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  9342. * the stream which belongs to the peer represented by this instance.
  9343. * @param ssrc RTP stream SSRC for which current audio level value will be
  9344. * updated.
  9345. * @param audioLevel the new audio level value to be set. Value is truncated to
  9346. * fit the range from 0 to 1.
  9347. */
  9348. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  9349. {
  9350. // Range limit 0 - 1
  9351. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  9352. };
  9353. function formatAudioLevel(audioLevel) {
  9354. return Math.min(Math.max(audioLevel, 0), 1);
  9355. }
  9356. /**
  9357. * Array with the transport information.
  9358. * @type {Array}
  9359. */
  9360. PeerStats.transport = [];
  9361. /**
  9362. * <tt>StatsCollector</tt> registers for stats updates of given
  9363. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  9364. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  9365. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  9366. * instance as an event source.
  9367. *
  9368. * @param peerconnection webRTC peer connection object.
  9369. * @param interval stats refresh interval given in ms.
  9370. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  9371. * called on stats update.
  9372. * @constructor
  9373. */
  9374. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  9375. {
  9376. this.peerconnection = peerconnection;
  9377. this.baselineAudioLevelsReport = null;
  9378. this.currentAudioLevelsReport = null;
  9379. this.currentStatsReport = null;
  9380. this.baselineStatsReport = null;
  9381. this.audioLevelsIntervalId = null;
  9382. this.eventEmitter = eventEmitter;
  9383. /**
  9384. * Gather PeerConnection stats once every this many milliseconds.
  9385. */
  9386. this.GATHER_INTERVAL = 15000;
  9387. /**
  9388. * Log stats via the focus once every this many milliseconds.
  9389. */
  9390. this.LOG_INTERVAL = 60000;
  9391. /**
  9392. * Gather stats and store them in this.statsToBeLogged.
  9393. */
  9394. this.gatherStatsIntervalId = null;
  9395. /**
  9396. * Send the stats already saved in this.statsToBeLogged to be logged via
  9397. * the focus.
  9398. */
  9399. this.logStatsIntervalId = null;
  9400. /**
  9401. * Stores the statistics which will be send to the focus to be logged.
  9402. */
  9403. this.statsToBeLogged =
  9404. {
  9405. timestamps: [],
  9406. stats: {}
  9407. };
  9408. // Updates stats interval
  9409. this.audioLevelsIntervalMilis = audioLevelsInterval;
  9410. this.statsIntervalId = null;
  9411. this.statsIntervalMilis = statsInterval;
  9412. // Map of jids to PeerStats
  9413. this.jid2stats = {};
  9414. }
  9415. module.exports = StatsCollector;
  9416. /**
  9417. * Stops stats updates.
  9418. */
  9419. StatsCollector.prototype.stop = function () {
  9420. if (this.audioLevelsIntervalId) {
  9421. clearInterval(this.audioLevelsIntervalId);
  9422. this.audioLevelsIntervalId = null;
  9423. }
  9424. if (this.statsIntervalId)
  9425. {
  9426. clearInterval(this.statsIntervalId);
  9427. this.statsIntervalId = null;
  9428. }
  9429. if(this.logStatsIntervalId)
  9430. {
  9431. clearInterval(this.logStatsIntervalId);
  9432. this.logStatsIntervalId = null;
  9433. }
  9434. if(this.gatherStatsIntervalId)
  9435. {
  9436. clearInterval(this.gatherStatsIntervalId);
  9437. this.gatherStatsIntervalId = null;
  9438. }
  9439. };
  9440. /**
  9441. * Callback passed to <tt>getStats</tt> method.
  9442. * @param error an error that occurred on <tt>getStats</tt> call.
  9443. */
  9444. StatsCollector.prototype.errorCallback = function (error)
  9445. {
  9446. console.error("Get stats error", error);
  9447. this.stop();
  9448. };
  9449. /**
  9450. * Starts stats updates.
  9451. */
  9452. StatsCollector.prototype.start = function ()
  9453. {
  9454. var self = this;
  9455. if(!config.disableAudioLevels) {
  9456. console.debug("set audio levels interval");
  9457. this.audioLevelsIntervalId = setInterval(
  9458. function () {
  9459. // Interval updates
  9460. self.peerconnection.getStats(
  9461. function (report) {
  9462. var results = null;
  9463. if (!report || !report.result ||
  9464. typeof report.result != 'function') {
  9465. results = report;
  9466. }
  9467. else {
  9468. results = report.result();
  9469. }
  9470. //console.error("Got interval report", results);
  9471. self.currentAudioLevelsReport = results;
  9472. self.processAudioLevelReport();
  9473. self.baselineAudioLevelsReport =
  9474. self.currentAudioLevelsReport;
  9475. },
  9476. self.errorCallback
  9477. );
  9478. },
  9479. self.audioLevelsIntervalMilis
  9480. );
  9481. }
  9482. if(!config.disableStats) {
  9483. console.debug("set stats interval");
  9484. this.statsIntervalId = setInterval(
  9485. function () {
  9486. // Interval updates
  9487. self.peerconnection.getStats(
  9488. function (report) {
  9489. var results = null;
  9490. if (!report || !report.result ||
  9491. typeof report.result != 'function') {
  9492. //firefox
  9493. results = report;
  9494. }
  9495. else {
  9496. //chrome
  9497. results = report.result();
  9498. }
  9499. //console.error("Got interval report", results);
  9500. self.currentStatsReport = results;
  9501. try {
  9502. self.processStatsReport();
  9503. }
  9504. catch (e) {
  9505. console.error("Unsupported key:" + e, e);
  9506. }
  9507. self.baselineStatsReport = self.currentStatsReport;
  9508. },
  9509. self.errorCallback
  9510. );
  9511. },
  9512. self.statsIntervalMilis
  9513. );
  9514. }
  9515. if (config.logStats) {
  9516. this.gatherStatsIntervalId = setInterval(
  9517. function () {
  9518. self.peerconnection.getStats(
  9519. function (report) {
  9520. self.addStatsToBeLogged(report.result());
  9521. },
  9522. function () {
  9523. }
  9524. );
  9525. },
  9526. this.GATHER_INTERVAL
  9527. );
  9528. this.logStatsIntervalId = setInterval(
  9529. function() { self.logStats(); },
  9530. this.LOG_INTERVAL);
  9531. }
  9532. };
  9533. /**
  9534. * Checks whether a certain record should be included in the logged statistics.
  9535. */
  9536. function acceptStat(reportId, reportType, statName) {
  9537. if (reportType == "googCandidatePair" && statName == "googChannelId")
  9538. return false;
  9539. if (reportType == "ssrc") {
  9540. if (statName == "googTrackId" ||
  9541. statName == "transportId" ||
  9542. statName == "ssrc")
  9543. return false;
  9544. }
  9545. return true;
  9546. }
  9547. /**
  9548. * Checks whether a certain record should be included in the logged statistics.
  9549. */
  9550. function acceptReport(id, type) {
  9551. if (id.substring(0, 15) == "googCertificate" ||
  9552. id.substring(0, 9) == "googTrack" ||
  9553. id.substring(0, 20) == "googLibjingleSession")
  9554. return false;
  9555. if (type == "googComponent")
  9556. return false;
  9557. return true;
  9558. }
  9559. /**
  9560. * Converts the stats to the format used for logging, and saves the data in
  9561. * this.statsToBeLogged.
  9562. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  9563. */
  9564. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  9565. var self = this;
  9566. var num_records = this.statsToBeLogged.timestamps.length;
  9567. this.statsToBeLogged.timestamps.push(new Date().getTime());
  9568. reports.map(function (report) {
  9569. if (!acceptReport(report.id, report.type))
  9570. return;
  9571. var stat = self.statsToBeLogged.stats[report.id];
  9572. if (!stat) {
  9573. stat = self.statsToBeLogged.stats[report.id] = {};
  9574. }
  9575. stat.type = report.type;
  9576. report.names().map(function (name) {
  9577. if (!acceptStat(report.id, report.type, name))
  9578. return;
  9579. var values = stat[name];
  9580. if (!values) {
  9581. values = stat[name] = [];
  9582. }
  9583. while (values.length < num_records) {
  9584. values.push(null);
  9585. }
  9586. values.push(report.stat(name));
  9587. });
  9588. });
  9589. };
  9590. StatsCollector.prototype.logStats = function () {
  9591. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  9592. return;
  9593. // Reset the stats
  9594. this.statsToBeLogged.stats = {};
  9595. this.statsToBeLogged.timestamps = [];
  9596. };
  9597. var keyMap = {};
  9598. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  9599. "ssrc": "ssrc",
  9600. "packetsReceived": "packetsReceived",
  9601. "packetsLost": "packetsLost",
  9602. "packetsSent": "packetsSent",
  9603. "bytesReceived": "bytesReceived",
  9604. "bytesSent": "bytesSent"
  9605. };
  9606. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  9607. "receiveBandwidth": "googAvailableReceiveBandwidth",
  9608. "sendBandwidth": "googAvailableSendBandwidth",
  9609. "remoteAddress": "googRemoteAddress",
  9610. "transportType": "googTransportType",
  9611. "localAddress": "googLocalAddress",
  9612. "activeConnection": "googActiveConnection",
  9613. "ssrc": "ssrc",
  9614. "packetsReceived": "packetsReceived",
  9615. "packetsSent": "packetsSent",
  9616. "packetsLost": "packetsLost",
  9617. "bytesReceived": "bytesReceived",
  9618. "bytesSent": "bytesSent",
  9619. "googFrameHeightReceived": "googFrameHeightReceived",
  9620. "googFrameWidthReceived": "googFrameWidthReceived",
  9621. "googFrameHeightSent": "googFrameHeightSent",
  9622. "googFrameWidthSent": "googFrameWidthSent",
  9623. "audioInputLevel": "audioInputLevel",
  9624. "audioOutputLevel": "audioOutputLevel"
  9625. };
  9626. /**
  9627. * Stats processing logic.
  9628. */
  9629. StatsCollector.prototype.processStatsReport = function () {
  9630. if (!this.baselineStatsReport) {
  9631. return;
  9632. }
  9633. for (var idx in this.currentStatsReport) {
  9634. var now = this.currentStatsReport[idx];
  9635. try {
  9636. if (getStatValue(now, 'receiveBandwidth') ||
  9637. getStatValue(now, 'sendBandwidth')) {
  9638. PeerStats.bandwidth = {
  9639. "download": Math.round(
  9640. (getStatValue(now, 'receiveBandwidth')) / 1000),
  9641. "upload": Math.round(
  9642. (getStatValue(now, 'sendBandwidth')) / 1000)
  9643. };
  9644. }
  9645. }
  9646. catch(e){/*not supported*/}
  9647. if(now.type == 'googCandidatePair')
  9648. {
  9649. var ip, type, localIP, active;
  9650. try {
  9651. ip = getStatValue(now, 'remoteAddress');
  9652. type = getStatValue(now, "transportType");
  9653. localIP = getStatValue(now, "localAddress");
  9654. active = getStatValue(now, "activeConnection");
  9655. }
  9656. catch(e){/*not supported*/}
  9657. if(!ip || !type || !localIP || active != "true")
  9658. continue;
  9659. var addressSaved = false;
  9660. for(var i = 0; i < PeerStats.transport.length; i++)
  9661. {
  9662. if(PeerStats.transport[i].ip == ip &&
  9663. PeerStats.transport[i].type == type &&
  9664. PeerStats.transport[i].localip == localIP)
  9665. {
  9666. addressSaved = true;
  9667. }
  9668. }
  9669. if(addressSaved)
  9670. continue;
  9671. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  9672. continue;
  9673. }
  9674. if(now.type == "candidatepair")
  9675. {
  9676. if(now.state == "succeeded")
  9677. continue;
  9678. var local = this.currentStatsReport[now.localCandidateId];
  9679. var remote = this.currentStatsReport[now.remoteCandidateId];
  9680. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  9681. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  9682. }
  9683. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  9684. now.type != "inboundrtp") {
  9685. continue;
  9686. }
  9687. var before = this.baselineStatsReport[idx];
  9688. if (!before) {
  9689. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  9690. continue;
  9691. }
  9692. var ssrc = getStatValue(now, 'ssrc');
  9693. if(!ssrc)
  9694. continue;
  9695. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  9696. if (!jid && (Date.now() - now.timestamp) < 3000) {
  9697. console.warn("No jid for ssrc: " + ssrc);
  9698. continue;
  9699. }
  9700. var jidStats = this.jid2stats[jid];
  9701. if (!jidStats) {
  9702. jidStats = new PeerStats();
  9703. this.jid2stats[jid] = jidStats;
  9704. }
  9705. var isDownloadStream = true;
  9706. var key = 'packetsReceived';
  9707. if (!getStatValue(now, key))
  9708. {
  9709. isDownloadStream = false;
  9710. key = 'packetsSent';
  9711. if (!getStatValue(now, key))
  9712. {
  9713. console.warn("No packetsReceived nor packetSent stat found");
  9714. continue;
  9715. }
  9716. }
  9717. var packetsNow = getStatValue(now, key);
  9718. if(!packetsNow || packetsNow < 0)
  9719. packetsNow = 0;
  9720. var packetsBefore = getStatValue(before, key);
  9721. if(!packetsBefore || packetsBefore < 0)
  9722. packetsBefore = 0;
  9723. var packetRate = packetsNow - packetsBefore;
  9724. if(!packetRate || packetRate < 0)
  9725. packetRate = 0;
  9726. var currentLoss = getStatValue(now, 'packetsLost');
  9727. if(!currentLoss || currentLoss < 0)
  9728. currentLoss = 0;
  9729. var previousLoss = getStatValue(before, 'packetsLost');
  9730. if(!previousLoss || previousLoss < 0)
  9731. previousLoss = 0;
  9732. var lossRate = currentLoss - previousLoss;
  9733. if(!lossRate || lossRate < 0)
  9734. lossRate = 0;
  9735. var packetsTotal = (packetRate + lossRate);
  9736. jidStats.setSsrcLoss(ssrc,
  9737. {"packetsTotal": packetsTotal,
  9738. "packetsLost": lossRate,
  9739. "isDownloadStream": isDownloadStream});
  9740. var bytesReceived = 0, bytesSent = 0;
  9741. if(getStatValue(now, "bytesReceived"))
  9742. {
  9743. bytesReceived = getStatValue(now, "bytesReceived") -
  9744. getStatValue(before, "bytesReceived");
  9745. }
  9746. if(getStatValue(now, "bytesSent"))
  9747. {
  9748. bytesSent = getStatValue(now, "bytesSent") -
  9749. getStatValue(before, "bytesSent");
  9750. }
  9751. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  9752. if(bytesReceived <= 0 || time <= 0)
  9753. {
  9754. bytesReceived = 0;
  9755. }
  9756. else
  9757. {
  9758. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  9759. }
  9760. if(bytesSent <= 0 || time <= 0)
  9761. {
  9762. bytesSent = 0;
  9763. }
  9764. else
  9765. {
  9766. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  9767. }
  9768. jidStats.setSsrcBitrate(ssrc, {
  9769. "download": bytesReceived,
  9770. "upload": bytesSent});
  9771. var resolution = {height: null, width: null};
  9772. try {
  9773. if (getStatValue(now, "googFrameHeightReceived") &&
  9774. getStatValue(now, "googFrameWidthReceived")) {
  9775. resolution.height = getStatValue(now, "googFrameHeightReceived");
  9776. resolution.width = getStatValue(now, "googFrameWidthReceived");
  9777. }
  9778. else if (getStatValue(now, "googFrameHeightSent") &&
  9779. getStatValue(now, "googFrameWidthSent")) {
  9780. resolution.height = getStatValue(now, "googFrameHeightSent");
  9781. resolution.width = getStatValue(now, "googFrameWidthSent");
  9782. }
  9783. }
  9784. catch(e){/*not supported*/}
  9785. if(resolution.height && resolution.width)
  9786. {
  9787. jidStats.setSsrcResolution(ssrc, resolution);
  9788. }
  9789. else
  9790. {
  9791. jidStats.setSsrcResolution(ssrc, null);
  9792. }
  9793. }
  9794. var self = this;
  9795. // Jid stats
  9796. var totalPackets = {download: 0, upload: 0};
  9797. var lostPackets = {download: 0, upload: 0};
  9798. var bitrateDownload = 0;
  9799. var bitrateUpload = 0;
  9800. var resolutions = {};
  9801. Object.keys(this.jid2stats).forEach(
  9802. function (jid)
  9803. {
  9804. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  9805. function (ssrc)
  9806. {
  9807. var type = "upload";
  9808. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  9809. type = "download";
  9810. totalPackets[type] +=
  9811. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  9812. lostPackets[type] +=
  9813. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  9814. }
  9815. );
  9816. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  9817. function (ssrc) {
  9818. bitrateDownload +=
  9819. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  9820. bitrateUpload +=
  9821. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  9822. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  9823. }
  9824. );
  9825. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  9826. }
  9827. );
  9828. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  9829. PeerStats.packetLoss = {
  9830. total:
  9831. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  9832. totalPackets.download + totalPackets.upload),
  9833. download:
  9834. calculatePacketLoss(lostPackets.download, totalPackets.download),
  9835. upload:
  9836. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  9837. };
  9838. this.eventEmitter.emit("statistics.connectionstats",
  9839. {
  9840. "bitrate": PeerStats.bitrate,
  9841. "packetLoss": PeerStats.packetLoss,
  9842. "bandwidth": PeerStats.bandwidth,
  9843. "resolution": resolutions,
  9844. "transport": PeerStats.transport
  9845. });
  9846. PeerStats.transport = [];
  9847. };
  9848. /**
  9849. * Stats processing logic.
  9850. */
  9851. StatsCollector.prototype.processAudioLevelReport = function ()
  9852. {
  9853. if (!this.baselineAudioLevelsReport)
  9854. {
  9855. return;
  9856. }
  9857. for (var idx in this.currentAudioLevelsReport)
  9858. {
  9859. var now = this.currentAudioLevelsReport[idx];
  9860. if (now.type != 'ssrc')
  9861. {
  9862. continue;
  9863. }
  9864. var before = this.baselineAudioLevelsReport[idx];
  9865. if (!before)
  9866. {
  9867. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  9868. continue;
  9869. }
  9870. var ssrc = getStatValue(now, 'ssrc');
  9871. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  9872. if (!jid && (Date.now() - now.timestamp) < 3000)
  9873. {
  9874. console.warn("No jid for ssrc: " + ssrc);
  9875. continue;
  9876. }
  9877. var jidStats = this.jid2stats[jid];
  9878. if (!jidStats)
  9879. {
  9880. jidStats = new PeerStats();
  9881. this.jid2stats[jid] = jidStats;
  9882. }
  9883. // Audio level
  9884. var audioLevel = null;
  9885. try {
  9886. audioLevel = getStatValue(now, 'audioInputLevel');
  9887. if (!audioLevel)
  9888. audioLevel = getStatValue(now, 'audioOutputLevel');
  9889. }
  9890. catch(e) {/*not supported*/
  9891. console.warn("Audio Levels are not available in the statistics.");
  9892. clearInterval(this.audioLevelsIntervalId);
  9893. return;
  9894. }
  9895. if (audioLevel)
  9896. {
  9897. // TODO: can't find specs about what this value really is,
  9898. // but it seems to vary between 0 and around 32k.
  9899. audioLevel = audioLevel / 32767;
  9900. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  9901. if(jid != APP.xmpp.myJid())
  9902. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  9903. }
  9904. }
  9905. };
  9906. },{"../../service/RTC/RTCBrowserType":79}],45:[function(require,module,exports){
  9907. /**
  9908. * Created by hristo on 8/4/14.
  9909. */
  9910. var LocalStats = require("./LocalStatsCollector.js");
  9911. var RTPStats = require("./RTPStatsCollector.js");
  9912. var EventEmitter = require("events");
  9913. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  9914. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9915. var eventEmitter = new EventEmitter();
  9916. var localStats = null;
  9917. var rtpStats = null;
  9918. function stopLocal()
  9919. {
  9920. if(localStats)
  9921. {
  9922. localStats.stop();
  9923. localStats = null;
  9924. }
  9925. }
  9926. function stopRemote()
  9927. {
  9928. if(rtpStats)
  9929. {
  9930. rtpStats.stop();
  9931. eventEmitter.emit("statistics.stop");
  9932. rtpStats = null;
  9933. }
  9934. }
  9935. function startRemoteStats (peerconnection) {
  9936. if(rtpStats)
  9937. {
  9938. rtpStats.stop();
  9939. rtpStats = null;
  9940. }
  9941. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  9942. rtpStats.start();
  9943. }
  9944. function onStreamCreated(stream)
  9945. {
  9946. if(stream.getOriginalStream().getAudioTracks().length === 0)
  9947. return;
  9948. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  9949. eventEmitter);
  9950. localStats.start();
  9951. }
  9952. function onDisposeConference(onUnload) {
  9953. stopRemote();
  9954. if(onUnload) {
  9955. stopLocal();
  9956. eventEmitter.removeAllListeners();
  9957. }
  9958. }
  9959. var statistics =
  9960. {
  9961. /**
  9962. * Indicates that this audio level is for local jid.
  9963. * @type {string}
  9964. */
  9965. LOCAL_JID: 'local',
  9966. addAudioLevelListener: function(listener)
  9967. {
  9968. eventEmitter.on("statistics.audioLevel", listener);
  9969. },
  9970. removeAudioLevelListener: function(listener)
  9971. {
  9972. eventEmitter.removeListener("statistics.audioLevel", listener);
  9973. },
  9974. addConnectionStatsListener: function(listener)
  9975. {
  9976. eventEmitter.on("statistics.connectionstats", listener);
  9977. },
  9978. removeConnectionStatsListener: function(listener)
  9979. {
  9980. eventEmitter.removeListener("statistics.connectionstats", listener);
  9981. },
  9982. addRemoteStatsStopListener: function(listener)
  9983. {
  9984. eventEmitter.on("statistics.stop", listener);
  9985. },
  9986. removeRemoteStatsStopListener: function(listener)
  9987. {
  9988. eventEmitter.removeListener("statistics.stop", listener);
  9989. },
  9990. stop: function () {
  9991. stopLocal();
  9992. stopRemote();
  9993. if(eventEmitter)
  9994. {
  9995. eventEmitter.removeAllListeners();
  9996. }
  9997. },
  9998. stopRemoteStatistics: function()
  9999. {
  10000. stopRemote();
  10001. },
  10002. start: function () {
  10003. APP.RTC.addStreamListener(onStreamCreated,
  10004. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  10005. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  10006. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  10007. startRemoteStats(event.peerconnection);
  10008. });
  10009. }
  10010. };
  10011. module.exports = statistics;
  10012. },{"../../service/RTC/StreamEventTypes.js":82,"../../service/xmpp/XMPPEvents":88,"./LocalStatsCollector.js":43,"./RTPStatsCollector.js":44,"events":89}],46:[function(require,module,exports){
  10013. var i18n = require("i18next-client");
  10014. var languages = require("../../service/translation/languages");
  10015. var Settings = require("../settings/Settings");
  10016. var DEFAULT_LANG = languages.EN;
  10017. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  10018. return value.replace("__app__", interfaceConfig.APP_NAME);
  10019. });
  10020. var defaultOptions = {
  10021. detectLngQS: "lang",
  10022. useCookie: false,
  10023. fallbackLng: DEFAULT_LANG,
  10024. load: "unspecific",
  10025. resGetPath: 'lang/__ns__-__lng__.json',
  10026. ns: {
  10027. namespaces: ['main', 'languages'],
  10028. defaultNs: 'main'
  10029. },
  10030. lngWhitelist : languages.getLanguages(),
  10031. fallbackOnNull: true,
  10032. fallbackOnEmpty: true,
  10033. useDataAttrOptions: true,
  10034. defaultValueFromContent: false,
  10035. app: interfaceConfig.APP_NAME,
  10036. getAsync: false,
  10037. customLoad: function(lng, ns, options, done) {
  10038. var resPath = "lang/__ns__-__lng__.json";
  10039. if(lng === languages.EN)
  10040. resPath = "lang/__ns__.json";
  10041. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  10042. i18n.functions.ajax({
  10043. url: url,
  10044. success: function(data, status, xhr) {
  10045. i18n.functions.log('loaded: ' + url);
  10046. done(null, data);
  10047. },
  10048. error : function(xhr, status, error) {
  10049. if ((status && status == 200) ||
  10050. (xhr && xhr.status && xhr.status == 200)) {
  10051. // file loaded but invalid json, stop waste time !
  10052. i18n.functions.error('There is a typo in: ' + url);
  10053. } else if ((status && status == 404) ||
  10054. (xhr && xhr.status && xhr.status == 404)) {
  10055. i18n.functions.log('Does not exist: ' + url);
  10056. } else {
  10057. var theStatus = status ? status :
  10058. ((xhr && xhr.status) ? xhr.status : null);
  10059. i18n.functions.log(theStatus + ' when loading ' + url);
  10060. }
  10061. done(error, {});
  10062. },
  10063. dataType: "json",
  10064. async : options.getAsync
  10065. });
  10066. }
  10067. // options for caching
  10068. // useLocalStorage: true,
  10069. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  10070. };
  10071. function initCompleted(t)
  10072. {
  10073. $("[data-i18n]").i18n();
  10074. }
  10075. function checkForParameter() {
  10076. var query = window.location.search.substring(1);
  10077. var vars = query.split("&");
  10078. for (var i=0;i<vars.length;i++) {
  10079. var pair = vars[i].split("=");
  10080. if(pair[0] == "lang")
  10081. {
  10082. return pair[1];
  10083. }
  10084. }
  10085. return null;
  10086. }
  10087. module.exports = {
  10088. init: function (lang) {
  10089. var options = defaultOptions;
  10090. if(!lang)
  10091. {
  10092. lang = checkForParameter();
  10093. if(!lang)
  10094. {
  10095. var settings = Settings.getSettings();
  10096. if(settings)
  10097. lang = settings.language;
  10098. }
  10099. }
  10100. if(lang) {
  10101. options.lng = lang;
  10102. }
  10103. i18n.init(options, initCompleted);
  10104. },
  10105. translateString: function (key, options) {
  10106. return i18n.t(key, options);
  10107. },
  10108. setLanguage: function (lang) {
  10109. if(!lang)
  10110. lang = DEFAULT_LANG;
  10111. i18n.setLng(lang, defaultOptions, initCompleted);
  10112. },
  10113. getCurrentLanguage: function () {
  10114. return i18n.lng();
  10115. },
  10116. translateElement: function (selector) {
  10117. selector.i18n();
  10118. },
  10119. generateTranslatonHTML: function (key, options) {
  10120. var str = "<span data-i18n=\"" + key + "\"";
  10121. if(options)
  10122. {
  10123. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  10124. }
  10125. str += ">";
  10126. str += this.translateString(key, options);
  10127. str += "</span>";
  10128. return str;
  10129. }
  10130. };
  10131. },{"../../service/translation/languages":87,"../settings/Settings":37,"i18next-client":61}],47:[function(require,module,exports){
  10132. /* jshint -W117 */
  10133. var TraceablePeerConnection = require("./TraceablePeerConnection");
  10134. var SDPDiffer = require("./SDPDiffer");
  10135. var SDPUtil = require("./SDPUtil");
  10136. var SDP = require("./SDP");
  10137. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  10138. // Jingle stuff
  10139. function JingleSession(me, sid, connection, service) {
  10140. this.me = me;
  10141. this.sid = sid;
  10142. this.connection = connection;
  10143. this.initiator = null;
  10144. this.responder = null;
  10145. this.isInitiator = null;
  10146. this.peerjid = null;
  10147. this.state = null;
  10148. this.localSDP = null;
  10149. this.remoteSDP = null;
  10150. this.relayedStreams = [];
  10151. this.startTime = null;
  10152. this.stopTime = null;
  10153. this.media_constraints = null;
  10154. this.pc_constraints = null;
  10155. this.ice_config = {};
  10156. this.drip_container = [];
  10157. this.service = service;
  10158. this.usetrickle = true;
  10159. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  10160. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  10161. this.hadstuncandidate = false;
  10162. this.hadturncandidate = false;
  10163. this.lasticecandidate = false;
  10164. this.statsinterval = null;
  10165. this.reason = null;
  10166. this.addssrc = [];
  10167. this.removessrc = [];
  10168. this.pendingop = null;
  10169. this.switchstreams = false;
  10170. this.wait = true;
  10171. this.localStreamsSSRC = null;
  10172. /**
  10173. * The indicator which determines whether the (local) video has been muted
  10174. * in response to a user command in contrast to an automatic decision made
  10175. * by the application logic.
  10176. */
  10177. this.videoMuteByUser = false;
  10178. }
  10179. //TODO: this array must be removed when firefox implement multistream support
  10180. JingleSession.notReceivedSSRCs = [];
  10181. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  10182. var self = this;
  10183. if (this.state !== null) {
  10184. console.error('attempt to initiate on session ' + this.sid +
  10185. 'in state ' + this.state);
  10186. return;
  10187. }
  10188. this.isInitiator = isInitiator;
  10189. this.state = 'pending';
  10190. this.initiator = isInitiator ? this.me : peerjid;
  10191. this.responder = !isInitiator ? this.me : peerjid;
  10192. this.peerjid = peerjid;
  10193. this.hadstuncandidate = false;
  10194. this.hadturncandidate = false;
  10195. this.lasticecandidate = false;
  10196. this.peerconnection
  10197. = new TraceablePeerConnection(
  10198. this.connection.jingle.ice_config,
  10199. this.connection.jingle.pc_constraints );
  10200. this.peerconnection.onicecandidate = function (event) {
  10201. self.sendIceCandidate(event.candidate);
  10202. };
  10203. this.peerconnection.onaddstream = function (event) {
  10204. console.log("REMOTE STREAM ADDED: " + event.stream + " - " + event.stream.id);
  10205. self.remoteStreamAdded(event);
  10206. };
  10207. this.peerconnection.onremovestream = function (event) {
  10208. // Remove the stream from remoteStreams
  10209. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  10210. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  10211. };
  10212. this.peerconnection.onsignalingstatechange = function (event) {
  10213. if (!(self && self.peerconnection)) return;
  10214. };
  10215. this.peerconnection.oniceconnectionstatechange = function (event) {
  10216. if (!(self && self.peerconnection)) return;
  10217. switch (self.peerconnection.iceConnectionState) {
  10218. case 'connected':
  10219. this.startTime = new Date();
  10220. break;
  10221. case 'disconnected':
  10222. this.stopTime = new Date();
  10223. break;
  10224. }
  10225. onIceConnectionStateChange(self.sid, self);
  10226. };
  10227. // add any local and relayed stream
  10228. APP.RTC.localStreams.forEach(function(stream) {
  10229. self.peerconnection.addStream(stream.getOriginalStream());
  10230. });
  10231. this.relayedStreams.forEach(function(stream) {
  10232. self.peerconnection.addStream(stream);
  10233. });
  10234. };
  10235. function onIceConnectionStateChange(sid, session) {
  10236. switch (session.peerconnection.iceConnectionState) {
  10237. case 'checking':
  10238. session.timeChecking = (new Date()).getTime();
  10239. session.firstconnect = true;
  10240. break;
  10241. case 'completed': // on caller side
  10242. case 'connected':
  10243. if (session.firstconnect) {
  10244. session.firstconnect = false;
  10245. var metadata = {};
  10246. metadata.setupTime
  10247. = (new Date()).getTime() - session.timeChecking;
  10248. session.peerconnection.getStats(function (res) {
  10249. if(res && res.result) {
  10250. res.result().forEach(function (report) {
  10251. if (report.type == 'googCandidatePair' &&
  10252. report.stat('googActiveConnection') == 'true') {
  10253. metadata.localCandidateType
  10254. = report.stat('googLocalCandidateType');
  10255. metadata.remoteCandidateType
  10256. = report.stat('googRemoteCandidateType');
  10257. // log pair as well so we can get nice pie
  10258. // charts
  10259. metadata.candidatePair
  10260. = report.stat('googLocalCandidateType') +
  10261. ';' +
  10262. report.stat('googRemoteCandidateType');
  10263. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  10264. {
  10265. metadata.ipv6 = true;
  10266. }
  10267. }
  10268. });
  10269. }
  10270. });
  10271. }
  10272. break;
  10273. }
  10274. }
  10275. JingleSession.prototype.accept = function () {
  10276. var self = this;
  10277. this.state = 'active';
  10278. var pranswer = this.peerconnection.localDescription;
  10279. if (!pranswer || pranswer.type != 'pranswer') {
  10280. return;
  10281. }
  10282. console.log('going from pranswer to answer');
  10283. if (this.usetrickle) {
  10284. // remove candidates already sent from session-accept
  10285. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  10286. for (var i = 0; i < lines.length; i++) {
  10287. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  10288. }
  10289. }
  10290. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  10291. // FIXME: change any inactive to sendrecv or whatever they were originally
  10292. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  10293. }
  10294. pranswer = APP.simulcast.reverseTransformLocalDescription(pranswer);
  10295. var prsdp = new SDP(pranswer.sdp);
  10296. var accept = $iq({to: this.peerjid,
  10297. type: 'set'})
  10298. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10299. action: 'session-accept',
  10300. initiator: this.initiator,
  10301. responder: this.responder,
  10302. sid: this.sid });
  10303. prsdp.toJingle(accept, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10304. var sdp = this.peerconnection.localDescription.sdp;
  10305. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  10306. // FIXME: change any inactive to sendrecv or whatever they were originally
  10307. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  10308. }
  10309. var self = this;
  10310. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  10311. function () {
  10312. //console.log('setLocalDescription success');
  10313. self.setLocalDescription();
  10314. self.connection.sendIQ(accept,
  10315. function () {
  10316. var ack = {};
  10317. ack.source = 'answer';
  10318. $(document).trigger('ack.jingle', [self.sid, ack]);
  10319. },
  10320. function (stanza) {
  10321. var error = ($(stanza).find('error').length) ? {
  10322. code: $(stanza).find('error').attr('code'),
  10323. reason: $(stanza).find('error :first')[0].tagName
  10324. }:{};
  10325. error.source = 'answer';
  10326. JingleSession.onJingleError(self.sid, error);
  10327. },
  10328. 10000);
  10329. },
  10330. function (e) {
  10331. console.error('setLocalDescription failed', e);
  10332. }
  10333. );
  10334. };
  10335. JingleSession.prototype.terminate = function (reason) {
  10336. this.state = 'ended';
  10337. this.reason = reason;
  10338. this.peerconnection.close();
  10339. if (this.statsinterval !== null) {
  10340. window.clearInterval(this.statsinterval);
  10341. this.statsinterval = null;
  10342. }
  10343. };
  10344. JingleSession.prototype.active = function () {
  10345. return this.state == 'active';
  10346. };
  10347. JingleSession.prototype.sendIceCandidate = function (candidate) {
  10348. var self = this;
  10349. if (candidate && !this.lasticecandidate) {
  10350. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  10351. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  10352. if (!(ice && jcand)) {
  10353. console.error('failed to get ice && jcand');
  10354. return;
  10355. }
  10356. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10357. if (jcand.type === 'srflx') {
  10358. this.hadstuncandidate = true;
  10359. } else if (jcand.type === 'relay') {
  10360. this.hadturncandidate = true;
  10361. }
  10362. if (this.usetrickle) {
  10363. if (this.usedrip) {
  10364. if (this.drip_container.length === 0) {
  10365. // start 20ms callout
  10366. window.setTimeout(function () {
  10367. if (self.drip_container.length === 0) return;
  10368. self.sendIceCandidates(self.drip_container);
  10369. self.drip_container = [];
  10370. }, 20);
  10371. }
  10372. this.drip_container.push(candidate);
  10373. return;
  10374. } else {
  10375. self.sendIceCandidate([candidate]);
  10376. }
  10377. }
  10378. } else {
  10379. //console.log('sendIceCandidate: last candidate.');
  10380. if (!this.usetrickle) {
  10381. //console.log('should send full offer now...');
  10382. var init = $iq({to: this.peerjid,
  10383. type: 'set'})
  10384. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10385. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  10386. initiator: this.initiator,
  10387. sid: this.sid});
  10388. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  10389. var self = this;
  10390. var sendJingle = function (ssrc) {
  10391. if(!ssrc)
  10392. ssrc = {};
  10393. self.localSDP.toJingle(init, self.initiator == self.me ? 'initiator' : 'responder', ssrc);
  10394. self.connection.sendIQ(init,
  10395. function () {
  10396. //console.log('session initiate ack');
  10397. var ack = {};
  10398. ack.source = 'offer';
  10399. $(document).trigger('ack.jingle', [self.sid, ack]);
  10400. },
  10401. function (stanza) {
  10402. self.state = 'error';
  10403. self.peerconnection.close();
  10404. var error = ($(stanza).find('error').length) ? {
  10405. code: $(stanza).find('error').attr('code'),
  10406. reason: $(stanza).find('error :first')[0].tagName,
  10407. }:{};
  10408. error.source = 'offer';
  10409. JingleSession.onJingleError(self.sid, error);
  10410. },
  10411. 10000);
  10412. }
  10413. sendJingle();
  10414. }
  10415. this.lasticecandidate = true;
  10416. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  10417. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  10418. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  10419. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  10420. }
  10421. }
  10422. };
  10423. JingleSession.prototype.sendIceCandidates = function (candidates) {
  10424. console.log('sendIceCandidates', candidates);
  10425. var cand = $iq({to: this.peerjid, type: 'set'})
  10426. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10427. action: 'transport-info',
  10428. initiator: this.initiator,
  10429. sid: this.sid});
  10430. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  10431. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  10432. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  10433. if (cands.length > 0) {
  10434. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  10435. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10436. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  10437. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  10438. }).c('transport', ice);
  10439. for (var i = 0; i < cands.length; i++) {
  10440. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  10441. }
  10442. // add fingerprint
  10443. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  10444. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  10445. tmp.required = true;
  10446. cand.c(
  10447. 'fingerprint',
  10448. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  10449. .t(tmp.fingerprint);
  10450. delete tmp.fingerprint;
  10451. cand.attrs(tmp);
  10452. cand.up();
  10453. }
  10454. cand.up(); // transport
  10455. cand.up(); // content
  10456. }
  10457. }
  10458. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  10459. //console.log('was this the last candidate', this.lasticecandidate);
  10460. this.connection.sendIQ(cand,
  10461. function () {
  10462. var ack = {};
  10463. ack.source = 'transportinfo';
  10464. $(document).trigger('ack.jingle', [this.sid, ack]);
  10465. },
  10466. function (stanza) {
  10467. var error = ($(stanza).find('error').length) ? {
  10468. code: $(stanza).find('error').attr('code'),
  10469. reason: $(stanza).find('error :first')[0].tagName,
  10470. }:{};
  10471. error.source = 'transportinfo';
  10472. JingleSession.onJingleError(this.sid, error);
  10473. },
  10474. 10000);
  10475. };
  10476. JingleSession.prototype.sendOffer = function () {
  10477. //console.log('sendOffer...');
  10478. var self = this;
  10479. this.peerconnection.createOffer(function (sdp) {
  10480. self.createdOffer(sdp);
  10481. },
  10482. function (e) {
  10483. console.error('createOffer failed', e);
  10484. },
  10485. this.media_constraints
  10486. );
  10487. };
  10488. JingleSession.prototype.createdOffer = function (sdp) {
  10489. //console.log('createdOffer', sdp);
  10490. var self = this;
  10491. this.localSDP = new SDP(sdp.sdp);
  10492. //this.localSDP.mangle();
  10493. var sendJingle = function () {
  10494. var init = $iq({to: this.peerjid,
  10495. type: 'set'})
  10496. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10497. action: 'session-initiate',
  10498. initiator: this.initiator,
  10499. sid: this.sid});
  10500. self.localSDP.toJingle(init, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10501. self.connection.sendIQ(init,
  10502. function () {
  10503. var ack = {};
  10504. ack.source = 'offer';
  10505. $(document).trigger('ack.jingle', [self.sid, ack]);
  10506. },
  10507. function (stanza) {
  10508. self.state = 'error';
  10509. self.peerconnection.close();
  10510. var error = ($(stanza).find('error').length) ? {
  10511. code: $(stanza).find('error').attr('code'),
  10512. reason: $(stanza).find('error :first')[0].tagName,
  10513. }:{};
  10514. error.source = 'offer';
  10515. JingleSession.onJingleError(self.sid, error);
  10516. },
  10517. 10000);
  10518. }
  10519. sdp.sdp = this.localSDP.raw;
  10520. this.peerconnection.setLocalDescription(sdp,
  10521. function () {
  10522. if(self.usetrickle)
  10523. {
  10524. sendJingle();
  10525. }
  10526. self.setLocalDescription();
  10527. //console.log('setLocalDescription success');
  10528. },
  10529. function (e) {
  10530. console.error('setLocalDescription failed', e);
  10531. }
  10532. );
  10533. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  10534. for (var i = 0; i < cands.length; i++) {
  10535. var cand = SDPUtil.parse_icecandidate(cands[i]);
  10536. if (cand.type == 'srflx') {
  10537. this.hadstuncandidate = true;
  10538. } else if (cand.type == 'relay') {
  10539. this.hadturncandidate = true;
  10540. }
  10541. }
  10542. };
  10543. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  10544. //console.log('setting remote description... ', desctype);
  10545. this.remoteSDP = new SDP('');
  10546. this.remoteSDP.fromJingle(elem);
  10547. if (this.peerconnection.remoteDescription !== null) {
  10548. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  10549. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  10550. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  10551. for (var i = 0; i < pranswer.media.length; i++) {
  10552. // make sure we have ice ufrag and pwd
  10553. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  10554. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  10555. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  10556. } else {
  10557. console.warn('no ice ufrag?');
  10558. }
  10559. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  10560. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  10561. } else {
  10562. console.warn('no ice pwd?');
  10563. }
  10564. }
  10565. // copy over candidates
  10566. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  10567. for (var j = 0; j < lines.length; j++) {
  10568. this.remoteSDP.media[i] += lines[j] + '\r\n';
  10569. }
  10570. }
  10571. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  10572. }
  10573. }
  10574. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  10575. this.peerconnection.setRemoteDescription(remotedesc,
  10576. function () {
  10577. //console.log('setRemoteDescription success');
  10578. },
  10579. function (e) {
  10580. console.error('setRemoteDescription error', e);
  10581. JingleSession.onJingleFatalError(self, e);
  10582. }
  10583. );
  10584. };
  10585. JingleSession.prototype.addIceCandidate = function (elem) {
  10586. var self = this;
  10587. if (this.peerconnection.signalingState == 'closed') {
  10588. return;
  10589. }
  10590. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  10591. console.log('trickle ice candidate arriving before session accept...');
  10592. // create a PRANSWER for setRemoteDescription
  10593. if (!this.remoteSDP) {
  10594. var cobbled = 'v=0\r\n' +
  10595. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  10596. 's=-\r\n' +
  10597. 't=0 0\r\n';
  10598. // first, take some things from the local description
  10599. for (var i = 0; i < this.localSDP.media.length; i++) {
  10600. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  10601. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  10602. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  10603. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  10604. }
  10605. cobbled += 'a=inactive\r\n';
  10606. }
  10607. this.remoteSDP = new SDP(cobbled);
  10608. }
  10609. // then add things like ice and dtls from remote candidate
  10610. elem.each(function () {
  10611. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  10612. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10613. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10614. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  10615. var tmp = $(this).find('transport');
  10616. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  10617. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  10618. tmp = $(this).find('transport>fingerprint');
  10619. if (tmp.length) {
  10620. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  10621. } else {
  10622. console.log('no dtls fingerprint (webrtc issue #1718?)');
  10623. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  10624. }
  10625. break;
  10626. }
  10627. }
  10628. }
  10629. });
  10630. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  10631. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  10632. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  10633. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  10634. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  10635. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  10636. }).length == this.remoteSDP.media.length;
  10637. if (iscomplete) {
  10638. console.log('setting pranswer');
  10639. try {
  10640. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  10641. function() {
  10642. },
  10643. function(e) {
  10644. console.log('setRemoteDescription pranswer failed', e.toString());
  10645. });
  10646. } catch (e) {
  10647. console.error('setting pranswer failed', e);
  10648. }
  10649. } else {
  10650. //console.log('not yet setting pranswer');
  10651. }
  10652. }
  10653. // operate on each content element
  10654. elem.each(function () {
  10655. // would love to deactivate this, but firefox still requires it
  10656. var idx = -1;
  10657. var i;
  10658. for (i = 0; i < self.remoteSDP.media.length; i++) {
  10659. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10660. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10661. idx = i;
  10662. break;
  10663. }
  10664. }
  10665. if (idx == -1) { // fall back to localdescription
  10666. for (i = 0; i < self.localSDP.media.length; i++) {
  10667. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10668. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10669. idx = i;
  10670. break;
  10671. }
  10672. }
  10673. }
  10674. var name = $(this).attr('name');
  10675. // TODO: check ice-pwd and ice-ufrag?
  10676. $(this).find('transport>candidate').each(function () {
  10677. var line, candidate;
  10678. line = SDPUtil.candidateFromJingle(this);
  10679. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  10680. sdpMid: name,
  10681. candidate: line});
  10682. try {
  10683. self.peerconnection.addIceCandidate(candidate);
  10684. } catch (e) {
  10685. console.error('addIceCandidate failed', e.toString(), line);
  10686. }
  10687. });
  10688. });
  10689. };
  10690. JingleSession.prototype.sendAnswer = function (provisional) {
  10691. //console.log('createAnswer', provisional);
  10692. var self = this;
  10693. this.peerconnection.createAnswer(
  10694. function (sdp) {
  10695. self.createdAnswer(sdp, provisional);
  10696. },
  10697. function (e) {
  10698. console.error('createAnswer failed', e);
  10699. },
  10700. this.media_constraints
  10701. );
  10702. };
  10703. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  10704. //console.log('createAnswer callback');
  10705. var self = this;
  10706. this.localSDP = new SDP(sdp.sdp);
  10707. //this.localSDP.mangle();
  10708. this.usepranswer = provisional === true;
  10709. if (this.usetrickle) {
  10710. if (this.usepranswer) {
  10711. sdp.type = 'pranswer';
  10712. for (var i = 0; i < this.localSDP.media.length; i++) {
  10713. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  10714. }
  10715. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  10716. }
  10717. }
  10718. var self = this;
  10719. var sendJingle = function (ssrcs) {
  10720. var accept = $iq({to: self.peerjid,
  10721. type: 'set'})
  10722. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10723. action: 'session-accept',
  10724. initiator: self.initiator,
  10725. responder: self.responder,
  10726. sid: self.sid });
  10727. var publicLocalDesc = APP.simulcast.reverseTransformLocalDescription(sdp);
  10728. var publicLocalSDP = new SDP(publicLocalDesc.sdp);
  10729. publicLocalSDP.toJingle(accept, self.initiator == self.me ? 'initiator' : 'responder', ssrcs);
  10730. self.connection.sendIQ(accept,
  10731. function () {
  10732. var ack = {};
  10733. ack.source = 'answer';
  10734. $(document).trigger('ack.jingle', [self.sid, ack]);
  10735. },
  10736. function (stanza) {
  10737. var error = ($(stanza).find('error').length) ? {
  10738. code: $(stanza).find('error').attr('code'),
  10739. reason: $(stanza).find('error :first')[0].tagName,
  10740. }:{};
  10741. error.source = 'answer';
  10742. JingleSession.onJingleError(self.sid, error);
  10743. },
  10744. 10000);
  10745. }
  10746. sdp.sdp = this.localSDP.raw;
  10747. this.peerconnection.setLocalDescription(sdp,
  10748. function () {
  10749. //console.log('setLocalDescription success');
  10750. if (self.usetrickle && !self.usepranswer) {
  10751. sendJingle();
  10752. }
  10753. self.setLocalDescription();
  10754. },
  10755. function (e) {
  10756. console.error('setLocalDescription failed', e);
  10757. }
  10758. );
  10759. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  10760. for (var j = 0; j < cands.length; j++) {
  10761. var cand = SDPUtil.parse_icecandidate(cands[j]);
  10762. if (cand.type == 'srflx') {
  10763. this.hadstuncandidate = true;
  10764. } else if (cand.type == 'relay') {
  10765. this.hadturncandidate = true;
  10766. }
  10767. }
  10768. };
  10769. JingleSession.prototype.sendTerminate = function (reason, text) {
  10770. var self = this,
  10771. term = $iq({to: this.peerjid,
  10772. type: 'set'})
  10773. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10774. action: 'session-terminate',
  10775. initiator: this.initiator,
  10776. sid: this.sid})
  10777. .c('reason')
  10778. .c(reason || 'success');
  10779. if (text) {
  10780. term.up().c('text').t(text);
  10781. }
  10782. this.connection.sendIQ(term,
  10783. function () {
  10784. self.peerconnection.close();
  10785. self.peerconnection = null;
  10786. self.terminate();
  10787. var ack = {};
  10788. ack.source = 'terminate';
  10789. $(document).trigger('ack.jingle', [self.sid, ack]);
  10790. },
  10791. function (stanza) {
  10792. var error = ($(stanza).find('error').length) ? {
  10793. code: $(stanza).find('error').attr('code'),
  10794. reason: $(stanza).find('error :first')[0].tagName,
  10795. }:{};
  10796. $(document).trigger('ack.jingle', [self.sid, error]);
  10797. },
  10798. 10000);
  10799. if (this.statsinterval !== null) {
  10800. window.clearInterval(this.statsinterval);
  10801. this.statsinterval = null;
  10802. }
  10803. };
  10804. JingleSession.prototype.addSource = function (elem, fromJid) {
  10805. var self = this;
  10806. // FIXME: dirty waiting
  10807. if (!this.peerconnection.localDescription)
  10808. {
  10809. console.warn("addSource - localDescription not ready yet")
  10810. setTimeout(function()
  10811. {
  10812. self.addSource(elem, fromJid);
  10813. },
  10814. 200
  10815. );
  10816. return;
  10817. }
  10818. console.log('addssrc', new Date().getTime());
  10819. console.log('ice', this.peerconnection.iceConnectionState);
  10820. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  10821. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  10822. $(elem).each(function (idx, content) {
  10823. var name = $(content).attr('name');
  10824. var lines = '';
  10825. tmp = $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  10826. var semantics = this.getAttribute('semantics');
  10827. var ssrcs = $(this).find('>source').map(function () {
  10828. return this.getAttribute('ssrc');
  10829. }).get();
  10830. if (ssrcs.length != 0) {
  10831. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  10832. }
  10833. });
  10834. tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  10835. tmp.each(function () {
  10836. var ssrc = $(this).attr('ssrc');
  10837. if(mySdp.containsSSRC(ssrc)){
  10838. /**
  10839. * This happens when multiple participants change their streams at the same time and
  10840. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  10841. * addssrc are scheduled for update IQ. See
  10842. */
  10843. console.warn("Got add stream request for my own ssrc: "+ssrc);
  10844. return;
  10845. }
  10846. $(this).find('>parameter').each(function () {
  10847. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  10848. if ($(this).attr('value') && $(this).attr('value').length)
  10849. lines += ':' + $(this).attr('value');
  10850. lines += '\r\n';
  10851. });
  10852. });
  10853. sdp.media.forEach(function(media, idx) {
  10854. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  10855. return;
  10856. sdp.media[idx] += lines;
  10857. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  10858. self.addssrc[idx] += lines;
  10859. });
  10860. sdp.raw = sdp.session + sdp.media.join('');
  10861. });
  10862. this.modifySources();
  10863. };
  10864. JingleSession.prototype.removeSource = function (elem, fromJid) {
  10865. var self = this;
  10866. // FIXME: dirty waiting
  10867. if (!this.peerconnection.localDescription)
  10868. {
  10869. console.warn("removeSource - localDescription not ready yet")
  10870. setTimeout(function()
  10871. {
  10872. self.removeSource(elem, fromJid);
  10873. },
  10874. 200
  10875. );
  10876. return;
  10877. }
  10878. console.log('removessrc', new Date().getTime());
  10879. console.log('ice', this.peerconnection.iceConnectionState);
  10880. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  10881. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  10882. $(elem).each(function (idx, content) {
  10883. var name = $(content).attr('name');
  10884. var lines = '';
  10885. tmp = $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  10886. var semantics = this.getAttribute('semantics');
  10887. var ssrcs = $(this).find('>source').map(function () {
  10888. return this.getAttribute('ssrc');
  10889. }).get();
  10890. if (ssrcs.length != 0) {
  10891. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  10892. }
  10893. });
  10894. tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  10895. tmp.each(function () {
  10896. var ssrc = $(this).attr('ssrc');
  10897. // This should never happen, but can be useful for bug detection
  10898. if(mySdp.containsSSRC(ssrc)){
  10899. console.error("Got remove stream request for my own ssrc: "+ssrc);
  10900. return;
  10901. }
  10902. $(this).find('>parameter').each(function () {
  10903. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  10904. if ($(this).attr('value') && $(this).attr('value').length)
  10905. lines += ':' + $(this).attr('value');
  10906. lines += '\r\n';
  10907. });
  10908. });
  10909. sdp.media.forEach(function(media, idx) {
  10910. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  10911. return;
  10912. sdp.media[idx] += lines;
  10913. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  10914. self.removessrc[idx] += lines;
  10915. });
  10916. sdp.raw = sdp.session + sdp.media.join('');
  10917. });
  10918. this.modifySources();
  10919. };
  10920. JingleSession.prototype.modifySources = function (successCallback) {
  10921. var self = this;
  10922. if (this.peerconnection.signalingState == 'closed') return;
  10923. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  10924. // There is nothing to do since scheduled job might have been executed by another succeeding call
  10925. this.setLocalDescription();
  10926. if(successCallback){
  10927. successCallback();
  10928. }
  10929. return;
  10930. }
  10931. // FIXME: this is a big hack
  10932. // https://code.google.com/p/webrtc/issues/detail?id=2688
  10933. // ^ has been fixed.
  10934. if (!(this.peerconnection.signalingState == 'stable' && this.peerconnection.iceConnectionState == 'connected')) {
  10935. console.warn('modifySources not yet', this.peerconnection.signalingState, this.peerconnection.iceConnectionState);
  10936. this.wait = true;
  10937. window.setTimeout(function() { self.modifySources(successCallback); }, 250);
  10938. return;
  10939. }
  10940. if (this.wait) {
  10941. window.setTimeout(function() { self.modifySources(successCallback); }, 2500);
  10942. this.wait = false;
  10943. return;
  10944. }
  10945. // Reset switch streams flag
  10946. this.switchstreams = false;
  10947. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  10948. // add sources
  10949. this.addssrc.forEach(function(lines, idx) {
  10950. sdp.media[idx] += lines;
  10951. });
  10952. this.addssrc = [];
  10953. // remove sources
  10954. this.removessrc.forEach(function(lines, idx) {
  10955. lines = lines.split('\r\n');
  10956. lines.pop(); // remove empty last element;
  10957. lines.forEach(function(line) {
  10958. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  10959. });
  10960. });
  10961. this.removessrc = [];
  10962. // FIXME:
  10963. // this was a hack for the situation when only one peer exists
  10964. // in the conference.
  10965. // check if still required and remove
  10966. if (sdp.media[0])
  10967. sdp.media[0] = sdp.media[0].replace('a=recvonly', 'a=sendrecv');
  10968. if (sdp.media[1])
  10969. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  10970. sdp.raw = sdp.session + sdp.media.join('');
  10971. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  10972. function() {
  10973. if(self.signalingState == 'closed') {
  10974. console.error("createAnswer attempt on closed state");
  10975. return;
  10976. }
  10977. self.peerconnection.createAnswer(
  10978. function(modifiedAnswer) {
  10979. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  10980. if (self.pendingop !== null) {
  10981. var sdp = new SDP(modifiedAnswer.sdp);
  10982. if (sdp.media.length > 1) {
  10983. switch(self.pendingop) {
  10984. case 'mute':
  10985. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  10986. break;
  10987. case 'unmute':
  10988. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  10989. break;
  10990. }
  10991. sdp.raw = sdp.session + sdp.media.join('');
  10992. modifiedAnswer.sdp = sdp.raw;
  10993. }
  10994. self.pendingop = null;
  10995. }
  10996. // FIXME: pushing down an answer while ice connection state
  10997. // is still checking is bad...
  10998. //console.log(self.peerconnection.iceConnectionState);
  10999. // trying to work around another chrome bug
  11000. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  11001. self.peerconnection.setLocalDescription(modifiedAnswer,
  11002. function() {
  11003. //console.log('modified setLocalDescription ok');
  11004. self.setLocalDescription();
  11005. if(successCallback){
  11006. successCallback();
  11007. }
  11008. },
  11009. function(error) {
  11010. console.error('modified setLocalDescription failed', error);
  11011. }
  11012. );
  11013. },
  11014. function(error) {
  11015. console.error('modified answer failed', error);
  11016. }
  11017. );
  11018. },
  11019. function(error) {
  11020. console.error('modify failed', error);
  11021. }
  11022. );
  11023. };
  11024. /**
  11025. * Switches video streams.
  11026. * @param new_stream new stream that will be used as video of this session.
  11027. * @param oldStream old video stream of this session.
  11028. * @param success_callback callback executed after successful stream switch.
  11029. */
  11030. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback) {
  11031. var self = this;
  11032. // Remember SDP to figure out added/removed SSRCs
  11033. var oldSdp = null;
  11034. if(self.peerconnection) {
  11035. if(self.peerconnection.localDescription) {
  11036. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  11037. }
  11038. self.peerconnection.removeStream(oldStream, true);
  11039. self.peerconnection.addStream(new_stream);
  11040. }
  11041. APP.RTC.switchVideoStreams(new_stream, oldStream);
  11042. // Conference is not active
  11043. if(!oldSdp || !self.peerconnection) {
  11044. success_callback();
  11045. return;
  11046. }
  11047. self.switchstreams = true;
  11048. self.modifySources(function() {
  11049. console.log('modify sources done');
  11050. success_callback();
  11051. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  11052. console.log("SDPs", oldSdp, newSdp);
  11053. self.notifyMySSRCUpdate(oldSdp, newSdp);
  11054. });
  11055. };
  11056. /**
  11057. * Figures out added/removed ssrcs and send update IQs.
  11058. * @param old_sdp SDP object for old description.
  11059. * @param new_sdp SDP object for new description.
  11060. */
  11061. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  11062. if (!(this.peerconnection.signalingState == 'stable' &&
  11063. this.peerconnection.iceConnectionState == 'connected')){
  11064. console.log("Too early to send updates");
  11065. return;
  11066. }
  11067. // send source-remove IQ.
  11068. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  11069. var remove = $iq({to: this.peerjid, type: 'set'})
  11070. .c('jingle', {
  11071. xmlns: 'urn:xmpp:jingle:1',
  11072. action: 'source-remove',
  11073. initiator: this.initiator,
  11074. sid: this.sid
  11075. }
  11076. );
  11077. var removed = sdpDiffer.toJingle(remove);
  11078. if (removed) {
  11079. this.connection.sendIQ(remove,
  11080. function (res) {
  11081. console.info('got remove result', res);
  11082. },
  11083. function (err) {
  11084. console.error('got remove error', err);
  11085. }
  11086. );
  11087. } else {
  11088. console.log('removal not necessary');
  11089. }
  11090. // send source-add IQ.
  11091. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  11092. var add = $iq({to: this.peerjid, type: 'set'})
  11093. .c('jingle', {
  11094. xmlns: 'urn:xmpp:jingle:1',
  11095. action: 'source-add',
  11096. initiator: this.initiator,
  11097. sid: this.sid
  11098. }
  11099. );
  11100. var added = sdpDiffer.toJingle(add);
  11101. if (added) {
  11102. this.connection.sendIQ(add,
  11103. function (res) {
  11104. console.info('got add result', res);
  11105. },
  11106. function (err) {
  11107. console.error('got add error', err);
  11108. }
  11109. );
  11110. } else {
  11111. console.log('addition not necessary');
  11112. }
  11113. };
  11114. /**
  11115. * Determines whether the (local) video is mute i.e. all video tracks are
  11116. * disabled.
  11117. *
  11118. * @return <tt>true</tt> if the (local) video is mute i.e. all video tracks are
  11119. * disabled; otherwise, <tt>false</tt>
  11120. */
  11121. JingleSession.prototype.isVideoMute = function () {
  11122. var tracks = APP.RTC.localVideo.getVideoTracks();
  11123. var mute = true;
  11124. for (var i = 0; i < tracks.length; ++i) {
  11125. if (tracks[i].enabled) {
  11126. mute = false;
  11127. break;
  11128. }
  11129. }
  11130. return mute;
  11131. };
  11132. /**
  11133. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  11134. *
  11135. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  11136. * tracks; otherwise, <tt>false</tt>
  11137. * @param callback a function to be invoked with <tt>mute</tt> after all video
  11138. * tracks have been enabled/disabled. The function may, optionally, return
  11139. * another function which is to be invoked after the whole mute/unmute operation
  11140. * has completed successfully.
  11141. * @param options an object which specifies optional arguments such as the
  11142. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  11143. * specifies whether the method was initiated in response to a user command (in
  11144. * contrast to an automatic decision made by the application logic)
  11145. */
  11146. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  11147. var byUser;
  11148. if (options) {
  11149. byUser = options.byUser;
  11150. if (typeof byUser === 'undefined') {
  11151. byUser = true;
  11152. }
  11153. } else {
  11154. byUser = true;
  11155. }
  11156. // The user's command to mute the (local) video takes precedence over any
  11157. // automatic decision made by the application logic.
  11158. if (byUser) {
  11159. this.videoMuteByUser = mute;
  11160. } else if (this.videoMuteByUser) {
  11161. return;
  11162. }
  11163. var self = this;
  11164. var localCallback = function (mute) {
  11165. self.connection.emuc.addVideoInfoToPresence(mute);
  11166. self.connection.emuc.sendPresence();
  11167. return callback(mute)
  11168. };
  11169. if (mute == APP.RTC.localVideo.isMuted())
  11170. {
  11171. // Even if no change occurs, the specified callback is to be executed.
  11172. // The specified callback may, optionally, return a successCallback
  11173. // which is to be executed as well.
  11174. var successCallback = localCallback(mute);
  11175. if (successCallback) {
  11176. successCallback();
  11177. }
  11178. } else {
  11179. APP.RTC.localVideo.setMute(!mute);
  11180. this.hardMuteVideo(mute);
  11181. this.modifySources(localCallback(mute));
  11182. }
  11183. };
  11184. // SDP-based mute by going recvonly/sendrecv
  11185. // FIXME: should probably black out the screen as well
  11186. JingleSession.prototype.toggleVideoMute = function (callback) {
  11187. this.service.setVideoMute(APP.RTC.localVideo.isMuted(), callback);
  11188. };
  11189. JingleSession.prototype.hardMuteVideo = function (muted) {
  11190. this.pendingop = muted ? 'mute' : 'unmute';
  11191. };
  11192. JingleSession.prototype.sendMute = function (muted, content) {
  11193. var info = $iq({to: this.peerjid,
  11194. type: 'set'})
  11195. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11196. action: 'session-info',
  11197. initiator: this.initiator,
  11198. sid: this.sid });
  11199. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11200. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  11201. if (content) {
  11202. info.attrs({'name': content});
  11203. }
  11204. this.connection.send(info);
  11205. };
  11206. JingleSession.prototype.sendRinging = function () {
  11207. var info = $iq({to: this.peerjid,
  11208. type: 'set'})
  11209. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11210. action: 'session-info',
  11211. initiator: this.initiator,
  11212. sid: this.sid });
  11213. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11214. this.connection.send(info);
  11215. };
  11216. JingleSession.prototype.getStats = function (interval) {
  11217. var self = this;
  11218. var recv = {audio: 0, video: 0};
  11219. var lost = {audio: 0, video: 0};
  11220. var lastrecv = {audio: 0, video: 0};
  11221. var lastlost = {audio: 0, video: 0};
  11222. var loss = {audio: 0, video: 0};
  11223. var delta = {audio: 0, video: 0};
  11224. this.statsinterval = window.setInterval(function () {
  11225. if (self && self.peerconnection && self.peerconnection.getStats) {
  11226. self.peerconnection.getStats(function (stats) {
  11227. var results = stats.result();
  11228. // TODO: there are so much statistics you can get from this..
  11229. for (var i = 0; i < results.length; ++i) {
  11230. if (results[i].type == 'ssrc') {
  11231. var packetsrecv = results[i].stat('packetsReceived');
  11232. var packetslost = results[i].stat('packetsLost');
  11233. if (packetsrecv && packetslost) {
  11234. packetsrecv = parseInt(packetsrecv, 10);
  11235. packetslost = parseInt(packetslost, 10);
  11236. if (results[i].stat('googFrameRateReceived')) {
  11237. lastlost.video = lost.video;
  11238. lastrecv.video = recv.video;
  11239. recv.video = packetsrecv;
  11240. lost.video = packetslost;
  11241. } else {
  11242. lastlost.audio = lost.audio;
  11243. lastrecv.audio = recv.audio;
  11244. recv.audio = packetsrecv;
  11245. lost.audio = packetslost;
  11246. }
  11247. }
  11248. }
  11249. }
  11250. delta.audio = recv.audio - lastrecv.audio;
  11251. delta.video = recv.video - lastrecv.video;
  11252. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  11253. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  11254. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  11255. });
  11256. }
  11257. }, interval || 3000);
  11258. return this.statsinterval;
  11259. };
  11260. JingleSession.onJingleError = function (session, error)
  11261. {
  11262. console.error("Jingle error", error);
  11263. }
  11264. JingleSession.onJingleFatalError = function (session, error)
  11265. {
  11266. this.service.sessionTerminated = true;
  11267. this.connection.emuc.doLeave();
  11268. APP.UI.messageHandler.showError("dialog.sorry",
  11269. "dialog.internalError");
  11270. }
  11271. JingleSession.prototype.setLocalDescription = function () {
  11272. // put our ssrcs into presence so other clients can identify our stream
  11273. var newssrcs = [];
  11274. var media = APP.simulcast.parseMedia(this.peerconnection.localDescription);
  11275. media.forEach(function (media) {
  11276. if(Object.keys(media.sources).length > 0) {
  11277. // TODO(gp) maybe exclude FID streams?
  11278. Object.keys(media.sources).forEach(function (ssrc) {
  11279. newssrcs.push({
  11280. 'ssrc': ssrc,
  11281. 'type': media.type,
  11282. 'direction': media.direction
  11283. });
  11284. });
  11285. }
  11286. else if(this.localStreamsSSRC && this.localStreamsSSRC[media.type])
  11287. {
  11288. newssrcs.push({
  11289. 'ssrc': this.localStreamsSSRC[media.type],
  11290. 'type': media.type,
  11291. 'direction': media.direction
  11292. });
  11293. }
  11294. });
  11295. console.log('new ssrcs', newssrcs);
  11296. // Have to clear presence map to get rid of removed streams
  11297. this.connection.emuc.clearPresenceMedia();
  11298. if (newssrcs.length > 0) {
  11299. for (var i = 1; i <= newssrcs.length; i ++) {
  11300. // Change video type to screen
  11301. if (newssrcs[i-1].type === 'video' && APP.desktopsharing.isUsingScreenStream()) {
  11302. newssrcs[i-1].type = 'screen';
  11303. }
  11304. this.connection.emuc.addMediaToPresence(i,
  11305. newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
  11306. }
  11307. this.connection.emuc.sendPresence();
  11308. }
  11309. }
  11310. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11311. function sendKeyframe(pc) {
  11312. console.log('sendkeyframe', pc.iceConnectionState);
  11313. if (pc.iceConnectionState !== 'connected') return; // safe...
  11314. pc.setRemoteDescription(
  11315. pc.remoteDescription,
  11316. function () {
  11317. pc.createAnswer(
  11318. function (modifiedAnswer) {
  11319. pc.setLocalDescription(
  11320. modifiedAnswer,
  11321. function () {
  11322. // noop
  11323. },
  11324. function (error) {
  11325. console.log('triggerKeyframe setLocalDescription failed', error);
  11326. APP.UI.messageHandler.showError();
  11327. }
  11328. );
  11329. },
  11330. function (error) {
  11331. console.log('triggerKeyframe createAnswer failed', error);
  11332. APP.UI.messageHandler.showError();
  11333. }
  11334. );
  11335. },
  11336. function (error) {
  11337. console.log('triggerKeyframe setRemoteDescription failed', error);
  11338. APP.UI.messageHandler.showError();
  11339. }
  11340. );
  11341. }
  11342. JingleSession.prototype.remoteStreamAdded = function (data) {
  11343. var self = this;
  11344. var thessrc;
  11345. var ssrc2jid = this.connection.emuc.ssrc2jid;
  11346. // look up an associated JID for a stream id
  11347. if (data.stream.id && data.stream.id.indexOf('mixedmslabel') === -1) {
  11348. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  11349. var ssrclines
  11350. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  11351. ssrclines = ssrclines.filter(function (line) {
  11352. // NOTE(gp) previously we filtered on the mslabel, but that property
  11353. // is not always present.
  11354. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  11355. return ((line.indexOf('msid:' + data.stream.id) !== -1));
  11356. });
  11357. if (ssrclines.length) {
  11358. thessrc = ssrclines[0].substring(7).split(' ')[0];
  11359. // We signal our streams (through Jingle to the focus) before we set
  11360. // our presence (through which peers associate remote streams to
  11361. // jids). So, it might arrive that a remote stream is added but
  11362. // ssrc2jid is not yet updated and thus data.peerjid cannot be
  11363. // successfully set. Here we wait for up to a second for the
  11364. // presence to arrive.
  11365. if (!ssrc2jid[thessrc]) {
  11366. // TODO(gp) limit wait duration to 1 sec.
  11367. setTimeout(function(d) {
  11368. return function() {
  11369. self.remoteStreamAdded(d);
  11370. }
  11371. }(data), 250);
  11372. return;
  11373. }
  11374. // ok to overwrite the one from focus? might save work in colibri.js
  11375. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  11376. if (ssrc2jid[thessrc]) {
  11377. data.peerjid = ssrc2jid[thessrc];
  11378. }
  11379. }
  11380. }
  11381. //TODO: this code should be removed when firefox implement multistream support
  11382. if(APP.RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_FIREFOX)
  11383. {
  11384. if((JingleSession.notReceivedSSRCs.length == 0) ||
  11385. !ssrc2jid[JingleSession.notReceivedSSRCs[JingleSession.notReceivedSSRCs.length - 1]])
  11386. {
  11387. // TODO(gp) limit wait duration to 1 sec.
  11388. setTimeout(function(d) {
  11389. return function() {
  11390. self.remoteStreamAdded(d);
  11391. }
  11392. }(data), 250);
  11393. return;
  11394. }
  11395. thessrc = JingleSession.notReceivedSSRCs.pop();
  11396. if (ssrc2jid[thessrc]) {
  11397. data.peerjid = ssrc2jid[thessrc];
  11398. }
  11399. }
  11400. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  11401. var isVideo = data.stream.getVideoTracks().length > 0;
  11402. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11403. if (isVideo &&
  11404. data.peerjid && this.peerjid === data.peerjid &&
  11405. data.stream.getVideoTracks().length === 0 &&
  11406. APP.RTC.localVideo.getTracks().length > 0) {
  11407. window.setTimeout(function () {
  11408. sendKeyframe(self.peerconnection);
  11409. }, 3000);
  11410. }
  11411. }
  11412. module.exports = JingleSession;
  11413. },{"../../service/RTC/RTCBrowserType":79,"./SDP":48,"./SDPDiffer":49,"./SDPUtil":50,"./TraceablePeerConnection":51}],48:[function(require,module,exports){
  11414. /* jshint -W117 */
  11415. var SDPUtil = require("./SDPUtil");
  11416. // SDP STUFF
  11417. function SDP(sdp) {
  11418. this.media = sdp.split('\r\nm=');
  11419. for (var i = 1; i < this.media.length; i++) {
  11420. this.media[i] = 'm=' + this.media[i];
  11421. if (i != this.media.length - 1) {
  11422. this.media[i] += '\r\n';
  11423. }
  11424. }
  11425. this.session = this.media.shift() + '\r\n';
  11426. this.raw = this.session + this.media.join('');
  11427. }
  11428. /**
  11429. * Returns map of MediaChannel mapped per channel idx.
  11430. */
  11431. SDP.prototype.getMediaSsrcMap = function() {
  11432. var self = this;
  11433. var media_ssrcs = {};
  11434. var tmp;
  11435. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  11436. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  11437. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  11438. var media = {
  11439. mediaindex: mediaindex,
  11440. mid: mid,
  11441. ssrcs: {},
  11442. ssrcGroups: []
  11443. };
  11444. media_ssrcs[mediaindex] = media;
  11445. tmp.forEach(function (line) {
  11446. var linessrc = line.substring(7).split(' ')[0];
  11447. // allocate new ChannelSsrc
  11448. if(!media.ssrcs[linessrc]) {
  11449. media.ssrcs[linessrc] = {
  11450. ssrc: linessrc,
  11451. lines: []
  11452. };
  11453. }
  11454. media.ssrcs[linessrc].lines.push(line);
  11455. });
  11456. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  11457. tmp.forEach(function(line){
  11458. var semantics = line.substr(0, idx).substr(13);
  11459. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11460. if (ssrcs.length != 0) {
  11461. media.ssrcGroups.push({
  11462. semantics: semantics,
  11463. ssrcs: ssrcs
  11464. });
  11465. }
  11466. });
  11467. }
  11468. return media_ssrcs;
  11469. };
  11470. /**
  11471. * Returns <tt>true</tt> if this SDP contains given SSRC.
  11472. * @param ssrc the ssrc to check.
  11473. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  11474. */
  11475. SDP.prototype.containsSSRC = function(ssrc) {
  11476. var medias = this.getMediaSsrcMap();
  11477. var contains = false;
  11478. Object.keys(medias).forEach(function(mediaindex){
  11479. var media = medias[mediaindex];
  11480. //console.log("Check", channel, ssrc);
  11481. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  11482. contains = true;
  11483. }
  11484. });
  11485. return contains;
  11486. };
  11487. // remove iSAC and CN from SDP
  11488. SDP.prototype.mangle = function () {
  11489. var i, j, mline, lines, rtpmap, newdesc;
  11490. for (i = 0; i < this.media.length; i++) {
  11491. lines = this.media[i].split('\r\n');
  11492. lines.pop(); // remove empty last element
  11493. mline = SDPUtil.parse_mline(lines.shift());
  11494. if (mline.media != 'audio')
  11495. continue;
  11496. newdesc = '';
  11497. mline.fmt.length = 0;
  11498. for (j = 0; j < lines.length; j++) {
  11499. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  11500. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  11501. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  11502. continue;
  11503. mline.fmt.push(rtpmap.id);
  11504. newdesc += lines[j] + '\r\n';
  11505. } else {
  11506. newdesc += lines[j] + '\r\n';
  11507. }
  11508. }
  11509. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  11510. this.media[i] += newdesc;
  11511. }
  11512. this.raw = this.session + this.media.join('');
  11513. };
  11514. // remove lines matching prefix from session section
  11515. SDP.prototype.removeSessionLines = function(prefix) {
  11516. var self = this;
  11517. var lines = SDPUtil.find_lines(this.session, prefix);
  11518. lines.forEach(function(line) {
  11519. self.session = self.session.replace(line + '\r\n', '');
  11520. });
  11521. this.raw = this.session + this.media.join('');
  11522. return lines;
  11523. }
  11524. // remove lines matching prefix from a media section specified by mediaindex
  11525. // TODO: non-numeric mediaindex could match mid
  11526. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  11527. var self = this;
  11528. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  11529. lines.forEach(function(line) {
  11530. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  11531. });
  11532. this.raw = this.session + this.media.join('');
  11533. return lines;
  11534. }
  11535. // add content's to a jingle element
  11536. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  11537. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  11538. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  11539. var self = this;
  11540. // new bundle plan
  11541. if (SDPUtil.find_line(this.session, 'a=group:')) {
  11542. lines = SDPUtil.find_lines(this.session, 'a=group:');
  11543. for (i = 0; i < lines.length; i++) {
  11544. tmp = lines[i].split(' ');
  11545. var semantics = tmp.shift().substr(8);
  11546. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  11547. for (j = 0; j < tmp.length; j++) {
  11548. elem.c('content', {name: tmp[j]}).up();
  11549. }
  11550. elem.up();
  11551. }
  11552. }
  11553. for (i = 0; i < this.media.length; i++) {
  11554. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  11555. if (!(mline.media === 'audio' ||
  11556. mline.media === 'video' ||
  11557. mline.media === 'application'))
  11558. {
  11559. continue;
  11560. }
  11561. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  11562. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  11563. } else {
  11564. if(ssrcs && ssrcs[mline.media])
  11565. {
  11566. ssrc = ssrcs[mline.media];
  11567. }
  11568. else
  11569. ssrc = false;
  11570. }
  11571. elem.c('content', {creator: thecreator, name: mline.media});
  11572. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  11573. // prefer identifier from a=mid if present
  11574. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  11575. elem.attrs({ name: mid });
  11576. }
  11577. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  11578. {
  11579. elem.c('description',
  11580. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  11581. media: mline.media });
  11582. if (ssrc) {
  11583. elem.attrs({ssrc: ssrc});
  11584. }
  11585. for (j = 0; j < mline.fmt.length; j++) {
  11586. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  11587. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  11588. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  11589. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  11590. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  11591. for (k = 0; k < tmp.length; k++) {
  11592. elem.c('parameter', tmp[k]).up();
  11593. }
  11594. }
  11595. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  11596. elem.up();
  11597. }
  11598. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  11599. elem.c('encryption', {required: 1});
  11600. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  11601. crypto.forEach(function(line) {
  11602. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  11603. });
  11604. elem.up(); // end of encryption
  11605. }
  11606. if (ssrc) {
  11607. // new style mapping
  11608. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11609. // FIXME: group by ssrc and support multiple different ssrcs
  11610. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  11611. if(ssrclines.length > 0) {
  11612. ssrclines.forEach(function (line) {
  11613. idx = line.indexOf(' ');
  11614. var linessrc = line.substr(0, idx).substr(7);
  11615. if (linessrc != ssrc) {
  11616. elem.up();
  11617. ssrc = linessrc;
  11618. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11619. }
  11620. var kv = line.substr(idx + 1);
  11621. elem.c('parameter');
  11622. if (kv.indexOf(':') == -1) {
  11623. elem.attrs({ name: kv });
  11624. } else {
  11625. elem.attrs({ name: kv.split(':', 2)[0] });
  11626. elem.attrs({ value: kv.split(':', 2)[1] });
  11627. }
  11628. elem.up();
  11629. });
  11630. elem.up();
  11631. }
  11632. else
  11633. {
  11634. elem.up();
  11635. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11636. elem.c('parameter');
  11637. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  11638. elem.up();
  11639. var msid = null;
  11640. if(mline.media == "audio")
  11641. {
  11642. msid = APP.RTC.localAudio.getId();
  11643. }
  11644. else
  11645. {
  11646. msid = APP.RTC.localVideo.getId();
  11647. }
  11648. if(msid != null)
  11649. {
  11650. msid = msid.replace(/[\{,\}]/g,"");
  11651. elem.c('parameter');
  11652. elem.attrs({name: "msid", value:msid});
  11653. elem.up();
  11654. elem.c('parameter');
  11655. elem.attrs({name: "mslabel", value:msid});
  11656. elem.up();
  11657. elem.c('parameter');
  11658. elem.attrs({name: "label", value:msid});
  11659. elem.up();
  11660. elem.up();
  11661. }
  11662. }
  11663. // XEP-0339 handle ssrc-group attributes
  11664. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  11665. ssrc_group_lines.forEach(function(line) {
  11666. idx = line.indexOf(' ');
  11667. var semantics = line.substr(0, idx).substr(13);
  11668. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11669. if (ssrcs.length != 0) {
  11670. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11671. ssrcs.forEach(function(ssrc) {
  11672. elem.c('source', { ssrc: ssrc })
  11673. .up();
  11674. });
  11675. elem.up();
  11676. }
  11677. });
  11678. }
  11679. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  11680. elem.c('rtcp-mux').up();
  11681. }
  11682. // XEP-0293 -- map a=rtcp-fb:*
  11683. this.RtcpFbToJingle(i, elem, '*');
  11684. // XEP-0294
  11685. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  11686. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  11687. for (j = 0; j < lines.length; j++) {
  11688. tmp = SDPUtil.parse_extmap(lines[j]);
  11689. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  11690. uri: tmp.uri,
  11691. id: tmp.value });
  11692. if (tmp.hasOwnProperty('direction')) {
  11693. switch (tmp.direction) {
  11694. case 'sendonly':
  11695. elem.attrs({senders: 'responder'});
  11696. break;
  11697. case 'recvonly':
  11698. elem.attrs({senders: 'initiator'});
  11699. break;
  11700. case 'sendrecv':
  11701. elem.attrs({senders: 'both'});
  11702. break;
  11703. case 'inactive':
  11704. elem.attrs({senders: 'none'});
  11705. break;
  11706. }
  11707. }
  11708. // TODO: handle params
  11709. elem.up();
  11710. }
  11711. }
  11712. elem.up(); // end of description
  11713. }
  11714. // map ice-ufrag/pwd, dtls fingerprint, candidates
  11715. this.TransportToJingle(i, elem);
  11716. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  11717. elem.attrs({senders: 'both'});
  11718. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  11719. elem.attrs({senders: 'initiator'});
  11720. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  11721. elem.attrs({senders: 'responder'});
  11722. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  11723. elem.attrs({senders: 'none'});
  11724. }
  11725. if (mline.port == '0') {
  11726. // estos hack to reject an m-line
  11727. elem.attrs({senders: 'rejected'});
  11728. }
  11729. elem.up(); // end of content
  11730. }
  11731. elem.up();
  11732. return elem;
  11733. };
  11734. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  11735. var i = mediaindex;
  11736. var tmp;
  11737. var self = this;
  11738. elem.c('transport');
  11739. // XEP-0343 DTLS/SCTP
  11740. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  11741. {
  11742. var sctpmap = SDPUtil.find_line(
  11743. this.media[i], 'a=sctpmap:', self.session);
  11744. if (sctpmap)
  11745. {
  11746. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  11747. elem.c('sctpmap',
  11748. {
  11749. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  11750. number: sctpAttrs[0], /* SCTP port */
  11751. protocol: sctpAttrs[1], /* protocol */
  11752. });
  11753. // Optional stream count attribute
  11754. if (sctpAttrs.length > 2)
  11755. elem.attrs({ streams: sctpAttrs[2]});
  11756. elem.up();
  11757. }
  11758. }
  11759. // XEP-0320
  11760. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  11761. fingerprints.forEach(function(line) {
  11762. tmp = SDPUtil.parse_fingerprint(line);
  11763. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  11764. elem.c('fingerprint').t(tmp.fingerprint);
  11765. delete tmp.fingerprint;
  11766. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  11767. if (line) {
  11768. tmp.setup = line.substr(8);
  11769. }
  11770. elem.attrs(tmp);
  11771. elem.up(); // end of fingerprint
  11772. });
  11773. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  11774. if (tmp) {
  11775. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11776. elem.attrs(tmp);
  11777. // XEP-0176
  11778. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  11779. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  11780. lines.forEach(function (line) {
  11781. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  11782. });
  11783. }
  11784. }
  11785. elem.up(); // end of transport
  11786. }
  11787. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  11788. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  11789. lines.forEach(function (line) {
  11790. var tmp = SDPUtil.parse_rtcpfb(line);
  11791. if (tmp.type == 'trr-int') {
  11792. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  11793. elem.up();
  11794. } else {
  11795. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  11796. if (tmp.params.length > 0) {
  11797. elem.attrs({'subtype': tmp.params[0]});
  11798. }
  11799. elem.up();
  11800. }
  11801. });
  11802. };
  11803. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  11804. var media = '';
  11805. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  11806. if (tmp.length) {
  11807. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  11808. if (tmp.attr('value')) {
  11809. media += tmp.attr('value');
  11810. } else {
  11811. media += '0';
  11812. }
  11813. media += '\r\n';
  11814. }
  11815. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  11816. tmp.each(function () {
  11817. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  11818. if ($(this).attr('subtype')) {
  11819. media += ' ' + $(this).attr('subtype');
  11820. }
  11821. media += '\r\n';
  11822. });
  11823. return media;
  11824. };
  11825. // construct an SDP from a jingle stanza
  11826. SDP.prototype.fromJingle = function (jingle) {
  11827. var self = this;
  11828. this.raw = 'v=0\r\n' +
  11829. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  11830. 's=-\r\n' +
  11831. 't=0 0\r\n';
  11832. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  11833. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  11834. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  11835. var contents = $(group).find('>content').map(function (idx, content) {
  11836. return content.getAttribute('name');
  11837. }).get();
  11838. if (contents.length > 0) {
  11839. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  11840. }
  11841. });
  11842. }
  11843. this.session = this.raw;
  11844. jingle.find('>content').each(function () {
  11845. var m = self.jingle2media($(this));
  11846. self.media.push(m);
  11847. });
  11848. // reconstruct msid-semantic -- apparently not necessary
  11849. /*
  11850. var msid = SDPUtil.parse_ssrc(this.raw);
  11851. if (msid.hasOwnProperty('mslabel')) {
  11852. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  11853. }
  11854. */
  11855. this.raw = this.session + this.media.join('');
  11856. };
  11857. // translate a jingle content element into an an SDP media part
  11858. SDP.prototype.jingle2media = function (content) {
  11859. var media = '',
  11860. desc = content.find('description'),
  11861. ssrc = desc.attr('ssrc'),
  11862. self = this,
  11863. tmp;
  11864. var sctp = content.find(
  11865. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  11866. tmp = { media: desc.attr('media') };
  11867. tmp.port = '1';
  11868. if (content.attr('senders') == 'rejected') {
  11869. // estos hack to reject an m-line.
  11870. tmp.port = '0';
  11871. }
  11872. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  11873. if (sctp.length)
  11874. tmp.proto = 'DTLS/SCTP';
  11875. else
  11876. tmp.proto = 'RTP/SAVPF';
  11877. } else {
  11878. tmp.proto = 'RTP/AVPF';
  11879. }
  11880. if (!sctp.length)
  11881. {
  11882. tmp.fmt = desc.find('payload-type').map(
  11883. function () { return this.getAttribute('id'); }).get();
  11884. media += SDPUtil.build_mline(tmp) + '\r\n';
  11885. }
  11886. else
  11887. {
  11888. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  11889. media += 'a=sctpmap:' + sctp.attr('number') +
  11890. ' ' + sctp.attr('protocol');
  11891. var streamCount = sctp.attr('streams');
  11892. if (streamCount)
  11893. media += ' ' + streamCount + '\r\n';
  11894. else
  11895. media += '\r\n';
  11896. }
  11897. media += 'c=IN IP4 0.0.0.0\r\n';
  11898. if (!sctp.length)
  11899. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  11900. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  11901. if (tmp.length) {
  11902. if (tmp.attr('ufrag')) {
  11903. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  11904. }
  11905. if (tmp.attr('pwd')) {
  11906. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  11907. }
  11908. tmp.find('>fingerprint').each(function () {
  11909. // FIXME: check namespace at some point
  11910. media += 'a=fingerprint:' + this.getAttribute('hash');
  11911. media += ' ' + $(this).text();
  11912. media += '\r\n';
  11913. if (this.getAttribute('setup')) {
  11914. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  11915. }
  11916. });
  11917. }
  11918. switch (content.attr('senders')) {
  11919. case 'initiator':
  11920. media += 'a=sendonly\r\n';
  11921. break;
  11922. case 'responder':
  11923. media += 'a=recvonly\r\n';
  11924. break;
  11925. case 'none':
  11926. media += 'a=inactive\r\n';
  11927. break;
  11928. case 'both':
  11929. media += 'a=sendrecv\r\n';
  11930. break;
  11931. }
  11932. media += 'a=mid:' + content.attr('name') + '\r\n';
  11933. // <description><rtcp-mux/></description>
  11934. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  11935. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  11936. if (desc.find('rtcp-mux').length) {
  11937. media += 'a=rtcp-mux\r\n';
  11938. }
  11939. if (desc.find('encryption').length) {
  11940. desc.find('encryption>crypto').each(function () {
  11941. media += 'a=crypto:' + this.getAttribute('tag');
  11942. media += ' ' + this.getAttribute('crypto-suite');
  11943. media += ' ' + this.getAttribute('key-params');
  11944. if (this.getAttribute('session-params')) {
  11945. media += ' ' + this.getAttribute('session-params');
  11946. }
  11947. media += '\r\n';
  11948. });
  11949. }
  11950. desc.find('payload-type').each(function () {
  11951. media += SDPUtil.build_rtpmap(this) + '\r\n';
  11952. if ($(this).find('>parameter').length) {
  11953. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  11954. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  11955. media += '\r\n';
  11956. }
  11957. // xep-0293
  11958. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  11959. });
  11960. // xep-0293
  11961. media += self.RtcpFbFromJingle(desc, '*');
  11962. // xep-0294
  11963. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  11964. tmp.each(function () {
  11965. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  11966. });
  11967. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  11968. media += SDPUtil.candidateFromJingle(this);
  11969. });
  11970. // XEP-0339 handle ssrc-group attributes
  11971. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  11972. var semantics = this.getAttribute('semantics');
  11973. var ssrcs = $(this).find('>source').map(function() {
  11974. return this.getAttribute('ssrc');
  11975. }).get();
  11976. if (ssrcs.length != 0) {
  11977. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  11978. }
  11979. });
  11980. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  11981. tmp.each(function () {
  11982. var ssrc = this.getAttribute('ssrc');
  11983. $(this).find('>parameter').each(function () {
  11984. media += 'a=ssrc:' + ssrc + ' ' + this.getAttribute('name');
  11985. if (this.getAttribute('value') && this.getAttribute('value').length)
  11986. media += ':' + this.getAttribute('value');
  11987. media += '\r\n';
  11988. });
  11989. });
  11990. return media;
  11991. };
  11992. module.exports = SDP;
  11993. },{"./SDPUtil":50}],49:[function(require,module,exports){
  11994. function SDPDiffer(mySDP, otherSDP) {
  11995. this.mySDP = mySDP;
  11996. this.otherSDP = otherSDP;
  11997. }
  11998. /**
  11999. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  12000. * @param otherSdp the other SDP to check ssrc with.
  12001. */
  12002. SDPDiffer.prototype.getNewMedia = function() {
  12003. // this could be useful in Array.prototype.
  12004. function arrayEquals(array) {
  12005. // if the other array is a falsy value, return
  12006. if (!array)
  12007. return false;
  12008. // compare lengths - can save a lot of time
  12009. if (this.length != array.length)
  12010. return false;
  12011. for (var i = 0, l=this.length; i < l; i++) {
  12012. // Check if we have nested arrays
  12013. if (this[i] instanceof Array && array[i] instanceof Array) {
  12014. // recurse into the nested arrays
  12015. if (!this[i].equals(array[i]))
  12016. return false;
  12017. }
  12018. else if (this[i] != array[i]) {
  12019. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  12020. return false;
  12021. }
  12022. }
  12023. return true;
  12024. }
  12025. var myMedias = this.mySDP.getMediaSsrcMap();
  12026. var othersMedias = this.otherSDP.getMediaSsrcMap();
  12027. var newMedia = {};
  12028. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  12029. var myMedia = myMedias[othersMediaIdx];
  12030. var othersMedia = othersMedias[othersMediaIdx];
  12031. if(!myMedia && othersMedia) {
  12032. // Add whole channel
  12033. newMedia[othersMediaIdx] = othersMedia;
  12034. return;
  12035. }
  12036. // Look for new ssrcs accross the channel
  12037. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  12038. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  12039. // Allocate channel if we've found ssrc that doesn't exist in our channel
  12040. if(!newMedia[othersMediaIdx]){
  12041. newMedia[othersMediaIdx] = {
  12042. mediaindex: othersMedia.mediaindex,
  12043. mid: othersMedia.mid,
  12044. ssrcs: {},
  12045. ssrcGroups: []
  12046. };
  12047. }
  12048. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  12049. }
  12050. });
  12051. // Look for new ssrc groups across the channels
  12052. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  12053. // try to match the other ssrc-group with an ssrc-group of ours
  12054. var matched = false;
  12055. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  12056. var mySsrcGroup = myMedia.ssrcGroups[i];
  12057. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  12058. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  12059. matched = true;
  12060. break;
  12061. }
  12062. }
  12063. if (!matched) {
  12064. // Allocate channel if we've found an ssrc-group that doesn't
  12065. // exist in our channel
  12066. if(!newMedia[othersMediaIdx]){
  12067. newMedia[othersMediaIdx] = {
  12068. mediaindex: othersMedia.mediaindex,
  12069. mid: othersMedia.mid,
  12070. ssrcs: {},
  12071. ssrcGroups: []
  12072. };
  12073. }
  12074. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  12075. }
  12076. });
  12077. });
  12078. return newMedia;
  12079. };
  12080. /**
  12081. * Sends SSRC update IQ.
  12082. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  12083. * @param sid session identifier that will be put into the IQ.
  12084. * @param initiator initiator identifier.
  12085. * @param toJid destination Jid
  12086. * @param isAdd indicates if this is remove or add operation.
  12087. */
  12088. SDPDiffer.prototype.toJingle = function(modify) {
  12089. var sdpMediaSsrcs = this.getNewMedia();
  12090. var self = this;
  12091. // FIXME: only announce video ssrcs since we mix audio and dont need
  12092. // the audio ssrcs therefore
  12093. var modified = false;
  12094. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  12095. modified = true;
  12096. var media = sdpMediaSsrcs[mediaindex];
  12097. modify.c('content', {name: media.mid});
  12098. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  12099. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  12100. // generate sources from lines
  12101. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  12102. var mediaSsrc = media.ssrcs[ssrcNum];
  12103. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12104. modify.attrs({ssrc: mediaSsrc.ssrc});
  12105. // iterate over ssrc lines
  12106. mediaSsrc.lines.forEach(function (line) {
  12107. var idx = line.indexOf(' ');
  12108. var kv = line.substr(idx + 1);
  12109. modify.c('parameter');
  12110. if (kv.indexOf(':') == -1) {
  12111. modify.attrs({ name: kv });
  12112. } else {
  12113. modify.attrs({ name: kv.split(':', 2)[0] });
  12114. modify.attrs({ value: kv.split(':', 2)[1] });
  12115. }
  12116. modify.up(); // end of parameter
  12117. });
  12118. modify.up(); // end of source
  12119. });
  12120. // generate source groups from lines
  12121. media.ssrcGroups.forEach(function(ssrcGroup) {
  12122. if (ssrcGroup.ssrcs.length != 0) {
  12123. modify.c('ssrc-group', {
  12124. semantics: ssrcGroup.semantics,
  12125. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  12126. });
  12127. ssrcGroup.ssrcs.forEach(function (ssrc) {
  12128. modify.c('source', { ssrc: ssrc })
  12129. .up(); // end of source
  12130. });
  12131. modify.up(); // end of ssrc-group
  12132. }
  12133. });
  12134. modify.up(); // end of description
  12135. modify.up(); // end of content
  12136. });
  12137. return modified;
  12138. };
  12139. module.exports = SDPDiffer;
  12140. },{}],50:[function(require,module,exports){
  12141. SDPUtil = {
  12142. iceparams: function (mediadesc, sessiondesc) {
  12143. var data = null;
  12144. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  12145. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  12146. data = {
  12147. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  12148. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  12149. };
  12150. }
  12151. return data;
  12152. },
  12153. parse_iceufrag: function (line) {
  12154. return line.substring(12);
  12155. },
  12156. build_iceufrag: function (frag) {
  12157. return 'a=ice-ufrag:' + frag;
  12158. },
  12159. parse_icepwd: function (line) {
  12160. return line.substring(10);
  12161. },
  12162. build_icepwd: function (pwd) {
  12163. return 'a=ice-pwd:' + pwd;
  12164. },
  12165. parse_mid: function (line) {
  12166. return line.substring(6);
  12167. },
  12168. parse_mline: function (line) {
  12169. var parts = line.substring(2).split(' '),
  12170. data = {};
  12171. data.media = parts.shift();
  12172. data.port = parts.shift();
  12173. data.proto = parts.shift();
  12174. if (parts[parts.length - 1] === '') { // trailing whitespace
  12175. parts.pop();
  12176. }
  12177. data.fmt = parts;
  12178. return data;
  12179. },
  12180. build_mline: function (mline) {
  12181. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  12182. },
  12183. parse_rtpmap: function (line) {
  12184. var parts = line.substring(9).split(' '),
  12185. data = {};
  12186. data.id = parts.shift();
  12187. parts = parts[0].split('/');
  12188. data.name = parts.shift();
  12189. data.clockrate = parts.shift();
  12190. data.channels = parts.length ? parts.shift() : '1';
  12191. return data;
  12192. },
  12193. /**
  12194. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  12195. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  12196. * @returns [SCTP port number, protocol, streams]
  12197. */
  12198. parse_sctpmap: function (line)
  12199. {
  12200. var parts = line.substring(10).split(' ');
  12201. var sctpPort = parts[0];
  12202. var protocol = parts[1];
  12203. // Stream count is optional
  12204. var streamCount = parts.length > 2 ? parts[2] : null;
  12205. return [sctpPort, protocol, streamCount];// SCTP port
  12206. },
  12207. build_rtpmap: function (el) {
  12208. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  12209. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  12210. line += '/' + el.getAttribute('channels');
  12211. }
  12212. return line;
  12213. },
  12214. parse_crypto: function (line) {
  12215. var parts = line.substring(9).split(' '),
  12216. data = {};
  12217. data.tag = parts.shift();
  12218. data['crypto-suite'] = parts.shift();
  12219. data['key-params'] = parts.shift();
  12220. if (parts.length) {
  12221. data['session-params'] = parts.join(' ');
  12222. }
  12223. return data;
  12224. },
  12225. parse_fingerprint: function (line) { // RFC 4572
  12226. var parts = line.substring(14).split(' '),
  12227. data = {};
  12228. data.hash = parts.shift();
  12229. data.fingerprint = parts.shift();
  12230. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  12231. return data;
  12232. },
  12233. parse_fmtp: function (line) {
  12234. var parts = line.split(' '),
  12235. i, key, value,
  12236. data = [];
  12237. parts.shift();
  12238. parts = parts.join(' ').split(';');
  12239. for (i = 0; i < parts.length; i++) {
  12240. key = parts[i].split('=')[0];
  12241. while (key.length && key[0] == ' ') {
  12242. key = key.substring(1);
  12243. }
  12244. value = parts[i].split('=')[1];
  12245. if (key && value) {
  12246. data.push({name: key, value: value});
  12247. } else if (key) {
  12248. // rfc 4733 (DTMF) style stuff
  12249. data.push({name: '', value: key});
  12250. }
  12251. }
  12252. return data;
  12253. },
  12254. parse_icecandidate: function (line) {
  12255. var candidate = {},
  12256. elems = line.split(' ');
  12257. candidate.foundation = elems[0].substring(12);
  12258. candidate.component = elems[1];
  12259. candidate.protocol = elems[2].toLowerCase();
  12260. candidate.priority = elems[3];
  12261. candidate.ip = elems[4];
  12262. candidate.port = elems[5];
  12263. // elems[6] => "typ"
  12264. candidate.type = elems[7];
  12265. candidate.generation = 0; // default value, may be overwritten below
  12266. for (var i = 8; i < elems.length; i += 2) {
  12267. switch (elems[i]) {
  12268. case 'raddr':
  12269. candidate['rel-addr'] = elems[i + 1];
  12270. break;
  12271. case 'rport':
  12272. candidate['rel-port'] = elems[i + 1];
  12273. break;
  12274. case 'generation':
  12275. candidate.generation = elems[i + 1];
  12276. break;
  12277. case 'tcptype':
  12278. candidate.tcptype = elems[i + 1];
  12279. break;
  12280. default: // TODO
  12281. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12282. }
  12283. }
  12284. candidate.network = '1';
  12285. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12286. return candidate;
  12287. },
  12288. build_icecandidate: function (cand) {
  12289. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  12290. line += ' ';
  12291. switch (cand.type) {
  12292. case 'srflx':
  12293. case 'prflx':
  12294. case 'relay':
  12295. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  12296. line += 'raddr';
  12297. line += ' ';
  12298. line += cand['rel-addr'];
  12299. line += ' ';
  12300. line += 'rport';
  12301. line += ' ';
  12302. line += cand['rel-port'];
  12303. line += ' ';
  12304. }
  12305. break;
  12306. }
  12307. if (cand.hasOwnAttribute('tcptype')) {
  12308. line += 'tcptype';
  12309. line += ' ';
  12310. line += cand.tcptype;
  12311. line += ' ';
  12312. }
  12313. line += 'generation';
  12314. line += ' ';
  12315. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  12316. return line;
  12317. },
  12318. parse_ssrc: function (desc) {
  12319. // proprietary mapping of a=ssrc lines
  12320. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  12321. // and parse according to that
  12322. var lines = desc.split('\r\n'),
  12323. data = {};
  12324. for (var i = 0; i < lines.length; i++) {
  12325. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  12326. var idx = lines[i].indexOf(' ');
  12327. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  12328. }
  12329. }
  12330. return data;
  12331. },
  12332. parse_rtcpfb: function (line) {
  12333. var parts = line.substr(10).split(' ');
  12334. var data = {};
  12335. data.pt = parts.shift();
  12336. data.type = parts.shift();
  12337. data.params = parts;
  12338. return data;
  12339. },
  12340. parse_extmap: function (line) {
  12341. var parts = line.substr(9).split(' ');
  12342. var data = {};
  12343. data.value = parts.shift();
  12344. if (data.value.indexOf('/') != -1) {
  12345. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  12346. data.value = data.value.substr(0, data.value.indexOf('/'));
  12347. } else {
  12348. data.direction = 'both';
  12349. }
  12350. data.uri = parts.shift();
  12351. data.params = parts;
  12352. return data;
  12353. },
  12354. find_line: function (haystack, needle, sessionpart) {
  12355. var lines = haystack.split('\r\n');
  12356. for (var i = 0; i < lines.length; i++) {
  12357. if (lines[i].substring(0, needle.length) == needle) {
  12358. return lines[i];
  12359. }
  12360. }
  12361. if (!sessionpart) {
  12362. return false;
  12363. }
  12364. // search session part
  12365. lines = sessionpart.split('\r\n');
  12366. for (var j = 0; j < lines.length; j++) {
  12367. if (lines[j].substring(0, needle.length) == needle) {
  12368. return lines[j];
  12369. }
  12370. }
  12371. return false;
  12372. },
  12373. find_lines: function (haystack, needle, sessionpart) {
  12374. var lines = haystack.split('\r\n'),
  12375. needles = [];
  12376. for (var i = 0; i < lines.length; i++) {
  12377. if (lines[i].substring(0, needle.length) == needle)
  12378. needles.push(lines[i]);
  12379. }
  12380. if (needles.length || !sessionpart) {
  12381. return needles;
  12382. }
  12383. // search session part
  12384. lines = sessionpart.split('\r\n');
  12385. for (var j = 0; j < lines.length; j++) {
  12386. if (lines[j].substring(0, needle.length) == needle) {
  12387. needles.push(lines[j]);
  12388. }
  12389. }
  12390. return needles;
  12391. },
  12392. candidateToJingle: function (line) {
  12393. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  12394. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  12395. if (line.indexOf('candidate:') === 0) {
  12396. line = 'a=' + line;
  12397. } else if (line.substring(0, 12) != 'a=candidate:') {
  12398. console.log('parseCandidate called with a line that is not a candidate line');
  12399. console.log(line);
  12400. return null;
  12401. }
  12402. if (line.substring(line.length - 2) == '\r\n') // chomp it
  12403. line = line.substring(0, line.length - 2);
  12404. var candidate = {},
  12405. elems = line.split(' '),
  12406. i;
  12407. if (elems[6] != 'typ') {
  12408. console.log('did not find typ in the right place');
  12409. console.log(line);
  12410. return null;
  12411. }
  12412. candidate.foundation = elems[0].substring(12);
  12413. candidate.component = elems[1];
  12414. candidate.protocol = elems[2].toLowerCase();
  12415. candidate.priority = elems[3];
  12416. candidate.ip = elems[4];
  12417. candidate.port = elems[5];
  12418. // elems[6] => "typ"
  12419. candidate.type = elems[7];
  12420. candidate.generation = '0'; // default, may be overwritten below
  12421. for (i = 8; i < elems.length; i += 2) {
  12422. switch (elems[i]) {
  12423. case 'raddr':
  12424. candidate['rel-addr'] = elems[i + 1];
  12425. break;
  12426. case 'rport':
  12427. candidate['rel-port'] = elems[i + 1];
  12428. break;
  12429. case 'generation':
  12430. candidate.generation = elems[i + 1];
  12431. break;
  12432. case 'tcptype':
  12433. candidate.tcptype = elems[i + 1];
  12434. break;
  12435. default: // TODO
  12436. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12437. }
  12438. }
  12439. candidate.network = '1';
  12440. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12441. return candidate;
  12442. },
  12443. candidateFromJingle: function (cand) {
  12444. var line = 'a=candidate:';
  12445. line += cand.getAttribute('foundation');
  12446. line += ' ';
  12447. line += cand.getAttribute('component');
  12448. line += ' ';
  12449. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  12450. line += ' ';
  12451. line += cand.getAttribute('priority');
  12452. line += ' ';
  12453. line += cand.getAttribute('ip');
  12454. line += ' ';
  12455. line += cand.getAttribute('port');
  12456. line += ' ';
  12457. line += 'typ';
  12458. line += ' ' + cand.getAttribute('type');
  12459. line += ' ';
  12460. switch (cand.getAttribute('type')) {
  12461. case 'srflx':
  12462. case 'prflx':
  12463. case 'relay':
  12464. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  12465. line += 'raddr';
  12466. line += ' ';
  12467. line += cand.getAttribute('rel-addr');
  12468. line += ' ';
  12469. line += 'rport';
  12470. line += ' ';
  12471. line += cand.getAttribute('rel-port');
  12472. line += ' ';
  12473. }
  12474. break;
  12475. }
  12476. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  12477. line += 'tcptype';
  12478. line += ' ';
  12479. line += cand.getAttribute('tcptype');
  12480. line += ' ';
  12481. }
  12482. line += 'generation';
  12483. line += ' ';
  12484. line += cand.getAttribute('generation') || '0';
  12485. return line + '\r\n';
  12486. }
  12487. };
  12488. module.exports = SDPUtil;
  12489. },{}],51:[function(require,module,exports){
  12490. function TraceablePeerConnection(ice_config, constraints) {
  12491. var self = this;
  12492. var RTCPeerconnection = navigator.mozGetUserMedia ? mozRTCPeerConnection : webkitRTCPeerConnection;
  12493. this.peerconnection = new RTCPeerconnection(ice_config, constraints);
  12494. this.updateLog = [];
  12495. this.stats = {};
  12496. this.statsinterval = null;
  12497. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  12498. // override as desired
  12499. this.trace = function (what, info) {
  12500. //console.warn('WTRACE', what, info);
  12501. self.updateLog.push({
  12502. time: new Date(),
  12503. type: what,
  12504. value: info || ""
  12505. });
  12506. };
  12507. this.onicecandidate = null;
  12508. this.peerconnection.onicecandidate = function (event) {
  12509. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  12510. if (self.onicecandidate !== null) {
  12511. self.onicecandidate(event);
  12512. }
  12513. };
  12514. this.onaddstream = null;
  12515. this.peerconnection.onaddstream = function (event) {
  12516. self.trace('onaddstream', event.stream.id);
  12517. if (self.onaddstream !== null) {
  12518. self.onaddstream(event);
  12519. }
  12520. };
  12521. this.onremovestream = null;
  12522. this.peerconnection.onremovestream = function (event) {
  12523. self.trace('onremovestream', event.stream.id);
  12524. if (self.onremovestream !== null) {
  12525. self.onremovestream(event);
  12526. }
  12527. };
  12528. this.onsignalingstatechange = null;
  12529. this.peerconnection.onsignalingstatechange = function (event) {
  12530. self.trace('onsignalingstatechange', self.signalingState);
  12531. if (self.onsignalingstatechange !== null) {
  12532. self.onsignalingstatechange(event);
  12533. }
  12534. };
  12535. this.oniceconnectionstatechange = null;
  12536. this.peerconnection.oniceconnectionstatechange = function (event) {
  12537. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  12538. if (self.oniceconnectionstatechange !== null) {
  12539. self.oniceconnectionstatechange(event);
  12540. }
  12541. };
  12542. this.onnegotiationneeded = null;
  12543. this.peerconnection.onnegotiationneeded = function (event) {
  12544. self.trace('onnegotiationneeded');
  12545. if (self.onnegotiationneeded !== null) {
  12546. self.onnegotiationneeded(event);
  12547. }
  12548. };
  12549. self.ondatachannel = null;
  12550. this.peerconnection.ondatachannel = function (event) {
  12551. self.trace('ondatachannel', event);
  12552. if (self.ondatachannel !== null) {
  12553. self.ondatachannel(event);
  12554. }
  12555. };
  12556. if (!navigator.mozGetUserMedia && this.maxstats) {
  12557. this.statsinterval = window.setInterval(function() {
  12558. self.peerconnection.getStats(function(stats) {
  12559. var results = stats.result();
  12560. for (var i = 0; i < results.length; ++i) {
  12561. //console.log(results[i].type, results[i].id, results[i].names())
  12562. var now = new Date();
  12563. results[i].names().forEach(function (name) {
  12564. var id = results[i].id + '-' + name;
  12565. if (!self.stats[id]) {
  12566. self.stats[id] = {
  12567. startTime: now,
  12568. endTime: now,
  12569. values: [],
  12570. times: []
  12571. };
  12572. }
  12573. self.stats[id].values.push(results[i].stat(name));
  12574. self.stats[id].times.push(now.getTime());
  12575. if (self.stats[id].values.length > self.maxstats) {
  12576. self.stats[id].values.shift();
  12577. self.stats[id].times.shift();
  12578. }
  12579. self.stats[id].endTime = now;
  12580. });
  12581. }
  12582. });
  12583. }, 1000);
  12584. }
  12585. };
  12586. dumpSDP = function(description) {
  12587. return 'type: ' + description.type + '\r\n' + description.sdp;
  12588. }
  12589. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  12590. TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
  12591. TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
  12592. TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() {
  12593. var publicLocalDescription = APP.simulcast.reverseTransformLocalDescription(this.peerconnection.localDescription);
  12594. return publicLocalDescription;
  12595. });
  12596. TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() {
  12597. var publicRemoteDescription = APP.simulcast.reverseTransformRemoteDescription(this.peerconnection.remoteDescription);
  12598. return publicRemoteDescription;
  12599. });
  12600. }
  12601. TraceablePeerConnection.prototype.addStream = function (stream) {
  12602. this.trace('addStream', stream.id);
  12603. APP.simulcast.resetSender();
  12604. try
  12605. {
  12606. this.peerconnection.addStream(stream);
  12607. }
  12608. catch (e)
  12609. {
  12610. console.error(e);
  12611. return;
  12612. }
  12613. };
  12614. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  12615. this.trace('removeStream', stream.id);
  12616. APP.simulcast.resetSender();
  12617. if(stopStreams) {
  12618. stream.getAudioTracks().forEach(function (track) {
  12619. track.stop();
  12620. });
  12621. stream.getVideoTracks().forEach(function (track) {
  12622. track.stop();
  12623. });
  12624. }
  12625. this.peerconnection.removeStream(stream);
  12626. };
  12627. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  12628. this.trace('createDataChannel', label, opts);
  12629. return this.peerconnection.createDataChannel(label, opts);
  12630. };
  12631. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  12632. var self = this;
  12633. description = APP.simulcast.transformLocalDescription(description);
  12634. this.trace('setLocalDescription', dumpSDP(description));
  12635. this.peerconnection.setLocalDescription(description,
  12636. function () {
  12637. self.trace('setLocalDescriptionOnSuccess');
  12638. successCallback();
  12639. },
  12640. function (err) {
  12641. self.trace('setLocalDescriptionOnFailure', err);
  12642. failureCallback(err);
  12643. }
  12644. );
  12645. /*
  12646. if (this.statsinterval === null && this.maxstats > 0) {
  12647. // start gathering stats
  12648. }
  12649. */
  12650. };
  12651. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  12652. var self = this;
  12653. description = APP.simulcast.transformRemoteDescription(description);
  12654. this.trace('setRemoteDescription', dumpSDP(description));
  12655. this.peerconnection.setRemoteDescription(description,
  12656. function () {
  12657. self.trace('setRemoteDescriptionOnSuccess');
  12658. successCallback();
  12659. },
  12660. function (err) {
  12661. self.trace('setRemoteDescriptionOnFailure', err);
  12662. failureCallback(err);
  12663. }
  12664. );
  12665. /*
  12666. if (this.statsinterval === null && this.maxstats > 0) {
  12667. // start gathering stats
  12668. }
  12669. */
  12670. };
  12671. TraceablePeerConnection.prototype.close = function () {
  12672. this.trace('stop');
  12673. if (this.statsinterval !== null) {
  12674. window.clearInterval(this.statsinterval);
  12675. this.statsinterval = null;
  12676. }
  12677. this.peerconnection.close();
  12678. };
  12679. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  12680. var self = this;
  12681. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  12682. this.peerconnection.createOffer(
  12683. function (offer) {
  12684. self.trace('createOfferOnSuccess', dumpSDP(offer));
  12685. successCallback(offer);
  12686. },
  12687. function(err) {
  12688. self.trace('createOfferOnFailure', err);
  12689. failureCallback(err);
  12690. },
  12691. constraints
  12692. );
  12693. };
  12694. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  12695. var self = this;
  12696. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  12697. this.peerconnection.createAnswer(
  12698. function (answer) {
  12699. answer = APP.simulcast.transformAnswer(answer);
  12700. self.trace('createAnswerOnSuccess', dumpSDP(answer));
  12701. successCallback(answer);
  12702. },
  12703. function(err) {
  12704. self.trace('createAnswerOnFailure', err);
  12705. failureCallback(err);
  12706. },
  12707. constraints
  12708. );
  12709. };
  12710. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  12711. var self = this;
  12712. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  12713. this.peerconnection.addIceCandidate(candidate);
  12714. /* maybe later
  12715. this.peerconnection.addIceCandidate(candidate,
  12716. function () {
  12717. self.trace('addIceCandidateOnSuccess');
  12718. successCallback();
  12719. },
  12720. function (err) {
  12721. self.trace('addIceCandidateOnFailure', err);
  12722. failureCallback(err);
  12723. }
  12724. );
  12725. */
  12726. };
  12727. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  12728. if (navigator.mozGetUserMedia) {
  12729. // ignore for now...
  12730. if(!errback)
  12731. errback = function () {
  12732. }
  12733. this.peerconnection.getStats(null,callback,errback);
  12734. } else {
  12735. this.peerconnection.getStats(callback);
  12736. }
  12737. };
  12738. module.exports = TraceablePeerConnection;
  12739. },{}],52:[function(require,module,exports){
  12740. /* global $, $iq, APP, config, connection, UI, messageHandler,
  12741. roomName, sessionTerminated, Strophe, Util */
  12742. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  12743. var Settings = require("../settings/Settings");
  12744. var AuthenticationEvents
  12745. = require("../../service/authentication/AuthenticationEvents");
  12746. /**
  12747. * Contains logic responsible for enabling/disabling functionality available
  12748. * only to moderator users.
  12749. */
  12750. var connection = null;
  12751. var focusUserJid;
  12752. function createExpBackoffTimer(step) {
  12753. var count = 1;
  12754. return function (reset) {
  12755. // Reset call
  12756. if (reset) {
  12757. count = 1;
  12758. return;
  12759. }
  12760. // Calculate next timeout
  12761. var timeout = Math.pow(2, count - 1);
  12762. count += 1;
  12763. return timeout * step;
  12764. };
  12765. }
  12766. var getNextTimeout = createExpBackoffTimer(1000);
  12767. var getNextErrorTimeout = createExpBackoffTimer(1000);
  12768. // External authentication stuff
  12769. var externalAuthEnabled = false;
  12770. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  12771. // it will be enabled automatically if focus detects the component through
  12772. // service discovery.
  12773. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  12774. var eventEmitter = null;
  12775. var Moderator = {
  12776. isModerator: function () {
  12777. return connection && connection.emuc.isModerator();
  12778. },
  12779. isPeerModerator: function (peerJid) {
  12780. return connection &&
  12781. connection.emuc.getMemberRole(peerJid) === 'moderator';
  12782. },
  12783. isExternalAuthEnabled: function () {
  12784. return externalAuthEnabled;
  12785. },
  12786. isSipGatewayEnabled: function () {
  12787. return sipGatewayEnabled;
  12788. },
  12789. setConnection: function (con) {
  12790. connection = con;
  12791. },
  12792. init: function (xmpp, emitter) {
  12793. this.xmppService = xmpp;
  12794. eventEmitter = emitter;
  12795. // Message listener that talks to POPUP window
  12796. function listener(event) {
  12797. if (event.data && event.data.sessionId) {
  12798. if (event.origin !== window.location.origin) {
  12799. console.warn(
  12800. "Ignoring sessionId from different origin: " + event.origin);
  12801. return;
  12802. }
  12803. localStorage.setItem('sessionId', event.data.sessionId);
  12804. // After popup is closed we will authenticate
  12805. }
  12806. }
  12807. // Register
  12808. if (window.addEventListener) {
  12809. window.addEventListener("message", listener, false);
  12810. } else {
  12811. window.attachEvent("onmessage", listener);
  12812. }
  12813. },
  12814. onMucLeft: function (jid) {
  12815. console.info("Someone left is it focus ? " + jid);
  12816. var resource = Strophe.getResourceFromJid(jid);
  12817. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  12818. console.info(
  12819. "Focus has left the room - leaving conference");
  12820. //hangUp();
  12821. // We'd rather reload to have everything re-initialized
  12822. // FIXME: show some message before reload
  12823. location.reload();
  12824. }
  12825. },
  12826. setFocusUserJid: function (focusJid) {
  12827. if (!focusUserJid) {
  12828. focusUserJid = focusJid;
  12829. console.info("Focus jid set to: " + focusUserJid);
  12830. }
  12831. },
  12832. getFocusUserJid: function () {
  12833. return focusUserJid;
  12834. },
  12835. getFocusComponent: function () {
  12836. // Get focus component address
  12837. var focusComponent = config.hosts.focus;
  12838. // If not specified use default: 'focus.domain'
  12839. if (!focusComponent) {
  12840. focusComponent = 'focus.' + config.hosts.domain;
  12841. }
  12842. return focusComponent;
  12843. },
  12844. createConferenceIq: function (roomName) {
  12845. // Generate create conference IQ
  12846. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  12847. // Session Id used for authentication
  12848. var sessionId = localStorage.getItem('sessionId');
  12849. var machineUID = Settings.getSettings().uid;
  12850. console.info(
  12851. "Session ID: " + sessionId + " machine UID: " + machineUID);
  12852. elem.c('conference', {
  12853. xmlns: 'http://jitsi.org/protocol/focus',
  12854. room: roomName,
  12855. 'machine-uid': machineUID
  12856. });
  12857. if (sessionId) {
  12858. elem.attrs({ 'session-id': sessionId});
  12859. }
  12860. if (config.hosts.bridge !== undefined) {
  12861. elem.c(
  12862. 'property',
  12863. { name: 'bridge', value: config.hosts.bridge})
  12864. .up();
  12865. }
  12866. // Tell the focus we have Jigasi configured
  12867. if (config.hosts.call_control !== undefined) {
  12868. elem.c(
  12869. 'property',
  12870. { name: 'call_control', value: config.hosts.call_control})
  12871. .up();
  12872. }
  12873. if (config.channelLastN !== undefined) {
  12874. elem.c(
  12875. 'property',
  12876. { name: 'channelLastN', value: config.channelLastN})
  12877. .up();
  12878. }
  12879. if (config.adaptiveLastN !== undefined) {
  12880. elem.c(
  12881. 'property',
  12882. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  12883. .up();
  12884. }
  12885. if (config.adaptiveSimulcast !== undefined) {
  12886. elem.c(
  12887. 'property',
  12888. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  12889. .up();
  12890. }
  12891. if (config.openSctp !== undefined) {
  12892. elem.c(
  12893. 'property',
  12894. { name: 'openSctp', value: config.openSctp})
  12895. .up();
  12896. }
  12897. if (config.enableFirefoxSupport !== undefined) {
  12898. elem.c(
  12899. 'property',
  12900. { name: 'enableFirefoxHacks',
  12901. value: config.enableFirefoxSupport})
  12902. .up();
  12903. }
  12904. elem.up();
  12905. return elem;
  12906. },
  12907. parseConfigOptions: function (resultIq) {
  12908. Moderator.setFocusUserJid(
  12909. $(resultIq).find('conference').attr('focusjid'));
  12910. var authenticationEnabled
  12911. = $(resultIq).find(
  12912. '>conference>property' +
  12913. '[name=\'authentication\'][value=\'true\']').length > 0;
  12914. console.info("Authentication enabled: " + authenticationEnabled);
  12915. externalAuthEnabled
  12916. = $(resultIq).find(
  12917. '>conference>property' +
  12918. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  12919. console.info('External authentication enabled: ' + externalAuthEnabled);
  12920. if (!externalAuthEnabled) {
  12921. // We expect to receive sessionId in 'internal' authentication mode
  12922. var sessionId
  12923. = $(resultIq).find('conference').attr('session-id');
  12924. if (sessionId) {
  12925. console.info('Received sessionId: ' + sessionId);
  12926. localStorage.setItem('sessionId', sessionId);
  12927. }
  12928. }
  12929. var authIdentity = $(resultIq).find('>conference').attr('identity');
  12930. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  12931. authenticationEnabled, authIdentity);
  12932. // Check if focus has auto-detected Jigasi component(this will be also
  12933. // included if we have passed our host from the config)
  12934. if ($(resultIq).find(
  12935. '>conference>property' +
  12936. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  12937. sipGatewayEnabled = true;
  12938. }
  12939. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  12940. },
  12941. // FIXME: we need to show the fact that we're waiting for the focus
  12942. // to the user(or that focus is not available)
  12943. allocateConferenceFocus: function (roomName, callback) {
  12944. // Try to use focus user JID from the config
  12945. Moderator.setFocusUserJid(config.focusUserJid);
  12946. // Send create conference IQ
  12947. var iq = Moderator.createConferenceIq(roomName);
  12948. var self = this;
  12949. connection.sendIQ(
  12950. iq,
  12951. function (result) {
  12952. // Setup config options
  12953. Moderator.parseConfigOptions(result);
  12954. if ('true' === $(result).find('conference').attr('ready')) {
  12955. // Reset both timers
  12956. getNextTimeout(true);
  12957. getNextErrorTimeout(true);
  12958. // Exec callback
  12959. callback();
  12960. } else {
  12961. var waitMs = getNextTimeout();
  12962. console.info("Waiting for the focus... " + waitMs);
  12963. // Reset error timeout
  12964. getNextErrorTimeout(true);
  12965. window.setTimeout(
  12966. function () {
  12967. Moderator.allocateConferenceFocus(
  12968. roomName, callback);
  12969. }, waitMs);
  12970. }
  12971. },
  12972. function (error) {
  12973. // Invalid session ? remove and try again
  12974. // without session ID to get a new one
  12975. var invalidSession
  12976. = $(error).find('>error>session-invalid').length;
  12977. if (invalidSession) {
  12978. console.info("Session expired! - removing");
  12979. localStorage.removeItem("sessionId");
  12980. }
  12981. if ($(error).find('>error>graceful-shutdown').length) {
  12982. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  12983. return;
  12984. }
  12985. // Check for error returned by the reservation system
  12986. var reservationErr = $(error).find('>error>reservation-error');
  12987. if (reservationErr.length) {
  12988. // Trigger error event
  12989. var errorCode = reservationErr.attr('error-code');
  12990. var errorMsg;
  12991. if ($(error).find('>error>text')) {
  12992. errorMsg = $(error).find('>error>text').text();
  12993. }
  12994. eventEmitter.emit(
  12995. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  12996. return;
  12997. }
  12998. // Not authorized to create new room
  12999. if ($(error).find('>error>not-authorized').length) {
  13000. console.warn("Unauthorized to start the conference", error);
  13001. var toDomain
  13002. = Strophe.getDomainFromJid(error.getAttribute('to'));
  13003. if (toDomain === config.hosts.anonymousdomain) {
  13004. // we are connected with anonymous domain and
  13005. // only non anonymous users can create rooms
  13006. // we must authorize the user
  13007. self.xmppService.promptLogin();
  13008. } else {
  13009. // External authentication mode
  13010. eventEmitter.emit(
  13011. XMPPEvents.AUTHENTICATION_REQUIRED,
  13012. function () {
  13013. Moderator.allocateConferenceFocus(
  13014. roomName, callback);
  13015. });
  13016. }
  13017. return;
  13018. }
  13019. var waitMs = getNextErrorTimeout();
  13020. console.error("Focus error, retry after " + waitMs, error);
  13021. // Show message
  13022. var focusComponent = Moderator.getFocusComponent();
  13023. var retrySec = waitMs / 1000;
  13024. // FIXME: message is duplicated ?
  13025. // Do not show in case of session invalid
  13026. // which means just a retry
  13027. if (!invalidSession) {
  13028. APP.UI.messageHandler.notify(
  13029. null, "notify.focus",
  13030. 'disconnected', "notify.focusFail",
  13031. {component: focusComponent, ms: retrySec});
  13032. }
  13033. // Reset response timeout
  13034. getNextTimeout(true);
  13035. window.setTimeout(
  13036. function () {
  13037. Moderator.allocateConferenceFocus(roomName, callback);
  13038. }, waitMs);
  13039. }
  13040. );
  13041. },
  13042. getLoginUrl: function (roomName, urlCallback) {
  13043. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13044. iq.c('login-url', {
  13045. xmlns: 'http://jitsi.org/protocol/focus',
  13046. room: roomName,
  13047. 'machine-uid': Settings.getSettings().uid
  13048. });
  13049. connection.sendIQ(
  13050. iq,
  13051. function (result) {
  13052. var url = $(result).find('login-url').attr('url');
  13053. url = url = decodeURIComponent(url);
  13054. if (url) {
  13055. console.info("Got auth url: " + url);
  13056. urlCallback(url);
  13057. } else {
  13058. console.error(
  13059. "Failed to get auth url from the focus", result);
  13060. }
  13061. },
  13062. function (error) {
  13063. console.error("Get auth url error", error);
  13064. }
  13065. );
  13066. },
  13067. getPopupLoginUrl: function (roomName, urlCallback) {
  13068. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13069. iq.c('login-url', {
  13070. xmlns: 'http://jitsi.org/protocol/focus',
  13071. room: roomName,
  13072. 'machine-uid': Settings.getSettings().uid,
  13073. popup: true
  13074. });
  13075. connection.sendIQ(
  13076. iq,
  13077. function (result) {
  13078. var url = $(result).find('login-url').attr('url');
  13079. url = url = decodeURIComponent(url);
  13080. if (url) {
  13081. console.info("Got POPUP auth url: " + url);
  13082. urlCallback(url);
  13083. } else {
  13084. console.error(
  13085. "Failed to get POPUP auth url from the focus", result);
  13086. }
  13087. },
  13088. function (error) {
  13089. console.error('Get POPUP auth url error', error);
  13090. }
  13091. );
  13092. },
  13093. logout: function (callback) {
  13094. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  13095. var sessionId = localStorage.getItem('sessionId');
  13096. if (!sessionId) {
  13097. callback();
  13098. return;
  13099. }
  13100. iq.c('logout', {
  13101. xmlns: 'http://jitsi.org/protocol/focus',
  13102. 'session-id': sessionId
  13103. });
  13104. connection.sendIQ(
  13105. iq,
  13106. function (result) {
  13107. var logoutUrl = $(result).find('logout').attr('logout-url');
  13108. if (logoutUrl) {
  13109. logoutUrl = decodeURIComponent(logoutUrl);
  13110. }
  13111. console.info("Log out OK, url: " + logoutUrl, result);
  13112. localStorage.removeItem('sessionId');
  13113. callback(logoutUrl);
  13114. },
  13115. function (error) {
  13116. console.error("Logout error", error);
  13117. }
  13118. );
  13119. }
  13120. };
  13121. module.exports = Moderator;
  13122. },{"../../service/authentication/AuthenticationEvents":84,"../../service/xmpp/XMPPEvents":88,"../settings/Settings":37}],53:[function(require,module,exports){
  13123. /* global $, $iq, config, connection, focusMucJid, messageHandler, Moderator,
  13124. Toolbar, Util */
  13125. var Moderator = require("./moderator");
  13126. var recordingToken = null;
  13127. var recordingEnabled;
  13128. /**
  13129. * Whether to use a jirecon component for recording, or use the videobridge
  13130. * through COLIBRI.
  13131. */
  13132. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  13133. /**
  13134. * The ID of the jirecon recording session. Jirecon generates it when we
  13135. * initially start recording, and it needs to be used in subsequent requests
  13136. * to jirecon.
  13137. */
  13138. var jireconRid = null;
  13139. function setRecordingToken(token) {
  13140. recordingToken = token;
  13141. }
  13142. function setRecording(state, token, callback, connection) {
  13143. if (useJirecon){
  13144. setRecordingJirecon(state, token, callback, connection);
  13145. } else {
  13146. setRecordingColibri(state, token, callback, connection);
  13147. }
  13148. }
  13149. function setRecordingJirecon(state, token, callback, connection) {
  13150. if (state == recordingEnabled){
  13151. return;
  13152. }
  13153. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  13154. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  13155. action: state ? 'start' : 'stop',
  13156. mucjid: connection.emuc.roomjid});
  13157. if (!state){
  13158. iq.attrs({rid: jireconRid});
  13159. }
  13160. console.log('Start recording');
  13161. connection.sendIQ(
  13162. iq,
  13163. function (result) {
  13164. // TODO wait for an IQ with the real status, since this is
  13165. // provisional?
  13166. jireconRid = $(result).find('recording').attr('rid');
  13167. console.log('Recording ' + (state ? 'started' : 'stopped') +
  13168. '(jirecon)' + result);
  13169. recordingEnabled = state;
  13170. if (!state){
  13171. jireconRid = null;
  13172. }
  13173. callback(state);
  13174. },
  13175. function (error) {
  13176. console.log('Failed to start recording, error: ', error);
  13177. callback(recordingEnabled);
  13178. });
  13179. }
  13180. // Sends a COLIBRI message which enables or disables (according to 'state')
  13181. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  13182. // with the new recording state, according to the IQ.
  13183. function setRecordingColibri(state, token, callback, connection) {
  13184. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  13185. elem.c('conference', {
  13186. xmlns: 'http://jitsi.org/protocol/colibri'
  13187. });
  13188. elem.c('recording', {state: state, token: token});
  13189. connection.sendIQ(elem,
  13190. function (result) {
  13191. console.log('Set recording "', state, '". Result:', result);
  13192. var recordingElem = $(result).find('>conference>recording');
  13193. var newState = ('true' === recordingElem.attr('state'));
  13194. recordingEnabled = newState;
  13195. callback(newState);
  13196. },
  13197. function (error) {
  13198. console.warn(error);
  13199. callback(recordingEnabled);
  13200. }
  13201. );
  13202. }
  13203. var Recording = {
  13204. toggleRecording: function (tokenEmptyCallback,
  13205. startingCallback, startedCallback, connection) {
  13206. if (!Moderator.isModerator()) {
  13207. console.log(
  13208. 'non-focus, or conference not yet organized:' +
  13209. ' not enabling recording');
  13210. return;
  13211. }
  13212. var self = this;
  13213. // Jirecon does not (currently) support a token.
  13214. if (!recordingToken && !useJirecon) {
  13215. tokenEmptyCallback(function (value) {
  13216. setRecordingToken(value);
  13217. self.toggleRecording(tokenEmptyCallback,
  13218. startingCallback, startedCallback, connection);
  13219. });
  13220. return;
  13221. }
  13222. var oldState = recordingEnabled;
  13223. startingCallback(!oldState);
  13224. setRecording(!oldState,
  13225. recordingToken,
  13226. function (state) {
  13227. console.log("New recording state: ", state);
  13228. if (state === oldState) {
  13229. // FIXME: new focus:
  13230. // this will not work when moderator changes
  13231. // during active session. Then it will assume that
  13232. // recording status has changed to true, but it might have
  13233. // been already true(and we only received actual status from
  13234. // the focus).
  13235. //
  13236. // SO we start with status null, so that it is initialized
  13237. // here and will fail only after second click, so if invalid
  13238. // token was used we have to press the button twice before
  13239. // current status will be fetched and token will be reset.
  13240. //
  13241. // Reliable way would be to return authentication error.
  13242. // Or status update when moderator connects.
  13243. // Or we have to stop recording session when current
  13244. // moderator leaves the room.
  13245. // Failed to change, reset the token because it might
  13246. // have been wrong
  13247. setRecordingToken(null);
  13248. }
  13249. startedCallback(state);
  13250. },
  13251. connection
  13252. );
  13253. }
  13254. }
  13255. module.exports = Recording;
  13256. },{"./moderator":52}],54:[function(require,module,exports){
  13257. /* jshint -W117 */
  13258. /* a simple MUC connection plugin
  13259. * can only handle a single MUC room
  13260. */
  13261. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13262. var Moderator = require("./moderator");
  13263. var JingleSession = require("./JingleSession");
  13264. var bridgeIsDown = false;
  13265. module.exports = function(XMPP, eventEmitter) {
  13266. Strophe.addConnectionPlugin('emuc', {
  13267. connection: null,
  13268. roomjid: null,
  13269. myroomjid: null,
  13270. members: {},
  13271. list_members: [], // so we can elect a new focus
  13272. presMap: {},
  13273. preziMap: {},
  13274. joined: false,
  13275. isOwner: false,
  13276. role: null,
  13277. focusMucJid: null,
  13278. ssrc2jid: {},
  13279. init: function (conn) {
  13280. this.connection = conn;
  13281. },
  13282. initPresenceMap: function (myroomjid) {
  13283. this.presMap['to'] = myroomjid;
  13284. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  13285. },
  13286. doJoin: function (jid, password) {
  13287. this.myroomjid = jid;
  13288. console.info("Joined MUC as " + this.myroomjid);
  13289. this.initPresenceMap(this.myroomjid);
  13290. if (!this.roomjid) {
  13291. this.roomjid = Strophe.getBareJidFromJid(jid);
  13292. // add handlers (just once)
  13293. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  13294. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  13295. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  13296. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  13297. }
  13298. if (password !== undefined) {
  13299. this.presMap['password'] = password;
  13300. }
  13301. this.sendPresence();
  13302. },
  13303. doLeave: function () {
  13304. console.log("do leave", this.myroomjid);
  13305. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  13306. this.presMap.length = 0;
  13307. this.connection.send(pres);
  13308. },
  13309. createNonAnonymousRoom: function () {
  13310. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  13311. var getForm = $iq({type: 'get', to: this.roomjid})
  13312. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  13313. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13314. var self = this;
  13315. this.connection.sendIQ(getForm, function (form) {
  13316. if (!$(form).find(
  13317. '>query>x[xmlns="jabber:x:data"]' +
  13318. '>field[var="muc#roomconfig_whois"]').length) {
  13319. console.error('non-anonymous rooms not supported');
  13320. return;
  13321. }
  13322. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  13323. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  13324. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13325. formSubmit.c('field', {'var': 'FORM_TYPE'})
  13326. .c('value')
  13327. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  13328. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  13329. .c('value').t('anyone').up().up();
  13330. self.connection.sendIQ(formSubmit);
  13331. }, function (error) {
  13332. console.error("Error getting room configuration form");
  13333. });
  13334. },
  13335. onPresence: function (pres) {
  13336. var from = pres.getAttribute('from');
  13337. // What is this for? A workaround for something?
  13338. if (pres.getAttribute('type')) {
  13339. return true;
  13340. }
  13341. // Parse etherpad tag.
  13342. var etherpad = $(pres).find('>etherpad');
  13343. if (etherpad.length) {
  13344. if (config.etherpad_base && !Moderator.isModerator()) {
  13345. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  13346. }
  13347. }
  13348. // Parse prezi tag.
  13349. var presentation = $(pres).find('>prezi');
  13350. if (presentation.length) {
  13351. var url = presentation.attr('url');
  13352. var current = presentation.find('>current').text();
  13353. console.log('presentation info received from', from, url);
  13354. if (this.preziMap[from] == null) {
  13355. this.preziMap[from] = url;
  13356. $(document).trigger('presentationadded.muc', [from, url, current]);
  13357. }
  13358. else {
  13359. $(document).trigger('gotoslide.muc', [from, url, current]);
  13360. }
  13361. }
  13362. else if (this.preziMap[from] != null) {
  13363. var url = this.preziMap[from];
  13364. delete this.preziMap[from];
  13365. $(document).trigger('presentationremoved.muc', [from, url]);
  13366. }
  13367. // Parse audio info tag.
  13368. var audioMuted = $(pres).find('>audiomuted');
  13369. if (audioMuted.length) {
  13370. $(document).trigger('audiomuted.muc', [from, audioMuted.text()]);
  13371. }
  13372. // Parse video info tag.
  13373. var videoMuted = $(pres).find('>videomuted');
  13374. if (videoMuted.length) {
  13375. $(document).trigger('videomuted.muc', [from, videoMuted.text()]);
  13376. }
  13377. var stats = $(pres).find('>stats');
  13378. if (stats.length) {
  13379. var statsObj = {};
  13380. Strophe.forEachChild(stats[0], "stat", function (el) {
  13381. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  13382. });
  13383. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  13384. }
  13385. // Parse status.
  13386. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  13387. this.isOwner = true;
  13388. this.createNonAnonymousRoom();
  13389. }
  13390. // Parse roles.
  13391. var member = {};
  13392. member.show = $(pres).find('>show').text();
  13393. member.status = $(pres).find('>status').text();
  13394. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  13395. member.affiliation = tmp.attr('affiliation');
  13396. member.role = tmp.attr('role');
  13397. // Focus recognition
  13398. member.jid = tmp.attr('jid');
  13399. member.isFocus = false;
  13400. if (member.jid
  13401. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  13402. member.isFocus = true;
  13403. }
  13404. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  13405. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  13406. if (from == this.myroomjid) {
  13407. if (member.affiliation == 'owner') this.isOwner = true;
  13408. if (this.role !== member.role) {
  13409. this.role = member.role;
  13410. eventEmitter.emit(XMPPEvents.LOCALROLE_CHANGED,
  13411. from, member, pres, Moderator.isModerator());
  13412. }
  13413. if (!this.joined) {
  13414. this.joined = true;
  13415. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  13416. this.list_members.push(from);
  13417. }
  13418. } else if (this.members[from] === undefined) {
  13419. // new participant
  13420. this.members[from] = member;
  13421. this.list_members.push(from);
  13422. console.log('entered', from, member);
  13423. if (member.isFocus) {
  13424. this.focusMucJid = from;
  13425. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  13426. }
  13427. else {
  13428. var id = $(pres).find('>userID').text();
  13429. var email = $(pres).find('>email');
  13430. if (email.length > 0) {
  13431. id = email.text();
  13432. }
  13433. eventEmitter.emit(XMPPEvents.MUC_ENTER, from, id, member.displayName);
  13434. }
  13435. } else {
  13436. // Presence update for existing participant
  13437. // Watch role change:
  13438. if (this.members[from].role != member.role) {
  13439. this.members[from].role = member.role;
  13440. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  13441. member.role, member.displayName);
  13442. }
  13443. }
  13444. // Always trigger presence to update bindings
  13445. this.parsePresence(from, member, pres);
  13446. // Trigger status message update
  13447. if (member.status) {
  13448. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  13449. }
  13450. return true;
  13451. },
  13452. onPresenceUnavailable: function (pres) {
  13453. var from = pres.getAttribute('from');
  13454. // room destroyed ?
  13455. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  13456. '>destroy').length) {
  13457. var reason;
  13458. var reasonSelect = $(pres).find(
  13459. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  13460. '>destroy>reason');
  13461. if (reasonSelect.length) {
  13462. reason = reasonSelect.text();
  13463. }
  13464. XMPP.disposeConference(false);
  13465. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  13466. return true;
  13467. }
  13468. // Status code 110 indicates that this notification is "self-presence".
  13469. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  13470. delete this.members[from];
  13471. this.list_members.splice(this.list_members.indexOf(from), 1);
  13472. this.onParticipantLeft(from);
  13473. }
  13474. // If the status code is 110 this means we're leaving and we would like
  13475. // to remove everyone else from our view, so we trigger the event.
  13476. else if (this.list_members.length > 1) {
  13477. for (var i = 0; i < this.list_members.length; i++) {
  13478. var member = this.list_members[i];
  13479. delete this.members[i];
  13480. this.list_members.splice(i, 1);
  13481. this.onParticipantLeft(member);
  13482. }
  13483. }
  13484. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  13485. $(document).trigger('kicked.muc', [from]);
  13486. if (this.myroomjid === from) {
  13487. XMPP.disposeConference(false);
  13488. eventEmitter.emit(XMPPEvents.KICKED);
  13489. }
  13490. }
  13491. return true;
  13492. },
  13493. onPresenceError: function (pres) {
  13494. var from = pres.getAttribute('from');
  13495. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13496. console.log('on password required', from);
  13497. var self = this;
  13498. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  13499. self.doJoin(from, value);
  13500. });
  13501. } else if ($(pres).find(
  13502. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13503. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  13504. if (toDomain === config.hosts.anonymousdomain) {
  13505. // enter the room by replying with 'not-authorized'. This would
  13506. // result in reconnection from authorized domain.
  13507. // We're either missing Jicofo/Prosody config for anonymous
  13508. // domains or something is wrong.
  13509. // XMPP.promptLogin();
  13510. APP.UI.messageHandler.openReportDialog(null,
  13511. "dialog.joinError", pres);
  13512. } else {
  13513. console.warn('onPresError ', pres);
  13514. APP.UI.messageHandler.openReportDialog(null,
  13515. "dialog.connectError",
  13516. pres);
  13517. }
  13518. } else {
  13519. console.warn('onPresError ', pres);
  13520. APP.UI.messageHandler.openReportDialog(null,
  13521. "dialog.connectError",
  13522. pres);
  13523. }
  13524. return true;
  13525. },
  13526. sendMessage: function (body, nickname) {
  13527. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  13528. msg.c('body', body).up();
  13529. if (nickname) {
  13530. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  13531. }
  13532. this.connection.send(msg);
  13533. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  13534. },
  13535. setSubject: function (subject) {
  13536. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  13537. msg.c('subject', subject);
  13538. this.connection.send(msg);
  13539. console.log("topic changed to " + subject);
  13540. },
  13541. onMessage: function (msg) {
  13542. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  13543. var from = msg.getAttribute('from');
  13544. var nick =
  13545. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  13546. .text() ||
  13547. Strophe.getResourceFromJid(from);
  13548. var txt = $(msg).find('>body').text();
  13549. var type = msg.getAttribute("type");
  13550. if (type == "error") {
  13551. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  13552. $(msg).find('>text').text(), txt);
  13553. return true;
  13554. }
  13555. var subject = $(msg).find('>subject');
  13556. if (subject.length) {
  13557. var subjectText = subject.text();
  13558. if (subjectText || subjectText == "") {
  13559. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  13560. console.log("Subject is changed to " + subjectText);
  13561. }
  13562. }
  13563. if (txt) {
  13564. console.log('chat', nick, txt);
  13565. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  13566. from, nick, txt, this.myroomjid);
  13567. }
  13568. return true;
  13569. },
  13570. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  13571. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  13572. var ob = this;
  13573. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  13574. function (res) {
  13575. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  13576. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  13577. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13578. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  13579. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  13580. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  13581. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  13582. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  13583. ob.connection.sendIQ(formsubmit,
  13584. onSuccess,
  13585. onError);
  13586. } else {
  13587. onNotSupported();
  13588. }
  13589. }, onError);
  13590. },
  13591. kick: function (jid) {
  13592. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  13593. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  13594. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  13595. .c('reason').t('You have been kicked.').up().up().up();
  13596. this.connection.sendIQ(
  13597. kickIQ,
  13598. function (result) {
  13599. console.log('Kick participant with jid: ', jid, result);
  13600. },
  13601. function (error) {
  13602. console.log('Kick participant error: ', error);
  13603. });
  13604. },
  13605. sendPresence: function () {
  13606. var pres = $pres({to: this.presMap['to'] });
  13607. pres.c('x', {xmlns: this.presMap['xns']});
  13608. if (this.presMap['password']) {
  13609. pres.c('password').t(this.presMap['password']).up();
  13610. }
  13611. pres.up();
  13612. // Send XEP-0115 'c' stanza that contains our capabilities info
  13613. if (this.connection.caps) {
  13614. this.connection.caps.node = config.clientNode;
  13615. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  13616. }
  13617. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  13618. .t(navigator.userAgent).up();
  13619. if (this.presMap['bridgeIsDown']) {
  13620. pres.c('bridgeIsDown').up();
  13621. }
  13622. if (this.presMap['email']) {
  13623. pres.c('email').t(this.presMap['email']).up();
  13624. }
  13625. if (this.presMap['userId']) {
  13626. pres.c('userId').t(this.presMap['userId']).up();
  13627. }
  13628. if (this.presMap['displayName']) {
  13629. // XEP-0172
  13630. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  13631. .t(this.presMap['displayName']).up();
  13632. }
  13633. if (this.presMap['audions']) {
  13634. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  13635. .t(this.presMap['audiomuted']).up();
  13636. }
  13637. if (this.presMap['videons']) {
  13638. pres.c('videomuted', {xmlns: this.presMap['videons']})
  13639. .t(this.presMap['videomuted']).up();
  13640. }
  13641. if (this.presMap['statsns']) {
  13642. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  13643. for (var stat in this.presMap["stats"])
  13644. if (this.presMap["stats"][stat] != null)
  13645. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  13646. pres.up();
  13647. }
  13648. if (this.presMap['prezins']) {
  13649. pres.c('prezi',
  13650. {xmlns: this.presMap['prezins'],
  13651. 'url': this.presMap['preziurl']})
  13652. .c('current').t(this.presMap['prezicurrent']).up().up();
  13653. }
  13654. if (this.presMap['etherpadns']) {
  13655. pres.c('etherpad', {xmlns: this.presMap['etherpadns']})
  13656. .t(this.presMap['etherpadname']).up();
  13657. }
  13658. if (this.presMap['medians']) {
  13659. pres.c('media', {xmlns: this.presMap['medians']});
  13660. var sourceNumber = 0;
  13661. Object.keys(this.presMap).forEach(function (key) {
  13662. if (key.indexOf('source') >= 0) {
  13663. sourceNumber++;
  13664. }
  13665. });
  13666. if (sourceNumber > 0)
  13667. for (var i = 1; i <= sourceNumber / 3; i++) {
  13668. pres.c('source',
  13669. {type: this.presMap['source' + i + '_type'],
  13670. ssrc: this.presMap['source' + i + '_ssrc'],
  13671. direction: this.presMap['source' + i + '_direction']
  13672. || 'sendrecv' }
  13673. ).up();
  13674. }
  13675. }
  13676. pres.up();
  13677. this.connection.send(pres);
  13678. },
  13679. addDisplayNameToPresence: function (displayName) {
  13680. this.presMap['displayName'] = displayName;
  13681. },
  13682. addMediaToPresence: function (sourceNumber, mtype, ssrcs, direction) {
  13683. if (!this.presMap['medians'])
  13684. this.presMap['medians'] = 'http://estos.de/ns/mjs';
  13685. this.presMap['source' + sourceNumber + '_type'] = mtype;
  13686. this.presMap['source' + sourceNumber + '_ssrc'] = ssrcs;
  13687. this.presMap['source' + sourceNumber + '_direction'] = direction;
  13688. },
  13689. clearPresenceMedia: function () {
  13690. var self = this;
  13691. Object.keys(this.presMap).forEach(function (key) {
  13692. if (key.indexOf('source') != -1) {
  13693. delete self.presMap[key];
  13694. }
  13695. });
  13696. },
  13697. addPreziToPresence: function (url, currentSlide) {
  13698. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  13699. this.presMap['preziurl'] = url;
  13700. this.presMap['prezicurrent'] = currentSlide;
  13701. },
  13702. removePreziFromPresence: function () {
  13703. delete this.presMap['prezins'];
  13704. delete this.presMap['preziurl'];
  13705. delete this.presMap['prezicurrent'];
  13706. },
  13707. addCurrentSlideToPresence: function (currentSlide) {
  13708. this.presMap['prezicurrent'] = currentSlide;
  13709. },
  13710. getPrezi: function (roomjid) {
  13711. return this.preziMap[roomjid];
  13712. },
  13713. addEtherpadToPresence: function (etherpadName) {
  13714. this.presMap['etherpadns'] = 'http://jitsi.org/jitmeet/etherpad';
  13715. this.presMap['etherpadname'] = etherpadName;
  13716. },
  13717. addAudioInfoToPresence: function (isMuted) {
  13718. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  13719. this.presMap['audiomuted'] = isMuted.toString();
  13720. },
  13721. addVideoInfoToPresence: function (isMuted) {
  13722. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  13723. this.presMap['videomuted'] = isMuted.toString();
  13724. },
  13725. addConnectionInfoToPresence: function (stats) {
  13726. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  13727. this.presMap['stats'] = stats;
  13728. },
  13729. findJidFromResource: function (resourceJid) {
  13730. if (resourceJid &&
  13731. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  13732. return this.myroomjid;
  13733. }
  13734. var peerJid = null;
  13735. Object.keys(this.members).some(function (jid) {
  13736. peerJid = jid;
  13737. return Strophe.getResourceFromJid(jid) === resourceJid;
  13738. });
  13739. return peerJid;
  13740. },
  13741. addBridgeIsDownToPresence: function () {
  13742. this.presMap['bridgeIsDown'] = true;
  13743. },
  13744. addEmailToPresence: function (email) {
  13745. this.presMap['email'] = email;
  13746. },
  13747. addUserIdToPresence: function (userId) {
  13748. this.presMap['userId'] = userId;
  13749. },
  13750. isModerator: function () {
  13751. return this.role === 'moderator';
  13752. },
  13753. getMemberRole: function (peerJid) {
  13754. if (this.members[peerJid]) {
  13755. return this.members[peerJid].role;
  13756. }
  13757. return null;
  13758. },
  13759. onParticipantLeft: function (jid) {
  13760. eventEmitter.emit(XMPPEvents.MUC_LEFT, jid);
  13761. this.connection.jingle.terminateByJid(jid);
  13762. if (this.getPrezi(jid)) {
  13763. $(document).trigger('presentationremoved.muc',
  13764. [jid, this.getPrezi(jid)]);
  13765. }
  13766. Moderator.onMucLeft(jid);
  13767. },
  13768. parsePresence: function (from, memeber, pres) {
  13769. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  13770. bridgeIsDown = true;
  13771. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  13772. }
  13773. if(memeber.isFocus)
  13774. return;
  13775. var self = this;
  13776. // Remove old ssrcs coming from the jid
  13777. Object.keys(this.ssrc2jid).forEach(function (ssrc) {
  13778. if (self.ssrc2jid[ssrc] == from) {
  13779. delete self.ssrc2jid[ssrc];
  13780. }
  13781. });
  13782. var changedStreams = [];
  13783. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  13784. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  13785. var ssrcV = ssrc.getAttribute('ssrc');
  13786. self.ssrc2jid[ssrcV] = from;
  13787. JingleSession.notReceivedSSRCs.push(ssrcV);
  13788. var type = ssrc.getAttribute('type');
  13789. var direction = ssrc.getAttribute('direction');
  13790. changedStreams.push({type: type, direction: direction});
  13791. });
  13792. eventEmitter.emit(XMPPEvents.CHANGED_STREAMS, from, changedStreams);
  13793. var displayName = !config.displayJids
  13794. ? memeber.displayName : Strophe.getResourceFromJid(from);
  13795. if (displayName && displayName.length > 0)
  13796. {
  13797. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  13798. }
  13799. var id = $(pres).find('>userID').text();
  13800. var email = $(pres).find('>email');
  13801. if(email.length > 0) {
  13802. id = email.text();
  13803. }
  13804. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  13805. }
  13806. });
  13807. };
  13808. },{"../../service/xmpp/XMPPEvents":88,"./JingleSession":47,"./moderator":52}],55:[function(require,module,exports){
  13809. /* jshint -W117 */
  13810. var JingleSession = require("./JingleSession");
  13811. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13812. module.exports = function(XMPP, eventEmitter)
  13813. {
  13814. function CallIncomingJingle(sid, connection) {
  13815. var sess = connection.jingle.sessions[sid];
  13816. // TODO: do we check activecall == null?
  13817. connection.jingle.activecall = sess;
  13818. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  13819. // TODO: check affiliation and/or role
  13820. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  13821. sess.usedrip = true; // not-so-naive trickle ice
  13822. sess.sendAnswer();
  13823. sess.accept();
  13824. };
  13825. Strophe.addConnectionPlugin('jingle', {
  13826. connection: null,
  13827. sessions: {},
  13828. jid2session: {},
  13829. ice_config: {iceServers: []},
  13830. pc_constraints: {},
  13831. activecall: null,
  13832. media_constraints: {
  13833. mandatory: {
  13834. 'OfferToReceiveAudio': true,
  13835. 'OfferToReceiveVideo': true
  13836. }
  13837. // MozDontOfferDataChannel: true when this is firefox
  13838. },
  13839. init: function (conn) {
  13840. this.connection = conn;
  13841. if (this.connection.disco) {
  13842. // http://xmpp.org/extensions/xep-0167.html#support
  13843. // http://xmpp.org/extensions/xep-0176.html#support
  13844. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  13845. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  13846. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  13847. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  13848. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  13849. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  13850. // this is dealt with by SDP O/A so we don't need to annouce this
  13851. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  13852. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  13853. if (config.useRtcpMux) {
  13854. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  13855. }
  13856. if (config.useBundle) {
  13857. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  13858. }
  13859. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  13860. }
  13861. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  13862. },
  13863. onJingle: function (iq) {
  13864. var sid = $(iq).find('jingle').attr('sid');
  13865. var action = $(iq).find('jingle').attr('action');
  13866. var fromJid = iq.getAttribute('from');
  13867. // send ack first
  13868. var ack = $iq({type: 'result',
  13869. to: fromJid,
  13870. id: iq.getAttribute('id')
  13871. });
  13872. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  13873. var sess = this.sessions[sid];
  13874. if ('session-initiate' != action) {
  13875. if (sess === null) {
  13876. ack.type = 'error';
  13877. ack.c('error', {type: 'cancel'})
  13878. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  13879. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  13880. this.connection.send(ack);
  13881. return true;
  13882. }
  13883. // compare from to sess.peerjid (bare jid comparison for later compat with message-mode)
  13884. // local jid is not checked
  13885. if (Strophe.getBareJidFromJid(fromJid) != Strophe.getBareJidFromJid(sess.peerjid)) {
  13886. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  13887. ack.type = 'error';
  13888. ack.c('error', {type: 'cancel'})
  13889. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  13890. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  13891. this.connection.send(ack);
  13892. return true;
  13893. }
  13894. } else if (sess !== undefined) {
  13895. // existing session with same session id
  13896. // this might be out-of-order if the sess.peerjid is the same as from
  13897. ack.type = 'error';
  13898. ack.c('error', {type: 'cancel'})
  13899. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  13900. console.warn('duplicate session id', sid);
  13901. this.connection.send(ack);
  13902. return true;
  13903. }
  13904. // FIXME: check for a defined action
  13905. this.connection.send(ack);
  13906. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  13907. switch (action) {
  13908. case 'session-initiate':
  13909. sess = new JingleSession(
  13910. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  13911. this.connection, XMPP);
  13912. // configure session
  13913. sess.media_constraints = this.media_constraints;
  13914. sess.pc_constraints = this.pc_constraints;
  13915. sess.ice_config = this.ice_config;
  13916. sess.initiate(fromJid, false);
  13917. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  13918. sess.setRemoteDescription($(iq).find('>jingle'), 'offer');
  13919. this.sessions[sess.sid] = sess;
  13920. this.jid2session[sess.peerjid] = sess;
  13921. // the callback should either
  13922. // .sendAnswer and .accept
  13923. // or .sendTerminate -- not necessarily synchronus
  13924. CallIncomingJingle(sess.sid, this.connection);
  13925. break;
  13926. case 'session-accept':
  13927. sess.setRemoteDescription($(iq).find('>jingle'), 'answer');
  13928. sess.accept();
  13929. $(document).trigger('callaccepted.jingle', [sess.sid]);
  13930. break;
  13931. case 'session-terminate':
  13932. // If this is not the focus sending the terminate, we have
  13933. // nothing more to do here.
  13934. if (Object.keys(this.sessions).length < 1
  13935. || !(this.sessions[Object.keys(this.sessions)[0]]
  13936. instanceof JingleSession))
  13937. {
  13938. break;
  13939. }
  13940. console.log('terminating...', sess.sid);
  13941. sess.terminate();
  13942. this.terminate(sess.sid);
  13943. if ($(iq).find('>jingle>reason').length) {
  13944. $(document).trigger('callterminated.jingle', [
  13945. sess.sid,
  13946. sess.peerjid,
  13947. $(iq).find('>jingle>reason>:first')[0].tagName,
  13948. $(iq).find('>jingle>reason>text').text()
  13949. ]);
  13950. } else {
  13951. $(document).trigger('callterminated.jingle',
  13952. [sess.sid, sess.peerjid]);
  13953. }
  13954. break;
  13955. case 'transport-info':
  13956. sess.addIceCandidate($(iq).find('>jingle>content'));
  13957. break;
  13958. case 'session-info':
  13959. var affected;
  13960. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  13961. $(document).trigger('ringing.jingle', [sess.sid]);
  13962. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  13963. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  13964. $(document).trigger('mute.jingle', [sess.sid, affected]);
  13965. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  13966. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  13967. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  13968. }
  13969. break;
  13970. case 'addsource': // FIXME: proprietary, un-jingleish
  13971. case 'source-add': // FIXME: proprietary
  13972. sess.addSource($(iq).find('>jingle>content'), fromJid);
  13973. break;
  13974. case 'removesource': // FIXME: proprietary, un-jingleish
  13975. case 'source-remove': // FIXME: proprietary
  13976. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  13977. break;
  13978. default:
  13979. console.warn('jingle action not implemented', action);
  13980. break;
  13981. }
  13982. return true;
  13983. },
  13984. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  13985. var sess = new JingleSession(myjid || this.connection.jid,
  13986. Math.random().toString(36).substr(2, 12), // random string
  13987. this.connection, XMPP);
  13988. // configure session
  13989. sess.media_constraints = this.media_constraints;
  13990. sess.pc_constraints = this.pc_constraints;
  13991. sess.ice_config = this.ice_config;
  13992. sess.initiate(peerjid, true);
  13993. this.sessions[sess.sid] = sess;
  13994. this.jid2session[sess.peerjid] = sess;
  13995. sess.sendOffer();
  13996. return sess;
  13997. },
  13998. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  13999. if (sid === null || sid === undefined) {
  14000. for (sid in this.sessions) {
  14001. if (this.sessions[sid].state != 'ended') {
  14002. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14003. this.sessions[sid].terminate();
  14004. }
  14005. delete this.jid2session[this.sessions[sid].peerjid];
  14006. delete this.sessions[sid];
  14007. }
  14008. } else if (this.sessions.hasOwnProperty(sid)) {
  14009. if (this.sessions[sid].state != 'ended') {
  14010. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14011. this.sessions[sid].terminate();
  14012. }
  14013. delete this.jid2session[this.sessions[sid].peerjid];
  14014. delete this.sessions[sid];
  14015. }
  14016. },
  14017. // Used to terminate a session when an unavailable presence is received.
  14018. terminateByJid: function (jid) {
  14019. if (this.jid2session.hasOwnProperty(jid)) {
  14020. var sess = this.jid2session[jid];
  14021. if (sess) {
  14022. sess.terminate();
  14023. console.log('peer went away silently', jid);
  14024. delete this.sessions[sess.sid];
  14025. delete this.jid2session[jid];
  14026. $(document).trigger('callterminated.jingle',
  14027. [sess.sid, jid], 'gone');
  14028. }
  14029. }
  14030. },
  14031. terminateRemoteByJid: function (jid, reason) {
  14032. if (this.jid2session.hasOwnProperty(jid)) {
  14033. var sess = this.jid2session[jid];
  14034. if (sess) {
  14035. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  14036. sess.terminate();
  14037. console.log('terminate peer with jid', sess.sid, jid);
  14038. delete this.sessions[sess.sid];
  14039. delete this.jid2session[jid];
  14040. $(document).trigger('callterminated.jingle',
  14041. [sess.sid, jid, 'kicked']);
  14042. }
  14043. }
  14044. },
  14045. getStunAndTurnCredentials: function () {
  14046. // get stun and turn configuration from server via xep-0215
  14047. // uses time-limited credentials as described in
  14048. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  14049. //
  14050. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  14051. // for a prosody module which implements this
  14052. //
  14053. // currently, this doesn't work with updateIce and therefore credentials with a long
  14054. // validity have to be fetched before creating the peerconnection
  14055. // TODO: implement refresh via updateIce as described in
  14056. // https://code.google.com/p/webrtc/issues/detail?id=1650
  14057. var self = this;
  14058. this.connection.sendIQ(
  14059. $iq({type: 'get', to: this.connection.domain})
  14060. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  14061. function (res) {
  14062. var iceservers = [];
  14063. $(res).find('>services>service').each(function (idx, el) {
  14064. el = $(el);
  14065. var dict = {};
  14066. var type = el.attr('type');
  14067. switch (type) {
  14068. case 'stun':
  14069. dict.url = 'stun:' + el.attr('host');
  14070. if (el.attr('port')) {
  14071. dict.url += ':' + el.attr('port');
  14072. }
  14073. iceservers.push(dict);
  14074. break;
  14075. case 'turn':
  14076. case 'turns':
  14077. dict.url = type + ':';
  14078. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  14079. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  14080. dict.url += el.attr('username') + '@';
  14081. } else {
  14082. dict.username = el.attr('username'); // only works in M28
  14083. }
  14084. }
  14085. dict.url += el.attr('host');
  14086. if (el.attr('port') && el.attr('port') != '3478') {
  14087. dict.url += ':' + el.attr('port');
  14088. }
  14089. if (el.attr('transport') && el.attr('transport') != 'udp') {
  14090. dict.url += '?transport=' + el.attr('transport');
  14091. }
  14092. if (el.attr('password')) {
  14093. dict.credential = el.attr('password');
  14094. }
  14095. iceservers.push(dict);
  14096. break;
  14097. }
  14098. });
  14099. self.ice_config.iceServers = iceservers;
  14100. },
  14101. function (err) {
  14102. console.warn('getting turn credentials failed', err);
  14103. console.warn('is mod_turncredentials or similar installed?');
  14104. }
  14105. );
  14106. // implement push?
  14107. },
  14108. /**
  14109. * Populates the log data
  14110. */
  14111. populateData: function () {
  14112. var data = {};
  14113. Object.keys(this.sessions).forEach(function (sid) {
  14114. var session = this.sessions[sid];
  14115. if (session.peerconnection && session.peerconnection.updateLog) {
  14116. // FIXME: should probably be a .dump call
  14117. data["jingle_" + session.sid] = {
  14118. updateLog: session.peerconnection.updateLog,
  14119. stats: session.peerconnection.stats,
  14120. url: window.location.href
  14121. };
  14122. }
  14123. });
  14124. return data;
  14125. }
  14126. });
  14127. };
  14128. },{"../../service/xmpp/XMPPEvents":88,"./JingleSession":47}],56:[function(require,module,exports){
  14129. /* global Strophe */
  14130. module.exports = function () {
  14131. Strophe.addConnectionPlugin('logger', {
  14132. // logs raw stanzas and makes them available for download as JSON
  14133. connection: null,
  14134. log: [],
  14135. init: function (conn) {
  14136. this.connection = conn;
  14137. this.connection.rawInput = this.log_incoming.bind(this);
  14138. this.connection.rawOutput = this.log_outgoing.bind(this);
  14139. },
  14140. log_incoming: function (stanza) {
  14141. this.log.push([new Date().getTime(), 'incoming', stanza]);
  14142. },
  14143. log_outgoing: function (stanza) {
  14144. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  14145. }
  14146. });
  14147. };
  14148. },{}],57:[function(require,module,exports){
  14149. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  14150. setAudioMuted, Strophe */
  14151. /**
  14152. * Moderate connection plugin.
  14153. */
  14154. module.exports = function (XMPP) {
  14155. Strophe.addConnectionPlugin('moderate', {
  14156. connection: null,
  14157. init: function (conn) {
  14158. this.connection = conn;
  14159. this.connection.addHandler(this.onMute.bind(this),
  14160. 'http://jitsi.org/jitmeet/audio',
  14161. 'iq',
  14162. 'set',
  14163. null,
  14164. null);
  14165. },
  14166. setMute: function (jid, mute) {
  14167. console.info("set mute", mute);
  14168. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  14169. .c('mute', {
  14170. xmlns: 'http://jitsi.org/jitmeet/audio',
  14171. jid: jid
  14172. })
  14173. .t(mute.toString())
  14174. .up();
  14175. this.connection.sendIQ(
  14176. iqToFocus,
  14177. function (result) {
  14178. console.log('set mute', result);
  14179. },
  14180. function (error) {
  14181. console.log('set mute error', error);
  14182. });
  14183. },
  14184. onMute: function (iq) {
  14185. var from = iq.getAttribute('from');
  14186. if (from !== this.connection.emuc.focusMucJid) {
  14187. console.warn("Ignored mute from non focus peer");
  14188. return false;
  14189. }
  14190. var mute = $(iq).find('mute');
  14191. if (mute.length) {
  14192. var doMuteAudio = mute.text() === "true";
  14193. APP.UI.setAudioMuted(doMuteAudio);
  14194. XMPP.forceMuted = doMuteAudio;
  14195. }
  14196. return true;
  14197. },
  14198. eject: function (jid) {
  14199. // We're not the focus, so can't terminate
  14200. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  14201. this.connection.emuc.kick(jid);
  14202. }
  14203. });
  14204. }
  14205. },{}],58:[function(require,module,exports){
  14206. /* jshint -W117 */
  14207. module.exports = function() {
  14208. Strophe.addConnectionPlugin('rayo',
  14209. {
  14210. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  14211. connection: null,
  14212. init: function (conn) {
  14213. this.connection = conn;
  14214. if (this.connection.disco) {
  14215. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  14216. }
  14217. this.connection.addHandler(
  14218. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  14219. },
  14220. onRayo: function (iq) {
  14221. console.info("Rayo IQ", iq);
  14222. },
  14223. dial: function (to, from, roomName, roomPass) {
  14224. var self = this;
  14225. var req = $iq(
  14226. {
  14227. type: 'set',
  14228. to: this.connection.emuc.focusMucJid
  14229. }
  14230. );
  14231. req.c('dial',
  14232. {
  14233. xmlns: this.RAYO_XMLNS,
  14234. to: to,
  14235. from: from
  14236. });
  14237. req.c('header',
  14238. {
  14239. name: 'JvbRoomName',
  14240. value: roomName
  14241. }).up();
  14242. if (roomPass !== null && roomPass.length) {
  14243. req.c('header',
  14244. {
  14245. name: 'JvbRoomPassword',
  14246. value: roomPass
  14247. }).up();
  14248. }
  14249. this.connection.sendIQ(
  14250. req,
  14251. function (result) {
  14252. console.info('Dial result ', result);
  14253. var resource = $(result).find('ref').attr('uri');
  14254. this.call_resource = resource.substr('xmpp:'.length);
  14255. console.info(
  14256. "Received call resource: " + this.call_resource);
  14257. },
  14258. function (error) {
  14259. console.info('Dial error ', error);
  14260. }
  14261. );
  14262. },
  14263. hang_up: function () {
  14264. if (!this.call_resource) {
  14265. console.warn("No call in progress");
  14266. return;
  14267. }
  14268. var self = this;
  14269. var req = $iq(
  14270. {
  14271. type: 'set',
  14272. to: this.call_resource
  14273. }
  14274. );
  14275. req.c('hangup',
  14276. {
  14277. xmlns: this.RAYO_XMLNS
  14278. });
  14279. this.connection.sendIQ(
  14280. req,
  14281. function (result) {
  14282. console.info('Hangup result ', result);
  14283. self.call_resource = null;
  14284. },
  14285. function (error) {
  14286. console.info('Hangup error ', error);
  14287. self.call_resource = null;
  14288. }
  14289. );
  14290. }
  14291. }
  14292. );
  14293. };
  14294. },{}],59:[function(require,module,exports){
  14295. /**
  14296. * Strophe logger implementation. Logs from level WARN and above.
  14297. */
  14298. module.exports = function () {
  14299. Strophe.log = function (level, msg) {
  14300. switch (level) {
  14301. case Strophe.LogLevel.WARN:
  14302. console.warn("Strophe: " + msg);
  14303. break;
  14304. case Strophe.LogLevel.ERROR:
  14305. case Strophe.LogLevel.FATAL:
  14306. console.error("Strophe: " + msg);
  14307. break;
  14308. }
  14309. };
  14310. Strophe.getStatusString = function (status) {
  14311. switch (status) {
  14312. case Strophe.Status.ERROR:
  14313. return "ERROR";
  14314. case Strophe.Status.CONNECTING:
  14315. return "CONNECTING";
  14316. case Strophe.Status.CONNFAIL:
  14317. return "CONNFAIL";
  14318. case Strophe.Status.AUTHENTICATING:
  14319. return "AUTHENTICATING";
  14320. case Strophe.Status.AUTHFAIL:
  14321. return "AUTHFAIL";
  14322. case Strophe.Status.CONNECTED:
  14323. return "CONNECTED";
  14324. case Strophe.Status.DISCONNECTED:
  14325. return "DISCONNECTED";
  14326. case Strophe.Status.DISCONNECTING:
  14327. return "DISCONNECTING";
  14328. case Strophe.Status.ATTACHED:
  14329. return "ATTACHED";
  14330. default:
  14331. return "unknown";
  14332. }
  14333. };
  14334. };
  14335. },{}],60:[function(require,module,exports){
  14336. var Moderator = require("./moderator");
  14337. var EventEmitter = require("events");
  14338. var Recording = require("./recording");
  14339. var SDP = require("./SDP");
  14340. var Pako = require("pako");
  14341. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  14342. var UIEvents = require("../../service/UI/UIEvents");
  14343. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14344. var eventEmitter = new EventEmitter();
  14345. var connection = null;
  14346. var authenticatedUser = false;
  14347. function connect(jid, password, uiCredentials) {
  14348. var bosh
  14349. = (uiCredentials && uiCredentials.bosh? uiCredentials.bosh : null)
  14350. || config.bosh || '/http-bind';
  14351. connection = new Strophe.Connection(bosh);
  14352. Moderator.setConnection(connection);
  14353. if(uiCredentials) {
  14354. var email = uiCredentials.email;
  14355. var displayName = uiCredentials.displayName;
  14356. if (email) {
  14357. connection.emuc.addEmailToPresence(email);
  14358. } else {
  14359. connection.emuc.addUserIdToPresence(uiCredentials.uid);
  14360. }
  14361. if (displayName) {
  14362. connection.emuc.addDisplayNameToPresence(displayName);
  14363. }
  14364. }
  14365. if (connection.disco) {
  14366. // for chrome, add multistream cap
  14367. }
  14368. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  14369. if (config.useIPv6) {
  14370. // https://code.google.com/p/webrtc/issues/detail?id=2828
  14371. if (!connection.jingle.pc_constraints.optional)
  14372. connection.jingle.pc_constraints.optional = [];
  14373. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  14374. }
  14375. if(!password)
  14376. password = uiCredentials.password;
  14377. var anonymousConnectionFailed = false;
  14378. connection.connect(jid, password, function (status, msg) {
  14379. console.log('Strophe status changed to',
  14380. Strophe.getStatusString(status));
  14381. if (status === Strophe.Status.CONNECTED) {
  14382. if (config.useStunTurn) {
  14383. connection.jingle.getStunAndTurnCredentials();
  14384. }
  14385. APP.UI.disableConnect();
  14386. console.info("My Jabber ID: " + connection.jid);
  14387. if(password)
  14388. authenticatedUser = true;
  14389. maybeDoJoin();
  14390. } else if (status === Strophe.Status.CONNFAIL) {
  14391. if(msg === 'x-strophe-bad-non-anon-jid') {
  14392. anonymousConnectionFailed = true;
  14393. }
  14394. } else if (status === Strophe.Status.DISCONNECTED) {
  14395. if(anonymousConnectionFailed) {
  14396. // prompt user for username and password
  14397. XMPP.promptLogin();
  14398. }
  14399. } else if (status === Strophe.Status.AUTHFAIL) {
  14400. // wrong password or username, prompt user
  14401. XMPP.promptLogin();
  14402. }
  14403. });
  14404. }
  14405. function maybeDoJoin() {
  14406. if (connection && connection.connected &&
  14407. Strophe.getResourceFromJid(connection.jid)
  14408. && (APP.RTC.localAudio || APP.RTC.localVideo)) {
  14409. // .connected is true while connecting?
  14410. doJoin();
  14411. }
  14412. }
  14413. function doJoin() {
  14414. var roomName = APP.UI.generateRoomName();
  14415. Moderator.allocateConferenceFocus(
  14416. roomName, APP.UI.checkForNicknameAndJoin);
  14417. }
  14418. function initStrophePlugins()
  14419. {
  14420. require("./strophe.emuc")(XMPP, eventEmitter);
  14421. require("./strophe.jingle")(XMPP, eventEmitter);
  14422. require("./strophe.moderate")(XMPP);
  14423. require("./strophe.util")();
  14424. require("./strophe.rayo")();
  14425. require("./strophe.logger")();
  14426. }
  14427. function registerListeners() {
  14428. APP.RTC.addStreamListener(maybeDoJoin,
  14429. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  14430. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  14431. XMPP.addToPresence("displayName", nickname);
  14432. });
  14433. }
  14434. function setupEvents() {
  14435. $(window).bind('beforeunload', function () {
  14436. if (connection && connection.connected) {
  14437. // ensure signout
  14438. $.ajax({
  14439. type: 'POST',
  14440. url: config.bosh,
  14441. async: false,
  14442. cache: false,
  14443. contentType: 'application/xml',
  14444. data: "<body rid='" + (connection.rid || connection._proto.rid)
  14445. + "' xmlns='http://jabber.org/protocol/httpbind' sid='"
  14446. + (connection.sid || connection._proto.sid)
  14447. + "' type='terminate'>" +
  14448. "<presence xmlns='jabber:client' type='unavailable'/>" +
  14449. "</body>",
  14450. success: function (data) {
  14451. console.log('signed out');
  14452. console.log(data);
  14453. },
  14454. error: function (XMLHttpRequest, textStatus, errorThrown) {
  14455. console.log('signout error',
  14456. textStatus + ' (' + errorThrown + ')');
  14457. }
  14458. });
  14459. }
  14460. XMPP.disposeConference(true);
  14461. });
  14462. }
  14463. var XMPP = {
  14464. sessionTerminated: false,
  14465. /**
  14466. * Remembers if we were muted by the focus.
  14467. * @type {boolean}
  14468. */
  14469. forceMuted: false,
  14470. start: function (uiCredentials) {
  14471. setupEvents();
  14472. initStrophePlugins();
  14473. registerListeners();
  14474. Moderator.init(this, eventEmitter);
  14475. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  14476. // Force authenticated domain if room is appended with '?login=true'
  14477. if (config.hosts.anonymousdomain &&
  14478. window.location.search.indexOf("login=true") !== -1) {
  14479. configDomain = config.hosts.domain;
  14480. }
  14481. var jid = uiCredentials.jid || configDomain || window.location.hostname;
  14482. connect(jid, null, uiCredentials);
  14483. },
  14484. promptLogin: function () {
  14485. APP.UI.showLoginPopup(connect);
  14486. },
  14487. joinRoom: function(roomName, useNicks, nick)
  14488. {
  14489. var roomjid;
  14490. roomjid = roomName;
  14491. if (useNicks) {
  14492. if (nick) {
  14493. roomjid += '/' + nick;
  14494. } else {
  14495. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  14496. }
  14497. } else {
  14498. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  14499. if(!authenticatedUser)
  14500. tmpJid = tmpJid.substr(0, 8);
  14501. roomjid += '/' + tmpJid;
  14502. }
  14503. connection.emuc.doJoin(roomjid);
  14504. },
  14505. myJid: function () {
  14506. if(!connection)
  14507. return null;
  14508. return connection.emuc.myroomjid;
  14509. },
  14510. myResource: function () {
  14511. if(!connection || ! connection.emuc.myroomjid)
  14512. return null;
  14513. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  14514. },
  14515. disposeConference: function (onUnload) {
  14516. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  14517. var handler = connection.jingle.activecall;
  14518. if (handler && handler.peerconnection) {
  14519. // FIXME: probably removing streams is not required and close() should
  14520. // be enough
  14521. if (APP.RTC.localAudio) {
  14522. handler.peerconnection.removeStream(APP.RTC.localAudio.getOriginalStream(), onUnload);
  14523. }
  14524. if (APP.RTC.localVideo) {
  14525. handler.peerconnection.removeStream(APP.RTC.localVideo.getOriginalStream(), onUnload);
  14526. }
  14527. handler.peerconnection.close();
  14528. }
  14529. connection.jingle.activecall = null;
  14530. if(!onUnload)
  14531. {
  14532. this.sessionTerminated = true;
  14533. connection.emuc.doLeave();
  14534. }
  14535. },
  14536. addListener: function(type, listener)
  14537. {
  14538. eventEmitter.on(type, listener);
  14539. },
  14540. removeListener: function (type, listener) {
  14541. eventEmitter.removeListener(type, listener);
  14542. },
  14543. allocateConferenceFocus: function(roomName, callback) {
  14544. Moderator.allocateConferenceFocus(roomName, callback);
  14545. },
  14546. getLoginUrl: function (roomName, callback) {
  14547. Moderator.getLoginUrl(roomName, callback);
  14548. },
  14549. getPopupLoginUrl: function (roomName, callback) {
  14550. Moderator.getPopupLoginUrl(roomName, callback);
  14551. },
  14552. isModerator: function () {
  14553. return Moderator.isModerator();
  14554. },
  14555. isSipGatewayEnabled: function () {
  14556. return Moderator.isSipGatewayEnabled();
  14557. },
  14558. isExternalAuthEnabled: function () {
  14559. return Moderator.isExternalAuthEnabled();
  14560. },
  14561. switchStreams: function (stream, oldStream, callback) {
  14562. if (connection && connection.jingle.activecall) {
  14563. // FIXME: will block switchInProgress on true value in case of exception
  14564. connection.jingle.activecall.switchStreams(stream, oldStream, callback);
  14565. } else {
  14566. // We are done immediately
  14567. console.error("No conference handler");
  14568. APP.UI.messageHandler.showError("dialog.error",
  14569. "dialog.unableToSwitch");
  14570. callback();
  14571. }
  14572. },
  14573. setVideoMute: function (mute, callback, options) {
  14574. if(connection && APP.RTC.localVideo && connection.jingle.activecall)
  14575. {
  14576. connection.jingle.activecall.setVideoMute(mute, callback, options);
  14577. }
  14578. },
  14579. setAudioMute: function (mute, callback) {
  14580. if (!(connection && APP.RTC.localAudio)) {
  14581. return false;
  14582. }
  14583. if (this.forceMuted && !mute) {
  14584. console.info("Asking focus for unmute");
  14585. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  14586. // FIXME: wait for result before resetting muted status
  14587. this.forceMuted = false;
  14588. }
  14589. if (mute == APP.RTC.localAudio.isMuted()) {
  14590. // Nothing to do
  14591. return true;
  14592. }
  14593. // It is not clear what is the right way to handle multiple tracks.
  14594. // So at least make sure that they are all muted or all unmuted and
  14595. // that we send presence just once.
  14596. APP.RTC.localAudio.mute();
  14597. // isMuted is the opposite of audioEnabled
  14598. connection.emuc.addAudioInfoToPresence(mute);
  14599. connection.emuc.sendPresence();
  14600. callback();
  14601. return true;
  14602. },
  14603. // Really mute video, i.e. dont even send black frames
  14604. muteVideo: function (pc, unmute) {
  14605. // FIXME: this probably needs another of those lovely state safeguards...
  14606. // which checks for iceconn == connected and sigstate == stable
  14607. pc.setRemoteDescription(pc.remoteDescription,
  14608. function () {
  14609. pc.createAnswer(
  14610. function (answer) {
  14611. var sdp = new SDP(answer.sdp);
  14612. if (sdp.media.length > 1) {
  14613. if (unmute)
  14614. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  14615. else
  14616. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  14617. sdp.raw = sdp.session + sdp.media.join('');
  14618. answer.sdp = sdp.raw;
  14619. }
  14620. pc.setLocalDescription(answer,
  14621. function () {
  14622. console.log('mute SLD ok');
  14623. },
  14624. function (error) {
  14625. console.log('mute SLD error');
  14626. APP.UI.messageHandler.showError("dialog.error",
  14627. "dialog.SLDFailure");
  14628. }
  14629. );
  14630. },
  14631. function (error) {
  14632. console.log(error);
  14633. APP.UI.messageHandler.showError();
  14634. }
  14635. );
  14636. },
  14637. function (error) {
  14638. console.log('muteVideo SRD error');
  14639. APP.UI.messageHandler.showError("dialog.error",
  14640. "dialog.SRDFailure");
  14641. }
  14642. );
  14643. },
  14644. toggleRecording: function (tokenEmptyCallback,
  14645. startingCallback, startedCallback) {
  14646. Recording.toggleRecording(tokenEmptyCallback,
  14647. startingCallback, startedCallback, connection);
  14648. },
  14649. addToPresence: function (name, value, dontSend) {
  14650. switch (name)
  14651. {
  14652. case "displayName":
  14653. connection.emuc.addDisplayNameToPresence(value);
  14654. break;
  14655. case "etherpad":
  14656. connection.emuc.addEtherpadToPresence(value);
  14657. break;
  14658. case "prezi":
  14659. connection.emuc.addPreziToPresence(value, 0);
  14660. break;
  14661. case "preziSlide":
  14662. connection.emuc.addCurrentSlideToPresence(value);
  14663. break;
  14664. case "connectionQuality":
  14665. connection.emuc.addConnectionInfoToPresence(value);
  14666. break;
  14667. case "email":
  14668. connection.emuc.addEmailToPresence(value);
  14669. default :
  14670. console.log("Unknown tag for presence.");
  14671. return;
  14672. }
  14673. if(!dontSend)
  14674. connection.emuc.sendPresence();
  14675. },
  14676. /**
  14677. * Sends 'data' as a log message to the focus. Returns true iff a message
  14678. * was sent.
  14679. * @param data
  14680. * @returns {boolean} true iff a message was sent.
  14681. */
  14682. sendLogs: function (data) {
  14683. if(!connection.emuc.focusMucJid)
  14684. return false;
  14685. var deflate = true;
  14686. var content = JSON.stringify(data);
  14687. if (deflate) {
  14688. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  14689. }
  14690. content = Base64.encode(content);
  14691. // XEP-0337-ish
  14692. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  14693. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  14694. id: 'PeerConnectionStats'});
  14695. message.c('message').t(content).up();
  14696. if (deflate) {
  14697. message.c('tag', {name: "deflated", value: "true"}).up();
  14698. }
  14699. message.up();
  14700. connection.send(message);
  14701. return true;
  14702. },
  14703. populateData: function () {
  14704. var data = {};
  14705. if (connection.jingle) {
  14706. data = connection.jingle.populateData();
  14707. }
  14708. return data;
  14709. },
  14710. getLogger: function () {
  14711. if(connection.logger)
  14712. return connection.logger.log;
  14713. return null;
  14714. },
  14715. getPrezi: function () {
  14716. return connection.emuc.getPrezi(this.myJid());
  14717. },
  14718. removePreziFromPresence: function () {
  14719. connection.emuc.removePreziFromPresence();
  14720. connection.emuc.sendPresence();
  14721. },
  14722. sendChatMessage: function (message, nickname) {
  14723. connection.emuc.sendMessage(message, nickname);
  14724. },
  14725. setSubject: function (topic) {
  14726. connection.emuc.setSubject(topic);
  14727. },
  14728. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  14729. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  14730. },
  14731. dial: function (to, from, roomName,roomPass) {
  14732. connection.rayo.dial(to, from, roomName,roomPass);
  14733. },
  14734. setMute: function (jid, mute) {
  14735. connection.moderate.setMute(jid, mute);
  14736. },
  14737. eject: function (jid) {
  14738. connection.moderate.eject(jid);
  14739. },
  14740. logout: function (callback) {
  14741. Moderator.logout(callback);
  14742. },
  14743. findJidFromResource: function (resource) {
  14744. return connection.emuc.findJidFromResource(resource);
  14745. },
  14746. getMembers: function () {
  14747. return connection.emuc.members;
  14748. },
  14749. getJidFromSSRC: function (ssrc) {
  14750. if(!connection)
  14751. return null;
  14752. return connection.emuc.ssrc2jid[ssrc];
  14753. },
  14754. getMUCJoined: function () {
  14755. return connection.emuc.joined;
  14756. },
  14757. getSessions: function () {
  14758. return connection.jingle.sessions;
  14759. }
  14760. };
  14761. module.exports = XMPP;
  14762. },{"../../service/RTC/StreamEventTypes":82,"../../service/UI/UIEvents":83,"../../service/xmpp/XMPPEvents":88,"./SDP":48,"./moderator":52,"./recording":53,"./strophe.emuc":54,"./strophe.jingle":55,"./strophe.logger":56,"./strophe.moderate":57,"./strophe.rayo":58,"./strophe.util":59,"events":89,"pako":62}],61:[function(require,module,exports){
  14763. // i18next, v1.7.7
  14764. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  14765. // Distributed under MIT license
  14766. // http://i18next.com
  14767. (function() {
  14768. // add indexOf to non ECMA-262 standard compliant browsers
  14769. if (!Array.prototype.indexOf) {
  14770. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  14771. "use strict";
  14772. if (this == null) {
  14773. throw new TypeError();
  14774. }
  14775. var t = Object(this);
  14776. var len = t.length >>> 0;
  14777. if (len === 0) {
  14778. return -1;
  14779. }
  14780. var n = 0;
  14781. if (arguments.length > 0) {
  14782. n = Number(arguments[1]);
  14783. if (n != n) { // shortcut for verifying if it's NaN
  14784. n = 0;
  14785. } else if (n != 0 && n != Infinity && n != -Infinity) {
  14786. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  14787. }
  14788. }
  14789. if (n >= len) {
  14790. return -1;
  14791. }
  14792. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  14793. for (; k < len; k++) {
  14794. if (k in t && t[k] === searchElement) {
  14795. return k;
  14796. }
  14797. }
  14798. return -1;
  14799. }
  14800. }
  14801. // add lastIndexOf to non ECMA-262 standard compliant browsers
  14802. if (!Array.prototype.lastIndexOf) {
  14803. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  14804. "use strict";
  14805. if (this == null) {
  14806. throw new TypeError();
  14807. }
  14808. var t = Object(this);
  14809. var len = t.length >>> 0;
  14810. if (len === 0) {
  14811. return -1;
  14812. }
  14813. var n = len;
  14814. if (arguments.length > 1) {
  14815. n = Number(arguments[1]);
  14816. if (n != n) {
  14817. n = 0;
  14818. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  14819. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  14820. }
  14821. }
  14822. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  14823. for (; k >= 0; k--) {
  14824. if (k in t && t[k] === searchElement) {
  14825. return k;
  14826. }
  14827. }
  14828. return -1;
  14829. };
  14830. }
  14831. // Add string trim for IE8.
  14832. if (typeof String.prototype.trim !== 'function') {
  14833. String.prototype.trim = function() {
  14834. return this.replace(/^\s+|\s+$/g, '');
  14835. }
  14836. }
  14837. var root = this
  14838. , $ = root.jQuery || root.Zepto
  14839. , i18n = {}
  14840. , resStore = {}
  14841. , currentLng
  14842. , replacementCounter = 0
  14843. , languages = []
  14844. , initialized = false
  14845. , sync = {};
  14846. // Export the i18next object for **CommonJS**.
  14847. // If we're not in CommonJS, add `i18n` to the
  14848. // global object or to jquery.
  14849. if (typeof module !== 'undefined' && module.exports) {
  14850. if (!$) {
  14851. try {
  14852. $ = require('jquery');
  14853. } catch(e) {
  14854. // just ignore
  14855. }
  14856. }
  14857. if ($) {
  14858. $.i18n = $.i18n || i18n;
  14859. }
  14860. module.exports = i18n;
  14861. } else {
  14862. if ($) {
  14863. $.i18n = $.i18n || i18n;
  14864. }
  14865. root.i18n = root.i18n || i18n;
  14866. }
  14867. sync = {
  14868. load: function(lngs, options, cb) {
  14869. if (options.useLocalStorage) {
  14870. sync._loadLocal(lngs, options, function(err, store) {
  14871. var missingLngs = [];
  14872. for (var i = 0, len = lngs.length; i < len; i++) {
  14873. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  14874. }
  14875. if (missingLngs.length > 0) {
  14876. sync._fetch(missingLngs, options, function(err, fetched) {
  14877. f.extend(store, fetched);
  14878. sync._storeLocal(fetched);
  14879. cb(null, store);
  14880. });
  14881. } else {
  14882. cb(null, store);
  14883. }
  14884. });
  14885. } else {
  14886. sync._fetch(lngs, options, function(err, store){
  14887. cb(null, store);
  14888. });
  14889. }
  14890. },
  14891. _loadLocal: function(lngs, options, cb) {
  14892. var store = {}
  14893. , nowMS = new Date().getTime();
  14894. if(window.localStorage) {
  14895. var todo = lngs.length;
  14896. f.each(lngs, function(key, lng) {
  14897. var local = window.localStorage.getItem('res_' + lng);
  14898. if (local) {
  14899. local = JSON.parse(local);
  14900. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  14901. store[lng] = local;
  14902. }
  14903. }
  14904. todo--; // wait for all done befor callback
  14905. if (todo === 0) cb(null, store);
  14906. });
  14907. }
  14908. },
  14909. _storeLocal: function(store) {
  14910. if(window.localStorage) {
  14911. for (var m in store) {
  14912. store[m].i18nStamp = new Date().getTime();
  14913. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  14914. }
  14915. }
  14916. return;
  14917. },
  14918. _fetch: function(lngs, options, cb) {
  14919. var ns = options.ns
  14920. , store = {};
  14921. if (!options.dynamicLoad) {
  14922. var todo = ns.namespaces.length * lngs.length
  14923. , errors;
  14924. // load each file individual
  14925. f.each(ns.namespaces, function(nsIndex, nsValue) {
  14926. f.each(lngs, function(lngIndex, lngValue) {
  14927. // Call this once our translation has returned.
  14928. var loadComplete = function(err, data) {
  14929. if (err) {
  14930. errors = errors || [];
  14931. errors.push(err);
  14932. }
  14933. store[lngValue] = store[lngValue] || {};
  14934. store[lngValue][nsValue] = data;
  14935. todo--; // wait for all done befor callback
  14936. if (todo === 0) cb(errors, store);
  14937. };
  14938. if(typeof options.customLoad == 'function'){
  14939. // Use the specified custom callback.
  14940. options.customLoad(lngValue, nsValue, options, loadComplete);
  14941. } else {
  14942. //~ // Use our inbuilt sync.
  14943. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  14944. }
  14945. });
  14946. });
  14947. } else {
  14948. // Call this once our translation has returned.
  14949. var loadComplete = function(err, data) {
  14950. cb(null, data);
  14951. };
  14952. if(typeof options.customLoad == 'function'){
  14953. // Use the specified custom callback.
  14954. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  14955. } else {
  14956. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  14957. // load all needed stuff once
  14958. f.ajax({
  14959. url: url,
  14960. success: function(data, status, xhr) {
  14961. f.log('loaded: ' + url);
  14962. loadComplete(null, data);
  14963. },
  14964. error : function(xhr, status, error) {
  14965. f.log('failed loading: ' + url);
  14966. loadComplete('failed loading resource.json error: ' + error);
  14967. },
  14968. dataType: "json",
  14969. async : options.getAsync
  14970. });
  14971. }
  14972. }
  14973. },
  14974. _fetchOne: function(lng, ns, options, done) {
  14975. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  14976. f.ajax({
  14977. url: url,
  14978. success: function(data, status, xhr) {
  14979. f.log('loaded: ' + url);
  14980. done(null, data);
  14981. },
  14982. error : function(xhr, status, error) {
  14983. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  14984. // file loaded but invalid json, stop waste time !
  14985. f.error('There is a typo in: ' + url);
  14986. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  14987. f.log('Does not exist: ' + url);
  14988. } else {
  14989. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  14990. f.log(theStatus + ' when loading ' + url);
  14991. }
  14992. done(error, {});
  14993. },
  14994. dataType: "json",
  14995. async : options.getAsync
  14996. });
  14997. },
  14998. postMissing: function(lng, ns, key, defaultValue, lngs) {
  14999. var payload = {};
  15000. payload[key] = defaultValue;
  15001. var urls = [];
  15002. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  15003. for (var i = 0; i < o.fallbackLng.length; i++) {
  15004. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  15005. }
  15006. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  15007. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  15008. } else if (o.sendMissingTo === 'all') {
  15009. for (var i = 0, l = lngs.length; i < l; i++) {
  15010. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  15011. }
  15012. }
  15013. for (var y = 0, len = urls.length; y < len; y++) {
  15014. var item = urls[y];
  15015. f.ajax({
  15016. url: item.url,
  15017. type: o.sendType,
  15018. data: payload,
  15019. success: function(data, status, xhr) {
  15020. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  15021. // add key to resStore
  15022. var keys = key.split('.');
  15023. var x = 0;
  15024. var value = resStore[item.lng][ns];
  15025. while (keys[x]) {
  15026. if (x === keys.length - 1) {
  15027. value = value[keys[x]] = defaultValue;
  15028. } else {
  15029. value = value[keys[x]] = value[keys[x]] || {};
  15030. }
  15031. x++;
  15032. }
  15033. },
  15034. error : function(xhr, status, error) {
  15035. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  15036. },
  15037. dataType: "json",
  15038. async : o.postAsync
  15039. });
  15040. }
  15041. },
  15042. reload: reload
  15043. };
  15044. // defaults
  15045. var o = {
  15046. lng: undefined,
  15047. load: 'all',
  15048. preload: [],
  15049. lowerCaseLng: false,
  15050. returnObjectTrees: false,
  15051. fallbackLng: ['dev'],
  15052. fallbackNS: [],
  15053. detectLngQS: 'setLng',
  15054. detectLngFromLocalStorage: false,
  15055. ns: 'translation',
  15056. fallbackOnNull: true,
  15057. fallbackOnEmpty: false,
  15058. fallbackToDefaultNS: false,
  15059. nsseparator: ':',
  15060. keyseparator: '.',
  15061. selectorAttr: 'data-i18n',
  15062. debug: false,
  15063. resGetPath: 'locales/__lng__/__ns__.json',
  15064. resPostPath: 'locales/add/__lng__/__ns__',
  15065. getAsync: true,
  15066. postAsync: true,
  15067. resStore: undefined,
  15068. useLocalStorage: false,
  15069. localStorageExpirationTime: 7*24*60*60*1000,
  15070. dynamicLoad: false,
  15071. sendMissing: false,
  15072. sendMissingTo: 'fallback', // current | all
  15073. sendType: 'POST',
  15074. interpolationPrefix: '__',
  15075. interpolationSuffix: '__',
  15076. defaultVariables: false,
  15077. reusePrefix: '$t(',
  15078. reuseSuffix: ')',
  15079. pluralSuffix: '_plural',
  15080. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  15081. contextNotFound: ['context_not_found', Math.random()].join(''),
  15082. escapeInterpolation: false,
  15083. indefiniteSuffix: '_indefinite',
  15084. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  15085. setJqueryExt: true,
  15086. defaultValueFromContent: true,
  15087. useDataAttrOptions: false,
  15088. cookieExpirationTime: undefined,
  15089. useCookie: true,
  15090. cookieName: 'i18next',
  15091. cookieDomain: undefined,
  15092. objectTreeKeyHandler: undefined,
  15093. postProcess: undefined,
  15094. parseMissingKey: undefined,
  15095. missingKeyHandler: sync.postMissing,
  15096. shortcutFunction: 'sprintf' // or: defaultValue
  15097. };
  15098. function _extend(target, source) {
  15099. if (!source || typeof source === 'function') {
  15100. return target;
  15101. }
  15102. for (var attr in source) { target[attr] = source[attr]; }
  15103. return target;
  15104. }
  15105. function _deepExtend(target, source) {
  15106. for (var prop in source)
  15107. if (prop in target)
  15108. _deepExtend(target[prop], source[prop]);
  15109. else
  15110. target[prop] = source[prop];
  15111. return target;
  15112. }
  15113. function _each(object, callback, args) {
  15114. var name, i = 0,
  15115. length = object.length,
  15116. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  15117. if (args) {
  15118. if (isObj) {
  15119. for (name in object) {
  15120. if (callback.apply(object[name], args) === false) {
  15121. break;
  15122. }
  15123. }
  15124. } else {
  15125. for ( ; i < length; ) {
  15126. if (callback.apply(object[i++], args) === false) {
  15127. break;
  15128. }
  15129. }
  15130. }
  15131. // A special, fast, case for the most common use of each
  15132. } else {
  15133. if (isObj) {
  15134. for (name in object) {
  15135. if (callback.call(object[name], name, object[name]) === false) {
  15136. break;
  15137. }
  15138. }
  15139. } else {
  15140. for ( ; i < length; ) {
  15141. if (callback.call(object[i], i, object[i++]) === false) {
  15142. break;
  15143. }
  15144. }
  15145. }
  15146. }
  15147. return object;
  15148. }
  15149. var _entityMap = {
  15150. "&": "&amp;",
  15151. "<": "&lt;",
  15152. ">": "&gt;",
  15153. '"': '&quot;',
  15154. "'": '&#39;',
  15155. "/": '&#x2F;'
  15156. };
  15157. function _escape(data) {
  15158. if (typeof data === 'string') {
  15159. return data.replace(/[&<>"'\/]/g, function (s) {
  15160. return _entityMap[s];
  15161. });
  15162. }else{
  15163. return data;
  15164. }
  15165. }
  15166. function _ajax(options) {
  15167. // v0.5.0 of https://github.com/goloroden/http.js
  15168. var getXhr = function (callback) {
  15169. // Use the native XHR object if the browser supports it.
  15170. if (window.XMLHttpRequest) {
  15171. return callback(null, new XMLHttpRequest());
  15172. } else if (window.ActiveXObject) {
  15173. // In Internet Explorer check for ActiveX versions of the XHR object.
  15174. try {
  15175. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  15176. } catch (e) {
  15177. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  15178. }
  15179. }
  15180. // If no XHR support was found, throw an error.
  15181. return callback(new Error());
  15182. };
  15183. var encodeUsingUrlEncoding = function (data) {
  15184. if(typeof data === 'string') {
  15185. return data;
  15186. }
  15187. var result = [];
  15188. for(var dataItem in data) {
  15189. if(data.hasOwnProperty(dataItem)) {
  15190. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  15191. }
  15192. }
  15193. return result.join('&');
  15194. };
  15195. var utf8 = function (text) {
  15196. text = text.replace(/\r\n/g, '\n');
  15197. var result = '';
  15198. for(var i = 0; i < text.length; i++) {
  15199. var c = text.charCodeAt(i);
  15200. if(c < 128) {
  15201. result += String.fromCharCode(c);
  15202. } else if((c > 127) && (c < 2048)) {
  15203. result += String.fromCharCode((c >> 6) | 192);
  15204. result += String.fromCharCode((c & 63) | 128);
  15205. } else {
  15206. result += String.fromCharCode((c >> 12) | 224);
  15207. result += String.fromCharCode(((c >> 6) & 63) | 128);
  15208. result += String.fromCharCode((c & 63) | 128);
  15209. }
  15210. }
  15211. return result;
  15212. };
  15213. var base64 = function (text) {
  15214. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  15215. text = utf8(text);
  15216. var result = '',
  15217. chr1, chr2, chr3,
  15218. enc1, enc2, enc3, enc4,
  15219. i = 0;
  15220. do {
  15221. chr1 = text.charCodeAt(i++);
  15222. chr2 = text.charCodeAt(i++);
  15223. chr3 = text.charCodeAt(i++);
  15224. enc1 = chr1 >> 2;
  15225. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  15226. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  15227. enc4 = chr3 & 63;
  15228. if(isNaN(chr2)) {
  15229. enc3 = enc4 = 64;
  15230. } else if(isNaN(chr3)) {
  15231. enc4 = 64;
  15232. }
  15233. result +=
  15234. keyStr.charAt(enc1) +
  15235. keyStr.charAt(enc2) +
  15236. keyStr.charAt(enc3) +
  15237. keyStr.charAt(enc4);
  15238. chr1 = chr2 = chr3 = '';
  15239. enc1 = enc2 = enc3 = enc4 = '';
  15240. } while(i < text.length);
  15241. return result;
  15242. };
  15243. var mergeHeaders = function () {
  15244. // Use the first header object as base.
  15245. var result = arguments[0];
  15246. // Iterate through the remaining header objects and add them.
  15247. for(var i = 1; i < arguments.length; i++) {
  15248. var currentHeaders = arguments[i];
  15249. for(var header in currentHeaders) {
  15250. if(currentHeaders.hasOwnProperty(header)) {
  15251. result[header] = currentHeaders[header];
  15252. }
  15253. }
  15254. }
  15255. // Return the merged headers.
  15256. return result;
  15257. };
  15258. var ajax = function (method, url, options, callback) {
  15259. // Adjust parameters.
  15260. if(typeof options === 'function') {
  15261. callback = options;
  15262. options = {};
  15263. }
  15264. // Set default parameter values.
  15265. options.cache = options.cache || false;
  15266. options.data = options.data || {};
  15267. options.headers = options.headers || {};
  15268. options.jsonp = options.jsonp || false;
  15269. options.async = options.async === undefined ? true : options.async;
  15270. // Merge the various header objects.
  15271. var headers = mergeHeaders({
  15272. 'accept': '*/*',
  15273. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  15274. }, ajax.headers, options.headers);
  15275. // Encode the data according to the content-type.
  15276. var payload;
  15277. if (headers['content-type'] === 'application/json') {
  15278. payload = JSON.stringify(options.data);
  15279. } else {
  15280. payload = encodeUsingUrlEncoding(options.data);
  15281. }
  15282. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  15283. // if neccessary.
  15284. if(method === 'GET') {
  15285. // Setup the query string.
  15286. var queryString = [];
  15287. if(payload) {
  15288. queryString.push(payload);
  15289. payload = null;
  15290. }
  15291. // Handle caching.
  15292. if(!options.cache) {
  15293. queryString.push('_=' + (new Date()).getTime());
  15294. }
  15295. // If neccessary prepare the query string for a JSONP call.
  15296. if(options.jsonp) {
  15297. queryString.push('callback=' + options.jsonp);
  15298. queryString.push('jsonp=' + options.jsonp);
  15299. }
  15300. // Merge the query string and attach it to the url.
  15301. queryString = queryString.join('&');
  15302. if (queryString.length > 1) {
  15303. if (url.indexOf('?') > -1) {
  15304. url += '&' + queryString;
  15305. } else {
  15306. url += '?' + queryString;
  15307. }
  15308. }
  15309. // Make a JSONP call if neccessary.
  15310. if(options.jsonp) {
  15311. var head = document.getElementsByTagName('head')[0];
  15312. var script = document.createElement('script');
  15313. script.type = 'text/javascript';
  15314. script.src = url;
  15315. head.appendChild(script);
  15316. return;
  15317. }
  15318. }
  15319. // Since we got here, it is no JSONP request, so make a normal XHR request.
  15320. getXhr(function (err, xhr) {
  15321. if(err) return callback(err);
  15322. // Open the request.
  15323. xhr.open(method, url, options.async);
  15324. // Set the request headers.
  15325. for(var header in headers) {
  15326. if(headers.hasOwnProperty(header)) {
  15327. xhr.setRequestHeader(header, headers[header]);
  15328. }
  15329. }
  15330. // Handle the request events.
  15331. xhr.onreadystatechange = function () {
  15332. if(xhr.readyState === 4) {
  15333. var data = xhr.responseText || '';
  15334. // If no callback is given, return.
  15335. if(!callback) {
  15336. return;
  15337. }
  15338. // Return an object that provides access to the data as text and JSON.
  15339. callback(xhr.status, {
  15340. text: function () {
  15341. return data;
  15342. },
  15343. json: function () {
  15344. try {
  15345. return JSON.parse(data)
  15346. } catch (e) {
  15347. f.error('Can not parse JSON. URL: ' + url);
  15348. return {};
  15349. }
  15350. }
  15351. });
  15352. }
  15353. };
  15354. // Actually send the XHR request.
  15355. xhr.send(payload);
  15356. });
  15357. };
  15358. // Define the external interface.
  15359. var http = {
  15360. authBasic: function (username, password) {
  15361. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  15362. },
  15363. connect: function (url, options, callback) {
  15364. return ajax('CONNECT', url, options, callback);
  15365. },
  15366. del: function (url, options, callback) {
  15367. return ajax('DELETE', url, options, callback);
  15368. },
  15369. get: function (url, options, callback) {
  15370. return ajax('GET', url, options, callback);
  15371. },
  15372. head: function (url, options, callback) {
  15373. return ajax('HEAD', url, options, callback);
  15374. },
  15375. headers: function (headers) {
  15376. ajax.headers = headers || {};
  15377. },
  15378. isAllowed: function (url, verb, callback) {
  15379. this.options(url, function (status, data) {
  15380. callback(data.text().indexOf(verb) !== -1);
  15381. });
  15382. },
  15383. options: function (url, options, callback) {
  15384. return ajax('OPTIONS', url, options, callback);
  15385. },
  15386. patch: function (url, options, callback) {
  15387. return ajax('PATCH', url, options, callback);
  15388. },
  15389. post: function (url, options, callback) {
  15390. return ajax('POST', url, options, callback);
  15391. },
  15392. put: function (url, options, callback) {
  15393. return ajax('PUT', url, options, callback);
  15394. },
  15395. trace: function (url, options, callback) {
  15396. return ajax('TRACE', url, options, callback);
  15397. }
  15398. };
  15399. var methode = options.type ? options.type.toLowerCase() : 'get';
  15400. http[methode](options.url, options, function (status, data) {
  15401. // file: protocol always gives status code 0, so check for data
  15402. if (status === 200 || (status === 0 && data.text())) {
  15403. options.success(data.json(), status, null);
  15404. } else {
  15405. options.error(data.text(), status, null);
  15406. }
  15407. });
  15408. }
  15409. var _cookie = {
  15410. create: function(name,value,minutes,domain) {
  15411. var expires;
  15412. if (minutes) {
  15413. var date = new Date();
  15414. date.setTime(date.getTime()+(minutes*60*1000));
  15415. expires = "; expires="+date.toGMTString();
  15416. }
  15417. else expires = "";
  15418. domain = (domain)? "domain="+domain+";" : "";
  15419. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  15420. },
  15421. read: function(name) {
  15422. var nameEQ = name + "=";
  15423. var ca = document.cookie.split(';');
  15424. for(var i=0;i < ca.length;i++) {
  15425. var c = ca[i];
  15426. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  15427. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  15428. }
  15429. return null;
  15430. },
  15431. remove: function(name) {
  15432. this.create(name,"",-1);
  15433. }
  15434. };
  15435. var cookie_noop = {
  15436. create: function(name,value,minutes,domain) {},
  15437. read: function(name) { return null; },
  15438. remove: function(name) {}
  15439. };
  15440. // move dependent functions to a container so that
  15441. // they can be overriden easier in no jquery environment (node.js)
  15442. var f = {
  15443. extend: $ ? $.extend : _extend,
  15444. deepExtend: _deepExtend,
  15445. each: $ ? $.each : _each,
  15446. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  15447. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  15448. detectLanguage: detectLanguage,
  15449. escape: _escape,
  15450. log: function(str) {
  15451. if (o.debug && typeof console !== "undefined") console.log(str);
  15452. },
  15453. error: function(str) {
  15454. if (typeof console !== "undefined") console.error(str);
  15455. },
  15456. getCountyIndexOfLng: function(lng) {
  15457. var lng_index = 0;
  15458. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  15459. return lng_index;
  15460. },
  15461. toLanguages: function(lng) {
  15462. var log = this.log;
  15463. function applyCase(l) {
  15464. var ret = l;
  15465. if (typeof l === 'string' && l.indexOf('-') > -1) {
  15466. var parts = l.split('-');
  15467. ret = o.lowerCaseLng ?
  15468. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  15469. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  15470. } else {
  15471. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  15472. }
  15473. return ret;
  15474. }
  15475. var languages = [];
  15476. var whitelist = o.lngWhitelist || false;
  15477. var addLanguage = function(language){
  15478. //reject langs not whitelisted
  15479. if(!whitelist || whitelist.indexOf(language) > -1){
  15480. languages.push(language);
  15481. }else{
  15482. log('rejecting non-whitelisted language: ' + language);
  15483. }
  15484. };
  15485. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  15486. var parts = lng.split('-');
  15487. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  15488. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  15489. } else {
  15490. addLanguage(applyCase(lng));
  15491. }
  15492. for (var i = 0; i < o.fallbackLng.length; i++) {
  15493. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  15494. }
  15495. return languages;
  15496. },
  15497. regexEscape: function(str) {
  15498. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  15499. },
  15500. regexReplacementEscape: function(strOrFn) {
  15501. if (typeof strOrFn === 'string') {
  15502. return strOrFn.replace(/\$/g, "$$$$");
  15503. } else {
  15504. return strOrFn;
  15505. }
  15506. },
  15507. localStorage: {
  15508. setItem: function(key, value) {
  15509. if (window.localStorage) {
  15510. try {
  15511. window.localStorage.setItem(key, value);
  15512. } catch (e) {
  15513. f.log('failed to set value for key "' + key + '" to localStorage.');
  15514. }
  15515. }
  15516. }
  15517. }
  15518. };
  15519. function init(options, cb) {
  15520. if (typeof options === 'function') {
  15521. cb = options;
  15522. options = {};
  15523. }
  15524. options = options || {};
  15525. // override defaults with passed in options
  15526. f.extend(o, options);
  15527. delete o.fixLng; /* passed in each time */
  15528. // override functions: .log(), .detectLanguage(), etc
  15529. if (o.functions) {
  15530. delete o.functions;
  15531. f.extend(f, options.functions);
  15532. }
  15533. // create namespace object if namespace is passed in as string
  15534. if (typeof o.ns == 'string') {
  15535. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  15536. }
  15537. // fallback namespaces
  15538. if (typeof o.fallbackNS == 'string') {
  15539. o.fallbackNS = [o.fallbackNS];
  15540. }
  15541. // fallback languages
  15542. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  15543. o.fallbackLng = [o.fallbackLng];
  15544. }
  15545. // escape prefix/suffix
  15546. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  15547. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  15548. if (!o.lng) o.lng = f.detectLanguage();
  15549. languages = f.toLanguages(o.lng);
  15550. currentLng = languages[0];
  15551. f.log('currentLng set to: ' + currentLng);
  15552. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  15553. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  15554. }
  15555. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  15556. f.localStorage.setItem('i18next_lng', currentLng);
  15557. }
  15558. var lngTranslate = translate;
  15559. if (options.fixLng) {
  15560. lngTranslate = function(key, options) {
  15561. options = options || {};
  15562. options.lng = options.lng || lngTranslate.lng;
  15563. return translate(key, options);
  15564. };
  15565. lngTranslate.lng = currentLng;
  15566. }
  15567. pluralExtensions.setCurrentLng(currentLng);
  15568. // add JQuery extensions
  15569. if ($ && o.setJqueryExt) addJqueryFunct();
  15570. // jQuery deferred
  15571. var deferred;
  15572. if ($ && $.Deferred) {
  15573. deferred = $.Deferred();
  15574. }
  15575. // return immidiatly if res are passed in
  15576. if (o.resStore) {
  15577. resStore = o.resStore;
  15578. initialized = true;
  15579. if (cb) cb(lngTranslate);
  15580. if (deferred) deferred.resolve(lngTranslate);
  15581. if (deferred) return deferred.promise();
  15582. return;
  15583. }
  15584. // languages to load
  15585. var lngsToLoad = f.toLanguages(o.lng);
  15586. if (typeof o.preload === 'string') o.preload = [o.preload];
  15587. for (var i = 0, l = o.preload.length; i < l; i++) {
  15588. var pres = f.toLanguages(o.preload[i]);
  15589. for (var y = 0, len = pres.length; y < len; y++) {
  15590. if (lngsToLoad.indexOf(pres[y]) < 0) {
  15591. lngsToLoad.push(pres[y]);
  15592. }
  15593. }
  15594. }
  15595. // else load them
  15596. i18n.sync.load(lngsToLoad, o, function(err, store) {
  15597. resStore = store;
  15598. initialized = true;
  15599. if (cb) cb(lngTranslate);
  15600. if (deferred) deferred.resolve(lngTranslate);
  15601. });
  15602. if (deferred) return deferred.promise();
  15603. }
  15604. function preload(lngs, cb) {
  15605. if (typeof lngs === 'string') lngs = [lngs];
  15606. for (var i = 0, l = lngs.length; i < l; i++) {
  15607. if (o.preload.indexOf(lngs[i]) < 0) {
  15608. o.preload.push(lngs[i]);
  15609. }
  15610. }
  15611. return init(cb);
  15612. }
  15613. function addResourceBundle(lng, ns, resources, deep) {
  15614. if (typeof ns !== 'string') {
  15615. resources = ns;
  15616. ns = o.ns.defaultNs;
  15617. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  15618. o.ns.namespaces.push(ns);
  15619. }
  15620. resStore[lng] = resStore[lng] || {};
  15621. resStore[lng][ns] = resStore[lng][ns] || {};
  15622. if (deep) {
  15623. f.deepExtend(resStore[lng][ns], resources);
  15624. } else {
  15625. f.extend(resStore[lng][ns], resources);
  15626. }
  15627. }
  15628. function hasResourceBundle(lng, ns) {
  15629. if (typeof ns !== 'string') {
  15630. ns = o.ns.defaultNs;
  15631. }
  15632. resStore[lng] = resStore[lng] || {};
  15633. var res = resStore[lng][ns] || {};
  15634. var hasValues = false;
  15635. for(var prop in res) {
  15636. if (res.hasOwnProperty(prop)) {
  15637. hasValues = true;
  15638. }
  15639. }
  15640. return hasValues;
  15641. }
  15642. function removeResourceBundle(lng, ns) {
  15643. if (typeof ns !== 'string') {
  15644. ns = o.ns.defaultNs;
  15645. }
  15646. resStore[lng] = resStore[lng] || {};
  15647. resStore[lng][ns] = {};
  15648. }
  15649. function addResource(lng, ns, key, value) {
  15650. if (typeof ns !== 'string') {
  15651. resource = ns;
  15652. ns = o.ns.defaultNs;
  15653. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  15654. o.ns.namespaces.push(ns);
  15655. }
  15656. resStore[lng] = resStore[lng] || {};
  15657. resStore[lng][ns] = resStore[lng][ns] || {};
  15658. var keys = key.split(o.keyseparator);
  15659. var x = 0;
  15660. var node = resStore[lng][ns];
  15661. var origRef = node;
  15662. while (keys[x]) {
  15663. if (x == keys.length - 1)
  15664. node[keys[x]] = value;
  15665. else {
  15666. if (node[keys[x]] == null)
  15667. node[keys[x]] = {};
  15668. node = node[keys[x]];
  15669. }
  15670. x++;
  15671. }
  15672. }
  15673. function addResources(lng, ns, resources) {
  15674. if (typeof ns !== 'string') {
  15675. resource = ns;
  15676. ns = o.ns.defaultNs;
  15677. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  15678. o.ns.namespaces.push(ns);
  15679. }
  15680. for (var m in resources) {
  15681. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  15682. }
  15683. }
  15684. function setDefaultNamespace(ns) {
  15685. o.ns.defaultNs = ns;
  15686. }
  15687. function loadNamespace(namespace, cb) {
  15688. loadNamespaces([namespace], cb);
  15689. }
  15690. function loadNamespaces(namespaces, cb) {
  15691. var opts = {
  15692. dynamicLoad: o.dynamicLoad,
  15693. resGetPath: o.resGetPath,
  15694. getAsync: o.getAsync,
  15695. customLoad: o.customLoad,
  15696. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  15697. };
  15698. // languages to load
  15699. var lngsToLoad = f.toLanguages(o.lng);
  15700. if (typeof o.preload === 'string') o.preload = [o.preload];
  15701. for (var i = 0, l = o.preload.length; i < l; i++) {
  15702. var pres = f.toLanguages(o.preload[i]);
  15703. for (var y = 0, len = pres.length; y < len; y++) {
  15704. if (lngsToLoad.indexOf(pres[y]) < 0) {
  15705. lngsToLoad.push(pres[y]);
  15706. }
  15707. }
  15708. }
  15709. // check if we have to load
  15710. var lngNeedLoad = [];
  15711. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  15712. var needLoad = false;
  15713. var resSet = resStore[lngsToLoad[a]];
  15714. if (resSet) {
  15715. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  15716. if (!resSet[namespaces[b]]) needLoad = true;
  15717. }
  15718. } else {
  15719. needLoad = true;
  15720. }
  15721. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  15722. }
  15723. if (lngNeedLoad.length) {
  15724. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  15725. var todo = namespaces.length * lngNeedLoad.length;
  15726. // load each file individual
  15727. f.each(namespaces, function(nsIndex, nsValue) {
  15728. // append namespace to namespace array
  15729. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  15730. o.ns.namespaces.push(nsValue);
  15731. }
  15732. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  15733. resStore[lngValue] = resStore[lngValue] || {};
  15734. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  15735. todo--; // wait for all done befor callback
  15736. if (todo === 0 && cb) {
  15737. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  15738. cb();
  15739. }
  15740. });
  15741. });
  15742. });
  15743. } else {
  15744. if (cb) cb();
  15745. }
  15746. }
  15747. function setLng(lng, options, cb) {
  15748. if (typeof options === 'function') {
  15749. cb = options;
  15750. options = {};
  15751. } else if (!options) {
  15752. options = {};
  15753. }
  15754. options.lng = lng;
  15755. return init(options, cb);
  15756. }
  15757. function lng() {
  15758. return currentLng;
  15759. }
  15760. function reload(cb) {
  15761. resStore = {};
  15762. setLng(currentLng, cb);
  15763. }
  15764. function addJqueryFunct() {
  15765. // $.t shortcut
  15766. $.t = $.t || translate;
  15767. function parse(ele, key, options) {
  15768. if (key.length === 0) return;
  15769. var attr = 'text';
  15770. if (key.indexOf('[') === 0) {
  15771. var parts = key.split(']');
  15772. key = parts[1];
  15773. attr = parts[0].substr(1, parts[0].length-1);
  15774. }
  15775. if (key.indexOf(';') === key.length-1) {
  15776. key = key.substr(0, key.length-2);
  15777. }
  15778. var optionsToUse;
  15779. if (attr === 'html') {
  15780. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  15781. ele.html($.t(key, optionsToUse));
  15782. } else if (attr === 'text') {
  15783. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  15784. ele.text($.t(key, optionsToUse));
  15785. } else if (attr === 'prepend') {
  15786. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  15787. ele.prepend($.t(key, optionsToUse));
  15788. } else if (attr === 'append') {
  15789. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  15790. ele.append($.t(key, optionsToUse));
  15791. } else if (attr.indexOf("data-") === 0) {
  15792. var dataAttr = attr.substr(("data-").length);
  15793. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  15794. var translated = $.t(key, optionsToUse);
  15795. //we change into the data cache
  15796. ele.data(dataAttr, translated);
  15797. //we change into the dom
  15798. ele.attr(attr, translated);
  15799. } else {
  15800. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  15801. ele.attr(attr, $.t(key, optionsToUse));
  15802. }
  15803. }
  15804. function localize(ele, options) {
  15805. var key = ele.attr(o.selectorAttr);
  15806. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  15807. if (!key) return;
  15808. var target = ele
  15809. , targetSelector = ele.data("i18n-target");
  15810. if (targetSelector) {
  15811. target = ele.find(targetSelector) || ele;
  15812. }
  15813. if (!options && o.useDataAttrOptions === true) {
  15814. options = ele.data("i18n-options");
  15815. }
  15816. options = options || {};
  15817. if (key.indexOf(';') >= 0) {
  15818. var keys = key.split(';');
  15819. $.each(keys, function(m, k) {
  15820. if (k !== '') parse(target, k, options);
  15821. });
  15822. } else {
  15823. parse(target, key, options);
  15824. }
  15825. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  15826. }
  15827. // fn
  15828. $.fn.i18n = function (options) {
  15829. return this.each(function() {
  15830. // localize element itself
  15831. localize($(this), options);
  15832. // localize childs
  15833. var elements = $(this).find('[' + o.selectorAttr + ']');
  15834. elements.each(function() {
  15835. localize($(this), options);
  15836. });
  15837. });
  15838. };
  15839. }
  15840. function applyReplacement(str, replacementHash, nestedKey, options) {
  15841. if (!str) return str;
  15842. options = options || replacementHash; // first call uses replacement hash combined with options
  15843. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  15844. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  15845. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  15846. , unEscapingSuffix = 'HTML'+suffix;
  15847. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  15848. f.each(hash, function(key, value) {
  15849. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  15850. if (typeof value === 'object' && value !== null) {
  15851. str = applyReplacement(str, value, nextKey, options);
  15852. } else {
  15853. if (options.escapeInterpolation || o.escapeInterpolation) {
  15854. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  15855. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  15856. } else {
  15857. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  15858. }
  15859. // str = options.escapeInterpolation;
  15860. }
  15861. });
  15862. return str;
  15863. }
  15864. // append it to functions
  15865. f.applyReplacement = applyReplacement;
  15866. function applyReuse(translated, options) {
  15867. var comma = ',';
  15868. var options_open = '{';
  15869. var options_close = '}';
  15870. var opts = f.extend({}, options);
  15871. delete opts.postProcess;
  15872. while (translated.indexOf(o.reusePrefix) != -1) {
  15873. replacementCounter++;
  15874. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  15875. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  15876. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  15877. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  15878. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  15879. if (index_of_end_of_closing <= index_of_opening) {
  15880. f.error('there is an missing closing in following translation value', translated);
  15881. return '';
  15882. }
  15883. if (token_without_symbols.indexOf(comma) != -1) {
  15884. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  15885. 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) {
  15886. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  15887. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  15888. try {
  15889. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  15890. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  15891. } catch (e) {
  15892. }
  15893. }
  15894. }
  15895. var translated_token = _translate(token_without_symbols, opts);
  15896. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  15897. }
  15898. return translated;
  15899. }
  15900. function hasContext(options) {
  15901. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  15902. }
  15903. function needsPlural(options, lng) {
  15904. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  15905. }
  15906. function needsIndefiniteArticle(options) {
  15907. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  15908. }
  15909. function exists(key, options) {
  15910. options = options || {};
  15911. var notFound = _getDefaultValue(key, options)
  15912. , found = _find(key, options);
  15913. return found !== undefined || found === notFound;
  15914. }
  15915. function translate(key, options) {
  15916. options = options || {};
  15917. if (!initialized) {
  15918. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  15919. return options.defaultValue || '';
  15920. };
  15921. replacementCounter = 0;
  15922. return _translate.apply(null, arguments);
  15923. }
  15924. function _getDefaultValue(key, options) {
  15925. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  15926. }
  15927. function _injectSprintfProcessor() {
  15928. var values = [];
  15929. // mh: build array from second argument onwards
  15930. for (var i = 1; i < arguments.length; i++) {
  15931. values.push(arguments[i]);
  15932. }
  15933. return {
  15934. postProcess: 'sprintf',
  15935. sprintf: values
  15936. };
  15937. }
  15938. function _translate(potentialKeys, options) {
  15939. if (options && typeof options !== 'object') {
  15940. if (o.shortcutFunction === 'sprintf') {
  15941. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  15942. options = _injectSprintfProcessor.apply(null, arguments);
  15943. } else if (o.shortcutFunction === 'defaultValue') {
  15944. options = {
  15945. defaultValue: options
  15946. }
  15947. }
  15948. } else {
  15949. options = options || {};
  15950. }
  15951. if (typeof o.defaultVariables === 'object') {
  15952. options = f.extend({}, o.defaultVariables, options);
  15953. }
  15954. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  15955. if (typeof potentialKeys === 'string') {
  15956. potentialKeys = [potentialKeys];
  15957. }
  15958. var key = potentialKeys[0];
  15959. if (potentialKeys.length > 1) {
  15960. for (var i = 0; i < potentialKeys.length; i++) {
  15961. key = potentialKeys[i];
  15962. if (exists(key, options)) {
  15963. break;
  15964. }
  15965. }
  15966. }
  15967. var notFound = _getDefaultValue(key, options)
  15968. , found = _find(key, options)
  15969. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  15970. , ns = options.ns || o.ns.defaultNs
  15971. , parts;
  15972. // split ns and key
  15973. if (key.indexOf(o.nsseparator) > -1) {
  15974. parts = key.split(o.nsseparator);
  15975. ns = parts[0];
  15976. key = parts[1];
  15977. }
  15978. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  15979. if (options.lng) {
  15980. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  15981. } else {
  15982. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  15983. }
  15984. }
  15985. var postProcessor = options.postProcess || o.postProcess;
  15986. if (found !== undefined && postProcessor) {
  15987. if (postProcessors[postProcessor]) {
  15988. found = postProcessors[postProcessor](found, key, options);
  15989. }
  15990. }
  15991. // process notFound if function exists
  15992. var splitNotFound = notFound;
  15993. if (notFound.indexOf(o.nsseparator) > -1) {
  15994. parts = notFound.split(o.nsseparator);
  15995. splitNotFound = parts[1];
  15996. }
  15997. if (splitNotFound === key && o.parseMissingKey) {
  15998. notFound = o.parseMissingKey(notFound);
  15999. }
  16000. if (found === undefined) {
  16001. notFound = applyReplacement(notFound, options);
  16002. notFound = applyReuse(notFound, options);
  16003. if (postProcessor && postProcessors[postProcessor]) {
  16004. var val = _getDefaultValue(key, options);
  16005. found = postProcessors[postProcessor](val, key, options);
  16006. }
  16007. }
  16008. return (found !== undefined) ? found : notFound;
  16009. }
  16010. function _find(key, options) {
  16011. options = options || {};
  16012. var optionWithoutCount, translated
  16013. , notFound = _getDefaultValue(key, options)
  16014. , lngs = languages;
  16015. if (!resStore) { return notFound; } // no resStore to translate from
  16016. // CI mode
  16017. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  16018. // passed in lng
  16019. if (options.lngs) lngs = options.lngs;
  16020. if (options.lng) {
  16021. lngs = f.toLanguages(options.lng, options.fallbackLng);
  16022. if (!resStore[lngs[0]]) {
  16023. var oldAsync = o.getAsync;
  16024. o.getAsync = false;
  16025. i18n.sync.load(lngs, o, function(err, store) {
  16026. f.extend(resStore, store);
  16027. o.getAsync = oldAsync;
  16028. });
  16029. }
  16030. }
  16031. var ns = options.ns || o.ns.defaultNs;
  16032. if (key.indexOf(o.nsseparator) > -1) {
  16033. var parts = key.split(o.nsseparator);
  16034. ns = parts[0];
  16035. key = parts[1];
  16036. }
  16037. if (hasContext(options)) {
  16038. optionWithoutCount = f.extend({}, options);
  16039. delete optionWithoutCount.context;
  16040. optionWithoutCount.defaultValue = o.contextNotFound;
  16041. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  16042. translated = translate(contextKey, optionWithoutCount);
  16043. if (translated != o.contextNotFound) {
  16044. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  16045. } // else continue translation with original/nonContext key
  16046. }
  16047. if (needsPlural(options, lngs[0])) {
  16048. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  16049. delete optionWithoutCount.count;
  16050. delete optionWithoutCount.lng;
  16051. optionWithoutCount.defaultValue = o.pluralNotFound;
  16052. var pluralKey;
  16053. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  16054. pluralKey = ns + o.nsseparator + key;
  16055. } else {
  16056. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  16057. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  16058. if (pluralExtension >= 0) {
  16059. pluralKey = pluralKey + '_' + pluralExtension;
  16060. } else if (pluralExtension === 1) {
  16061. pluralKey = ns + o.nsseparator + key; // singular
  16062. }
  16063. }
  16064. translated = translate(pluralKey, optionWithoutCount);
  16065. if (translated != o.pluralNotFound) {
  16066. return applyReplacement(translated, {
  16067. count: options.count,
  16068. interpolationPrefix: options.interpolationPrefix,
  16069. interpolationSuffix: options.interpolationSuffix
  16070. }); // apply replacement for count only
  16071. } else if (lngs.length > 1) {
  16072. // remove failed lng
  16073. var clone = lngs.slice();
  16074. clone.shift();
  16075. options = f.extend(options, { lngs: clone });
  16076. delete options.lng;
  16077. // retry with fallbacks
  16078. translated = translate(ns + o.nsseparator + key, options);
  16079. if (translated != o.pluralNotFound) return translated;
  16080. } else {
  16081. return translated;
  16082. }
  16083. }
  16084. if (needsIndefiniteArticle(options)) {
  16085. var optionsWithoutIndef = f.extend({}, options);
  16086. delete optionsWithoutIndef.indefinite_article;
  16087. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  16088. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  16089. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  16090. translated = translate(indefiniteKey, optionsWithoutIndef);
  16091. if (translated != o.indefiniteNotFound) {
  16092. return translated;
  16093. }
  16094. }
  16095. var found;
  16096. var keys = key.split(o.keyseparator);
  16097. for (var i = 0, len = lngs.length; i < len; i++ ) {
  16098. if (found !== undefined) break;
  16099. var l = lngs[i];
  16100. var x = 0;
  16101. var value = resStore[l] && resStore[l][ns];
  16102. while (keys[x]) {
  16103. value = value && value[keys[x]];
  16104. x++;
  16105. }
  16106. if (value !== undefined) {
  16107. var valueType = Object.prototype.toString.apply(value);
  16108. if (typeof value === 'string') {
  16109. value = applyReplacement(value, options);
  16110. value = applyReuse(value, options);
  16111. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  16112. value = value.join('\n');
  16113. value = applyReplacement(value, options);
  16114. value = applyReuse(value, options);
  16115. } else if (value === null && o.fallbackOnNull === true) {
  16116. value = undefined;
  16117. } else if (value !== null) {
  16118. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  16119. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  16120. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  16121. } else {
  16122. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  16123. 'returned an object instead of string.';
  16124. f.log(value);
  16125. }
  16126. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  16127. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  16128. f.each(value, function(m) {
  16129. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  16130. });
  16131. value = copy;
  16132. }
  16133. }
  16134. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  16135. value = undefined;
  16136. found = value;
  16137. }
  16138. }
  16139. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  16140. // set flag for fallback lookup - avoid recursion
  16141. options.isFallbackLookup = true;
  16142. if (o.fallbackNS.length) {
  16143. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  16144. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  16145. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  16146. /* compare value without namespace */
  16147. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  16148. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  16149. if (foundValue !== notFoundValue) break;
  16150. }
  16151. }
  16152. } else {
  16153. found = _find(key, options); // fallback to default NS
  16154. }
  16155. options.isFallbackLookup = false;
  16156. }
  16157. return found;
  16158. }
  16159. function detectLanguage() {
  16160. var detectedLng;
  16161. var whitelist = o.lngWhitelist || [];
  16162. var userLngChoices = [];
  16163. // get from qs
  16164. var qsParm = [];
  16165. if (typeof window !== 'undefined') {
  16166. (function() {
  16167. var query = window.location.search.substring(1);
  16168. var params = query.split('&');
  16169. for (var i=0; i<params.length; i++) {
  16170. var pos = params[i].indexOf('=');
  16171. if (pos > 0) {
  16172. var key = params[i].substring(0,pos);
  16173. if (key == o.detectLngQS) {
  16174. userLngChoices.push(params[i].substring(pos+1));
  16175. }
  16176. }
  16177. }
  16178. })();
  16179. }
  16180. // get from cookie
  16181. if (o.useCookie && typeof document !== 'undefined') {
  16182. var c = f.cookie.read(o.cookieName);
  16183. if (c) userLngChoices.push(c);
  16184. }
  16185. // get from localStorage
  16186. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  16187. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  16188. }
  16189. // get from navigator
  16190. if (typeof navigator !== 'undefined') {
  16191. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  16192. for (var i=0;i<navigator.languages.length;i++) {
  16193. userLngChoices.push(navigator.languages[i]);
  16194. }
  16195. }
  16196. if (navigator.userLanguage) {
  16197. userLngChoices.push(navigator.userLanguage);
  16198. }
  16199. if (navigator.language) {
  16200. userLngChoices.push(navigator.language);
  16201. }
  16202. }
  16203. (function() {
  16204. for (var i=0;i<userLngChoices.length;i++) {
  16205. var lng = userLngChoices[i];
  16206. if (lng.indexOf('-') > -1) {
  16207. var parts = lng.split('-');
  16208. lng = o.lowerCaseLng ?
  16209. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  16210. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  16211. }
  16212. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  16213. detectedLng = lng;
  16214. break;
  16215. }
  16216. }
  16217. })();
  16218. //fallback
  16219. if (!detectedLng){
  16220. detectedLng = o.fallbackLng[0];
  16221. }
  16222. return detectedLng;
  16223. }
  16224. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  16225. /* [code, name, numbers, pluralsType] */
  16226. var _rules = [
  16227. ["ach", "Acholi", [1,2], 1],
  16228. ["af", "Afrikaans",[1,2], 2],
  16229. ["ak", "Akan", [1,2], 1],
  16230. ["am", "Amharic", [1,2], 1],
  16231. ["an", "Aragonese",[1,2], 2],
  16232. ["ar", "Arabic", [0,1,2,3,11,100],5],
  16233. ["arn", "Mapudungun",[1,2], 1],
  16234. ["ast", "Asturian", [1,2], 2],
  16235. ["ay", "Aymará", [1], 3],
  16236. ["az", "Azerbaijani",[1,2],2],
  16237. ["be", "Belarusian",[1,2,5],4],
  16238. ["bg", "Bulgarian",[1,2], 2],
  16239. ["bn", "Bengali", [1,2], 2],
  16240. ["bo", "Tibetan", [1], 3],
  16241. ["br", "Breton", [1,2], 1],
  16242. ["bs", "Bosnian", [1,2,5],4],
  16243. ["ca", "Catalan", [1,2], 2],
  16244. ["cgg", "Chiga", [1], 3],
  16245. ["cs", "Czech", [1,2,5],6],
  16246. ["csb", "Kashubian",[1,2,5],7],
  16247. ["cy", "Welsh", [1,2,3,8],8],
  16248. ["da", "Danish", [1,2], 2],
  16249. ["de", "German", [1,2], 2],
  16250. ["dev", "Development Fallback", [1,2], 2],
  16251. ["dz", "Dzongkha", [1], 3],
  16252. ["el", "Greek", [1,2], 2],
  16253. ["en", "English", [1,2], 2],
  16254. ["eo", "Esperanto",[1,2], 2],
  16255. ["es", "Spanish", [1,2], 2],
  16256. ["es_ar","Argentinean Spanish", [1,2], 2],
  16257. ["et", "Estonian", [1,2], 2],
  16258. ["eu", "Basque", [1,2], 2],
  16259. ["fa", "Persian", [1], 3],
  16260. ["fi", "Finnish", [1,2], 2],
  16261. ["fil", "Filipino", [1,2], 1],
  16262. ["fo", "Faroese", [1,2], 2],
  16263. ["fr", "French", [1,2], 9],
  16264. ["fur", "Friulian", [1,2], 2],
  16265. ["fy", "Frisian", [1,2], 2],
  16266. ["ga", "Irish", [1,2,3,7,11],10],
  16267. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  16268. ["gl", "Galician", [1,2], 2],
  16269. ["gu", "Gujarati", [1,2], 2],
  16270. ["gun", "Gun", [1,2], 1],
  16271. ["ha", "Hausa", [1,2], 2],
  16272. ["he", "Hebrew", [1,2], 2],
  16273. ["hi", "Hindi", [1,2], 2],
  16274. ["hr", "Croatian", [1,2,5],4],
  16275. ["hu", "Hungarian",[1,2], 2],
  16276. ["hy", "Armenian", [1,2], 2],
  16277. ["ia", "Interlingua",[1,2],2],
  16278. ["id", "Indonesian",[1], 3],
  16279. ["is", "Icelandic",[1,2], 12],
  16280. ["it", "Italian", [1,2], 2],
  16281. ["ja", "Japanese", [1], 3],
  16282. ["jbo", "Lojban", [1], 3],
  16283. ["jv", "Javanese", [0,1], 13],
  16284. ["ka", "Georgian", [1], 3],
  16285. ["kk", "Kazakh", [1], 3],
  16286. ["km", "Khmer", [1], 3],
  16287. ["kn", "Kannada", [1,2], 2],
  16288. ["ko", "Korean", [1], 3],
  16289. ["ku", "Kurdish", [1,2], 2],
  16290. ["kw", "Cornish", [1,2,3,4],14],
  16291. ["ky", "Kyrgyz", [1], 3],
  16292. ["lb", "Letzeburgesch",[1,2],2],
  16293. ["ln", "Lingala", [1,2], 1],
  16294. ["lo", "Lao", [1], 3],
  16295. ["lt", "Lithuanian",[1,2,10],15],
  16296. ["lv", "Latvian", [1,2,0],16],
  16297. ["mai", "Maithili", [1,2], 2],
  16298. ["mfe", "Mauritian Creole",[1,2],1],
  16299. ["mg", "Malagasy", [1,2], 1],
  16300. ["mi", "Maori", [1,2], 1],
  16301. ["mk", "Macedonian",[1,2],17],
  16302. ["ml", "Malayalam",[1,2], 2],
  16303. ["mn", "Mongolian",[1,2], 2],
  16304. ["mnk", "Mandinka", [0,1,2],18],
  16305. ["mr", "Marathi", [1,2], 2],
  16306. ["ms", "Malay", [1], 3],
  16307. ["mt", "Maltese", [1,2,11,20],19],
  16308. ["nah", "Nahuatl", [1,2], 2],
  16309. ["nap", "Neapolitan",[1,2], 2],
  16310. ["nb", "Norwegian Bokmal",[1,2],2],
  16311. ["ne", "Nepali", [1,2], 2],
  16312. ["nl", "Dutch", [1,2], 2],
  16313. ["nn", "Norwegian Nynorsk",[1,2],2],
  16314. ["no", "Norwegian",[1,2], 2],
  16315. ["nso", "Northern Sotho",[1,2],2],
  16316. ["oc", "Occitan", [1,2], 1],
  16317. ["or", "Oriya", [2,1], 2],
  16318. ["pa", "Punjabi", [1,2], 2],
  16319. ["pap", "Papiamento",[1,2], 2],
  16320. ["pl", "Polish", [1,2,5],7],
  16321. ["pms", "Piemontese",[1,2], 2],
  16322. ["ps", "Pashto", [1,2], 2],
  16323. ["pt", "Portuguese",[1,2], 2],
  16324. ["pt_br","Brazilian Portuguese",[1,2], 2],
  16325. ["rm", "Romansh", [1,2], 2],
  16326. ["ro", "Romanian", [1,2,20],20],
  16327. ["ru", "Russian", [1,2,5],4],
  16328. ["sah", "Yakut", [1], 3],
  16329. ["sco", "Scots", [1,2], 2],
  16330. ["se", "Northern Sami",[1,2], 2],
  16331. ["si", "Sinhala", [1,2], 2],
  16332. ["sk", "Slovak", [1,2,5],6],
  16333. ["sl", "Slovenian",[5,1,2,3],21],
  16334. ["so", "Somali", [1,2], 2],
  16335. ["son", "Songhay", [1,2], 2],
  16336. ["sq", "Albanian", [1,2], 2],
  16337. ["sr", "Serbian", [1,2,5],4],
  16338. ["su", "Sundanese",[1], 3],
  16339. ["sv", "Swedish", [1,2], 2],
  16340. ["sw", "Swahili", [1,2], 2],
  16341. ["ta", "Tamil", [1,2], 2],
  16342. ["te", "Telugu", [1,2], 2],
  16343. ["tg", "Tajik", [1,2], 1],
  16344. ["th", "Thai", [1], 3],
  16345. ["ti", "Tigrinya", [1,2], 1],
  16346. ["tk", "Turkmen", [1,2], 2],
  16347. ["tr", "Turkish", [1,2], 1],
  16348. ["tt", "Tatar", [1], 3],
  16349. ["ug", "Uyghur", [1], 3],
  16350. ["uk", "Ukrainian",[1,2,5],4],
  16351. ["ur", "Urdu", [1,2], 2],
  16352. ["uz", "Uzbek", [1,2], 1],
  16353. ["vi", "Vietnamese",[1], 3],
  16354. ["wa", "Walloon", [1,2], 1],
  16355. ["wo", "Wolof", [1], 3],
  16356. ["yo", "Yoruba", [1,2], 2],
  16357. ["zh", "Chinese", [1], 3]
  16358. ];
  16359. var _rulesPluralsTypes = {
  16360. 1: function(n) {return Number(n > 1);},
  16361. 2: function(n) {return Number(n != 1);},
  16362. 3: function(n) {return 0;},
  16363. 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);},
  16364. 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);},
  16365. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  16366. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  16367. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  16368. 9: function(n) {return Number(n >= 2);},
  16369. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  16370. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  16371. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  16372. 13: function(n) {return Number(n !== 0);},
  16373. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  16374. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  16375. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  16376. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  16377. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  16378. 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);},
  16379. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  16380. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  16381. };
  16382. var pluralExtensions = {
  16383. rules: (function () {
  16384. var l, rules = {};
  16385. for (l=_rules.length; l-- ;) {
  16386. rules[_rules[l][0]] = {
  16387. name: _rules[l][1],
  16388. numbers: _rules[l][2],
  16389. plurals: _rulesPluralsTypes[_rules[l][3]]
  16390. }
  16391. }
  16392. return rules;
  16393. }()),
  16394. // you can add your own pluralExtensions
  16395. addRule: function(lng, obj) {
  16396. pluralExtensions.rules[lng] = obj;
  16397. },
  16398. setCurrentLng: function(lng) {
  16399. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  16400. var parts = lng.split('-');
  16401. pluralExtensions.currentRule = {
  16402. lng: lng,
  16403. rule: pluralExtensions.rules[parts[0]]
  16404. };
  16405. }
  16406. },
  16407. needsPlural: function(lng, count) {
  16408. var parts = lng.split('-');
  16409. var ext;
  16410. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  16411. ext = pluralExtensions.currentRule.rule;
  16412. } else {
  16413. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  16414. }
  16415. if (ext && ext.numbers.length <= 1) {
  16416. return false;
  16417. } else {
  16418. return this.get(lng, count) !== 1;
  16419. }
  16420. },
  16421. get: function(lng, count) {
  16422. var parts = lng.split('-');
  16423. function getResult(l, c) {
  16424. var ext;
  16425. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  16426. ext = pluralExtensions.currentRule.rule;
  16427. } else {
  16428. ext = pluralExtensions.rules[l];
  16429. }
  16430. if (ext) {
  16431. var i;
  16432. if (ext.noAbs) {
  16433. i = ext.plurals(c);
  16434. } else {
  16435. i = ext.plurals(Math.abs(c));
  16436. }
  16437. var number = ext.numbers[i];
  16438. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  16439. if (number === 2) {
  16440. number = -1; // regular plural
  16441. } else if (number === 1) {
  16442. number = 1; // singular
  16443. }
  16444. }//console.log(count + '-' + number);
  16445. return number;
  16446. } else {
  16447. return c === 1 ? '1' : '-1';
  16448. }
  16449. }
  16450. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  16451. }
  16452. };
  16453. var postProcessors = {};
  16454. var addPostProcessor = function(name, fc) {
  16455. postProcessors[name] = fc;
  16456. };
  16457. // sprintf support
  16458. var sprintf = (function() {
  16459. function get_type(variable) {
  16460. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  16461. }
  16462. function str_repeat(input, multiplier) {
  16463. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  16464. return output.join('');
  16465. }
  16466. var str_format = function() {
  16467. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  16468. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  16469. }
  16470. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  16471. };
  16472. str_format.format = function(parse_tree, argv) {
  16473. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  16474. for (i = 0; i < tree_length; i++) {
  16475. node_type = get_type(parse_tree[i]);
  16476. if (node_type === 'string') {
  16477. output.push(parse_tree[i]);
  16478. }
  16479. else if (node_type === 'array') {
  16480. match = parse_tree[i]; // convenience purposes only
  16481. if (match[2]) { // keyword argument
  16482. arg = argv[cursor];
  16483. for (k = 0; k < match[2].length; k++) {
  16484. if (!arg.hasOwnProperty(match[2][k])) {
  16485. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  16486. }
  16487. arg = arg[match[2][k]];
  16488. }
  16489. }
  16490. else if (match[1]) { // positional argument (explicit)
  16491. arg = argv[match[1]];
  16492. }
  16493. else { // positional argument (implicit)
  16494. arg = argv[cursor++];
  16495. }
  16496. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  16497. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  16498. }
  16499. switch (match[8]) {
  16500. case 'b': arg = arg.toString(2); break;
  16501. case 'c': arg = String.fromCharCode(arg); break;
  16502. case 'd': arg = parseInt(arg, 10); break;
  16503. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  16504. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  16505. case 'o': arg = arg.toString(8); break;
  16506. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  16507. case 'u': arg = Math.abs(arg); break;
  16508. case 'x': arg = arg.toString(16); break;
  16509. case 'X': arg = arg.toString(16).toUpperCase(); break;
  16510. }
  16511. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  16512. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  16513. pad_length = match[6] - String(arg).length;
  16514. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  16515. output.push(match[5] ? arg + pad : pad + arg);
  16516. }
  16517. }
  16518. return output.join('');
  16519. };
  16520. str_format.cache = {};
  16521. str_format.parse = function(fmt) {
  16522. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  16523. while (_fmt) {
  16524. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  16525. parse_tree.push(match[0]);
  16526. }
  16527. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  16528. parse_tree.push('%');
  16529. }
  16530. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  16531. if (match[2]) {
  16532. arg_names |= 1;
  16533. var field_list = [], replacement_field = match[2], field_match = [];
  16534. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  16535. field_list.push(field_match[1]);
  16536. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  16537. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  16538. field_list.push(field_match[1]);
  16539. }
  16540. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  16541. field_list.push(field_match[1]);
  16542. }
  16543. else {
  16544. throw('[sprintf] huh?');
  16545. }
  16546. }
  16547. }
  16548. else {
  16549. throw('[sprintf] huh?');
  16550. }
  16551. match[2] = field_list;
  16552. }
  16553. else {
  16554. arg_names |= 2;
  16555. }
  16556. if (arg_names === 3) {
  16557. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  16558. }
  16559. parse_tree.push(match);
  16560. }
  16561. else {
  16562. throw('[sprintf] huh?');
  16563. }
  16564. _fmt = _fmt.substring(match[0].length);
  16565. }
  16566. return parse_tree;
  16567. };
  16568. return str_format;
  16569. })();
  16570. var vsprintf = function(fmt, argv) {
  16571. argv.unshift(fmt);
  16572. return sprintf.apply(null, argv);
  16573. };
  16574. addPostProcessor("sprintf", function(val, key, opts) {
  16575. if (!opts.sprintf) return val;
  16576. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  16577. return vsprintf(val, opts.sprintf);
  16578. } else if (typeof opts.sprintf === 'object') {
  16579. return sprintf(val, opts.sprintf);
  16580. }
  16581. return val;
  16582. });
  16583. // public api interface
  16584. i18n.init = init;
  16585. i18n.setLng = setLng;
  16586. i18n.preload = preload;
  16587. i18n.addResourceBundle = addResourceBundle;
  16588. i18n.hasResourceBundle = hasResourceBundle;
  16589. i18n.addResource = addResource;
  16590. i18n.addResources = addResources;
  16591. i18n.removeResourceBundle = removeResourceBundle;
  16592. i18n.loadNamespace = loadNamespace;
  16593. i18n.loadNamespaces = loadNamespaces;
  16594. i18n.setDefaultNamespace = setDefaultNamespace;
  16595. i18n.t = translate;
  16596. i18n.translate = translate;
  16597. i18n.exists = exists;
  16598. i18n.detectLanguage = f.detectLanguage;
  16599. i18n.pluralExtensions = pluralExtensions;
  16600. i18n.sync = sync;
  16601. i18n.functions = f;
  16602. i18n.lng = lng;
  16603. i18n.addPostProcessor = addPostProcessor;
  16604. i18n.options = o;
  16605. })();
  16606. },{"jquery":"jquery"}],62:[function(require,module,exports){
  16607. // Top level file is just a mixin of submodules & constants
  16608. 'use strict';
  16609. var assign = require('./lib/utils/common').assign;
  16610. var deflate = require('./lib/deflate');
  16611. var inflate = require('./lib/inflate');
  16612. var constants = require('./lib/zlib/constants');
  16613. var pako = {};
  16614. assign(pako, deflate, inflate, constants);
  16615. module.exports = pako;
  16616. },{"./lib/deflate":63,"./lib/inflate":64,"./lib/utils/common":65,"./lib/zlib/constants":68}],63:[function(require,module,exports){
  16617. 'use strict';
  16618. var zlib_deflate = require('./zlib/deflate.js');
  16619. var utils = require('./utils/common');
  16620. var strings = require('./utils/strings');
  16621. var msg = require('./zlib/messages');
  16622. var zstream = require('./zlib/zstream');
  16623. /* Public constants ==========================================================*/
  16624. /* ===========================================================================*/
  16625. var Z_NO_FLUSH = 0;
  16626. var Z_FINISH = 4;
  16627. var Z_OK = 0;
  16628. var Z_STREAM_END = 1;
  16629. var Z_DEFAULT_COMPRESSION = -1;
  16630. var Z_DEFAULT_STRATEGY = 0;
  16631. var Z_DEFLATED = 8;
  16632. /* ===========================================================================*/
  16633. /**
  16634. * class Deflate
  16635. *
  16636. * Generic JS-style wrapper for zlib calls. If you don't need
  16637. * streaming behaviour - use more simple functions: [[deflate]],
  16638. * [[deflateRaw]] and [[gzip]].
  16639. **/
  16640. /* internal
  16641. * Deflate.chunks -> Array
  16642. *
  16643. * Chunks of output data, if [[Deflate#onData]] not overriden.
  16644. **/
  16645. /**
  16646. * Deflate.result -> Uint8Array|Array
  16647. *
  16648. * Compressed result, generated by default [[Deflate#onData]]
  16649. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  16650. * (call [[Deflate#push]] with `Z_FINISH` / `true` param).
  16651. **/
  16652. /**
  16653. * Deflate.err -> Number
  16654. *
  16655. * Error code after deflate finished. 0 (Z_OK) on success.
  16656. * You will not need it in real life, because deflate errors
  16657. * are possible only on wrong options or bad `onData` / `onEnd`
  16658. * custom handlers.
  16659. **/
  16660. /**
  16661. * Deflate.msg -> String
  16662. *
  16663. * Error message, if [[Deflate.err]] != 0
  16664. **/
  16665. /**
  16666. * new Deflate(options)
  16667. * - options (Object): zlib deflate options.
  16668. *
  16669. * Creates new deflator instance with specified params. Throws exception
  16670. * on bad params. Supported options:
  16671. *
  16672. * - `level`
  16673. * - `windowBits`
  16674. * - `memLevel`
  16675. * - `strategy`
  16676. *
  16677. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  16678. * for more information on these.
  16679. *
  16680. * Additional options, for internal needs:
  16681. *
  16682. * - `chunkSize` - size of generated data chunks (16K by default)
  16683. * - `raw` (Boolean) - do raw deflate
  16684. * - `gzip` (Boolean) - create gzip wrapper
  16685. * - `to` (String) - if equal to 'string', then result will be "binary string"
  16686. * (each char code [0..255])
  16687. * - `header` (Object) - custom header for gzip
  16688. * - `text` (Boolean) - true if compressed data believed to be text
  16689. * - `time` (Number) - modification time, unix timestamp
  16690. * - `os` (Number) - operation system code
  16691. * - `extra` (Array) - array of bytes with extra data (max 65536)
  16692. * - `name` (String) - file name (binary string)
  16693. * - `comment` (String) - comment (binary string)
  16694. * - `hcrc` (Boolean) - true if header crc should be added
  16695. *
  16696. * ##### Example:
  16697. *
  16698. * ```javascript
  16699. * var pako = require('pako')
  16700. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  16701. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  16702. *
  16703. * var deflate = new pako.Deflate({ level: 3});
  16704. *
  16705. * deflate.push(chunk1, false);
  16706. * deflate.push(chunk2, true); // true -> last chunk
  16707. *
  16708. * if (deflate.err) { throw new Error(deflate.err); }
  16709. *
  16710. * console.log(deflate.result);
  16711. * ```
  16712. **/
  16713. var Deflate = function(options) {
  16714. this.options = utils.assign({
  16715. level: Z_DEFAULT_COMPRESSION,
  16716. method: Z_DEFLATED,
  16717. chunkSize: 16384,
  16718. windowBits: 15,
  16719. memLevel: 8,
  16720. strategy: Z_DEFAULT_STRATEGY,
  16721. to: ''
  16722. }, options || {});
  16723. var opt = this.options;
  16724. if (opt.raw && (opt.windowBits > 0)) {
  16725. opt.windowBits = -opt.windowBits;
  16726. }
  16727. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  16728. opt.windowBits += 16;
  16729. }
  16730. this.err = 0; // error code, if happens (0 = Z_OK)
  16731. this.msg = ''; // error message
  16732. this.ended = false; // used to avoid multiple onEnd() calls
  16733. this.chunks = []; // chunks of compressed data
  16734. this.strm = new zstream();
  16735. this.strm.avail_out = 0;
  16736. var status = zlib_deflate.deflateInit2(
  16737. this.strm,
  16738. opt.level,
  16739. opt.method,
  16740. opt.windowBits,
  16741. opt.memLevel,
  16742. opt.strategy
  16743. );
  16744. if (status !== Z_OK) {
  16745. throw new Error(msg[status]);
  16746. }
  16747. if (opt.header) {
  16748. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  16749. }
  16750. };
  16751. /**
  16752. * Deflate#push(data[, mode]) -> Boolean
  16753. * - data (Uint8Array|Array|String): input data. Strings will be converted to
  16754. * utf8 byte sequence.
  16755. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  16756. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  16757. *
  16758. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  16759. * new compressed chunks. Returns `true` on success. The last data block must have
  16760. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  16761. * [[Deflate#onEnd]].
  16762. *
  16763. * On fail call [[Deflate#onEnd]] with error code and return false.
  16764. *
  16765. * We strongly recommend to use `Uint8Array` on input for best speed (output
  16766. * array format is detected automatically). Also, don't skip last param and always
  16767. * use the same type in your code (boolean or number). That will improve JS speed.
  16768. *
  16769. * For regular `Array`-s make sure all elements are [0..255].
  16770. *
  16771. * ##### Example
  16772. *
  16773. * ```javascript
  16774. * push(chunk, false); // push one of data chunks
  16775. * ...
  16776. * push(chunk, true); // push last chunk
  16777. * ```
  16778. **/
  16779. Deflate.prototype.push = function(data, mode) {
  16780. var strm = this.strm;
  16781. var chunkSize = this.options.chunkSize;
  16782. var status, _mode;
  16783. if (this.ended) { return false; }
  16784. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  16785. // Convert data if needed
  16786. if (typeof data === 'string') {
  16787. // If we need to compress text, change encoding to utf8.
  16788. strm.input = strings.string2buf(data);
  16789. } else {
  16790. strm.input = data;
  16791. }
  16792. strm.next_in = 0;
  16793. strm.avail_in = strm.input.length;
  16794. do {
  16795. if (strm.avail_out === 0) {
  16796. strm.output = new utils.Buf8(chunkSize);
  16797. strm.next_out = 0;
  16798. strm.avail_out = chunkSize;
  16799. }
  16800. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  16801. if (status !== Z_STREAM_END && status !== Z_OK) {
  16802. this.onEnd(status);
  16803. this.ended = true;
  16804. return false;
  16805. }
  16806. if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) {
  16807. if (this.options.to === 'string') {
  16808. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  16809. } else {
  16810. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  16811. }
  16812. }
  16813. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  16814. // Finalize on the last chunk.
  16815. if (_mode === Z_FINISH) {
  16816. status = zlib_deflate.deflateEnd(this.strm);
  16817. this.onEnd(status);
  16818. this.ended = true;
  16819. return status === Z_OK;
  16820. }
  16821. return true;
  16822. };
  16823. /**
  16824. * Deflate#onData(chunk) -> Void
  16825. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  16826. * on js engine support. When string output requested, each chunk
  16827. * will be string.
  16828. *
  16829. * By default, stores data blocks in `chunks[]` property and glue
  16830. * those in `onEnd`. Override this handler, if you need another behaviour.
  16831. **/
  16832. Deflate.prototype.onData = function(chunk) {
  16833. this.chunks.push(chunk);
  16834. };
  16835. /**
  16836. * Deflate#onEnd(status) -> Void
  16837. * - status (Number): deflate status. 0 (Z_OK) on success,
  16838. * other if not.
  16839. *
  16840. * Called once after you tell deflate that input stream complete
  16841. * or error happenned. By default - join collected chunks,
  16842. * free memory and fill `results` / `err` properties.
  16843. **/
  16844. Deflate.prototype.onEnd = function(status) {
  16845. // On success - join
  16846. if (status === Z_OK) {
  16847. if (this.options.to === 'string') {
  16848. this.result = this.chunks.join('');
  16849. } else {
  16850. this.result = utils.flattenChunks(this.chunks);
  16851. }
  16852. }
  16853. this.chunks = [];
  16854. this.err = status;
  16855. this.msg = this.strm.msg;
  16856. };
  16857. /**
  16858. * deflate(data[, options]) -> Uint8Array|Array|String
  16859. * - data (Uint8Array|Array|String): input data to compress.
  16860. * - options (Object): zlib deflate options.
  16861. *
  16862. * Compress `data` with deflate alrorythm and `options`.
  16863. *
  16864. * Supported options are:
  16865. *
  16866. * - level
  16867. * - windowBits
  16868. * - memLevel
  16869. * - strategy
  16870. *
  16871. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  16872. * for more information on these.
  16873. *
  16874. * Sugar (options):
  16875. *
  16876. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  16877. * negative windowBits implicitly.
  16878. * - `to` (String) - if equal to 'string', then result will be "binary string"
  16879. * (each char code [0..255])
  16880. *
  16881. * ##### Example:
  16882. *
  16883. * ```javascript
  16884. * var pako = require('pako')
  16885. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  16886. *
  16887. * console.log(pako.deflate(data));
  16888. * ```
  16889. **/
  16890. function deflate(input, options) {
  16891. var deflator = new Deflate(options);
  16892. deflator.push(input, true);
  16893. // That will never happens, if you don't cheat with options :)
  16894. if (deflator.err) { throw deflator.msg; }
  16895. return deflator.result;
  16896. }
  16897. /**
  16898. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  16899. * - data (Uint8Array|Array|String): input data to compress.
  16900. * - options (Object): zlib deflate options.
  16901. *
  16902. * The same as [[deflate]], but creates raw data, without wrapper
  16903. * (header and adler32 crc).
  16904. **/
  16905. function deflateRaw(input, options) {
  16906. options = options || {};
  16907. options.raw = true;
  16908. return deflate(input, options);
  16909. }
  16910. /**
  16911. * gzip(data[, options]) -> Uint8Array|Array|String
  16912. * - data (Uint8Array|Array|String): input data to compress.
  16913. * - options (Object): zlib deflate options.
  16914. *
  16915. * The same as [[deflate]], but create gzip wrapper instead of
  16916. * deflate one.
  16917. **/
  16918. function gzip(input, options) {
  16919. options = options || {};
  16920. options.gzip = true;
  16921. return deflate(input, options);
  16922. }
  16923. exports.Deflate = Deflate;
  16924. exports.deflate = deflate;
  16925. exports.deflateRaw = deflateRaw;
  16926. exports.gzip = gzip;
  16927. },{"./utils/common":65,"./utils/strings":66,"./zlib/deflate.js":70,"./zlib/messages":75,"./zlib/zstream":77}],64:[function(require,module,exports){
  16928. 'use strict';
  16929. var zlib_inflate = require('./zlib/inflate.js');
  16930. var utils = require('./utils/common');
  16931. var strings = require('./utils/strings');
  16932. var c = require('./zlib/constants');
  16933. var msg = require('./zlib/messages');
  16934. var zstream = require('./zlib/zstream');
  16935. var gzheader = require('./zlib/gzheader');
  16936. /**
  16937. * class Inflate
  16938. *
  16939. * Generic JS-style wrapper for zlib calls. If you don't need
  16940. * streaming behaviour - use more simple functions: [[inflate]]
  16941. * and [[inflateRaw]].
  16942. **/
  16943. /* internal
  16944. * inflate.chunks -> Array
  16945. *
  16946. * Chunks of output data, if [[Inflate#onData]] not overriden.
  16947. **/
  16948. /**
  16949. * Inflate.result -> Uint8Array|Array|String
  16950. *
  16951. * Uncompressed result, generated by default [[Inflate#onData]]
  16952. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  16953. * (call [[Inflate#push]] with `Z_FINISH` / `true` param).
  16954. **/
  16955. /**
  16956. * Inflate.err -> Number
  16957. *
  16958. * Error code after inflate finished. 0 (Z_OK) on success.
  16959. * Should be checked if broken data possible.
  16960. **/
  16961. /**
  16962. * Inflate.msg -> String
  16963. *
  16964. * Error message, if [[Inflate.err]] != 0
  16965. **/
  16966. /**
  16967. * new Inflate(options)
  16968. * - options (Object): zlib inflate options.
  16969. *
  16970. * Creates new inflator instance with specified params. Throws exception
  16971. * on bad params. Supported options:
  16972. *
  16973. * - `windowBits`
  16974. *
  16975. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  16976. * for more information on these.
  16977. *
  16978. * Additional options, for internal needs:
  16979. *
  16980. * - `chunkSize` - size of generated data chunks (16K by default)
  16981. * - `raw` (Boolean) - do raw inflate
  16982. * - `to` (String) - if equal to 'string', then result will be converted
  16983. * from utf8 to utf16 (javascript) string. When string output requested,
  16984. * chunk length can differ from `chunkSize`, depending on content.
  16985. *
  16986. * By default, when no options set, autodetect deflate/gzip data format via
  16987. * wrapper header.
  16988. *
  16989. * ##### Example:
  16990. *
  16991. * ```javascript
  16992. * var pako = require('pako')
  16993. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  16994. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  16995. *
  16996. * var inflate = new pako.Inflate({ level: 3});
  16997. *
  16998. * inflate.push(chunk1, false);
  16999. * inflate.push(chunk2, true); // true -> last chunk
  17000. *
  17001. * if (inflate.err) { throw new Error(inflate.err); }
  17002. *
  17003. * console.log(inflate.result);
  17004. * ```
  17005. **/
  17006. var Inflate = function(options) {
  17007. this.options = utils.assign({
  17008. chunkSize: 16384,
  17009. windowBits: 0,
  17010. to: ''
  17011. }, options || {});
  17012. var opt = this.options;
  17013. // Force window size for `raw` data, if not set directly,
  17014. // because we have no header for autodetect.
  17015. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  17016. opt.windowBits = -opt.windowBits;
  17017. if (opt.windowBits === 0) { opt.windowBits = -15; }
  17018. }
  17019. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  17020. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  17021. !(options && options.windowBits)) {
  17022. opt.windowBits += 32;
  17023. }
  17024. // Gzip header has no info about windows size, we can do autodetect only
  17025. // for deflate. So, if window size not set, force it to max when gzip possible
  17026. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  17027. // bit 3 (16) -> gzipped data
  17028. // bit 4 (32) -> autodetect gzip/deflate
  17029. if ((opt.windowBits & 15) === 0) {
  17030. opt.windowBits |= 15;
  17031. }
  17032. }
  17033. this.err = 0; // error code, if happens (0 = Z_OK)
  17034. this.msg = ''; // error message
  17035. this.ended = false; // used to avoid multiple onEnd() calls
  17036. this.chunks = []; // chunks of compressed data
  17037. this.strm = new zstream();
  17038. this.strm.avail_out = 0;
  17039. var status = zlib_inflate.inflateInit2(
  17040. this.strm,
  17041. opt.windowBits
  17042. );
  17043. if (status !== c.Z_OK) {
  17044. throw new Error(msg[status]);
  17045. }
  17046. this.header = new gzheader();
  17047. zlib_inflate.inflateGetHeader(this.strm, this.header);
  17048. };
  17049. /**
  17050. * Inflate#push(data[, mode]) -> Boolean
  17051. * - data (Uint8Array|Array|String): input data
  17052. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  17053. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  17054. *
  17055. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  17056. * new output chunks. Returns `true` on success. The last data block must have
  17057. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  17058. * [[Inflate#onEnd]].
  17059. *
  17060. * On fail call [[Inflate#onEnd]] with error code and return false.
  17061. *
  17062. * We strongly recommend to use `Uint8Array` on input for best speed (output
  17063. * format is detected automatically). Also, don't skip last param and always
  17064. * use the same type in your code (boolean or number). That will improve JS speed.
  17065. *
  17066. * For regular `Array`-s make sure all elements are [0..255].
  17067. *
  17068. * ##### Example
  17069. *
  17070. * ```javascript
  17071. * push(chunk, false); // push one of data chunks
  17072. * ...
  17073. * push(chunk, true); // push last chunk
  17074. * ```
  17075. **/
  17076. Inflate.prototype.push = function(data, mode) {
  17077. var strm = this.strm;
  17078. var chunkSize = this.options.chunkSize;
  17079. var status, _mode;
  17080. var next_out_utf8, tail, utf8str;
  17081. if (this.ended) { return false; }
  17082. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  17083. // Convert data if needed
  17084. if (typeof data === 'string') {
  17085. // Only binary strings can be decompressed on practice
  17086. strm.input = strings.binstring2buf(data);
  17087. } else {
  17088. strm.input = data;
  17089. }
  17090. strm.next_in = 0;
  17091. strm.avail_in = strm.input.length;
  17092. do {
  17093. if (strm.avail_out === 0) {
  17094. strm.output = new utils.Buf8(chunkSize);
  17095. strm.next_out = 0;
  17096. strm.avail_out = chunkSize;
  17097. }
  17098. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  17099. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  17100. this.onEnd(status);
  17101. this.ended = true;
  17102. return false;
  17103. }
  17104. if (strm.next_out) {
  17105. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) {
  17106. if (this.options.to === 'string') {
  17107. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  17108. tail = strm.next_out - next_out_utf8;
  17109. utf8str = strings.buf2string(strm.output, next_out_utf8);
  17110. // move tail
  17111. strm.next_out = tail;
  17112. strm.avail_out = chunkSize - tail;
  17113. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  17114. this.onData(utf8str);
  17115. } else {
  17116. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  17117. }
  17118. }
  17119. }
  17120. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  17121. if (status === c.Z_STREAM_END) {
  17122. _mode = c.Z_FINISH;
  17123. }
  17124. // Finalize on the last chunk.
  17125. if (_mode === c.Z_FINISH) {
  17126. status = zlib_inflate.inflateEnd(this.strm);
  17127. this.onEnd(status);
  17128. this.ended = true;
  17129. return status === c.Z_OK;
  17130. }
  17131. return true;
  17132. };
  17133. /**
  17134. * Inflate#onData(chunk) -> Void
  17135. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  17136. * on js engine support. When string output requested, each chunk
  17137. * will be string.
  17138. *
  17139. * By default, stores data blocks in `chunks[]` property and glue
  17140. * those in `onEnd`. Override this handler, if you need another behaviour.
  17141. **/
  17142. Inflate.prototype.onData = function(chunk) {
  17143. this.chunks.push(chunk);
  17144. };
  17145. /**
  17146. * Inflate#onEnd(status) -> Void
  17147. * - status (Number): inflate status. 0 (Z_OK) on success,
  17148. * other if not.
  17149. *
  17150. * Called once after you tell inflate that input stream complete
  17151. * or error happenned. By default - join collected chunks,
  17152. * free memory and fill `results` / `err` properties.
  17153. **/
  17154. Inflate.prototype.onEnd = function(status) {
  17155. // On success - join
  17156. if (status === c.Z_OK) {
  17157. if (this.options.to === 'string') {
  17158. // Glue & convert here, until we teach pako to send
  17159. // utf8 alligned strings to onData
  17160. this.result = this.chunks.join('');
  17161. } else {
  17162. this.result = utils.flattenChunks(this.chunks);
  17163. }
  17164. }
  17165. this.chunks = [];
  17166. this.err = status;
  17167. this.msg = this.strm.msg;
  17168. };
  17169. /**
  17170. * inflate(data[, options]) -> Uint8Array|Array|String
  17171. * - data (Uint8Array|Array|String): input data to decompress.
  17172. * - options (Object): zlib inflate options.
  17173. *
  17174. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  17175. * format via wrapper header by default. That's why we don't provide
  17176. * separate `ungzip` method.
  17177. *
  17178. * Supported options are:
  17179. *
  17180. * - windowBits
  17181. *
  17182. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17183. * for more information.
  17184. *
  17185. * Sugar (options):
  17186. *
  17187. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  17188. * negative windowBits implicitly.
  17189. * - `to` (String) - if equal to 'string', then result will be converted
  17190. * from utf8 to utf16 (javascript) string. When string output requested,
  17191. * chunk length can differ from `chunkSize`, depending on content.
  17192. *
  17193. *
  17194. * ##### Example:
  17195. *
  17196. * ```javascript
  17197. * var pako = require('pako')
  17198. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  17199. * , output;
  17200. *
  17201. * try {
  17202. * output = pako.inflate(input);
  17203. * } catch (err)
  17204. * console.log(err);
  17205. * }
  17206. * ```
  17207. **/
  17208. function inflate(input, options) {
  17209. var inflator = new Inflate(options);
  17210. inflator.push(input, true);
  17211. // That will never happens, if you don't cheat with options :)
  17212. if (inflator.err) { throw inflator.msg; }
  17213. return inflator.result;
  17214. }
  17215. /**
  17216. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  17217. * - data (Uint8Array|Array|String): input data to decompress.
  17218. * - options (Object): zlib inflate options.
  17219. *
  17220. * The same as [[inflate]], but creates raw data, without wrapper
  17221. * (header and adler32 crc).
  17222. **/
  17223. function inflateRaw(input, options) {
  17224. options = options || {};
  17225. options.raw = true;
  17226. return inflate(input, options);
  17227. }
  17228. /**
  17229. * ungzip(data[, options]) -> Uint8Array|Array|String
  17230. * - data (Uint8Array|Array|String): input data to decompress.
  17231. * - options (Object): zlib inflate options.
  17232. *
  17233. * Just shortcut to [[inflate]], because it autodetects format
  17234. * by header.content. Done for convenience.
  17235. **/
  17236. exports.Inflate = Inflate;
  17237. exports.inflate = inflate;
  17238. exports.inflateRaw = inflateRaw;
  17239. exports.ungzip = inflate;
  17240. },{"./utils/common":65,"./utils/strings":66,"./zlib/constants":68,"./zlib/gzheader":71,"./zlib/inflate.js":73,"./zlib/messages":75,"./zlib/zstream":77}],65:[function(require,module,exports){
  17241. 'use strict';
  17242. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  17243. (typeof Uint16Array !== 'undefined') &&
  17244. (typeof Int32Array !== 'undefined');
  17245. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  17246. var sources = Array.prototype.slice.call(arguments, 1);
  17247. while (sources.length) {
  17248. var source = sources.shift();
  17249. if (!source) { continue; }
  17250. if (typeof(source) !== 'object') {
  17251. throw new TypeError(source + 'must be non-object');
  17252. }
  17253. for (var p in source) {
  17254. if (source.hasOwnProperty(p)) {
  17255. obj[p] = source[p];
  17256. }
  17257. }
  17258. }
  17259. return obj;
  17260. };
  17261. // reduce buffer size, avoiding mem copy
  17262. exports.shrinkBuf = function (buf, size) {
  17263. if (buf.length === size) { return buf; }
  17264. if (buf.subarray) { return buf.subarray(0, size); }
  17265. buf.length = size;
  17266. return buf;
  17267. };
  17268. var fnTyped = {
  17269. arraySet: function (dest, src, src_offs, len, dest_offs) {
  17270. if (src.subarray && dest.subarray) {
  17271. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  17272. return;
  17273. }
  17274. // Fallback to ordinary array
  17275. for(var i=0; i<len; i++) {
  17276. dest[dest_offs + i] = src[src_offs + i];
  17277. }
  17278. },
  17279. // Join array of chunks to single array.
  17280. flattenChunks: function(chunks) {
  17281. var i, l, len, pos, chunk, result;
  17282. // calculate data length
  17283. len = 0;
  17284. for (i=0, l=chunks.length; i<l; i++) {
  17285. len += chunks[i].length;
  17286. }
  17287. // join chunks
  17288. result = new Uint8Array(len);
  17289. pos = 0;
  17290. for (i=0, l=chunks.length; i<l; i++) {
  17291. chunk = chunks[i];
  17292. result.set(chunk, pos);
  17293. pos += chunk.length;
  17294. }
  17295. return result;
  17296. }
  17297. };
  17298. var fnUntyped = {
  17299. arraySet: function (dest, src, src_offs, len, dest_offs) {
  17300. for(var i=0; i<len; i++) {
  17301. dest[dest_offs + i] = src[src_offs + i];
  17302. }
  17303. },
  17304. // Join array of chunks to single array.
  17305. flattenChunks: function(chunks) {
  17306. return [].concat.apply([], chunks);
  17307. }
  17308. };
  17309. // Enable/Disable typed arrays use, for testing
  17310. //
  17311. exports.setTyped = function (on) {
  17312. if (on) {
  17313. exports.Buf8 = Uint8Array;
  17314. exports.Buf16 = Uint16Array;
  17315. exports.Buf32 = Int32Array;
  17316. exports.assign(exports, fnTyped);
  17317. } else {
  17318. exports.Buf8 = Array;
  17319. exports.Buf16 = Array;
  17320. exports.Buf32 = Array;
  17321. exports.assign(exports, fnUntyped);
  17322. }
  17323. };
  17324. exports.setTyped(TYPED_OK);
  17325. },{}],66:[function(require,module,exports){
  17326. // String encode/decode helpers
  17327. 'use strict';
  17328. var utils = require('./common');
  17329. // Quick check if we can use fast array to bin string conversion
  17330. //
  17331. // - apply(Array) can fail on Android 2.2
  17332. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  17333. //
  17334. var STR_APPLY_OK = true;
  17335. var STR_APPLY_UIA_OK = true;
  17336. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  17337. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  17338. // Table with utf8 lengths (calculated by first byte of sequence)
  17339. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  17340. // because max possible codepoint is 0x10ffff
  17341. var _utf8len = new utils.Buf8(256);
  17342. for (var i=0; i<256; i++) {
  17343. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  17344. }
  17345. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  17346. // convert string to array (typed, when possible)
  17347. exports.string2buf = function (str) {
  17348. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  17349. // count binary size
  17350. for (m_pos = 0; m_pos < str_len; m_pos++) {
  17351. c = str.charCodeAt(m_pos);
  17352. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  17353. c2 = str.charCodeAt(m_pos+1);
  17354. if ((c2 & 0xfc00) === 0xdc00) {
  17355. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  17356. m_pos++;
  17357. }
  17358. }
  17359. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  17360. }
  17361. // allocate buffer
  17362. buf = new utils.Buf8(buf_len);
  17363. // convert
  17364. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  17365. c = str.charCodeAt(m_pos);
  17366. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  17367. c2 = str.charCodeAt(m_pos+1);
  17368. if ((c2 & 0xfc00) === 0xdc00) {
  17369. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  17370. m_pos++;
  17371. }
  17372. }
  17373. if (c < 0x80) {
  17374. /* one byte */
  17375. buf[i++] = c;
  17376. } else if (c < 0x800) {
  17377. /* two bytes */
  17378. buf[i++] = 0xC0 | (c >>> 6);
  17379. buf[i++] = 0x80 | (c & 0x3f);
  17380. } else if (c < 0x10000) {
  17381. /* three bytes */
  17382. buf[i++] = 0xE0 | (c >>> 12);
  17383. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  17384. buf[i++] = 0x80 | (c & 0x3f);
  17385. } else {
  17386. /* four bytes */
  17387. buf[i++] = 0xf0 | (c >>> 18);
  17388. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  17389. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  17390. buf[i++] = 0x80 | (c & 0x3f);
  17391. }
  17392. }
  17393. return buf;
  17394. };
  17395. // Helper (used in 2 places)
  17396. function buf2binstring(buf, len) {
  17397. // use fallback for big arrays to avoid stack overflow
  17398. if (len < 65537) {
  17399. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  17400. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  17401. }
  17402. }
  17403. var result = '';
  17404. for(var i=0; i < len; i++) {
  17405. result += String.fromCharCode(buf[i]);
  17406. }
  17407. return result;
  17408. }
  17409. // Convert byte array to binary string
  17410. exports.buf2binstring = function(buf) {
  17411. return buf2binstring(buf, buf.length);
  17412. };
  17413. // Convert binary string (typed, when possible)
  17414. exports.binstring2buf = function(str) {
  17415. var buf = new utils.Buf8(str.length);
  17416. for(var i=0, len=buf.length; i < len; i++) {
  17417. buf[i] = str.charCodeAt(i);
  17418. }
  17419. return buf;
  17420. };
  17421. // convert array to string
  17422. exports.buf2string = function (buf, max) {
  17423. var i, out, c, c_len;
  17424. var len = max || buf.length;
  17425. // Reserve max possible length (2 words per char)
  17426. // NB: by unknown reasons, Array is significantly faster for
  17427. // String.fromCharCode.apply than Uint16Array.
  17428. var utf16buf = new Array(len*2);
  17429. for (out=0, i=0; i<len;) {
  17430. c = buf[i++];
  17431. // quick process ascii
  17432. if (c < 0x80) { utf16buf[out++] = c; continue; }
  17433. c_len = _utf8len[c];
  17434. // skip 5 & 6 byte codes
  17435. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  17436. // apply mask on first byte
  17437. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  17438. // join the rest
  17439. while (c_len > 1 && i < len) {
  17440. c = (c << 6) | (buf[i++] & 0x3f);
  17441. c_len--;
  17442. }
  17443. // terminated by end of string?
  17444. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  17445. if (c < 0x10000) {
  17446. utf16buf[out++] = c;
  17447. } else {
  17448. c -= 0x10000;
  17449. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  17450. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  17451. }
  17452. }
  17453. return buf2binstring(utf16buf, out);
  17454. };
  17455. // Calculate max possible position in utf8 buffer,
  17456. // that will not break sequence. If that's not possible
  17457. // - (very small limits) return max size as is.
  17458. //
  17459. // buf[] - utf8 bytes array
  17460. // max - length limit (mandatory);
  17461. exports.utf8border = function(buf, max) {
  17462. var pos;
  17463. max = max || buf.length;
  17464. if (max > buf.length) { max = buf.length; }
  17465. // go back from last position, until start of sequence found
  17466. pos = max-1;
  17467. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  17468. // Fuckup - very small and broken sequence,
  17469. // return max, because we should return something anyway.
  17470. if (pos < 0) { return max; }
  17471. // If we came to start of buffer - that means vuffer is too small,
  17472. // return max too.
  17473. if (pos === 0) { return max; }
  17474. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  17475. };
  17476. },{"./common":65}],67:[function(require,module,exports){
  17477. 'use strict';
  17478. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  17479. // It doesn't worth to make additional optimizationa as in original.
  17480. // Small size is preferable.
  17481. function adler32(adler, buf, len, pos) {
  17482. var s1 = (adler & 0xffff) |0
  17483. , s2 = ((adler >>> 16) & 0xffff) |0
  17484. , n = 0;
  17485. while (len !== 0) {
  17486. // Set limit ~ twice less than 5552, to keep
  17487. // s2 in 31-bits, because we force signed ints.
  17488. // in other case %= will fail.
  17489. n = len > 2000 ? 2000 : len;
  17490. len -= n;
  17491. do {
  17492. s1 = (s1 + buf[pos++]) |0;
  17493. s2 = (s2 + s1) |0;
  17494. } while (--n);
  17495. s1 %= 65521;
  17496. s2 %= 65521;
  17497. }
  17498. return (s1 | (s2 << 16)) |0;
  17499. }
  17500. module.exports = adler32;
  17501. },{}],68:[function(require,module,exports){
  17502. module.exports = {
  17503. /* Allowed flush values; see deflate() and inflate() below for details */
  17504. Z_NO_FLUSH: 0,
  17505. Z_PARTIAL_FLUSH: 1,
  17506. Z_SYNC_FLUSH: 2,
  17507. Z_FULL_FLUSH: 3,
  17508. Z_FINISH: 4,
  17509. Z_BLOCK: 5,
  17510. Z_TREES: 6,
  17511. /* Return codes for the compression/decompression functions. Negative values
  17512. * are errors, positive values are used for special but normal events.
  17513. */
  17514. Z_OK: 0,
  17515. Z_STREAM_END: 1,
  17516. Z_NEED_DICT: 2,
  17517. Z_ERRNO: -1,
  17518. Z_STREAM_ERROR: -2,
  17519. Z_DATA_ERROR: -3,
  17520. //Z_MEM_ERROR: -4,
  17521. Z_BUF_ERROR: -5,
  17522. //Z_VERSION_ERROR: -6,
  17523. /* compression levels */
  17524. Z_NO_COMPRESSION: 0,
  17525. Z_BEST_SPEED: 1,
  17526. Z_BEST_COMPRESSION: 9,
  17527. Z_DEFAULT_COMPRESSION: -1,
  17528. Z_FILTERED: 1,
  17529. Z_HUFFMAN_ONLY: 2,
  17530. Z_RLE: 3,
  17531. Z_FIXED: 4,
  17532. Z_DEFAULT_STRATEGY: 0,
  17533. /* Possible values of the data_type field (though see inflate()) */
  17534. Z_BINARY: 0,
  17535. Z_TEXT: 1,
  17536. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  17537. Z_UNKNOWN: 2,
  17538. /* The deflate compression method */
  17539. Z_DEFLATED: 8
  17540. //Z_NULL: null // Use -1 or null inline, depending on var type
  17541. };
  17542. },{}],69:[function(require,module,exports){
  17543. 'use strict';
  17544. // Note: we can't get significant speed boost here.
  17545. // So write code to minimize size - no pregenerated tables
  17546. // and array tools dependencies.
  17547. // Use ordinary array, since untyped makes no boost here
  17548. function makeTable() {
  17549. var c, table = [];
  17550. for(var n =0; n < 256; n++){
  17551. c = n;
  17552. for(var k =0; k < 8; k++){
  17553. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  17554. }
  17555. table[n] = c;
  17556. }
  17557. return table;
  17558. }
  17559. // Create table on load. Just 255 signed longs. Not a problem.
  17560. var crcTable = makeTable();
  17561. function crc32(crc, buf, len, pos) {
  17562. var t = crcTable
  17563. , end = pos + len;
  17564. crc = crc ^ (-1);
  17565. for (var i = pos; i < end; i++ ) {
  17566. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  17567. }
  17568. return (crc ^ (-1)); // >>> 0;
  17569. }
  17570. module.exports = crc32;
  17571. },{}],70:[function(require,module,exports){
  17572. 'use strict';
  17573. var utils = require('../utils/common');
  17574. var trees = require('./trees');
  17575. var adler32 = require('./adler32');
  17576. var crc32 = require('./crc32');
  17577. var msg = require('./messages');
  17578. /* Public constants ==========================================================*/
  17579. /* ===========================================================================*/
  17580. /* Allowed flush values; see deflate() and inflate() below for details */
  17581. var Z_NO_FLUSH = 0;
  17582. var Z_PARTIAL_FLUSH = 1;
  17583. //var Z_SYNC_FLUSH = 2;
  17584. var Z_FULL_FLUSH = 3;
  17585. var Z_FINISH = 4;
  17586. var Z_BLOCK = 5;
  17587. //var Z_TREES = 6;
  17588. /* Return codes for the compression/decompression functions. Negative values
  17589. * are errors, positive values are used for special but normal events.
  17590. */
  17591. var Z_OK = 0;
  17592. var Z_STREAM_END = 1;
  17593. //var Z_NEED_DICT = 2;
  17594. //var Z_ERRNO = -1;
  17595. var Z_STREAM_ERROR = -2;
  17596. var Z_DATA_ERROR = -3;
  17597. //var Z_MEM_ERROR = -4;
  17598. var Z_BUF_ERROR = -5;
  17599. //var Z_VERSION_ERROR = -6;
  17600. /* compression levels */
  17601. //var Z_NO_COMPRESSION = 0;
  17602. //var Z_BEST_SPEED = 1;
  17603. //var Z_BEST_COMPRESSION = 9;
  17604. var Z_DEFAULT_COMPRESSION = -1;
  17605. var Z_FILTERED = 1;
  17606. var Z_HUFFMAN_ONLY = 2;
  17607. var Z_RLE = 3;
  17608. var Z_FIXED = 4;
  17609. var Z_DEFAULT_STRATEGY = 0;
  17610. /* Possible values of the data_type field (though see inflate()) */
  17611. //var Z_BINARY = 0;
  17612. //var Z_TEXT = 1;
  17613. //var Z_ASCII = 1; // = Z_TEXT
  17614. var Z_UNKNOWN = 2;
  17615. /* The deflate compression method */
  17616. var Z_DEFLATED = 8;
  17617. /*============================================================================*/
  17618. var MAX_MEM_LEVEL = 9;
  17619. /* Maximum value for memLevel in deflateInit2 */
  17620. var MAX_WBITS = 15;
  17621. /* 32K LZ77 window */
  17622. var DEF_MEM_LEVEL = 8;
  17623. var LENGTH_CODES = 29;
  17624. /* number of length codes, not counting the special END_BLOCK code */
  17625. var LITERALS = 256;
  17626. /* number of literal bytes 0..255 */
  17627. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  17628. /* number of Literal or Length codes, including the END_BLOCK code */
  17629. var D_CODES = 30;
  17630. /* number of distance codes */
  17631. var BL_CODES = 19;
  17632. /* number of codes used to transfer the bit lengths */
  17633. var HEAP_SIZE = 2*L_CODES + 1;
  17634. /* maximum heap size */
  17635. var MAX_BITS = 15;
  17636. /* All codes must not exceed MAX_BITS bits */
  17637. var MIN_MATCH = 3;
  17638. var MAX_MATCH = 258;
  17639. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  17640. var PRESET_DICT = 0x20;
  17641. var INIT_STATE = 42;
  17642. var EXTRA_STATE = 69;
  17643. var NAME_STATE = 73;
  17644. var COMMENT_STATE = 91;
  17645. var HCRC_STATE = 103;
  17646. var BUSY_STATE = 113;
  17647. var FINISH_STATE = 666;
  17648. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  17649. var BS_BLOCK_DONE = 2; /* block flush performed */
  17650. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  17651. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  17652. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  17653. function err(strm, errorCode) {
  17654. strm.msg = msg[errorCode];
  17655. return errorCode;
  17656. }
  17657. function rank(f) {
  17658. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  17659. }
  17660. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  17661. /* =========================================================================
  17662. * Flush as much pending output as possible. All deflate() output goes
  17663. * through this function so some applications may wish to modify it
  17664. * to avoid allocating a large strm->output buffer and copying into it.
  17665. * (See also read_buf()).
  17666. */
  17667. function flush_pending(strm) {
  17668. var s = strm.state;
  17669. //_tr_flush_bits(s);
  17670. var len = s.pending;
  17671. if (len > strm.avail_out) {
  17672. len = strm.avail_out;
  17673. }
  17674. if (len === 0) { return; }
  17675. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  17676. strm.next_out += len;
  17677. s.pending_out += len;
  17678. strm.total_out += len;
  17679. strm.avail_out -= len;
  17680. s.pending -= len;
  17681. if (s.pending === 0) {
  17682. s.pending_out = 0;
  17683. }
  17684. }
  17685. function flush_block_only (s, last) {
  17686. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  17687. s.block_start = s.strstart;
  17688. flush_pending(s.strm);
  17689. }
  17690. function put_byte(s, b) {
  17691. s.pending_buf[s.pending++] = b;
  17692. }
  17693. /* =========================================================================
  17694. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  17695. * IN assertion: the stream state is correct and there is enough room in
  17696. * pending_buf.
  17697. */
  17698. function putShortMSB(s, b) {
  17699. // put_byte(s, (Byte)(b >> 8));
  17700. // put_byte(s, (Byte)(b & 0xff));
  17701. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  17702. s.pending_buf[s.pending++] = b & 0xff;
  17703. }
  17704. /* ===========================================================================
  17705. * Read a new buffer from the current input stream, update the adler32
  17706. * and total number of bytes read. All deflate() input goes through
  17707. * this function so some applications may wish to modify it to avoid
  17708. * allocating a large strm->input buffer and copying from it.
  17709. * (See also flush_pending()).
  17710. */
  17711. function read_buf(strm, buf, start, size) {
  17712. var len = strm.avail_in;
  17713. if (len > size) { len = size; }
  17714. if (len === 0) { return 0; }
  17715. strm.avail_in -= len;
  17716. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  17717. if (strm.state.wrap === 1) {
  17718. strm.adler = adler32(strm.adler, buf, len, start);
  17719. }
  17720. else if (strm.state.wrap === 2) {
  17721. strm.adler = crc32(strm.adler, buf, len, start);
  17722. }
  17723. strm.next_in += len;
  17724. strm.total_in += len;
  17725. return len;
  17726. }
  17727. /* ===========================================================================
  17728. * Set match_start to the longest match starting at the given string and
  17729. * return its length. Matches shorter or equal to prev_length are discarded,
  17730. * in which case the result is equal to prev_length and match_start is
  17731. * garbage.
  17732. * IN assertions: cur_match is the head of the hash chain for the current
  17733. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  17734. * OUT assertion: the match length is not greater than s->lookahead.
  17735. */
  17736. function longest_match(s, cur_match) {
  17737. var chain_length = s.max_chain_length; /* max hash chain length */
  17738. var scan = s.strstart; /* current string */
  17739. var match; /* matched string */
  17740. var len; /* length of current match */
  17741. var best_len = s.prev_length; /* best match length so far */
  17742. var nice_match = s.nice_match; /* stop if match long enough */
  17743. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  17744. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  17745. var _win = s.window; // shortcut
  17746. var wmask = s.w_mask;
  17747. var prev = s.prev;
  17748. /* Stop when cur_match becomes <= limit. To simplify the code,
  17749. * we prevent matches with the string of window index 0.
  17750. */
  17751. var strend = s.strstart + MAX_MATCH;
  17752. var scan_end1 = _win[scan + best_len - 1];
  17753. var scan_end = _win[scan + best_len];
  17754. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  17755. * It is easy to get rid of this optimization if necessary.
  17756. */
  17757. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  17758. /* Do not waste too much time if we already have a good match: */
  17759. if (s.prev_length >= s.good_match) {
  17760. chain_length >>= 2;
  17761. }
  17762. /* Do not look for matches beyond the end of the input. This is necessary
  17763. * to make deflate deterministic.
  17764. */
  17765. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  17766. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  17767. do {
  17768. // Assert(cur_match < s->strstart, "no future");
  17769. match = cur_match;
  17770. /* Skip to next match if the match length cannot increase
  17771. * or if the match length is less than 2. Note that the checks below
  17772. * for insufficient lookahead only occur occasionally for performance
  17773. * reasons. Therefore uninitialized memory will be accessed, and
  17774. * conditional jumps will be made that depend on those values.
  17775. * However the length of the match is limited to the lookahead, so
  17776. * the output of deflate is not affected by the uninitialized values.
  17777. */
  17778. if (_win[match + best_len] !== scan_end ||
  17779. _win[match + best_len - 1] !== scan_end1 ||
  17780. _win[match] !== _win[scan] ||
  17781. _win[++match] !== _win[scan + 1]) {
  17782. continue;
  17783. }
  17784. /* The check at best_len-1 can be removed because it will be made
  17785. * again later. (This heuristic is not always a win.)
  17786. * It is not necessary to compare scan[2] and match[2] since they
  17787. * are always equal when the other bytes match, given that
  17788. * the hash keys are equal and that HASH_BITS >= 8.
  17789. */
  17790. scan += 2;
  17791. match++;
  17792. // Assert(*scan == *match, "match[2]?");
  17793. /* We check for insufficient lookahead only every 8th comparison;
  17794. * the 256th check will be made at strstart+258.
  17795. */
  17796. do {
  17797. /*jshint noempty:false*/
  17798. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  17799. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  17800. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  17801. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  17802. scan < strend);
  17803. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  17804. len = MAX_MATCH - (strend - scan);
  17805. scan = strend - MAX_MATCH;
  17806. if (len > best_len) {
  17807. s.match_start = cur_match;
  17808. best_len = len;
  17809. if (len >= nice_match) {
  17810. break;
  17811. }
  17812. scan_end1 = _win[scan + best_len - 1];
  17813. scan_end = _win[scan + best_len];
  17814. }
  17815. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  17816. if (best_len <= s.lookahead) {
  17817. return best_len;
  17818. }
  17819. return s.lookahead;
  17820. }
  17821. /* ===========================================================================
  17822. * Fill the window when the lookahead becomes insufficient.
  17823. * Updates strstart and lookahead.
  17824. *
  17825. * IN assertion: lookahead < MIN_LOOKAHEAD
  17826. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  17827. * At least one byte has been read, or avail_in == 0; reads are
  17828. * performed for at least two bytes (required for the zip translate_eol
  17829. * option -- not supported here).
  17830. */
  17831. function fill_window(s) {
  17832. var _w_size = s.w_size;
  17833. var p, n, m, more, str;
  17834. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  17835. do {
  17836. more = s.window_size - s.lookahead - s.strstart;
  17837. // JS ints have 32 bit, block below not needed
  17838. /* Deal with !@#$% 64K limit: */
  17839. //if (sizeof(int) <= 2) {
  17840. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  17841. // more = wsize;
  17842. //
  17843. // } else if (more == (unsigned)(-1)) {
  17844. // /* Very unlikely, but possible on 16 bit machine if
  17845. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  17846. // */
  17847. // more--;
  17848. // }
  17849. //}
  17850. /* If the window is almost full and there is insufficient lookahead,
  17851. * move the upper half to the lower one to make room in the upper half.
  17852. */
  17853. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  17854. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  17855. s.match_start -= _w_size;
  17856. s.strstart -= _w_size;
  17857. /* we now have strstart >= MAX_DIST */
  17858. s.block_start -= _w_size;
  17859. /* Slide the hash table (could be avoided with 32 bit values
  17860. at the expense of memory usage). We slide even when level == 0
  17861. to keep the hash table consistent if we switch back to level > 0
  17862. later. (Using level 0 permanently is not an optimal usage of
  17863. zlib, so we don't care about this pathological case.)
  17864. */
  17865. n = s.hash_size;
  17866. p = n;
  17867. do {
  17868. m = s.head[--p];
  17869. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  17870. } while (--n);
  17871. n = _w_size;
  17872. p = n;
  17873. do {
  17874. m = s.prev[--p];
  17875. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  17876. /* If n is not on any hash chain, prev[n] is garbage but
  17877. * its value will never be used.
  17878. */
  17879. } while (--n);
  17880. more += _w_size;
  17881. }
  17882. if (s.strm.avail_in === 0) {
  17883. break;
  17884. }
  17885. /* If there was no sliding:
  17886. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  17887. * more == window_size - lookahead - strstart
  17888. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  17889. * => more >= window_size - 2*WSIZE + 2
  17890. * In the BIG_MEM or MMAP case (not yet supported),
  17891. * window_size == input_size + MIN_LOOKAHEAD &&
  17892. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  17893. * Otherwise, window_size == 2*WSIZE so more >= 2.
  17894. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  17895. */
  17896. //Assert(more >= 2, "more < 2");
  17897. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  17898. s.lookahead += n;
  17899. /* Initialize the hash value now that we have some input: */
  17900. if (s.lookahead + s.insert >= MIN_MATCH) {
  17901. str = s.strstart - s.insert;
  17902. s.ins_h = s.window[str];
  17903. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  17904. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  17905. //#if MIN_MATCH != 3
  17906. // Call update_hash() MIN_MATCH-3 more times
  17907. //#endif
  17908. while (s.insert) {
  17909. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  17910. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  17911. s.prev[str & s.w_mask] = s.head[s.ins_h];
  17912. s.head[s.ins_h] = str;
  17913. str++;
  17914. s.insert--;
  17915. if (s.lookahead + s.insert < MIN_MATCH) {
  17916. break;
  17917. }
  17918. }
  17919. }
  17920. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  17921. * but this is not important since only literal bytes will be emitted.
  17922. */
  17923. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  17924. /* If the WIN_INIT bytes after the end of the current data have never been
  17925. * written, then zero those bytes in order to avoid memory check reports of
  17926. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  17927. * the longest match routines. Update the high water mark for the next
  17928. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  17929. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  17930. */
  17931. // if (s.high_water < s.window_size) {
  17932. // var curr = s.strstart + s.lookahead;
  17933. // var init = 0;
  17934. //
  17935. // if (s.high_water < curr) {
  17936. // /* Previous high water mark below current data -- zero WIN_INIT
  17937. // * bytes or up to end of window, whichever is less.
  17938. // */
  17939. // init = s.window_size - curr;
  17940. // if (init > WIN_INIT)
  17941. // init = WIN_INIT;
  17942. // zmemzero(s->window + curr, (unsigned)init);
  17943. // s->high_water = curr + init;
  17944. // }
  17945. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  17946. // /* High water mark at or above current data, but below current data
  17947. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  17948. // * to end of window, whichever is less.
  17949. // */
  17950. // init = (ulg)curr + WIN_INIT - s->high_water;
  17951. // if (init > s->window_size - s->high_water)
  17952. // init = s->window_size - s->high_water;
  17953. // zmemzero(s->window + s->high_water, (unsigned)init);
  17954. // s->high_water += init;
  17955. // }
  17956. // }
  17957. //
  17958. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  17959. // "not enough room for search");
  17960. }
  17961. /* ===========================================================================
  17962. * Copy without compression as much as possible from the input stream, return
  17963. * the current block state.
  17964. * This function does not insert new strings in the dictionary since
  17965. * uncompressible data is probably not useful. This function is used
  17966. * only for the level=0 compression option.
  17967. * NOTE: this function should be optimized to avoid extra copying from
  17968. * window to pending_buf.
  17969. */
  17970. function deflate_stored(s, flush) {
  17971. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  17972. * to pending_buf_size, and each stored block has a 5 byte header:
  17973. */
  17974. var max_block_size = 0xffff;
  17975. if (max_block_size > s.pending_buf_size - 5) {
  17976. max_block_size = s.pending_buf_size - 5;
  17977. }
  17978. /* Copy as much as possible from input to output: */
  17979. for (;;) {
  17980. /* Fill the window as much as possible: */
  17981. if (s.lookahead <= 1) {
  17982. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  17983. // s->block_start >= (long)s->w_size, "slide too late");
  17984. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  17985. // s.block_start >= s.w_size)) {
  17986. // throw new Error("slide too late");
  17987. // }
  17988. fill_window(s);
  17989. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  17990. return BS_NEED_MORE;
  17991. }
  17992. if (s.lookahead === 0) {
  17993. break;
  17994. }
  17995. /* flush the current block */
  17996. }
  17997. //Assert(s->block_start >= 0L, "block gone");
  17998. // if (s.block_start < 0) throw new Error("block gone");
  17999. s.strstart += s.lookahead;
  18000. s.lookahead = 0;
  18001. /* Emit a stored block if pending_buf will be full: */
  18002. var max_start = s.block_start + max_block_size;
  18003. if (s.strstart === 0 || s.strstart >= max_start) {
  18004. /* strstart == 0 is possible when wraparound on 16-bit machine */
  18005. s.lookahead = s.strstart - max_start;
  18006. s.strstart = max_start;
  18007. /*** FLUSH_BLOCK(s, 0); ***/
  18008. flush_block_only(s, false);
  18009. if (s.strm.avail_out === 0) {
  18010. return BS_NEED_MORE;
  18011. }
  18012. /***/
  18013. }
  18014. /* Flush if we may have to slide, otherwise block_start may become
  18015. * negative and the data will be gone:
  18016. */
  18017. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  18018. /*** FLUSH_BLOCK(s, 0); ***/
  18019. flush_block_only(s, false);
  18020. if (s.strm.avail_out === 0) {
  18021. return BS_NEED_MORE;
  18022. }
  18023. /***/
  18024. }
  18025. }
  18026. s.insert = 0;
  18027. if (flush === Z_FINISH) {
  18028. /*** FLUSH_BLOCK(s, 1); ***/
  18029. flush_block_only(s, true);
  18030. if (s.strm.avail_out === 0) {
  18031. return BS_FINISH_STARTED;
  18032. }
  18033. /***/
  18034. return BS_FINISH_DONE;
  18035. }
  18036. if (s.strstart > s.block_start) {
  18037. /*** FLUSH_BLOCK(s, 0); ***/
  18038. flush_block_only(s, false);
  18039. if (s.strm.avail_out === 0) {
  18040. return BS_NEED_MORE;
  18041. }
  18042. /***/
  18043. }
  18044. return BS_NEED_MORE;
  18045. }
  18046. /* ===========================================================================
  18047. * Compress as much as possible from the input stream, return the current
  18048. * block state.
  18049. * This function does not perform lazy evaluation of matches and inserts
  18050. * new strings in the dictionary only for unmatched strings or for short
  18051. * matches. It is used only for the fast compression options.
  18052. */
  18053. function deflate_fast(s, flush) {
  18054. var hash_head; /* head of the hash chain */
  18055. var bflush; /* set if current block must be flushed */
  18056. for (;;) {
  18057. /* Make sure that we always have enough lookahead, except
  18058. * at the end of the input file. We need MAX_MATCH bytes
  18059. * for the next match, plus MIN_MATCH bytes to insert the
  18060. * string following the next match.
  18061. */
  18062. if (s.lookahead < MIN_LOOKAHEAD) {
  18063. fill_window(s);
  18064. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  18065. return BS_NEED_MORE;
  18066. }
  18067. if (s.lookahead === 0) {
  18068. break; /* flush the current block */
  18069. }
  18070. }
  18071. /* Insert the string window[strstart .. strstart+2] in the
  18072. * dictionary, and set hash_head to the head of the hash chain:
  18073. */
  18074. hash_head = 0/*NIL*/;
  18075. if (s.lookahead >= MIN_MATCH) {
  18076. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18077. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18078. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18079. s.head[s.ins_h] = s.strstart;
  18080. /***/
  18081. }
  18082. /* Find the longest match, discarding those <= prev_length.
  18083. * At this point we have always match_length < MIN_MATCH
  18084. */
  18085. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  18086. /* To simplify the code, we prevent matches with the string
  18087. * of window index 0 (in particular we have to avoid a match
  18088. * of the string with itself at the start of the input file).
  18089. */
  18090. s.match_length = longest_match(s, hash_head);
  18091. /* longest_match() sets match_start */
  18092. }
  18093. if (s.match_length >= MIN_MATCH) {
  18094. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  18095. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  18096. s.match_length - MIN_MATCH, bflush); ***/
  18097. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  18098. s.lookahead -= s.match_length;
  18099. /* Insert new strings in the hash table only if the match length
  18100. * is not too large. This saves time but degrades compression.
  18101. */
  18102. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  18103. s.match_length--; /* string at strstart already in table */
  18104. do {
  18105. s.strstart++;
  18106. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18107. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18108. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18109. s.head[s.ins_h] = s.strstart;
  18110. /***/
  18111. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  18112. * always MIN_MATCH bytes ahead.
  18113. */
  18114. } while (--s.match_length !== 0);
  18115. s.strstart++;
  18116. } else
  18117. {
  18118. s.strstart += s.match_length;
  18119. s.match_length = 0;
  18120. s.ins_h = s.window[s.strstart];
  18121. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  18122. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  18123. //#if MIN_MATCH != 3
  18124. // Call UPDATE_HASH() MIN_MATCH-3 more times
  18125. //#endif
  18126. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  18127. * matter since it will be recomputed at next deflate call.
  18128. */
  18129. }
  18130. } else {
  18131. /* No match, output a literal byte */
  18132. //Tracevv((stderr,"%c", s.window[s.strstart]));
  18133. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18134. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18135. s.lookahead--;
  18136. s.strstart++;
  18137. }
  18138. if (bflush) {
  18139. /*** FLUSH_BLOCK(s, 0); ***/
  18140. flush_block_only(s, false);
  18141. if (s.strm.avail_out === 0) {
  18142. return BS_NEED_MORE;
  18143. }
  18144. /***/
  18145. }
  18146. }
  18147. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  18148. if (flush === Z_FINISH) {
  18149. /*** FLUSH_BLOCK(s, 1); ***/
  18150. flush_block_only(s, true);
  18151. if (s.strm.avail_out === 0) {
  18152. return BS_FINISH_STARTED;
  18153. }
  18154. /***/
  18155. return BS_FINISH_DONE;
  18156. }
  18157. if (s.last_lit) {
  18158. /*** FLUSH_BLOCK(s, 0); ***/
  18159. flush_block_only(s, false);
  18160. if (s.strm.avail_out === 0) {
  18161. return BS_NEED_MORE;
  18162. }
  18163. /***/
  18164. }
  18165. return BS_BLOCK_DONE;
  18166. }
  18167. /* ===========================================================================
  18168. * Same as above, but achieves better compression. We use a lazy
  18169. * evaluation for matches: a match is finally adopted only if there is
  18170. * no better match at the next window position.
  18171. */
  18172. function deflate_slow(s, flush) {
  18173. var hash_head; /* head of hash chain */
  18174. var bflush; /* set if current block must be flushed */
  18175. var max_insert;
  18176. /* Process the input block. */
  18177. for (;;) {
  18178. /* Make sure that we always have enough lookahead, except
  18179. * at the end of the input file. We need MAX_MATCH bytes
  18180. * for the next match, plus MIN_MATCH bytes to insert the
  18181. * string following the next match.
  18182. */
  18183. if (s.lookahead < MIN_LOOKAHEAD) {
  18184. fill_window(s);
  18185. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  18186. return BS_NEED_MORE;
  18187. }
  18188. if (s.lookahead === 0) { break; } /* flush the current block */
  18189. }
  18190. /* Insert the string window[strstart .. strstart+2] in the
  18191. * dictionary, and set hash_head to the head of the hash chain:
  18192. */
  18193. hash_head = 0/*NIL*/;
  18194. if (s.lookahead >= MIN_MATCH) {
  18195. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18196. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18197. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18198. s.head[s.ins_h] = s.strstart;
  18199. /***/
  18200. }
  18201. /* Find the longest match, discarding those <= prev_length.
  18202. */
  18203. s.prev_length = s.match_length;
  18204. s.prev_match = s.match_start;
  18205. s.match_length = MIN_MATCH-1;
  18206. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  18207. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  18208. /* To simplify the code, we prevent matches with the string
  18209. * of window index 0 (in particular we have to avoid a match
  18210. * of the string with itself at the start of the input file).
  18211. */
  18212. s.match_length = longest_match(s, hash_head);
  18213. /* longest_match() sets match_start */
  18214. if (s.match_length <= 5 &&
  18215. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  18216. /* If prev_match is also MIN_MATCH, match_start is garbage
  18217. * but we will ignore the current match anyway.
  18218. */
  18219. s.match_length = MIN_MATCH-1;
  18220. }
  18221. }
  18222. /* If there was a match at the previous step and the current
  18223. * match is not better, output the previous match:
  18224. */
  18225. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  18226. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  18227. /* Do not insert strings in hash table beyond this. */
  18228. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  18229. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  18230. s.prev_length - MIN_MATCH, bflush);***/
  18231. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  18232. /* Insert in hash table all strings up to the end of the match.
  18233. * strstart-1 and strstart are already inserted. If there is not
  18234. * enough lookahead, the last two strings are not inserted in
  18235. * the hash table.
  18236. */
  18237. s.lookahead -= s.prev_length-1;
  18238. s.prev_length -= 2;
  18239. do {
  18240. if (++s.strstart <= max_insert) {
  18241. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18242. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18243. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18244. s.head[s.ins_h] = s.strstart;
  18245. /***/
  18246. }
  18247. } while (--s.prev_length !== 0);
  18248. s.match_available = 0;
  18249. s.match_length = MIN_MATCH-1;
  18250. s.strstart++;
  18251. if (bflush) {
  18252. /*** FLUSH_BLOCK(s, 0); ***/
  18253. flush_block_only(s, false);
  18254. if (s.strm.avail_out === 0) {
  18255. return BS_NEED_MORE;
  18256. }
  18257. /***/
  18258. }
  18259. } else if (s.match_available) {
  18260. /* If there was no match at the previous position, output a
  18261. * single literal. If there was a match but the current match
  18262. * is longer, truncate the previous match to a single literal.
  18263. */
  18264. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  18265. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  18266. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  18267. if (bflush) {
  18268. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  18269. flush_block_only(s, false);
  18270. /***/
  18271. }
  18272. s.strstart++;
  18273. s.lookahead--;
  18274. if (s.strm.avail_out === 0) {
  18275. return BS_NEED_MORE;
  18276. }
  18277. } else {
  18278. /* There is no previous match to compare with, wait for
  18279. * the next step to decide.
  18280. */
  18281. s.match_available = 1;
  18282. s.strstart++;
  18283. s.lookahead--;
  18284. }
  18285. }
  18286. //Assert (flush != Z_NO_FLUSH, "no flush?");
  18287. if (s.match_available) {
  18288. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  18289. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  18290. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  18291. s.match_available = 0;
  18292. }
  18293. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  18294. if (flush === Z_FINISH) {
  18295. /*** FLUSH_BLOCK(s, 1); ***/
  18296. flush_block_only(s, true);
  18297. if (s.strm.avail_out === 0) {
  18298. return BS_FINISH_STARTED;
  18299. }
  18300. /***/
  18301. return BS_FINISH_DONE;
  18302. }
  18303. if (s.last_lit) {
  18304. /*** FLUSH_BLOCK(s, 0); ***/
  18305. flush_block_only(s, false);
  18306. if (s.strm.avail_out === 0) {
  18307. return BS_NEED_MORE;
  18308. }
  18309. /***/
  18310. }
  18311. return BS_BLOCK_DONE;
  18312. }
  18313. /* ===========================================================================
  18314. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  18315. * one. Do not maintain a hash table. (It will be regenerated if this run of
  18316. * deflate switches away from Z_RLE.)
  18317. */
  18318. function deflate_rle(s, flush) {
  18319. var bflush; /* set if current block must be flushed */
  18320. var prev; /* byte at distance one to match */
  18321. var scan, strend; /* scan goes up to strend for length of run */
  18322. var _win = s.window;
  18323. for (;;) {
  18324. /* Make sure that we always have enough lookahead, except
  18325. * at the end of the input file. We need MAX_MATCH bytes
  18326. * for the longest run, plus one for the unrolled loop.
  18327. */
  18328. if (s.lookahead <= MAX_MATCH) {
  18329. fill_window(s);
  18330. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  18331. return BS_NEED_MORE;
  18332. }
  18333. if (s.lookahead === 0) { break; } /* flush the current block */
  18334. }
  18335. /* See how many times the previous byte repeats */
  18336. s.match_length = 0;
  18337. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  18338. scan = s.strstart - 1;
  18339. prev = _win[scan];
  18340. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  18341. strend = s.strstart + MAX_MATCH;
  18342. do {
  18343. /*jshint noempty:false*/
  18344. } while (prev === _win[++scan] && prev === _win[++scan] &&
  18345. prev === _win[++scan] && prev === _win[++scan] &&
  18346. prev === _win[++scan] && prev === _win[++scan] &&
  18347. prev === _win[++scan] && prev === _win[++scan] &&
  18348. scan < strend);
  18349. s.match_length = MAX_MATCH - (strend - scan);
  18350. if (s.match_length > s.lookahead) {
  18351. s.match_length = s.lookahead;
  18352. }
  18353. }
  18354. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  18355. }
  18356. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  18357. if (s.match_length >= MIN_MATCH) {
  18358. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  18359. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  18360. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  18361. s.lookahead -= s.match_length;
  18362. s.strstart += s.match_length;
  18363. s.match_length = 0;
  18364. } else {
  18365. /* No match, output a literal byte */
  18366. //Tracevv((stderr,"%c", s->window[s->strstart]));
  18367. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18368. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18369. s.lookahead--;
  18370. s.strstart++;
  18371. }
  18372. if (bflush) {
  18373. /*** FLUSH_BLOCK(s, 0); ***/
  18374. flush_block_only(s, false);
  18375. if (s.strm.avail_out === 0) {
  18376. return BS_NEED_MORE;
  18377. }
  18378. /***/
  18379. }
  18380. }
  18381. s.insert = 0;
  18382. if (flush === Z_FINISH) {
  18383. /*** FLUSH_BLOCK(s, 1); ***/
  18384. flush_block_only(s, true);
  18385. if (s.strm.avail_out === 0) {
  18386. return BS_FINISH_STARTED;
  18387. }
  18388. /***/
  18389. return BS_FINISH_DONE;
  18390. }
  18391. if (s.last_lit) {
  18392. /*** FLUSH_BLOCK(s, 0); ***/
  18393. flush_block_only(s, false);
  18394. if (s.strm.avail_out === 0) {
  18395. return BS_NEED_MORE;
  18396. }
  18397. /***/
  18398. }
  18399. return BS_BLOCK_DONE;
  18400. }
  18401. /* ===========================================================================
  18402. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  18403. * (It will be regenerated if this run of deflate switches away from Huffman.)
  18404. */
  18405. function deflate_huff(s, flush) {
  18406. var bflush; /* set if current block must be flushed */
  18407. for (;;) {
  18408. /* Make sure that we have a literal to write. */
  18409. if (s.lookahead === 0) {
  18410. fill_window(s);
  18411. if (s.lookahead === 0) {
  18412. if (flush === Z_NO_FLUSH) {
  18413. return BS_NEED_MORE;
  18414. }
  18415. break; /* flush the current block */
  18416. }
  18417. }
  18418. /* Output a literal byte */
  18419. s.match_length = 0;
  18420. //Tracevv((stderr,"%c", s->window[s->strstart]));
  18421. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18422. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18423. s.lookahead--;
  18424. s.strstart++;
  18425. if (bflush) {
  18426. /*** FLUSH_BLOCK(s, 0); ***/
  18427. flush_block_only(s, false);
  18428. if (s.strm.avail_out === 0) {
  18429. return BS_NEED_MORE;
  18430. }
  18431. /***/
  18432. }
  18433. }
  18434. s.insert = 0;
  18435. if (flush === Z_FINISH) {
  18436. /*** FLUSH_BLOCK(s, 1); ***/
  18437. flush_block_only(s, true);
  18438. if (s.strm.avail_out === 0) {
  18439. return BS_FINISH_STARTED;
  18440. }
  18441. /***/
  18442. return BS_FINISH_DONE;
  18443. }
  18444. if (s.last_lit) {
  18445. /*** FLUSH_BLOCK(s, 0); ***/
  18446. flush_block_only(s, false);
  18447. if (s.strm.avail_out === 0) {
  18448. return BS_NEED_MORE;
  18449. }
  18450. /***/
  18451. }
  18452. return BS_BLOCK_DONE;
  18453. }
  18454. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  18455. * the desired pack level (0..9). The values given below have been tuned to
  18456. * exclude worst case performance for pathological files. Better values may be
  18457. * found for specific files.
  18458. */
  18459. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  18460. this.good_length = good_length;
  18461. this.max_lazy = max_lazy;
  18462. this.nice_length = nice_length;
  18463. this.max_chain = max_chain;
  18464. this.func = func;
  18465. };
  18466. var configuration_table;
  18467. configuration_table = [
  18468. /* good lazy nice chain */
  18469. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  18470. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  18471. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  18472. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  18473. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  18474. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  18475. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  18476. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  18477. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  18478. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  18479. ];
  18480. /* ===========================================================================
  18481. * Initialize the "longest match" routines for a new zlib stream
  18482. */
  18483. function lm_init(s) {
  18484. s.window_size = 2 * s.w_size;
  18485. /*** CLEAR_HASH(s); ***/
  18486. zero(s.head); // Fill with NIL (= 0);
  18487. /* Set the default configuration parameters:
  18488. */
  18489. s.max_lazy_match = configuration_table[s.level].max_lazy;
  18490. s.good_match = configuration_table[s.level].good_length;
  18491. s.nice_match = configuration_table[s.level].nice_length;
  18492. s.max_chain_length = configuration_table[s.level].max_chain;
  18493. s.strstart = 0;
  18494. s.block_start = 0;
  18495. s.lookahead = 0;
  18496. s.insert = 0;
  18497. s.match_length = s.prev_length = MIN_MATCH - 1;
  18498. s.match_available = 0;
  18499. s.ins_h = 0;
  18500. }
  18501. function DeflateState() {
  18502. this.strm = null; /* pointer back to this zlib stream */
  18503. this.status = 0; /* as the name implies */
  18504. this.pending_buf = null; /* output still pending */
  18505. this.pending_buf_size = 0; /* size of pending_buf */
  18506. this.pending_out = 0; /* next pending byte to output to the stream */
  18507. this.pending = 0; /* nb of bytes in the pending buffer */
  18508. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  18509. this.gzhead = null; /* gzip header information to write */
  18510. this.gzindex = 0; /* where in extra, name, or comment */
  18511. this.method = Z_DEFLATED; /* can only be DEFLATED */
  18512. this.last_flush = -1; /* value of flush param for previous deflate call */
  18513. this.w_size = 0; /* LZ77 window size (32K by default) */
  18514. this.w_bits = 0; /* log2(w_size) (8..16) */
  18515. this.w_mask = 0; /* w_size - 1 */
  18516. this.window = null;
  18517. /* Sliding window. Input bytes are read into the second half of the window,
  18518. * and move to the first half later to keep a dictionary of at least wSize
  18519. * bytes. With this organization, matches are limited to a distance of
  18520. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  18521. * performed with a length multiple of the block size.
  18522. */
  18523. this.window_size = 0;
  18524. /* Actual size of window: 2*wSize, except when the user input buffer
  18525. * is directly used as sliding window.
  18526. */
  18527. this.prev = null;
  18528. /* Link to older string with same hash index. To limit the size of this
  18529. * array to 64K, this link is maintained only for the last 32K strings.
  18530. * An index in this array is thus a window index modulo 32K.
  18531. */
  18532. this.head = null; /* Heads of the hash chains or NIL. */
  18533. this.ins_h = 0; /* hash index of string to be inserted */
  18534. this.hash_size = 0; /* number of elements in hash table */
  18535. this.hash_bits = 0; /* log2(hash_size) */
  18536. this.hash_mask = 0; /* hash_size-1 */
  18537. this.hash_shift = 0;
  18538. /* Number of bits by which ins_h must be shifted at each input
  18539. * step. It must be such that after MIN_MATCH steps, the oldest
  18540. * byte no longer takes part in the hash key, that is:
  18541. * hash_shift * MIN_MATCH >= hash_bits
  18542. */
  18543. this.block_start = 0;
  18544. /* Window position at the beginning of the current output block. Gets
  18545. * negative when the window is moved backwards.
  18546. */
  18547. this.match_length = 0; /* length of best match */
  18548. this.prev_match = 0; /* previous match */
  18549. this.match_available = 0; /* set if previous match exists */
  18550. this.strstart = 0; /* start of string to insert */
  18551. this.match_start = 0; /* start of matching string */
  18552. this.lookahead = 0; /* number of valid bytes ahead in window */
  18553. this.prev_length = 0;
  18554. /* Length of the best match at previous step. Matches not greater than this
  18555. * are discarded. This is used in the lazy match evaluation.
  18556. */
  18557. this.max_chain_length = 0;
  18558. /* To speed up deflation, hash chains are never searched beyond this
  18559. * length. A higher limit improves compression ratio but degrades the
  18560. * speed.
  18561. */
  18562. this.max_lazy_match = 0;
  18563. /* Attempt to find a better match only when the current match is strictly
  18564. * smaller than this value. This mechanism is used only for compression
  18565. * levels >= 4.
  18566. */
  18567. // That's alias to max_lazy_match, don't use directly
  18568. //this.max_insert_length = 0;
  18569. /* Insert new strings in the hash table only if the match length is not
  18570. * greater than this length. This saves time but degrades compression.
  18571. * max_insert_length is used only for compression levels <= 3.
  18572. */
  18573. this.level = 0; /* compression level (1..9) */
  18574. this.strategy = 0; /* favor or force Huffman coding*/
  18575. this.good_match = 0;
  18576. /* Use a faster search when the previous match is longer than this */
  18577. this.nice_match = 0; /* Stop searching when current match exceeds this */
  18578. /* used by trees.c: */
  18579. /* Didn't use ct_data typedef below to suppress compiler warning */
  18580. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  18581. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  18582. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  18583. // Use flat array of DOUBLE size, with interleaved fata,
  18584. // because JS does not support effective
  18585. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  18586. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  18587. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  18588. zero(this.dyn_ltree);
  18589. zero(this.dyn_dtree);
  18590. zero(this.bl_tree);
  18591. this.l_desc = null; /* desc. for literal tree */
  18592. this.d_desc = null; /* desc. for distance tree */
  18593. this.bl_desc = null; /* desc. for bit length tree */
  18594. //ush bl_count[MAX_BITS+1];
  18595. this.bl_count = new utils.Buf16(MAX_BITS+1);
  18596. /* number of codes at each bit length for an optimal tree */
  18597. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  18598. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  18599. zero(this.heap);
  18600. this.heap_len = 0; /* number of elements in the heap */
  18601. this.heap_max = 0; /* element of largest frequency */
  18602. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  18603. * The same heap array is used to build all trees.
  18604. */
  18605. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  18606. zero(this.depth);
  18607. /* Depth of each subtree used as tie breaker for trees of equal frequency
  18608. */
  18609. this.l_buf = 0; /* buffer index for literals or lengths */
  18610. this.lit_bufsize = 0;
  18611. /* Size of match buffer for literals/lengths. There are 4 reasons for
  18612. * limiting lit_bufsize to 64K:
  18613. * - frequencies can be kept in 16 bit counters
  18614. * - if compression is not successful for the first block, all input
  18615. * data is still in the window so we can still emit a stored block even
  18616. * when input comes from standard input. (This can also be done for
  18617. * all blocks if lit_bufsize is not greater than 32K.)
  18618. * - if compression is not successful for a file smaller than 64K, we can
  18619. * even emit a stored file instead of a stored block (saving 5 bytes).
  18620. * This is applicable only for zip (not gzip or zlib).
  18621. * - creating new Huffman trees less frequently may not provide fast
  18622. * adaptation to changes in the input data statistics. (Take for
  18623. * example a binary file with poorly compressible code followed by
  18624. * a highly compressible string table.) Smaller buffer sizes give
  18625. * fast adaptation but have of course the overhead of transmitting
  18626. * trees more frequently.
  18627. * - I can't count above 4
  18628. */
  18629. this.last_lit = 0; /* running index in l_buf */
  18630. this.d_buf = 0;
  18631. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  18632. * the same number of elements. To use different lengths, an extra flag
  18633. * array would be necessary.
  18634. */
  18635. this.opt_len = 0; /* bit length of current block with optimal trees */
  18636. this.static_len = 0; /* bit length of current block with static trees */
  18637. this.matches = 0; /* number of string matches in current block */
  18638. this.insert = 0; /* bytes at end of window left to insert */
  18639. this.bi_buf = 0;
  18640. /* Output buffer. bits are inserted starting at the bottom (least
  18641. * significant bits).
  18642. */
  18643. this.bi_valid = 0;
  18644. /* Number of valid bits in bi_buf. All bits above the last valid bit
  18645. * are always zero.
  18646. */
  18647. // Used for window memory init. We safely ignore it for JS. That makes
  18648. // sense only for pointers and memory check tools.
  18649. //this.high_water = 0;
  18650. /* High water mark offset in window for initialized bytes -- bytes above
  18651. * this are set to zero in order to avoid memory check warnings when
  18652. * longest match routines access bytes past the input. This is then
  18653. * updated to the new high water mark.
  18654. */
  18655. }
  18656. function deflateResetKeep(strm) {
  18657. var s;
  18658. if (!strm || !strm.state) {
  18659. return err(strm, Z_STREAM_ERROR);
  18660. }
  18661. strm.total_in = strm.total_out = 0;
  18662. strm.data_type = Z_UNKNOWN;
  18663. s = strm.state;
  18664. s.pending = 0;
  18665. s.pending_out = 0;
  18666. if (s.wrap < 0) {
  18667. s.wrap = -s.wrap;
  18668. /* was made negative by deflate(..., Z_FINISH); */
  18669. }
  18670. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  18671. strm.adler = (s.wrap === 2) ?
  18672. 0 // crc32(0, Z_NULL, 0)
  18673. :
  18674. 1; // adler32(0, Z_NULL, 0)
  18675. s.last_flush = Z_NO_FLUSH;
  18676. trees._tr_init(s);
  18677. return Z_OK;
  18678. }
  18679. function deflateReset(strm) {
  18680. var ret = deflateResetKeep(strm);
  18681. if (ret === Z_OK) {
  18682. lm_init(strm.state);
  18683. }
  18684. return ret;
  18685. }
  18686. function deflateSetHeader(strm, head) {
  18687. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  18688. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  18689. strm.state.gzhead = head;
  18690. return Z_OK;
  18691. }
  18692. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  18693. if (!strm) { // === Z_NULL
  18694. return Z_STREAM_ERROR;
  18695. }
  18696. var wrap = 1;
  18697. if (level === Z_DEFAULT_COMPRESSION) {
  18698. level = 6;
  18699. }
  18700. if (windowBits < 0) { /* suppress zlib wrapper */
  18701. wrap = 0;
  18702. windowBits = -windowBits;
  18703. }
  18704. else if (windowBits > 15) {
  18705. wrap = 2; /* write gzip wrapper instead */
  18706. windowBits -= 16;
  18707. }
  18708. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  18709. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  18710. strategy < 0 || strategy > Z_FIXED) {
  18711. return err(strm, Z_STREAM_ERROR);
  18712. }
  18713. if (windowBits === 8) {
  18714. windowBits = 9;
  18715. }
  18716. /* until 256-byte window bug fixed */
  18717. var s = new DeflateState();
  18718. strm.state = s;
  18719. s.strm = strm;
  18720. s.wrap = wrap;
  18721. s.gzhead = null;
  18722. s.w_bits = windowBits;
  18723. s.w_size = 1 << s.w_bits;
  18724. s.w_mask = s.w_size - 1;
  18725. s.hash_bits = memLevel + 7;
  18726. s.hash_size = 1 << s.hash_bits;
  18727. s.hash_mask = s.hash_size - 1;
  18728. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  18729. s.window = new utils.Buf8(s.w_size * 2);
  18730. s.head = new utils.Buf16(s.hash_size);
  18731. s.prev = new utils.Buf16(s.w_size);
  18732. // Don't need mem init magic for JS.
  18733. //s.high_water = 0; /* nothing written to s->window yet */
  18734. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  18735. s.pending_buf_size = s.lit_bufsize * 4;
  18736. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  18737. s.d_buf = s.lit_bufsize >> 1;
  18738. s.l_buf = (1 + 2) * s.lit_bufsize;
  18739. s.level = level;
  18740. s.strategy = strategy;
  18741. s.method = method;
  18742. return deflateReset(strm);
  18743. }
  18744. function deflateInit(strm, level) {
  18745. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  18746. }
  18747. function deflate(strm, flush) {
  18748. var old_flush, s;
  18749. var beg, val; // for gzip header write only
  18750. if (!strm || !strm.state ||
  18751. flush > Z_BLOCK || flush < 0) {
  18752. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  18753. }
  18754. s = strm.state;
  18755. if (!strm.output ||
  18756. (!strm.input && strm.avail_in !== 0) ||
  18757. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  18758. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  18759. }
  18760. s.strm = strm; /* just in case */
  18761. old_flush = s.last_flush;
  18762. s.last_flush = flush;
  18763. /* Write the header */
  18764. if (s.status === INIT_STATE) {
  18765. if (s.wrap === 2) { // GZIP header
  18766. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  18767. put_byte(s, 31);
  18768. put_byte(s, 139);
  18769. put_byte(s, 8);
  18770. if (!s.gzhead) { // s->gzhead == Z_NULL
  18771. put_byte(s, 0);
  18772. put_byte(s, 0);
  18773. put_byte(s, 0);
  18774. put_byte(s, 0);
  18775. put_byte(s, 0);
  18776. put_byte(s, s.level === 9 ? 2 :
  18777. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  18778. 4 : 0));
  18779. put_byte(s, OS_CODE);
  18780. s.status = BUSY_STATE;
  18781. }
  18782. else {
  18783. put_byte(s, (s.gzhead.text ? 1 : 0) +
  18784. (s.gzhead.hcrc ? 2 : 0) +
  18785. (!s.gzhead.extra ? 0 : 4) +
  18786. (!s.gzhead.name ? 0 : 8) +
  18787. (!s.gzhead.comment ? 0 : 16)
  18788. );
  18789. put_byte(s, s.gzhead.time & 0xff);
  18790. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  18791. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  18792. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  18793. put_byte(s, s.level === 9 ? 2 :
  18794. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  18795. 4 : 0));
  18796. put_byte(s, s.gzhead.os & 0xff);
  18797. if (s.gzhead.extra && s.gzhead.extra.length) {
  18798. put_byte(s, s.gzhead.extra.length & 0xff);
  18799. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  18800. }
  18801. if (s.gzhead.hcrc) {
  18802. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  18803. }
  18804. s.gzindex = 0;
  18805. s.status = EXTRA_STATE;
  18806. }
  18807. }
  18808. else // DEFLATE header
  18809. {
  18810. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  18811. var level_flags = -1;
  18812. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  18813. level_flags = 0;
  18814. } else if (s.level < 6) {
  18815. level_flags = 1;
  18816. } else if (s.level === 6) {
  18817. level_flags = 2;
  18818. } else {
  18819. level_flags = 3;
  18820. }
  18821. header |= (level_flags << 6);
  18822. if (s.strstart !== 0) { header |= PRESET_DICT; }
  18823. header += 31 - (header % 31);
  18824. s.status = BUSY_STATE;
  18825. putShortMSB(s, header);
  18826. /* Save the adler32 of the preset dictionary: */
  18827. if (s.strstart !== 0) {
  18828. putShortMSB(s, strm.adler >>> 16);
  18829. putShortMSB(s, strm.adler & 0xffff);
  18830. }
  18831. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  18832. }
  18833. }
  18834. //#ifdef GZIP
  18835. if (s.status === EXTRA_STATE) {
  18836. if (s.gzhead.extra/* != Z_NULL*/) {
  18837. beg = s.pending; /* start of bytes to update crc */
  18838. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  18839. if (s.pending === s.pending_buf_size) {
  18840. if (s.gzhead.hcrc && s.pending > beg) {
  18841. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  18842. }
  18843. flush_pending(strm);
  18844. beg = s.pending;
  18845. if (s.pending === s.pending_buf_size) {
  18846. break;
  18847. }
  18848. }
  18849. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  18850. s.gzindex++;
  18851. }
  18852. if (s.gzhead.hcrc && s.pending > beg) {
  18853. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  18854. }
  18855. if (s.gzindex === s.gzhead.extra.length) {
  18856. s.gzindex = 0;
  18857. s.status = NAME_STATE;
  18858. }
  18859. }
  18860. else {
  18861. s.status = NAME_STATE;
  18862. }
  18863. }
  18864. if (s.status === NAME_STATE) {
  18865. if (s.gzhead.name/* != Z_NULL*/) {
  18866. beg = s.pending; /* start of bytes to update crc */
  18867. //int val;
  18868. do {
  18869. if (s.pending === s.pending_buf_size) {
  18870. if (s.gzhead.hcrc && s.pending > beg) {
  18871. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  18872. }
  18873. flush_pending(strm);
  18874. beg = s.pending;
  18875. if (s.pending === s.pending_buf_size) {
  18876. val = 1;
  18877. break;
  18878. }
  18879. }
  18880. // JS specific: little magic to add zero terminator to end of string
  18881. if (s.gzindex < s.gzhead.name.length) {
  18882. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  18883. } else {
  18884. val = 0;
  18885. }
  18886. put_byte(s, val);
  18887. } while (val !== 0);
  18888. if (s.gzhead.hcrc && s.pending > beg){
  18889. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  18890. }
  18891. if (val === 0) {
  18892. s.gzindex = 0;
  18893. s.status = COMMENT_STATE;
  18894. }
  18895. }
  18896. else {
  18897. s.status = COMMENT_STATE;
  18898. }
  18899. }
  18900. if (s.status === COMMENT_STATE) {
  18901. if (s.gzhead.comment/* != Z_NULL*/) {
  18902. beg = s.pending; /* start of bytes to update crc */
  18903. //int val;
  18904. do {
  18905. if (s.pending === s.pending_buf_size) {
  18906. if (s.gzhead.hcrc && s.pending > beg) {
  18907. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  18908. }
  18909. flush_pending(strm);
  18910. beg = s.pending;
  18911. if (s.pending === s.pending_buf_size) {
  18912. val = 1;
  18913. break;
  18914. }
  18915. }
  18916. // JS specific: little magic to add zero terminator to end of string
  18917. if (s.gzindex < s.gzhead.comment.length) {
  18918. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  18919. } else {
  18920. val = 0;
  18921. }
  18922. put_byte(s, val);
  18923. } while (val !== 0);
  18924. if (s.gzhead.hcrc && s.pending > beg) {
  18925. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  18926. }
  18927. if (val === 0) {
  18928. s.status = HCRC_STATE;
  18929. }
  18930. }
  18931. else {
  18932. s.status = HCRC_STATE;
  18933. }
  18934. }
  18935. if (s.status === HCRC_STATE) {
  18936. if (s.gzhead.hcrc) {
  18937. if (s.pending + 2 > s.pending_buf_size) {
  18938. flush_pending(strm);
  18939. }
  18940. if (s.pending + 2 <= s.pending_buf_size) {
  18941. put_byte(s, strm.adler & 0xff);
  18942. put_byte(s, (strm.adler >> 8) & 0xff);
  18943. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  18944. s.status = BUSY_STATE;
  18945. }
  18946. }
  18947. else {
  18948. s.status = BUSY_STATE;
  18949. }
  18950. }
  18951. //#endif
  18952. /* Flush as much pending output as possible */
  18953. if (s.pending !== 0) {
  18954. flush_pending(strm);
  18955. if (strm.avail_out === 0) {
  18956. /* Since avail_out is 0, deflate will be called again with
  18957. * more output space, but possibly with both pending and
  18958. * avail_in equal to zero. There won't be anything to do,
  18959. * but this is not an error situation so make sure we
  18960. * return OK instead of BUF_ERROR at next call of deflate:
  18961. */
  18962. s.last_flush = -1;
  18963. return Z_OK;
  18964. }
  18965. /* Make sure there is something to do and avoid duplicate consecutive
  18966. * flushes. For repeated and useless calls with Z_FINISH, we keep
  18967. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  18968. */
  18969. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  18970. flush !== Z_FINISH) {
  18971. return err(strm, Z_BUF_ERROR);
  18972. }
  18973. /* User must not provide more input after the first FINISH: */
  18974. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  18975. return err(strm, Z_BUF_ERROR);
  18976. }
  18977. /* Start a new block or continue the current one.
  18978. */
  18979. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  18980. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  18981. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  18982. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  18983. configuration_table[s.level].func(s, flush));
  18984. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  18985. s.status = FINISH_STATE;
  18986. }
  18987. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  18988. if (strm.avail_out === 0) {
  18989. s.last_flush = -1;
  18990. /* avoid BUF_ERROR next call, see above */
  18991. }
  18992. return Z_OK;
  18993. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  18994. * of deflate should use the same flush parameter to make sure
  18995. * that the flush is complete. So we don't have to output an
  18996. * empty block here, this will be done at next call. This also
  18997. * ensures that for a very small output buffer, we emit at most
  18998. * one empty block.
  18999. */
  19000. }
  19001. if (bstate === BS_BLOCK_DONE) {
  19002. if (flush === Z_PARTIAL_FLUSH) {
  19003. trees._tr_align(s);
  19004. }
  19005. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  19006. trees._tr_stored_block(s, 0, 0, false);
  19007. /* For a full flush, this empty block will be recognized
  19008. * as a special marker by inflate_sync().
  19009. */
  19010. if (flush === Z_FULL_FLUSH) {
  19011. /*** CLEAR_HASH(s); ***/ /* forget history */
  19012. zero(s.head); // Fill with NIL (= 0);
  19013. if (s.lookahead === 0) {
  19014. s.strstart = 0;
  19015. s.block_start = 0;
  19016. s.insert = 0;
  19017. }
  19018. }
  19019. }
  19020. flush_pending(strm);
  19021. if (strm.avail_out === 0) {
  19022. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  19023. return Z_OK;
  19024. }
  19025. }
  19026. }
  19027. //Assert(strm->avail_out > 0, "bug2");
  19028. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  19029. if (flush !== Z_FINISH) { return Z_OK; }
  19030. if (s.wrap <= 0) { return Z_STREAM_END; }
  19031. /* Write the trailer */
  19032. if (s.wrap === 2) {
  19033. put_byte(s, strm.adler & 0xff);
  19034. put_byte(s, (strm.adler >> 8) & 0xff);
  19035. put_byte(s, (strm.adler >> 16) & 0xff);
  19036. put_byte(s, (strm.adler >> 24) & 0xff);
  19037. put_byte(s, strm.total_in & 0xff);
  19038. put_byte(s, (strm.total_in >> 8) & 0xff);
  19039. put_byte(s, (strm.total_in >> 16) & 0xff);
  19040. put_byte(s, (strm.total_in >> 24) & 0xff);
  19041. }
  19042. else
  19043. {
  19044. putShortMSB(s, strm.adler >>> 16);
  19045. putShortMSB(s, strm.adler & 0xffff);
  19046. }
  19047. flush_pending(strm);
  19048. /* If avail_out is zero, the application will call deflate again
  19049. * to flush the rest.
  19050. */
  19051. if (s.wrap > 0) { s.wrap = -s.wrap; }
  19052. /* write the trailer only once! */
  19053. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  19054. }
  19055. function deflateEnd(strm) {
  19056. var status;
  19057. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  19058. return Z_STREAM_ERROR;
  19059. }
  19060. status = strm.state.status;
  19061. if (status !== INIT_STATE &&
  19062. status !== EXTRA_STATE &&
  19063. status !== NAME_STATE &&
  19064. status !== COMMENT_STATE &&
  19065. status !== HCRC_STATE &&
  19066. status !== BUSY_STATE &&
  19067. status !== FINISH_STATE
  19068. ) {
  19069. return err(strm, Z_STREAM_ERROR);
  19070. }
  19071. strm.state = null;
  19072. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  19073. }
  19074. /* =========================================================================
  19075. * Copy the source state to the destination state
  19076. */
  19077. //function deflateCopy(dest, source) {
  19078. //
  19079. //}
  19080. exports.deflateInit = deflateInit;
  19081. exports.deflateInit2 = deflateInit2;
  19082. exports.deflateReset = deflateReset;
  19083. exports.deflateResetKeep = deflateResetKeep;
  19084. exports.deflateSetHeader = deflateSetHeader;
  19085. exports.deflate = deflate;
  19086. exports.deflateEnd = deflateEnd;
  19087. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  19088. /* Not implemented
  19089. exports.deflateBound = deflateBound;
  19090. exports.deflateCopy = deflateCopy;
  19091. exports.deflateSetDictionary = deflateSetDictionary;
  19092. exports.deflateParams = deflateParams;
  19093. exports.deflatePending = deflatePending;
  19094. exports.deflatePrime = deflatePrime;
  19095. exports.deflateTune = deflateTune;
  19096. */
  19097. },{"../utils/common":65,"./adler32":67,"./crc32":69,"./messages":75,"./trees":76}],71:[function(require,module,exports){
  19098. 'use strict';
  19099. function GZheader() {
  19100. /* true if compressed data believed to be text */
  19101. this.text = 0;
  19102. /* modification time */
  19103. this.time = 0;
  19104. /* extra flags (not used when writing a gzip file) */
  19105. this.xflags = 0;
  19106. /* operating system */
  19107. this.os = 0;
  19108. /* pointer to extra field or Z_NULL if none */
  19109. this.extra = null;
  19110. /* extra field length (valid if extra != Z_NULL) */
  19111. this.extra_len = 0; // Actually, we don't need it in JS,
  19112. // but leave for few code modifications
  19113. //
  19114. // Setup limits is not necessary because in js we should not preallocate memory
  19115. // for inflate use constant limit in 65536 bytes
  19116. //
  19117. /* space at extra (only when reading header) */
  19118. // this.extra_max = 0;
  19119. /* pointer to zero-terminated file name or Z_NULL */
  19120. this.name = '';
  19121. /* space at name (only when reading header) */
  19122. // this.name_max = 0;
  19123. /* pointer to zero-terminated comment or Z_NULL */
  19124. this.comment = '';
  19125. /* space at comment (only when reading header) */
  19126. // this.comm_max = 0;
  19127. /* true if there was or will be a header crc */
  19128. this.hcrc = 0;
  19129. /* true when done reading gzip header (not used when writing a gzip file) */
  19130. this.done = false;
  19131. }
  19132. module.exports = GZheader;
  19133. },{}],72:[function(require,module,exports){
  19134. 'use strict';
  19135. // See state defs from inflate.js
  19136. var BAD = 30; /* got a data error -- remain here until reset */
  19137. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  19138. /*
  19139. Decode literal, length, and distance codes and write out the resulting
  19140. literal and match bytes until either not enough input or output is
  19141. available, an end-of-block is encountered, or a data error is encountered.
  19142. When large enough input and output buffers are supplied to inflate(), for
  19143. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  19144. inflate execution time is spent in this routine.
  19145. Entry assumptions:
  19146. state.mode === LEN
  19147. strm.avail_in >= 6
  19148. strm.avail_out >= 258
  19149. start >= strm.avail_out
  19150. state.bits < 8
  19151. On return, state.mode is one of:
  19152. LEN -- ran out of enough output space or enough available input
  19153. TYPE -- reached end of block code, inflate() to interpret next block
  19154. BAD -- error in block data
  19155. Notes:
  19156. - The maximum input bits used by a length/distance pair is 15 bits for the
  19157. length code, 5 bits for the length extra, 15 bits for the distance code,
  19158. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  19159. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  19160. checking for available input while decoding.
  19161. - The maximum bytes that a single length/distance pair can output is 258
  19162. bytes, which is the maximum length that can be coded. inflate_fast()
  19163. requires strm.avail_out >= 258 for each loop to avoid checking for
  19164. output space.
  19165. */
  19166. module.exports = function inflate_fast(strm, start) {
  19167. var state;
  19168. var _in; /* local strm.input */
  19169. var last; /* have enough input while in < last */
  19170. var _out; /* local strm.output */
  19171. var beg; /* inflate()'s initial strm.output */
  19172. var end; /* while out < end, enough space available */
  19173. //#ifdef INFLATE_STRICT
  19174. var dmax; /* maximum distance from zlib header */
  19175. //#endif
  19176. var wsize; /* window size or zero if not using window */
  19177. var whave; /* valid bytes in the window */
  19178. var wnext; /* window write index */
  19179. var window; /* allocated sliding window, if wsize != 0 */
  19180. var hold; /* local strm.hold */
  19181. var bits; /* local strm.bits */
  19182. var lcode; /* local strm.lencode */
  19183. var dcode; /* local strm.distcode */
  19184. var lmask; /* mask for first level of length codes */
  19185. var dmask; /* mask for first level of distance codes */
  19186. var here; /* retrieved table entry */
  19187. var op; /* code bits, operation, extra bits, or */
  19188. /* window position, window bytes to copy */
  19189. var len; /* match length, unused bytes */
  19190. var dist; /* match distance */
  19191. var from; /* where to copy match from */
  19192. var from_source;
  19193. var input, output; // JS specific, because we have no pointers
  19194. /* copy state to local variables */
  19195. state = strm.state;
  19196. //here = state.here;
  19197. _in = strm.next_in;
  19198. input = strm.input;
  19199. last = _in + (strm.avail_in - 5);
  19200. _out = strm.next_out;
  19201. output = strm.output;
  19202. beg = _out - (start - strm.avail_out);
  19203. end = _out + (strm.avail_out - 257);
  19204. //#ifdef INFLATE_STRICT
  19205. dmax = state.dmax;
  19206. //#endif
  19207. wsize = state.wsize;
  19208. whave = state.whave;
  19209. wnext = state.wnext;
  19210. window = state.window;
  19211. hold = state.hold;
  19212. bits = state.bits;
  19213. lcode = state.lencode;
  19214. dcode = state.distcode;
  19215. lmask = (1 << state.lenbits) - 1;
  19216. dmask = (1 << state.distbits) - 1;
  19217. /* decode literals and length/distances until end-of-block or not enough
  19218. input data or output space */
  19219. top:
  19220. do {
  19221. if (bits < 15) {
  19222. hold += input[_in++] << bits;
  19223. bits += 8;
  19224. hold += input[_in++] << bits;
  19225. bits += 8;
  19226. }
  19227. here = lcode[hold & lmask];
  19228. dolen:
  19229. for (;;) { // Goto emulation
  19230. op = here >>> 24/*here.bits*/;
  19231. hold >>>= op;
  19232. bits -= op;
  19233. op = (here >>> 16) & 0xff/*here.op*/;
  19234. if (op === 0) { /* literal */
  19235. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  19236. // "inflate: literal '%c'\n" :
  19237. // "inflate: literal 0x%02x\n", here.val));
  19238. output[_out++] = here & 0xffff/*here.val*/;
  19239. }
  19240. else if (op & 16) { /* length base */
  19241. len = here & 0xffff/*here.val*/;
  19242. op &= 15; /* number of extra bits */
  19243. if (op) {
  19244. if (bits < op) {
  19245. hold += input[_in++] << bits;
  19246. bits += 8;
  19247. }
  19248. len += hold & ((1 << op) - 1);
  19249. hold >>>= op;
  19250. bits -= op;
  19251. }
  19252. //Tracevv((stderr, "inflate: length %u\n", len));
  19253. if (bits < 15) {
  19254. hold += input[_in++] << bits;
  19255. bits += 8;
  19256. hold += input[_in++] << bits;
  19257. bits += 8;
  19258. }
  19259. here = dcode[hold & dmask];
  19260. dodist:
  19261. for (;;) { // goto emulation
  19262. op = here >>> 24/*here.bits*/;
  19263. hold >>>= op;
  19264. bits -= op;
  19265. op = (here >>> 16) & 0xff/*here.op*/;
  19266. if (op & 16) { /* distance base */
  19267. dist = here & 0xffff/*here.val*/;
  19268. op &= 15; /* number of extra bits */
  19269. if (bits < op) {
  19270. hold += input[_in++] << bits;
  19271. bits += 8;
  19272. if (bits < op) {
  19273. hold += input[_in++] << bits;
  19274. bits += 8;
  19275. }
  19276. }
  19277. dist += hold & ((1 << op) - 1);
  19278. //#ifdef INFLATE_STRICT
  19279. if (dist > dmax) {
  19280. strm.msg = 'invalid distance too far back';
  19281. state.mode = BAD;
  19282. break top;
  19283. }
  19284. //#endif
  19285. hold >>>= op;
  19286. bits -= op;
  19287. //Tracevv((stderr, "inflate: distance %u\n", dist));
  19288. op = _out - beg; /* max distance in output */
  19289. if (dist > op) { /* see if copy from window */
  19290. op = dist - op; /* distance back in window */
  19291. if (op > whave) {
  19292. if (state.sane) {
  19293. strm.msg = 'invalid distance too far back';
  19294. state.mode = BAD;
  19295. break top;
  19296. }
  19297. // (!) This block is disabled in zlib defailts,
  19298. // don't enable it for binary compatibility
  19299. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  19300. // if (len <= op - whave) {
  19301. // do {
  19302. // output[_out++] = 0;
  19303. // } while (--len);
  19304. // continue top;
  19305. // }
  19306. // len -= op - whave;
  19307. // do {
  19308. // output[_out++] = 0;
  19309. // } while (--op > whave);
  19310. // if (op === 0) {
  19311. // from = _out - dist;
  19312. // do {
  19313. // output[_out++] = output[from++];
  19314. // } while (--len);
  19315. // continue top;
  19316. // }
  19317. //#endif
  19318. }
  19319. from = 0; // window index
  19320. from_source = window;
  19321. if (wnext === 0) { /* very common case */
  19322. from += wsize - op;
  19323. if (op < len) { /* some from window */
  19324. len -= op;
  19325. do {
  19326. output[_out++] = window[from++];
  19327. } while (--op);
  19328. from = _out - dist; /* rest from output */
  19329. from_source = output;
  19330. }
  19331. }
  19332. else if (wnext < op) { /* wrap around window */
  19333. from += wsize + wnext - op;
  19334. op -= wnext;
  19335. if (op < len) { /* some from end of window */
  19336. len -= op;
  19337. do {
  19338. output[_out++] = window[from++];
  19339. } while (--op);
  19340. from = 0;
  19341. if (wnext < len) { /* some from start of window */
  19342. op = wnext;
  19343. len -= op;
  19344. do {
  19345. output[_out++] = window[from++];
  19346. } while (--op);
  19347. from = _out - dist; /* rest from output */
  19348. from_source = output;
  19349. }
  19350. }
  19351. }
  19352. else { /* contiguous in window */
  19353. from += wnext - op;
  19354. if (op < len) { /* some from window */
  19355. len -= op;
  19356. do {
  19357. output[_out++] = window[from++];
  19358. } while (--op);
  19359. from = _out - dist; /* rest from output */
  19360. from_source = output;
  19361. }
  19362. }
  19363. while (len > 2) {
  19364. output[_out++] = from_source[from++];
  19365. output[_out++] = from_source[from++];
  19366. output[_out++] = from_source[from++];
  19367. len -= 3;
  19368. }
  19369. if (len) {
  19370. output[_out++] = from_source[from++];
  19371. if (len > 1) {
  19372. output[_out++] = from_source[from++];
  19373. }
  19374. }
  19375. }
  19376. else {
  19377. from = _out - dist; /* copy direct from output */
  19378. do { /* minimum length is three */
  19379. output[_out++] = output[from++];
  19380. output[_out++] = output[from++];
  19381. output[_out++] = output[from++];
  19382. len -= 3;
  19383. } while (len > 2);
  19384. if (len) {
  19385. output[_out++] = output[from++];
  19386. if (len > 1) {
  19387. output[_out++] = output[from++];
  19388. }
  19389. }
  19390. }
  19391. }
  19392. else if ((op & 64) === 0) { /* 2nd level distance code */
  19393. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  19394. continue dodist;
  19395. }
  19396. else {
  19397. strm.msg = 'invalid distance code';
  19398. state.mode = BAD;
  19399. break top;
  19400. }
  19401. break; // need to emulate goto via "continue"
  19402. }
  19403. }
  19404. else if ((op & 64) === 0) { /* 2nd level length code */
  19405. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  19406. continue dolen;
  19407. }
  19408. else if (op & 32) { /* end-of-block */
  19409. //Tracevv((stderr, "inflate: end of block\n"));
  19410. state.mode = TYPE;
  19411. break top;
  19412. }
  19413. else {
  19414. strm.msg = 'invalid literal/length code';
  19415. state.mode = BAD;
  19416. break top;
  19417. }
  19418. break; // need to emulate goto via "continue"
  19419. }
  19420. } while (_in < last && _out < end);
  19421. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  19422. len = bits >> 3;
  19423. _in -= len;
  19424. bits -= len << 3;
  19425. hold &= (1 << bits) - 1;
  19426. /* update state and return */
  19427. strm.next_in = _in;
  19428. strm.next_out = _out;
  19429. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  19430. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  19431. state.hold = hold;
  19432. state.bits = bits;
  19433. return;
  19434. };
  19435. },{}],73:[function(require,module,exports){
  19436. 'use strict';
  19437. var utils = require('../utils/common');
  19438. var adler32 = require('./adler32');
  19439. var crc32 = require('./crc32');
  19440. var inflate_fast = require('./inffast');
  19441. var inflate_table = require('./inftrees');
  19442. var CODES = 0;
  19443. var LENS = 1;
  19444. var DISTS = 2;
  19445. /* Public constants ==========================================================*/
  19446. /* ===========================================================================*/
  19447. /* Allowed flush values; see deflate() and inflate() below for details */
  19448. //var Z_NO_FLUSH = 0;
  19449. //var Z_PARTIAL_FLUSH = 1;
  19450. //var Z_SYNC_FLUSH = 2;
  19451. //var Z_FULL_FLUSH = 3;
  19452. var Z_FINISH = 4;
  19453. var Z_BLOCK = 5;
  19454. var Z_TREES = 6;
  19455. /* Return codes for the compression/decompression functions. Negative values
  19456. * are errors, positive values are used for special but normal events.
  19457. */
  19458. var Z_OK = 0;
  19459. var Z_STREAM_END = 1;
  19460. var Z_NEED_DICT = 2;
  19461. //var Z_ERRNO = -1;
  19462. var Z_STREAM_ERROR = -2;
  19463. var Z_DATA_ERROR = -3;
  19464. var Z_MEM_ERROR = -4;
  19465. var Z_BUF_ERROR = -5;
  19466. //var Z_VERSION_ERROR = -6;
  19467. /* The deflate compression method */
  19468. var Z_DEFLATED = 8;
  19469. /* STATES ====================================================================*/
  19470. /* ===========================================================================*/
  19471. var HEAD = 1; /* i: waiting for magic header */
  19472. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  19473. var TIME = 3; /* i: waiting for modification time (gzip) */
  19474. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  19475. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  19476. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  19477. var NAME = 7; /* i: waiting for end of file name (gzip) */
  19478. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  19479. var HCRC = 9; /* i: waiting for header crc (gzip) */
  19480. var DICTID = 10; /* i: waiting for dictionary check value */
  19481. var DICT = 11; /* waiting for inflateSetDictionary() call */
  19482. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  19483. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  19484. var STORED = 14; /* i: waiting for stored size (length and complement) */
  19485. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  19486. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  19487. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  19488. var LENLENS = 18; /* i: waiting for code length code lengths */
  19489. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  19490. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  19491. var LEN = 21; /* i: waiting for length/lit/eob code */
  19492. var LENEXT = 22; /* i: waiting for length extra bits */
  19493. var DIST = 23; /* i: waiting for distance code */
  19494. var DISTEXT = 24; /* i: waiting for distance extra bits */
  19495. var MATCH = 25; /* o: waiting for output space to copy string */
  19496. var LIT = 26; /* o: waiting for output space to write literal */
  19497. var CHECK = 27; /* i: waiting for 32-bit check value */
  19498. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  19499. var DONE = 29; /* finished check, done -- remain here until reset */
  19500. var BAD = 30; /* got a data error -- remain here until reset */
  19501. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  19502. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  19503. /* ===========================================================================*/
  19504. var ENOUGH_LENS = 852;
  19505. var ENOUGH_DISTS = 592;
  19506. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  19507. var MAX_WBITS = 15;
  19508. /* 32K LZ77 window */
  19509. var DEF_WBITS = MAX_WBITS;
  19510. function ZSWAP32(q) {
  19511. return (((q >>> 24) & 0xff) +
  19512. ((q >>> 8) & 0xff00) +
  19513. ((q & 0xff00) << 8) +
  19514. ((q & 0xff) << 24));
  19515. }
  19516. function InflateState() {
  19517. this.mode = 0; /* current inflate mode */
  19518. this.last = false; /* true if processing last block */
  19519. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  19520. this.havedict = false; /* true if dictionary provided */
  19521. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  19522. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  19523. this.check = 0; /* protected copy of check value */
  19524. this.total = 0; /* protected copy of output count */
  19525. // TODO: may be {}
  19526. this.head = null; /* where to save gzip header information */
  19527. /* sliding window */
  19528. this.wbits = 0; /* log base 2 of requested window size */
  19529. this.wsize = 0; /* window size or zero if not using window */
  19530. this.whave = 0; /* valid bytes in the window */
  19531. this.wnext = 0; /* window write index */
  19532. this.window = null; /* allocated sliding window, if needed */
  19533. /* bit accumulator */
  19534. this.hold = 0; /* input bit accumulator */
  19535. this.bits = 0; /* number of bits in "in" */
  19536. /* for string and stored block copying */
  19537. this.length = 0; /* literal or length of data to copy */
  19538. this.offset = 0; /* distance back to copy string from */
  19539. /* for table and code decoding */
  19540. this.extra = 0; /* extra bits needed */
  19541. /* fixed and dynamic code tables */
  19542. this.lencode = null; /* starting table for length/literal codes */
  19543. this.distcode = null; /* starting table for distance codes */
  19544. this.lenbits = 0; /* index bits for lencode */
  19545. this.distbits = 0; /* index bits for distcode */
  19546. /* dynamic table building */
  19547. this.ncode = 0; /* number of code length code lengths */
  19548. this.nlen = 0; /* number of length code lengths */
  19549. this.ndist = 0; /* number of distance code lengths */
  19550. this.have = 0; /* number of code lengths in lens[] */
  19551. this.next = null; /* next available space in codes[] */
  19552. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  19553. this.work = new utils.Buf16(288); /* work area for code table building */
  19554. /*
  19555. because we don't have pointers in js, we use lencode and distcode directly
  19556. as buffers so we don't need codes
  19557. */
  19558. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  19559. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  19560. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  19561. this.sane = 0; /* if false, allow invalid distance too far */
  19562. this.back = 0; /* bits back of last unprocessed length/lit */
  19563. this.was = 0; /* initial length of match */
  19564. }
  19565. function inflateResetKeep(strm) {
  19566. var state;
  19567. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19568. state = strm.state;
  19569. strm.total_in = strm.total_out = state.total = 0;
  19570. strm.msg = ''; /*Z_NULL*/
  19571. if (state.wrap) { /* to support ill-conceived Java test suite */
  19572. strm.adler = state.wrap & 1;
  19573. }
  19574. state.mode = HEAD;
  19575. state.last = 0;
  19576. state.havedict = 0;
  19577. state.dmax = 32768;
  19578. state.head = null/*Z_NULL*/;
  19579. state.hold = 0;
  19580. state.bits = 0;
  19581. //state.lencode = state.distcode = state.next = state.codes;
  19582. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  19583. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  19584. state.sane = 1;
  19585. state.back = -1;
  19586. //Tracev((stderr, "inflate: reset\n"));
  19587. return Z_OK;
  19588. }
  19589. function inflateReset(strm) {
  19590. var state;
  19591. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19592. state = strm.state;
  19593. state.wsize = 0;
  19594. state.whave = 0;
  19595. state.wnext = 0;
  19596. return inflateResetKeep(strm);
  19597. }
  19598. function inflateReset2(strm, windowBits) {
  19599. var wrap;
  19600. var state;
  19601. /* get the state */
  19602. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19603. state = strm.state;
  19604. /* extract wrap request from windowBits parameter */
  19605. if (windowBits < 0) {
  19606. wrap = 0;
  19607. windowBits = -windowBits;
  19608. }
  19609. else {
  19610. wrap = (windowBits >> 4) + 1;
  19611. if (windowBits < 48) {
  19612. windowBits &= 15;
  19613. }
  19614. }
  19615. /* set number of window bits, free window if different */
  19616. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  19617. return Z_STREAM_ERROR;
  19618. }
  19619. if (state.window !== null && state.wbits !== windowBits) {
  19620. state.window = null;
  19621. }
  19622. /* update state and reset the rest of it */
  19623. state.wrap = wrap;
  19624. state.wbits = windowBits;
  19625. return inflateReset(strm);
  19626. }
  19627. function inflateInit2(strm, windowBits) {
  19628. var ret;
  19629. var state;
  19630. if (!strm) { return Z_STREAM_ERROR; }
  19631. //strm.msg = Z_NULL; /* in case we return an error */
  19632. state = new InflateState();
  19633. //if (state === Z_NULL) return Z_MEM_ERROR;
  19634. //Tracev((stderr, "inflate: allocated\n"));
  19635. strm.state = state;
  19636. state.window = null/*Z_NULL*/;
  19637. ret = inflateReset2(strm, windowBits);
  19638. if (ret !== Z_OK) {
  19639. strm.state = null/*Z_NULL*/;
  19640. }
  19641. return ret;
  19642. }
  19643. function inflateInit(strm) {
  19644. return inflateInit2(strm, DEF_WBITS);
  19645. }
  19646. /*
  19647. Return state with length and distance decoding tables and index sizes set to
  19648. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  19649. If BUILDFIXED is defined, then instead this routine builds the tables the
  19650. first time it's called, and returns those tables the first time and
  19651. thereafter. This reduces the size of the code by about 2K bytes, in
  19652. exchange for a little execution time. However, BUILDFIXED should not be
  19653. used for threaded applications, since the rewriting of the tables and virgin
  19654. may not be thread-safe.
  19655. */
  19656. var virgin = true;
  19657. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  19658. function fixedtables(state) {
  19659. /* build fixed huffman tables if first call (may not be thread safe) */
  19660. if (virgin) {
  19661. var sym;
  19662. lenfix = new utils.Buf32(512);
  19663. distfix = new utils.Buf32(32);
  19664. /* literal/length table */
  19665. sym = 0;
  19666. while (sym < 144) { state.lens[sym++] = 8; }
  19667. while (sym < 256) { state.lens[sym++] = 9; }
  19668. while (sym < 280) { state.lens[sym++] = 7; }
  19669. while (sym < 288) { state.lens[sym++] = 8; }
  19670. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  19671. /* distance table */
  19672. sym = 0;
  19673. while (sym < 32) { state.lens[sym++] = 5; }
  19674. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  19675. /* do this just once */
  19676. virgin = false;
  19677. }
  19678. state.lencode = lenfix;
  19679. state.lenbits = 9;
  19680. state.distcode = distfix;
  19681. state.distbits = 5;
  19682. }
  19683. /*
  19684. Update the window with the last wsize (normally 32K) bytes written before
  19685. returning. If window does not exist yet, create it. This is only called
  19686. when a window is already in use, or when output has been written during this
  19687. inflate call, but the end of the deflate stream has not been reached yet.
  19688. It is also called to create a window for dictionary data when a dictionary
  19689. is loaded.
  19690. Providing output buffers larger than 32K to inflate() should provide a speed
  19691. advantage, since only the last 32K of output is copied to the sliding window
  19692. upon return from inflate(), and since all distances after the first 32K of
  19693. output will fall in the output data, making match copies simpler and faster.
  19694. The advantage may be dependent on the size of the processor's data caches.
  19695. */
  19696. function updatewindow(strm, src, end, copy) {
  19697. var dist;
  19698. var state = strm.state;
  19699. /* if it hasn't been done already, allocate space for the window */
  19700. if (state.window === null) {
  19701. state.wsize = 1 << state.wbits;
  19702. state.wnext = 0;
  19703. state.whave = 0;
  19704. state.window = new utils.Buf8(state.wsize);
  19705. }
  19706. /* copy state->wsize or less output bytes into the circular window */
  19707. if (copy >= state.wsize) {
  19708. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  19709. state.wnext = 0;
  19710. state.whave = state.wsize;
  19711. }
  19712. else {
  19713. dist = state.wsize - state.wnext;
  19714. if (dist > copy) {
  19715. dist = copy;
  19716. }
  19717. //zmemcpy(state->window + state->wnext, end - copy, dist);
  19718. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  19719. copy -= dist;
  19720. if (copy) {
  19721. //zmemcpy(state->window, end - copy, copy);
  19722. utils.arraySet(state.window,src, end - copy, copy, 0);
  19723. state.wnext = copy;
  19724. state.whave = state.wsize;
  19725. }
  19726. else {
  19727. state.wnext += dist;
  19728. if (state.wnext === state.wsize) { state.wnext = 0; }
  19729. if (state.whave < state.wsize) { state.whave += dist; }
  19730. }
  19731. }
  19732. return 0;
  19733. }
  19734. function inflate(strm, flush) {
  19735. var state;
  19736. var input, output; // input/output buffers
  19737. var next; /* next input INDEX */
  19738. var put; /* next output INDEX */
  19739. var have, left; /* available input and output */
  19740. var hold; /* bit buffer */
  19741. var bits; /* bits in bit buffer */
  19742. var _in, _out; /* save starting available input and output */
  19743. var copy; /* number of stored or match bytes to copy */
  19744. var from; /* where to copy match bytes from */
  19745. var from_source;
  19746. var here = 0; /* current decoding table entry */
  19747. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  19748. //var last; /* parent table entry */
  19749. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  19750. var len; /* length to copy for repeats, bits to drop */
  19751. var ret; /* return code */
  19752. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  19753. var opts;
  19754. var n; // temporary var for NEED_BITS
  19755. var order = /* permutation of code lengths */
  19756. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  19757. if (!strm || !strm.state || !strm.output ||
  19758. (!strm.input && strm.avail_in !== 0)) {
  19759. return Z_STREAM_ERROR;
  19760. }
  19761. state = strm.state;
  19762. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  19763. //--- LOAD() ---
  19764. put = strm.next_out;
  19765. output = strm.output;
  19766. left = strm.avail_out;
  19767. next = strm.next_in;
  19768. input = strm.input;
  19769. have = strm.avail_in;
  19770. hold = state.hold;
  19771. bits = state.bits;
  19772. //---
  19773. _in = have;
  19774. _out = left;
  19775. ret = Z_OK;
  19776. inf_leave: // goto emulation
  19777. for (;;) {
  19778. switch (state.mode) {
  19779. case HEAD:
  19780. if (state.wrap === 0) {
  19781. state.mode = TYPEDO;
  19782. break;
  19783. }
  19784. //=== NEEDBITS(16);
  19785. while (bits < 16) {
  19786. if (have === 0) { break inf_leave; }
  19787. have--;
  19788. hold += input[next++] << bits;
  19789. bits += 8;
  19790. }
  19791. //===//
  19792. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  19793. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  19794. //=== CRC2(state.check, hold);
  19795. hbuf[0] = hold & 0xff;
  19796. hbuf[1] = (hold >>> 8) & 0xff;
  19797. state.check = crc32(state.check, hbuf, 2, 0);
  19798. //===//
  19799. //=== INITBITS();
  19800. hold = 0;
  19801. bits = 0;
  19802. //===//
  19803. state.mode = FLAGS;
  19804. break;
  19805. }
  19806. state.flags = 0; /* expect zlib header */
  19807. if (state.head) {
  19808. state.head.done = false;
  19809. }
  19810. if (!(state.wrap & 1) || /* check if zlib header allowed */
  19811. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  19812. strm.msg = 'incorrect header check';
  19813. state.mode = BAD;
  19814. break;
  19815. }
  19816. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  19817. strm.msg = 'unknown compression method';
  19818. state.mode = BAD;
  19819. break;
  19820. }
  19821. //--- DROPBITS(4) ---//
  19822. hold >>>= 4;
  19823. bits -= 4;
  19824. //---//
  19825. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  19826. if (state.wbits === 0) {
  19827. state.wbits = len;
  19828. }
  19829. else if (len > state.wbits) {
  19830. strm.msg = 'invalid window size';
  19831. state.mode = BAD;
  19832. break;
  19833. }
  19834. state.dmax = 1 << len;
  19835. //Tracev((stderr, "inflate: zlib header ok\n"));
  19836. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  19837. state.mode = hold & 0x200 ? DICTID : TYPE;
  19838. //=== INITBITS();
  19839. hold = 0;
  19840. bits = 0;
  19841. //===//
  19842. break;
  19843. case FLAGS:
  19844. //=== NEEDBITS(16); */
  19845. while (bits < 16) {
  19846. if (have === 0) { break inf_leave; }
  19847. have--;
  19848. hold += input[next++] << bits;
  19849. bits += 8;
  19850. }
  19851. //===//
  19852. state.flags = hold;
  19853. if ((state.flags & 0xff) !== Z_DEFLATED) {
  19854. strm.msg = 'unknown compression method';
  19855. state.mode = BAD;
  19856. break;
  19857. }
  19858. if (state.flags & 0xe000) {
  19859. strm.msg = 'unknown header flags set';
  19860. state.mode = BAD;
  19861. break;
  19862. }
  19863. if (state.head) {
  19864. state.head.text = ((hold >> 8) & 1);
  19865. }
  19866. if (state.flags & 0x0200) {
  19867. //=== CRC2(state.check, hold);
  19868. hbuf[0] = hold & 0xff;
  19869. hbuf[1] = (hold >>> 8) & 0xff;
  19870. state.check = crc32(state.check, hbuf, 2, 0);
  19871. //===//
  19872. }
  19873. //=== INITBITS();
  19874. hold = 0;
  19875. bits = 0;
  19876. //===//
  19877. state.mode = TIME;
  19878. /* falls through */
  19879. case TIME:
  19880. //=== NEEDBITS(32); */
  19881. while (bits < 32) {
  19882. if (have === 0) { break inf_leave; }
  19883. have--;
  19884. hold += input[next++] << bits;
  19885. bits += 8;
  19886. }
  19887. //===//
  19888. if (state.head) {
  19889. state.head.time = hold;
  19890. }
  19891. if (state.flags & 0x0200) {
  19892. //=== CRC4(state.check, hold)
  19893. hbuf[0] = hold & 0xff;
  19894. hbuf[1] = (hold >>> 8) & 0xff;
  19895. hbuf[2] = (hold >>> 16) & 0xff;
  19896. hbuf[3] = (hold >>> 24) & 0xff;
  19897. state.check = crc32(state.check, hbuf, 4, 0);
  19898. //===
  19899. }
  19900. //=== INITBITS();
  19901. hold = 0;
  19902. bits = 0;
  19903. //===//
  19904. state.mode = OS;
  19905. /* falls through */
  19906. case OS:
  19907. //=== NEEDBITS(16); */
  19908. while (bits < 16) {
  19909. if (have === 0) { break inf_leave; }
  19910. have--;
  19911. hold += input[next++] << bits;
  19912. bits += 8;
  19913. }
  19914. //===//
  19915. if (state.head) {
  19916. state.head.xflags = (hold & 0xff);
  19917. state.head.os = (hold >> 8);
  19918. }
  19919. if (state.flags & 0x0200) {
  19920. //=== CRC2(state.check, hold);
  19921. hbuf[0] = hold & 0xff;
  19922. hbuf[1] = (hold >>> 8) & 0xff;
  19923. state.check = crc32(state.check, hbuf, 2, 0);
  19924. //===//
  19925. }
  19926. //=== INITBITS();
  19927. hold = 0;
  19928. bits = 0;
  19929. //===//
  19930. state.mode = EXLEN;
  19931. /* falls through */
  19932. case EXLEN:
  19933. if (state.flags & 0x0400) {
  19934. //=== NEEDBITS(16); */
  19935. while (bits < 16) {
  19936. if (have === 0) { break inf_leave; }
  19937. have--;
  19938. hold += input[next++] << bits;
  19939. bits += 8;
  19940. }
  19941. //===//
  19942. state.length = hold;
  19943. if (state.head) {
  19944. state.head.extra_len = hold;
  19945. }
  19946. if (state.flags & 0x0200) {
  19947. //=== CRC2(state.check, hold);
  19948. hbuf[0] = hold & 0xff;
  19949. hbuf[1] = (hold >>> 8) & 0xff;
  19950. state.check = crc32(state.check, hbuf, 2, 0);
  19951. //===//
  19952. }
  19953. //=== INITBITS();
  19954. hold = 0;
  19955. bits = 0;
  19956. //===//
  19957. }
  19958. else if (state.head) {
  19959. state.head.extra = null/*Z_NULL*/;
  19960. }
  19961. state.mode = EXTRA;
  19962. /* falls through */
  19963. case EXTRA:
  19964. if (state.flags & 0x0400) {
  19965. copy = state.length;
  19966. if (copy > have) { copy = have; }
  19967. if (copy) {
  19968. if (state.head) {
  19969. len = state.head.extra_len - state.length;
  19970. if (!state.head.extra) {
  19971. // Use untyped array for more conveniend processing later
  19972. state.head.extra = new Array(state.head.extra_len);
  19973. }
  19974. utils.arraySet(
  19975. state.head.extra,
  19976. input,
  19977. next,
  19978. // extra field is limited to 65536 bytes
  19979. // - no need for additional size check
  19980. copy,
  19981. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  19982. len
  19983. );
  19984. //zmemcpy(state.head.extra + len, next,
  19985. // len + copy > state.head.extra_max ?
  19986. // state.head.extra_max - len : copy);
  19987. }
  19988. if (state.flags & 0x0200) {
  19989. state.check = crc32(state.check, input, copy, next);
  19990. }
  19991. have -= copy;
  19992. next += copy;
  19993. state.length -= copy;
  19994. }
  19995. if (state.length) { break inf_leave; }
  19996. }
  19997. state.length = 0;
  19998. state.mode = NAME;
  19999. /* falls through */
  20000. case NAME:
  20001. if (state.flags & 0x0800) {
  20002. if (have === 0) { break inf_leave; }
  20003. copy = 0;
  20004. do {
  20005. // TODO: 2 or 1 bytes?
  20006. len = input[next + copy++];
  20007. /* use constant limit because in js we should not preallocate memory */
  20008. if (state.head && len &&
  20009. (state.length < 65536 /*state.head.name_max*/)) {
  20010. state.head.name += String.fromCharCode(len);
  20011. }
  20012. } while (len && copy < have);
  20013. if (state.flags & 0x0200) {
  20014. state.check = crc32(state.check, input, copy, next);
  20015. }
  20016. have -= copy;
  20017. next += copy;
  20018. if (len) { break inf_leave; }
  20019. }
  20020. else if (state.head) {
  20021. state.head.name = null;
  20022. }
  20023. state.length = 0;
  20024. state.mode = COMMENT;
  20025. /* falls through */
  20026. case COMMENT:
  20027. if (state.flags & 0x1000) {
  20028. if (have === 0) { break inf_leave; }
  20029. copy = 0;
  20030. do {
  20031. len = input[next + copy++];
  20032. /* use constant limit because in js we should not preallocate memory */
  20033. if (state.head && len &&
  20034. (state.length < 65536 /*state.head.comm_max*/)) {
  20035. state.head.comment += String.fromCharCode(len);
  20036. }
  20037. } while (len && copy < have);
  20038. if (state.flags & 0x0200) {
  20039. state.check = crc32(state.check, input, copy, next);
  20040. }
  20041. have -= copy;
  20042. next += copy;
  20043. if (len) { break inf_leave; }
  20044. }
  20045. else if (state.head) {
  20046. state.head.comment = null;
  20047. }
  20048. state.mode = HCRC;
  20049. /* falls through */
  20050. case HCRC:
  20051. if (state.flags & 0x0200) {
  20052. //=== NEEDBITS(16); */
  20053. while (bits < 16) {
  20054. if (have === 0) { break inf_leave; }
  20055. have--;
  20056. hold += input[next++] << bits;
  20057. bits += 8;
  20058. }
  20059. //===//
  20060. if (hold !== (state.check & 0xffff)) {
  20061. strm.msg = 'header crc mismatch';
  20062. state.mode = BAD;
  20063. break;
  20064. }
  20065. //=== INITBITS();
  20066. hold = 0;
  20067. bits = 0;
  20068. //===//
  20069. }
  20070. if (state.head) {
  20071. state.head.hcrc = ((state.flags >> 9) & 1);
  20072. state.head.done = true;
  20073. }
  20074. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  20075. state.mode = TYPE;
  20076. break;
  20077. case DICTID:
  20078. //=== NEEDBITS(32); */
  20079. while (bits < 32) {
  20080. if (have === 0) { break inf_leave; }
  20081. have--;
  20082. hold += input[next++] << bits;
  20083. bits += 8;
  20084. }
  20085. //===//
  20086. strm.adler = state.check = ZSWAP32(hold);
  20087. //=== INITBITS();
  20088. hold = 0;
  20089. bits = 0;
  20090. //===//
  20091. state.mode = DICT;
  20092. /* falls through */
  20093. case DICT:
  20094. if (state.havedict === 0) {
  20095. //--- RESTORE() ---
  20096. strm.next_out = put;
  20097. strm.avail_out = left;
  20098. strm.next_in = next;
  20099. strm.avail_in = have;
  20100. state.hold = hold;
  20101. state.bits = bits;
  20102. //---
  20103. return Z_NEED_DICT;
  20104. }
  20105. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  20106. state.mode = TYPE;
  20107. /* falls through */
  20108. case TYPE:
  20109. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  20110. /* falls through */
  20111. case TYPEDO:
  20112. if (state.last) {
  20113. //--- BYTEBITS() ---//
  20114. hold >>>= bits & 7;
  20115. bits -= bits & 7;
  20116. //---//
  20117. state.mode = CHECK;
  20118. break;
  20119. }
  20120. //=== NEEDBITS(3); */
  20121. while (bits < 3) {
  20122. if (have === 0) { break inf_leave; }
  20123. have--;
  20124. hold += input[next++] << bits;
  20125. bits += 8;
  20126. }
  20127. //===//
  20128. state.last = (hold & 0x01)/*BITS(1)*/;
  20129. //--- DROPBITS(1) ---//
  20130. hold >>>= 1;
  20131. bits -= 1;
  20132. //---//
  20133. switch ((hold & 0x03)/*BITS(2)*/) {
  20134. case 0: /* stored block */
  20135. //Tracev((stderr, "inflate: stored block%s\n",
  20136. // state.last ? " (last)" : ""));
  20137. state.mode = STORED;
  20138. break;
  20139. case 1: /* fixed block */
  20140. fixedtables(state);
  20141. //Tracev((stderr, "inflate: fixed codes block%s\n",
  20142. // state.last ? " (last)" : ""));
  20143. state.mode = LEN_; /* decode codes */
  20144. if (flush === Z_TREES) {
  20145. //--- DROPBITS(2) ---//
  20146. hold >>>= 2;
  20147. bits -= 2;
  20148. //---//
  20149. break inf_leave;
  20150. }
  20151. break;
  20152. case 2: /* dynamic block */
  20153. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  20154. // state.last ? " (last)" : ""));
  20155. state.mode = TABLE;
  20156. break;
  20157. case 3:
  20158. strm.msg = 'invalid block type';
  20159. state.mode = BAD;
  20160. }
  20161. //--- DROPBITS(2) ---//
  20162. hold >>>= 2;
  20163. bits -= 2;
  20164. //---//
  20165. break;
  20166. case STORED:
  20167. //--- BYTEBITS() ---// /* go to byte boundary */
  20168. hold >>>= bits & 7;
  20169. bits -= bits & 7;
  20170. //---//
  20171. //=== NEEDBITS(32); */
  20172. while (bits < 32) {
  20173. if (have === 0) { break inf_leave; }
  20174. have--;
  20175. hold += input[next++] << bits;
  20176. bits += 8;
  20177. }
  20178. //===//
  20179. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  20180. strm.msg = 'invalid stored block lengths';
  20181. state.mode = BAD;
  20182. break;
  20183. }
  20184. state.length = hold & 0xffff;
  20185. //Tracev((stderr, "inflate: stored length %u\n",
  20186. // state.length));
  20187. //=== INITBITS();
  20188. hold = 0;
  20189. bits = 0;
  20190. //===//
  20191. state.mode = COPY_;
  20192. if (flush === Z_TREES) { break inf_leave; }
  20193. /* falls through */
  20194. case COPY_:
  20195. state.mode = COPY;
  20196. /* falls through */
  20197. case COPY:
  20198. copy = state.length;
  20199. if (copy) {
  20200. if (copy > have) { copy = have; }
  20201. if (copy > left) { copy = left; }
  20202. if (copy === 0) { break inf_leave; }
  20203. //--- zmemcpy(put, next, copy); ---
  20204. utils.arraySet(output, input, next, copy, put);
  20205. //---//
  20206. have -= copy;
  20207. next += copy;
  20208. left -= copy;
  20209. put += copy;
  20210. state.length -= copy;
  20211. break;
  20212. }
  20213. //Tracev((stderr, "inflate: stored end\n"));
  20214. state.mode = TYPE;
  20215. break;
  20216. case TABLE:
  20217. //=== NEEDBITS(14); */
  20218. while (bits < 14) {
  20219. if (have === 0) { break inf_leave; }
  20220. have--;
  20221. hold += input[next++] << bits;
  20222. bits += 8;
  20223. }
  20224. //===//
  20225. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  20226. //--- DROPBITS(5) ---//
  20227. hold >>>= 5;
  20228. bits -= 5;
  20229. //---//
  20230. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  20231. //--- DROPBITS(5) ---//
  20232. hold >>>= 5;
  20233. bits -= 5;
  20234. //---//
  20235. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  20236. //--- DROPBITS(4) ---//
  20237. hold >>>= 4;
  20238. bits -= 4;
  20239. //---//
  20240. //#ifndef PKZIP_BUG_WORKAROUND
  20241. if (state.nlen > 286 || state.ndist > 30) {
  20242. strm.msg = 'too many length or distance symbols';
  20243. state.mode = BAD;
  20244. break;
  20245. }
  20246. //#endif
  20247. //Tracev((stderr, "inflate: table sizes ok\n"));
  20248. state.have = 0;
  20249. state.mode = LENLENS;
  20250. /* falls through */
  20251. case LENLENS:
  20252. while (state.have < state.ncode) {
  20253. //=== NEEDBITS(3);
  20254. while (bits < 3) {
  20255. if (have === 0) { break inf_leave; }
  20256. have--;
  20257. hold += input[next++] << bits;
  20258. bits += 8;
  20259. }
  20260. //===//
  20261. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  20262. //--- DROPBITS(3) ---//
  20263. hold >>>= 3;
  20264. bits -= 3;
  20265. //---//
  20266. }
  20267. while (state.have < 19) {
  20268. state.lens[order[state.have++]] = 0;
  20269. }
  20270. // We have separate tables & no pointers. 2 commented lines below not needed.
  20271. //state.next = state.codes;
  20272. //state.lencode = state.next;
  20273. // Switch to use dynamic table
  20274. state.lencode = state.lendyn;
  20275. state.lenbits = 7;
  20276. opts = {bits: state.lenbits};
  20277. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  20278. state.lenbits = opts.bits;
  20279. if (ret) {
  20280. strm.msg = 'invalid code lengths set';
  20281. state.mode = BAD;
  20282. break;
  20283. }
  20284. //Tracev((stderr, "inflate: code lengths ok\n"));
  20285. state.have = 0;
  20286. state.mode = CODELENS;
  20287. /* falls through */
  20288. case CODELENS:
  20289. while (state.have < state.nlen + state.ndist) {
  20290. for (;;) {
  20291. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  20292. here_bits = here >>> 24;
  20293. here_op = (here >>> 16) & 0xff;
  20294. here_val = here & 0xffff;
  20295. if ((here_bits) <= bits) { break; }
  20296. //--- PULLBYTE() ---//
  20297. if (have === 0) { break inf_leave; }
  20298. have--;
  20299. hold += input[next++] << bits;
  20300. bits += 8;
  20301. //---//
  20302. }
  20303. if (here_val < 16) {
  20304. //--- DROPBITS(here.bits) ---//
  20305. hold >>>= here_bits;
  20306. bits -= here_bits;
  20307. //---//
  20308. state.lens[state.have++] = here_val;
  20309. }
  20310. else {
  20311. if (here_val === 16) {
  20312. //=== NEEDBITS(here.bits + 2);
  20313. n = here_bits + 2;
  20314. while (bits < n) {
  20315. if (have === 0) { break inf_leave; }
  20316. have--;
  20317. hold += input[next++] << bits;
  20318. bits += 8;
  20319. }
  20320. //===//
  20321. //--- DROPBITS(here.bits) ---//
  20322. hold >>>= here_bits;
  20323. bits -= here_bits;
  20324. //---//
  20325. if (state.have === 0) {
  20326. strm.msg = 'invalid bit length repeat';
  20327. state.mode = BAD;
  20328. break;
  20329. }
  20330. len = state.lens[state.have - 1];
  20331. copy = 3 + (hold & 0x03);//BITS(2);
  20332. //--- DROPBITS(2) ---//
  20333. hold >>>= 2;
  20334. bits -= 2;
  20335. //---//
  20336. }
  20337. else if (here_val === 17) {
  20338. //=== NEEDBITS(here.bits + 3);
  20339. n = here_bits + 3;
  20340. while (bits < n) {
  20341. if (have === 0) { break inf_leave; }
  20342. have--;
  20343. hold += input[next++] << bits;
  20344. bits += 8;
  20345. }
  20346. //===//
  20347. //--- DROPBITS(here.bits) ---//
  20348. hold >>>= here_bits;
  20349. bits -= here_bits;
  20350. //---//
  20351. len = 0;
  20352. copy = 3 + (hold & 0x07);//BITS(3);
  20353. //--- DROPBITS(3) ---//
  20354. hold >>>= 3;
  20355. bits -= 3;
  20356. //---//
  20357. }
  20358. else {
  20359. //=== NEEDBITS(here.bits + 7);
  20360. n = here_bits + 7;
  20361. while (bits < n) {
  20362. if (have === 0) { break inf_leave; }
  20363. have--;
  20364. hold += input[next++] << bits;
  20365. bits += 8;
  20366. }
  20367. //===//
  20368. //--- DROPBITS(here.bits) ---//
  20369. hold >>>= here_bits;
  20370. bits -= here_bits;
  20371. //---//
  20372. len = 0;
  20373. copy = 11 + (hold & 0x7f);//BITS(7);
  20374. //--- DROPBITS(7) ---//
  20375. hold >>>= 7;
  20376. bits -= 7;
  20377. //---//
  20378. }
  20379. if (state.have + copy > state.nlen + state.ndist) {
  20380. strm.msg = 'invalid bit length repeat';
  20381. state.mode = BAD;
  20382. break;
  20383. }
  20384. while (copy--) {
  20385. state.lens[state.have++] = len;
  20386. }
  20387. }
  20388. }
  20389. /* handle error breaks in while */
  20390. if (state.mode === BAD) { break; }
  20391. /* check for end-of-block code (better have one) */
  20392. if (state.lens[256] === 0) {
  20393. strm.msg = 'invalid code -- missing end-of-block';
  20394. state.mode = BAD;
  20395. break;
  20396. }
  20397. /* build code tables -- note: do not change the lenbits or distbits
  20398. values here (9 and 6) without reading the comments in inftrees.h
  20399. concerning the ENOUGH constants, which depend on those values */
  20400. state.lenbits = 9;
  20401. opts = {bits: state.lenbits};
  20402. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  20403. // We have separate tables & no pointers. 2 commented lines below not needed.
  20404. // state.next_index = opts.table_index;
  20405. state.lenbits = opts.bits;
  20406. // state.lencode = state.next;
  20407. if (ret) {
  20408. strm.msg = 'invalid literal/lengths set';
  20409. state.mode = BAD;
  20410. break;
  20411. }
  20412. state.distbits = 6;
  20413. //state.distcode.copy(state.codes);
  20414. // Switch to use dynamic table
  20415. state.distcode = state.distdyn;
  20416. opts = {bits: state.distbits};
  20417. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  20418. // We have separate tables & no pointers. 2 commented lines below not needed.
  20419. // state.next_index = opts.table_index;
  20420. state.distbits = opts.bits;
  20421. // state.distcode = state.next;
  20422. if (ret) {
  20423. strm.msg = 'invalid distances set';
  20424. state.mode = BAD;
  20425. break;
  20426. }
  20427. //Tracev((stderr, 'inflate: codes ok\n'));
  20428. state.mode = LEN_;
  20429. if (flush === Z_TREES) { break inf_leave; }
  20430. /* falls through */
  20431. case LEN_:
  20432. state.mode = LEN;
  20433. /* falls through */
  20434. case LEN:
  20435. if (have >= 6 && left >= 258) {
  20436. //--- RESTORE() ---
  20437. strm.next_out = put;
  20438. strm.avail_out = left;
  20439. strm.next_in = next;
  20440. strm.avail_in = have;
  20441. state.hold = hold;
  20442. state.bits = bits;
  20443. //---
  20444. inflate_fast(strm, _out);
  20445. //--- LOAD() ---
  20446. put = strm.next_out;
  20447. output = strm.output;
  20448. left = strm.avail_out;
  20449. next = strm.next_in;
  20450. input = strm.input;
  20451. have = strm.avail_in;
  20452. hold = state.hold;
  20453. bits = state.bits;
  20454. //---
  20455. if (state.mode === TYPE) {
  20456. state.back = -1;
  20457. }
  20458. break;
  20459. }
  20460. state.back = 0;
  20461. for (;;) {
  20462. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  20463. here_bits = here >>> 24;
  20464. here_op = (here >>> 16) & 0xff;
  20465. here_val = here & 0xffff;
  20466. if (here_bits <= bits) { break; }
  20467. //--- PULLBYTE() ---//
  20468. if (have === 0) { break inf_leave; }
  20469. have--;
  20470. hold += input[next++] << bits;
  20471. bits += 8;
  20472. //---//
  20473. }
  20474. if (here_op && (here_op & 0xf0) === 0) {
  20475. last_bits = here_bits;
  20476. last_op = here_op;
  20477. last_val = here_val;
  20478. for (;;) {
  20479. here = state.lencode[last_val +
  20480. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  20481. here_bits = here >>> 24;
  20482. here_op = (here >>> 16) & 0xff;
  20483. here_val = here & 0xffff;
  20484. if ((last_bits + here_bits) <= bits) { break; }
  20485. //--- PULLBYTE() ---//
  20486. if (have === 0) { break inf_leave; }
  20487. have--;
  20488. hold += input[next++] << bits;
  20489. bits += 8;
  20490. //---//
  20491. }
  20492. //--- DROPBITS(last.bits) ---//
  20493. hold >>>= last_bits;
  20494. bits -= last_bits;
  20495. //---//
  20496. state.back += last_bits;
  20497. }
  20498. //--- DROPBITS(here.bits) ---//
  20499. hold >>>= here_bits;
  20500. bits -= here_bits;
  20501. //---//
  20502. state.back += here_bits;
  20503. state.length = here_val;
  20504. if (here_op === 0) {
  20505. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  20506. // "inflate: literal '%c'\n" :
  20507. // "inflate: literal 0x%02x\n", here.val));
  20508. state.mode = LIT;
  20509. break;
  20510. }
  20511. if (here_op & 32) {
  20512. //Tracevv((stderr, "inflate: end of block\n"));
  20513. state.back = -1;
  20514. state.mode = TYPE;
  20515. break;
  20516. }
  20517. if (here_op & 64) {
  20518. strm.msg = 'invalid literal/length code';
  20519. state.mode = BAD;
  20520. break;
  20521. }
  20522. state.extra = here_op & 15;
  20523. state.mode = LENEXT;
  20524. /* falls through */
  20525. case LENEXT:
  20526. if (state.extra) {
  20527. //=== NEEDBITS(state.extra);
  20528. n = state.extra;
  20529. while (bits < n) {
  20530. if (have === 0) { break inf_leave; }
  20531. have--;
  20532. hold += input[next++] << bits;
  20533. bits += 8;
  20534. }
  20535. //===//
  20536. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  20537. //--- DROPBITS(state.extra) ---//
  20538. hold >>>= state.extra;
  20539. bits -= state.extra;
  20540. //---//
  20541. state.back += state.extra;
  20542. }
  20543. //Tracevv((stderr, "inflate: length %u\n", state.length));
  20544. state.was = state.length;
  20545. state.mode = DIST;
  20546. /* falls through */
  20547. case DIST:
  20548. for (;;) {
  20549. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  20550. here_bits = here >>> 24;
  20551. here_op = (here >>> 16) & 0xff;
  20552. here_val = here & 0xffff;
  20553. if ((here_bits) <= bits) { break; }
  20554. //--- PULLBYTE() ---//
  20555. if (have === 0) { break inf_leave; }
  20556. have--;
  20557. hold += input[next++] << bits;
  20558. bits += 8;
  20559. //---//
  20560. }
  20561. if ((here_op & 0xf0) === 0) {
  20562. last_bits = here_bits;
  20563. last_op = here_op;
  20564. last_val = here_val;
  20565. for (;;) {
  20566. here = state.distcode[last_val +
  20567. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  20568. here_bits = here >>> 24;
  20569. here_op = (here >>> 16) & 0xff;
  20570. here_val = here & 0xffff;
  20571. if ((last_bits + here_bits) <= bits) { break; }
  20572. //--- PULLBYTE() ---//
  20573. if (have === 0) { break inf_leave; }
  20574. have--;
  20575. hold += input[next++] << bits;
  20576. bits += 8;
  20577. //---//
  20578. }
  20579. //--- DROPBITS(last.bits) ---//
  20580. hold >>>= last_bits;
  20581. bits -= last_bits;
  20582. //---//
  20583. state.back += last_bits;
  20584. }
  20585. //--- DROPBITS(here.bits) ---//
  20586. hold >>>= here_bits;
  20587. bits -= here_bits;
  20588. //---//
  20589. state.back += here_bits;
  20590. if (here_op & 64) {
  20591. strm.msg = 'invalid distance code';
  20592. state.mode = BAD;
  20593. break;
  20594. }
  20595. state.offset = here_val;
  20596. state.extra = (here_op) & 15;
  20597. state.mode = DISTEXT;
  20598. /* falls through */
  20599. case DISTEXT:
  20600. if (state.extra) {
  20601. //=== NEEDBITS(state.extra);
  20602. n = state.extra;
  20603. while (bits < n) {
  20604. if (have === 0) { break inf_leave; }
  20605. have--;
  20606. hold += input[next++] << bits;
  20607. bits += 8;
  20608. }
  20609. //===//
  20610. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  20611. //--- DROPBITS(state.extra) ---//
  20612. hold >>>= state.extra;
  20613. bits -= state.extra;
  20614. //---//
  20615. state.back += state.extra;
  20616. }
  20617. //#ifdef INFLATE_STRICT
  20618. if (state.offset > state.dmax) {
  20619. strm.msg = 'invalid distance too far back';
  20620. state.mode = BAD;
  20621. break;
  20622. }
  20623. //#endif
  20624. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  20625. state.mode = MATCH;
  20626. /* falls through */
  20627. case MATCH:
  20628. if (left === 0) { break inf_leave; }
  20629. copy = _out - left;
  20630. if (state.offset > copy) { /* copy from window */
  20631. copy = state.offset - copy;
  20632. if (copy > state.whave) {
  20633. if (state.sane) {
  20634. strm.msg = 'invalid distance too far back';
  20635. state.mode = BAD;
  20636. break;
  20637. }
  20638. // (!) This block is disabled in zlib defailts,
  20639. // don't enable it for binary compatibility
  20640. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  20641. // Trace((stderr, "inflate.c too far\n"));
  20642. // copy -= state.whave;
  20643. // if (copy > state.length) { copy = state.length; }
  20644. // if (copy > left) { copy = left; }
  20645. // left -= copy;
  20646. // state.length -= copy;
  20647. // do {
  20648. // output[put++] = 0;
  20649. // } while (--copy);
  20650. // if (state.length === 0) { state.mode = LEN; }
  20651. // break;
  20652. //#endif
  20653. }
  20654. if (copy > state.wnext) {
  20655. copy -= state.wnext;
  20656. from = state.wsize - copy;
  20657. }
  20658. else {
  20659. from = state.wnext - copy;
  20660. }
  20661. if (copy > state.length) { copy = state.length; }
  20662. from_source = state.window;
  20663. }
  20664. else { /* copy from output */
  20665. from_source = output;
  20666. from = put - state.offset;
  20667. copy = state.length;
  20668. }
  20669. if (copy > left) { copy = left; }
  20670. left -= copy;
  20671. state.length -= copy;
  20672. do {
  20673. output[put++] = from_source[from++];
  20674. } while (--copy);
  20675. if (state.length === 0) { state.mode = LEN; }
  20676. break;
  20677. case LIT:
  20678. if (left === 0) { break inf_leave; }
  20679. output[put++] = state.length;
  20680. left--;
  20681. state.mode = LEN;
  20682. break;
  20683. case CHECK:
  20684. if (state.wrap) {
  20685. //=== NEEDBITS(32);
  20686. while (bits < 32) {
  20687. if (have === 0) { break inf_leave; }
  20688. have--;
  20689. // Use '|' insdead of '+' to make sure that result is signed
  20690. hold |= input[next++] << bits;
  20691. bits += 8;
  20692. }
  20693. //===//
  20694. _out -= left;
  20695. strm.total_out += _out;
  20696. state.total += _out;
  20697. if (_out) {
  20698. strm.adler = state.check =
  20699. /*UPDATE(state.check, put - _out, _out);*/
  20700. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  20701. }
  20702. _out = left;
  20703. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  20704. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  20705. strm.msg = 'incorrect data check';
  20706. state.mode = BAD;
  20707. break;
  20708. }
  20709. //=== INITBITS();
  20710. hold = 0;
  20711. bits = 0;
  20712. //===//
  20713. //Tracev((stderr, "inflate: check matches trailer\n"));
  20714. }
  20715. state.mode = LENGTH;
  20716. /* falls through */
  20717. case LENGTH:
  20718. if (state.wrap && state.flags) {
  20719. //=== NEEDBITS(32);
  20720. while (bits < 32) {
  20721. if (have === 0) { break inf_leave; }
  20722. have--;
  20723. hold += input[next++] << bits;
  20724. bits += 8;
  20725. }
  20726. //===//
  20727. if (hold !== (state.total & 0xffffffff)) {
  20728. strm.msg = 'incorrect length check';
  20729. state.mode = BAD;
  20730. break;
  20731. }
  20732. //=== INITBITS();
  20733. hold = 0;
  20734. bits = 0;
  20735. //===//
  20736. //Tracev((stderr, "inflate: length matches trailer\n"));
  20737. }
  20738. state.mode = DONE;
  20739. /* falls through */
  20740. case DONE:
  20741. ret = Z_STREAM_END;
  20742. break inf_leave;
  20743. case BAD:
  20744. ret = Z_DATA_ERROR;
  20745. break inf_leave;
  20746. case MEM:
  20747. return Z_MEM_ERROR;
  20748. case SYNC:
  20749. /* falls through */
  20750. default:
  20751. return Z_STREAM_ERROR;
  20752. }
  20753. }
  20754. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  20755. /*
  20756. Return from inflate(), updating the total counts and the check value.
  20757. If there was no progress during the inflate() call, return a buffer
  20758. error. Call updatewindow() to create and/or update the window state.
  20759. Note: a memory error from inflate() is non-recoverable.
  20760. */
  20761. //--- RESTORE() ---
  20762. strm.next_out = put;
  20763. strm.avail_out = left;
  20764. strm.next_in = next;
  20765. strm.avail_in = have;
  20766. state.hold = hold;
  20767. state.bits = bits;
  20768. //---
  20769. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  20770. (state.mode < CHECK || flush !== Z_FINISH))) {
  20771. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  20772. state.mode = MEM;
  20773. return Z_MEM_ERROR;
  20774. }
  20775. }
  20776. _in -= strm.avail_in;
  20777. _out -= strm.avail_out;
  20778. strm.total_in += _in;
  20779. strm.total_out += _out;
  20780. state.total += _out;
  20781. if (state.wrap && _out) {
  20782. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  20783. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  20784. }
  20785. strm.data_type = state.bits + (state.last ? 64 : 0) +
  20786. (state.mode === TYPE ? 128 : 0) +
  20787. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  20788. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  20789. ret = Z_BUF_ERROR;
  20790. }
  20791. return ret;
  20792. }
  20793. function inflateEnd(strm) {
  20794. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  20795. return Z_STREAM_ERROR;
  20796. }
  20797. var state = strm.state;
  20798. if (state.window) {
  20799. state.window = null;
  20800. }
  20801. strm.state = null;
  20802. return Z_OK;
  20803. }
  20804. function inflateGetHeader(strm, head) {
  20805. var state;
  20806. /* check state */
  20807. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  20808. state = strm.state;
  20809. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  20810. /* save header structure */
  20811. state.head = head;
  20812. head.done = false;
  20813. return Z_OK;
  20814. }
  20815. exports.inflateReset = inflateReset;
  20816. exports.inflateReset2 = inflateReset2;
  20817. exports.inflateResetKeep = inflateResetKeep;
  20818. exports.inflateInit = inflateInit;
  20819. exports.inflateInit2 = inflateInit2;
  20820. exports.inflate = inflate;
  20821. exports.inflateEnd = inflateEnd;
  20822. exports.inflateGetHeader = inflateGetHeader;
  20823. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  20824. /* Not implemented
  20825. exports.inflateCopy = inflateCopy;
  20826. exports.inflateGetDictionary = inflateGetDictionary;
  20827. exports.inflateMark = inflateMark;
  20828. exports.inflatePrime = inflatePrime;
  20829. exports.inflateSetDictionary = inflateSetDictionary;
  20830. exports.inflateSync = inflateSync;
  20831. exports.inflateSyncPoint = inflateSyncPoint;
  20832. exports.inflateUndermine = inflateUndermine;
  20833. */
  20834. },{"../utils/common":65,"./adler32":67,"./crc32":69,"./inffast":72,"./inftrees":74}],74:[function(require,module,exports){
  20835. 'use strict';
  20836. var utils = require('../utils/common');
  20837. var MAXBITS = 15;
  20838. var ENOUGH_LENS = 852;
  20839. var ENOUGH_DISTS = 592;
  20840. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  20841. var CODES = 0;
  20842. var LENS = 1;
  20843. var DISTS = 2;
  20844. var lbase = [ /* Length codes 257..285 base */
  20845. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  20846. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  20847. ];
  20848. var lext = [ /* Length codes 257..285 extra */
  20849. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  20850. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  20851. ];
  20852. var dbase = [ /* Distance codes 0..29 base */
  20853. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  20854. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  20855. 8193, 12289, 16385, 24577, 0, 0
  20856. ];
  20857. var dext = [ /* Distance codes 0..29 extra */
  20858. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  20859. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  20860. 28, 28, 29, 29, 64, 64
  20861. ];
  20862. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  20863. {
  20864. var bits = opts.bits;
  20865. //here = opts.here; /* table entry for duplication */
  20866. var len = 0; /* a code's length in bits */
  20867. var sym = 0; /* index of code symbols */
  20868. var min = 0, max = 0; /* minimum and maximum code lengths */
  20869. var root = 0; /* number of index bits for root table */
  20870. var curr = 0; /* number of index bits for current table */
  20871. var drop = 0; /* code bits to drop for sub-table */
  20872. var left = 0; /* number of prefix codes available */
  20873. var used = 0; /* code entries in table used */
  20874. var huff = 0; /* Huffman code */
  20875. var incr; /* for incrementing code, index */
  20876. var fill; /* index for replicating entries */
  20877. var low; /* low bits for current root entry */
  20878. var mask; /* mask for low root bits */
  20879. var next; /* next available space in table */
  20880. var base = null; /* base value table to use */
  20881. var base_index = 0;
  20882. // var shoextra; /* extra bits table to use */
  20883. var end; /* use base and extra for symbol > end */
  20884. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  20885. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  20886. var extra = null;
  20887. var extra_index = 0;
  20888. var here_bits, here_op, here_val;
  20889. /*
  20890. Process a set of code lengths to create a canonical Huffman code. The
  20891. code lengths are lens[0..codes-1]. Each length corresponds to the
  20892. symbols 0..codes-1. The Huffman code is generated by first sorting the
  20893. symbols by length from short to long, and retaining the symbol order
  20894. for codes with equal lengths. Then the code starts with all zero bits
  20895. for the first code of the shortest length, and the codes are integer
  20896. increments for the same length, and zeros are appended as the length
  20897. increases. For the deflate format, these bits are stored backwards
  20898. from their more natural integer increment ordering, and so when the
  20899. decoding tables are built in the large loop below, the integer codes
  20900. are incremented backwards.
  20901. This routine assumes, but does not check, that all of the entries in
  20902. lens[] are in the range 0..MAXBITS. The caller must assure this.
  20903. 1..MAXBITS is interpreted as that code length. zero means that that
  20904. symbol does not occur in this code.
  20905. The codes are sorted by computing a count of codes for each length,
  20906. creating from that a table of starting indices for each length in the
  20907. sorted table, and then entering the symbols in order in the sorted
  20908. table. The sorted table is work[], with that space being provided by
  20909. the caller.
  20910. The length counts are used for other purposes as well, i.e. finding
  20911. the minimum and maximum length codes, determining if there are any
  20912. codes at all, checking for a valid set of lengths, and looking ahead
  20913. at length counts to determine sub-table sizes when building the
  20914. decoding tables.
  20915. */
  20916. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  20917. for (len = 0; len <= MAXBITS; len++) {
  20918. count[len] = 0;
  20919. }
  20920. for (sym = 0; sym < codes; sym++) {
  20921. count[lens[lens_index + sym]]++;
  20922. }
  20923. /* bound code lengths, force root to be within code lengths */
  20924. root = bits;
  20925. for (max = MAXBITS; max >= 1; max--) {
  20926. if (count[max] !== 0) { break; }
  20927. }
  20928. if (root > max) {
  20929. root = max;
  20930. }
  20931. if (max === 0) { /* no symbols to code at all */
  20932. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  20933. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  20934. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  20935. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  20936. //table.op[opts.table_index] = 64;
  20937. //table.bits[opts.table_index] = 1;
  20938. //table.val[opts.table_index++] = 0;
  20939. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  20940. opts.bits = 1;
  20941. return 0; /* no symbols, but wait for decoding to report error */
  20942. }
  20943. for (min = 1; min < max; min++) {
  20944. if (count[min] !== 0) { break; }
  20945. }
  20946. if (root < min) {
  20947. root = min;
  20948. }
  20949. /* check for an over-subscribed or incomplete set of lengths */
  20950. left = 1;
  20951. for (len = 1; len <= MAXBITS; len++) {
  20952. left <<= 1;
  20953. left -= count[len];
  20954. if (left < 0) {
  20955. return -1;
  20956. } /* over-subscribed */
  20957. }
  20958. if (left > 0 && (type === CODES || max !== 1)) {
  20959. return -1; /* incomplete set */
  20960. }
  20961. /* generate offsets into symbol table for each length for sorting */
  20962. offs[1] = 0;
  20963. for (len = 1; len < MAXBITS; len++) {
  20964. offs[len + 1] = offs[len] + count[len];
  20965. }
  20966. /* sort symbols by length, by symbol order within each length */
  20967. for (sym = 0; sym < codes; sym++) {
  20968. if (lens[lens_index + sym] !== 0) {
  20969. work[offs[lens[lens_index + sym]]++] = sym;
  20970. }
  20971. }
  20972. /*
  20973. Create and fill in decoding tables. In this loop, the table being
  20974. filled is at next and has curr index bits. The code being used is huff
  20975. with length len. That code is converted to an index by dropping drop
  20976. bits off of the bottom. For codes where len is less than drop + curr,
  20977. those top drop + curr - len bits are incremented through all values to
  20978. fill the table with replicated entries.
  20979. root is the number of index bits for the root table. When len exceeds
  20980. root, sub-tables are created pointed to by the root entry with an index
  20981. of the low root bits of huff. This is saved in low to check for when a
  20982. new sub-table should be started. drop is zero when the root table is
  20983. being filled, and drop is root when sub-tables are being filled.
  20984. When a new sub-table is needed, it is necessary to look ahead in the
  20985. code lengths to determine what size sub-table is needed. The length
  20986. counts are used for this, and so count[] is decremented as codes are
  20987. entered in the tables.
  20988. used keeps track of how many table entries have been allocated from the
  20989. provided *table space. It is checked for LENS and DIST tables against
  20990. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  20991. the initial root table size constants. See the comments in inftrees.h
  20992. for more information.
  20993. sym increments through all symbols, and the loop terminates when
  20994. all codes of length max, i.e. all codes, have been processed. This
  20995. routine permits incomplete codes, so another loop after this one fills
  20996. in the rest of the decoding tables with invalid code markers.
  20997. */
  20998. /* set up for code type */
  20999. // poor man optimization - use if-else instead of switch,
  21000. // to avoid deopts in old v8
  21001. if (type === CODES) {
  21002. base = extra = work; /* dummy value--not used */
  21003. end = 19;
  21004. } else if (type === LENS) {
  21005. base = lbase;
  21006. base_index -= 257;
  21007. extra = lext;
  21008. extra_index -= 257;
  21009. end = 256;
  21010. } else { /* DISTS */
  21011. base = dbase;
  21012. extra = dext;
  21013. end = -1;
  21014. }
  21015. /* initialize opts for loop */
  21016. huff = 0; /* starting code */
  21017. sym = 0; /* starting code symbol */
  21018. len = min; /* starting code length */
  21019. next = table_index; /* current table to fill in */
  21020. curr = root; /* current table index bits */
  21021. drop = 0; /* current bits to drop from code for index */
  21022. low = -1; /* trigger new sub-table when len > root */
  21023. used = 1 << root; /* use root table entries */
  21024. mask = used - 1; /* mask for comparing low */
  21025. /* check available table space */
  21026. if ((type === LENS && used > ENOUGH_LENS) ||
  21027. (type === DISTS && used > ENOUGH_DISTS)) {
  21028. return 1;
  21029. }
  21030. var i=0;
  21031. /* process all codes and make table entries */
  21032. for (;;) {
  21033. i++;
  21034. /* create table entry */
  21035. here_bits = len - drop;
  21036. if (work[sym] < end) {
  21037. here_op = 0;
  21038. here_val = work[sym];
  21039. }
  21040. else if (work[sym] > end) {
  21041. here_op = extra[extra_index + work[sym]];
  21042. here_val = base[base_index + work[sym]];
  21043. }
  21044. else {
  21045. here_op = 32 + 64; /* end of block */
  21046. here_val = 0;
  21047. }
  21048. /* replicate for those indices with low len bits equal to huff */
  21049. incr = 1 << (len - drop);
  21050. fill = 1 << curr;
  21051. min = fill; /* save offset to next table */
  21052. do {
  21053. fill -= incr;
  21054. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  21055. } while (fill !== 0);
  21056. /* backwards increment the len-bit code huff */
  21057. incr = 1 << (len - 1);
  21058. while (huff & incr) {
  21059. incr >>= 1;
  21060. }
  21061. if (incr !== 0) {
  21062. huff &= incr - 1;
  21063. huff += incr;
  21064. } else {
  21065. huff = 0;
  21066. }
  21067. /* go to next symbol, update count, len */
  21068. sym++;
  21069. if (--count[len] === 0) {
  21070. if (len === max) { break; }
  21071. len = lens[lens_index + work[sym]];
  21072. }
  21073. /* create new sub-table if needed */
  21074. if (len > root && (huff & mask) !== low) {
  21075. /* if first time, transition to sub-tables */
  21076. if (drop === 0) {
  21077. drop = root;
  21078. }
  21079. /* increment past last table */
  21080. next += min; /* here min is 1 << curr */
  21081. /* determine length of next table */
  21082. curr = len - drop;
  21083. left = 1 << curr;
  21084. while (curr + drop < max) {
  21085. left -= count[curr + drop];
  21086. if (left <= 0) { break; }
  21087. curr++;
  21088. left <<= 1;
  21089. }
  21090. /* check for enough space */
  21091. used += 1 << curr;
  21092. if ((type === LENS && used > ENOUGH_LENS) ||
  21093. (type === DISTS && used > ENOUGH_DISTS)) {
  21094. return 1;
  21095. }
  21096. /* point entry in root table to sub-table */
  21097. low = huff & mask;
  21098. /*table.op[low] = curr;
  21099. table.bits[low] = root;
  21100. table.val[low] = next - opts.table_index;*/
  21101. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  21102. }
  21103. }
  21104. /* fill in remaining table entry if code is incomplete (guaranteed to have
  21105. at most one remaining entry, since if the code is incomplete, the
  21106. maximum code length that was allowed to get this far is one bit) */
  21107. if (huff !== 0) {
  21108. //table.op[next + huff] = 64; /* invalid code marker */
  21109. //table.bits[next + huff] = len - drop;
  21110. //table.val[next + huff] = 0;
  21111. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  21112. }
  21113. /* set return parameters */
  21114. //opts.table_index += used;
  21115. opts.bits = root;
  21116. return 0;
  21117. };
  21118. },{"../utils/common":65}],75:[function(require,module,exports){
  21119. 'use strict';
  21120. module.exports = {
  21121. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  21122. '1': 'stream end', /* Z_STREAM_END 1 */
  21123. '0': '', /* Z_OK 0 */
  21124. '-1': 'file error', /* Z_ERRNO (-1) */
  21125. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  21126. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  21127. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  21128. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  21129. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  21130. };
  21131. },{}],76:[function(require,module,exports){
  21132. 'use strict';
  21133. var utils = require('../utils/common');
  21134. /* Public constants ==========================================================*/
  21135. /* ===========================================================================*/
  21136. //var Z_FILTERED = 1;
  21137. //var Z_HUFFMAN_ONLY = 2;
  21138. //var Z_RLE = 3;
  21139. var Z_FIXED = 4;
  21140. //var Z_DEFAULT_STRATEGY = 0;
  21141. /* Possible values of the data_type field (though see inflate()) */
  21142. var Z_BINARY = 0;
  21143. var Z_TEXT = 1;
  21144. //var Z_ASCII = 1; // = Z_TEXT
  21145. var Z_UNKNOWN = 2;
  21146. /*============================================================================*/
  21147. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  21148. // From zutil.h
  21149. var STORED_BLOCK = 0;
  21150. var STATIC_TREES = 1;
  21151. var DYN_TREES = 2;
  21152. /* The three kinds of block type */
  21153. var MIN_MATCH = 3;
  21154. var MAX_MATCH = 258;
  21155. /* The minimum and maximum match lengths */
  21156. // From deflate.h
  21157. /* ===========================================================================
  21158. * Internal compression state.
  21159. */
  21160. var LENGTH_CODES = 29;
  21161. /* number of length codes, not counting the special END_BLOCK code */
  21162. var LITERALS = 256;
  21163. /* number of literal bytes 0..255 */
  21164. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  21165. /* number of Literal or Length codes, including the END_BLOCK code */
  21166. var D_CODES = 30;
  21167. /* number of distance codes */
  21168. var BL_CODES = 19;
  21169. /* number of codes used to transfer the bit lengths */
  21170. var HEAP_SIZE = 2*L_CODES + 1;
  21171. /* maximum heap size */
  21172. var MAX_BITS = 15;
  21173. /* All codes must not exceed MAX_BITS bits */
  21174. var Buf_size = 16;
  21175. /* size of bit buffer in bi_buf */
  21176. /* ===========================================================================
  21177. * Constants
  21178. */
  21179. var MAX_BL_BITS = 7;
  21180. /* Bit length codes must not exceed MAX_BL_BITS bits */
  21181. var END_BLOCK = 256;
  21182. /* end of block literal code */
  21183. var REP_3_6 = 16;
  21184. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  21185. var REPZ_3_10 = 17;
  21186. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  21187. var REPZ_11_138 = 18;
  21188. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  21189. var extra_lbits = /* extra bits for each length code */
  21190. [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];
  21191. var extra_dbits = /* extra bits for each distance code */
  21192. [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];
  21193. var extra_blbits = /* extra bits for each bit length code */
  21194. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  21195. var bl_order =
  21196. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  21197. /* The lengths of the bit length codes are sent in order of decreasing
  21198. * probability, to avoid transmitting the lengths for unused bit length codes.
  21199. */
  21200. /* ===========================================================================
  21201. * Local data. These are initialized only once.
  21202. */
  21203. // We pre-fill arrays with 0 to avoid uninitialized gaps
  21204. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  21205. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  21206. var static_ltree = new Array((L_CODES+2) * 2);
  21207. zero(static_ltree);
  21208. /* The static literal tree. Since the bit lengths are imposed, there is no
  21209. * need for the L_CODES extra codes used during heap construction. However
  21210. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  21211. * below).
  21212. */
  21213. var static_dtree = new Array(D_CODES * 2);
  21214. zero(static_dtree);
  21215. /* The static distance tree. (Actually a trivial tree since all codes use
  21216. * 5 bits.)
  21217. */
  21218. var _dist_code = new Array(DIST_CODE_LEN);
  21219. zero(_dist_code);
  21220. /* Distance codes. The first 256 values correspond to the distances
  21221. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  21222. * the 15 bit distances.
  21223. */
  21224. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  21225. zero(_length_code);
  21226. /* length code for each normalized match length (0 == MIN_MATCH) */
  21227. var base_length = new Array(LENGTH_CODES);
  21228. zero(base_length);
  21229. /* First normalized length for each code (0 = MIN_MATCH) */
  21230. var base_dist = new Array(D_CODES);
  21231. zero(base_dist);
  21232. /* First normalized distance for each code (0 = distance of 1) */
  21233. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  21234. this.static_tree = static_tree; /* static tree or NULL */
  21235. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  21236. this.extra_base = extra_base; /* base index for extra_bits */
  21237. this.elems = elems; /* max number of elements in the tree */
  21238. this.max_length = max_length; /* max bit length for the codes */
  21239. // show if `static_tree` has data or dummy - needed for monomorphic objects
  21240. this.has_stree = static_tree && static_tree.length;
  21241. };
  21242. var static_l_desc;
  21243. var static_d_desc;
  21244. var static_bl_desc;
  21245. var TreeDesc = function(dyn_tree, stat_desc) {
  21246. this.dyn_tree = dyn_tree; /* the dynamic tree */
  21247. this.max_code = 0; /* largest code with non zero frequency */
  21248. this.stat_desc = stat_desc; /* the corresponding static tree */
  21249. };
  21250. function d_code(dist) {
  21251. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  21252. }
  21253. /* ===========================================================================
  21254. * Output a short LSB first on the stream.
  21255. * IN assertion: there is enough room in pendingBuf.
  21256. */
  21257. function put_short (s, w) {
  21258. // put_byte(s, (uch)((w) & 0xff));
  21259. // put_byte(s, (uch)((ush)(w) >> 8));
  21260. s.pending_buf[s.pending++] = (w) & 0xff;
  21261. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  21262. }
  21263. /* ===========================================================================
  21264. * Send a value on a given number of bits.
  21265. * IN assertion: length <= 16 and value fits in length bits.
  21266. */
  21267. function send_bits(s, value, length) {
  21268. if (s.bi_valid > (Buf_size - length)) {
  21269. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  21270. put_short(s, s.bi_buf);
  21271. s.bi_buf = value >> (Buf_size - s.bi_valid);
  21272. s.bi_valid += length - Buf_size;
  21273. } else {
  21274. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  21275. s.bi_valid += length;
  21276. }
  21277. }
  21278. function send_code(s, c, tree) {
  21279. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  21280. }
  21281. /* ===========================================================================
  21282. * Reverse the first len bits of a code, using straightforward code (a faster
  21283. * method would use a table)
  21284. * IN assertion: 1 <= len <= 15
  21285. */
  21286. function bi_reverse(code, len) {
  21287. var res = 0;
  21288. do {
  21289. res |= code & 1;
  21290. code >>>= 1;
  21291. res <<= 1;
  21292. } while (--len > 0);
  21293. return res >>> 1;
  21294. }
  21295. /* ===========================================================================
  21296. * Flush the bit buffer, keeping at most 7 bits in it.
  21297. */
  21298. function bi_flush(s) {
  21299. if (s.bi_valid === 16) {
  21300. put_short(s, s.bi_buf);
  21301. s.bi_buf = 0;
  21302. s.bi_valid = 0;
  21303. } else if (s.bi_valid >= 8) {
  21304. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  21305. s.bi_buf >>= 8;
  21306. s.bi_valid -= 8;
  21307. }
  21308. }
  21309. /* ===========================================================================
  21310. * Compute the optimal bit lengths for a tree and update the total bit length
  21311. * for the current block.
  21312. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  21313. * above are the tree nodes sorted by increasing frequency.
  21314. * OUT assertions: the field len is set to the optimal bit length, the
  21315. * array bl_count contains the frequencies for each bit length.
  21316. * The length opt_len is updated; static_len is also updated if stree is
  21317. * not null.
  21318. */
  21319. function gen_bitlen(s, desc)
  21320. // deflate_state *s;
  21321. // tree_desc *desc; /* the tree descriptor */
  21322. {
  21323. var tree = desc.dyn_tree;
  21324. var max_code = desc.max_code;
  21325. var stree = desc.stat_desc.static_tree;
  21326. var has_stree = desc.stat_desc.has_stree;
  21327. var extra = desc.stat_desc.extra_bits;
  21328. var base = desc.stat_desc.extra_base;
  21329. var max_length = desc.stat_desc.max_length;
  21330. var h; /* heap index */
  21331. var n, m; /* iterate over the tree elements */
  21332. var bits; /* bit length */
  21333. var xbits; /* extra bits */
  21334. var f; /* frequency */
  21335. var overflow = 0; /* number of elements with bit length too large */
  21336. for (bits = 0; bits <= MAX_BITS; bits++) {
  21337. s.bl_count[bits] = 0;
  21338. }
  21339. /* In a first pass, compute the optimal bit lengths (which may
  21340. * overflow in the case of the bit length tree).
  21341. */
  21342. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  21343. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  21344. n = s.heap[h];
  21345. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  21346. if (bits > max_length) {
  21347. bits = max_length;
  21348. overflow++;
  21349. }
  21350. tree[n*2 + 1]/*.Len*/ = bits;
  21351. /* We overwrite tree[n].Dad which is no longer needed */
  21352. if (n > max_code) { continue; } /* not a leaf node */
  21353. s.bl_count[bits]++;
  21354. xbits = 0;
  21355. if (n >= base) {
  21356. xbits = extra[n-base];
  21357. }
  21358. f = tree[n * 2]/*.Freq*/;
  21359. s.opt_len += f * (bits + xbits);
  21360. if (has_stree) {
  21361. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  21362. }
  21363. }
  21364. if (overflow === 0) { return; }
  21365. // Trace((stderr,"\nbit length overflow\n"));
  21366. /* This happens for example on obj2 and pic of the Calgary corpus */
  21367. /* Find the first bit length which could increase: */
  21368. do {
  21369. bits = max_length-1;
  21370. while (s.bl_count[bits] === 0) { bits--; }
  21371. s.bl_count[bits]--; /* move one leaf down the tree */
  21372. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  21373. s.bl_count[max_length]--;
  21374. /* The brother of the overflow item also moves one step up,
  21375. * but this does not affect bl_count[max_length]
  21376. */
  21377. overflow -= 2;
  21378. } while (overflow > 0);
  21379. /* Now recompute all bit lengths, scanning in increasing frequency.
  21380. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  21381. * lengths instead of fixing only the wrong ones. This idea is taken
  21382. * from 'ar' written by Haruhiko Okumura.)
  21383. */
  21384. for (bits = max_length; bits !== 0; bits--) {
  21385. n = s.bl_count[bits];
  21386. while (n !== 0) {
  21387. m = s.heap[--h];
  21388. if (m > max_code) { continue; }
  21389. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  21390. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  21391. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  21392. tree[m*2 + 1]/*.Len*/ = bits;
  21393. }
  21394. n--;
  21395. }
  21396. }
  21397. }
  21398. /* ===========================================================================
  21399. * Generate the codes for a given tree and bit counts (which need not be
  21400. * optimal).
  21401. * IN assertion: the array bl_count contains the bit length statistics for
  21402. * the given tree and the field len is set for all tree elements.
  21403. * OUT assertion: the field code is set for all tree elements of non
  21404. * zero code length.
  21405. */
  21406. function gen_codes(tree, max_code, bl_count)
  21407. // ct_data *tree; /* the tree to decorate */
  21408. // int max_code; /* largest code with non zero frequency */
  21409. // ushf *bl_count; /* number of codes at each bit length */
  21410. {
  21411. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  21412. var code = 0; /* running code value */
  21413. var bits; /* bit index */
  21414. var n; /* code index */
  21415. /* The distribution counts are first used to generate the code values
  21416. * without bit reversal.
  21417. */
  21418. for (bits = 1; bits <= MAX_BITS; bits++) {
  21419. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  21420. }
  21421. /* Check that the bit counts in bl_count are consistent. The last code
  21422. * must be all ones.
  21423. */
  21424. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  21425. // "inconsistent bit counts");
  21426. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  21427. for (n = 0; n <= max_code; n++) {
  21428. var len = tree[n*2 + 1]/*.Len*/;
  21429. if (len === 0) { continue; }
  21430. /* Now reverse the bits */
  21431. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  21432. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  21433. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  21434. }
  21435. }
  21436. /* ===========================================================================
  21437. * Initialize the various 'constant' tables.
  21438. */
  21439. function tr_static_init() {
  21440. var n; /* iterates over tree elements */
  21441. var bits; /* bit counter */
  21442. var length; /* length value */
  21443. var code; /* code value */
  21444. var dist; /* distance index */
  21445. var bl_count = new Array(MAX_BITS+1);
  21446. /* number of codes at each bit length for an optimal tree */
  21447. // do check in _tr_init()
  21448. //if (static_init_done) return;
  21449. /* For some embedded targets, global variables are not initialized: */
  21450. /*#ifdef NO_INIT_GLOBAL_POINTERS
  21451. static_l_desc.static_tree = static_ltree;
  21452. static_l_desc.extra_bits = extra_lbits;
  21453. static_d_desc.static_tree = static_dtree;
  21454. static_d_desc.extra_bits = extra_dbits;
  21455. static_bl_desc.extra_bits = extra_blbits;
  21456. #endif*/
  21457. /* Initialize the mapping length (0..255) -> length code (0..28) */
  21458. length = 0;
  21459. for (code = 0; code < LENGTH_CODES-1; code++) {
  21460. base_length[code] = length;
  21461. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  21462. _length_code[length++] = code;
  21463. }
  21464. }
  21465. //Assert (length == 256, "tr_static_init: length != 256");
  21466. /* Note that the length 255 (match length 258) can be represented
  21467. * in two different ways: code 284 + 5 bits or code 285, so we
  21468. * overwrite length_code[255] to use the best encoding:
  21469. */
  21470. _length_code[length-1] = code;
  21471. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  21472. dist = 0;
  21473. for (code = 0 ; code < 16; code++) {
  21474. base_dist[code] = dist;
  21475. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  21476. _dist_code[dist++] = code;
  21477. }
  21478. }
  21479. //Assert (dist == 256, "tr_static_init: dist != 256");
  21480. dist >>= 7; /* from now on, all distances are divided by 128 */
  21481. for ( ; code < D_CODES; code++) {
  21482. base_dist[code] = dist << 7;
  21483. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  21484. _dist_code[256 + dist++] = code;
  21485. }
  21486. }
  21487. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  21488. /* Construct the codes of the static literal tree */
  21489. for (bits = 0; bits <= MAX_BITS; bits++) {
  21490. bl_count[bits] = 0;
  21491. }
  21492. n = 0;
  21493. while (n <= 143) {
  21494. static_ltree[n*2 + 1]/*.Len*/ = 8;
  21495. n++;
  21496. bl_count[8]++;
  21497. }
  21498. while (n <= 255) {
  21499. static_ltree[n*2 + 1]/*.Len*/ = 9;
  21500. n++;
  21501. bl_count[9]++;
  21502. }
  21503. while (n <= 279) {
  21504. static_ltree[n*2 + 1]/*.Len*/ = 7;
  21505. n++;
  21506. bl_count[7]++;
  21507. }
  21508. while (n <= 287) {
  21509. static_ltree[n*2 + 1]/*.Len*/ = 8;
  21510. n++;
  21511. bl_count[8]++;
  21512. }
  21513. /* Codes 286 and 287 do not exist, but we must include them in the
  21514. * tree construction to get a canonical Huffman tree (longest code
  21515. * all ones)
  21516. */
  21517. gen_codes(static_ltree, L_CODES+1, bl_count);
  21518. /* The static distance tree is trivial: */
  21519. for (n = 0; n < D_CODES; n++) {
  21520. static_dtree[n*2 + 1]/*.Len*/ = 5;
  21521. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  21522. }
  21523. // Now data ready and we can init static trees
  21524. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  21525. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  21526. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  21527. //static_init_done = true;
  21528. }
  21529. /* ===========================================================================
  21530. * Initialize a new block.
  21531. */
  21532. function init_block(s) {
  21533. var n; /* iterates over tree elements */
  21534. /* Initialize the trees. */
  21535. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  21536. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  21537. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  21538. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  21539. s.opt_len = s.static_len = 0;
  21540. s.last_lit = s.matches = 0;
  21541. }
  21542. /* ===========================================================================
  21543. * Flush the bit buffer and align the output on a byte boundary
  21544. */
  21545. function bi_windup(s)
  21546. {
  21547. if (s.bi_valid > 8) {
  21548. put_short(s, s.bi_buf);
  21549. } else if (s.bi_valid > 0) {
  21550. //put_byte(s, (Byte)s->bi_buf);
  21551. s.pending_buf[s.pending++] = s.bi_buf;
  21552. }
  21553. s.bi_buf = 0;
  21554. s.bi_valid = 0;
  21555. }
  21556. /* ===========================================================================
  21557. * Copy a stored block, storing first the length and its
  21558. * one's complement if requested.
  21559. */
  21560. function copy_block(s, buf, len, header)
  21561. //DeflateState *s;
  21562. //charf *buf; /* the input data */
  21563. //unsigned len; /* its length */
  21564. //int header; /* true if block header must be written */
  21565. {
  21566. bi_windup(s); /* align on byte boundary */
  21567. if (header) {
  21568. put_short(s, len);
  21569. put_short(s, ~len);
  21570. }
  21571. // while (len--) {
  21572. // put_byte(s, *buf++);
  21573. // }
  21574. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  21575. s.pending += len;
  21576. }
  21577. /* ===========================================================================
  21578. * Compares to subtrees, using the tree depth as tie breaker when
  21579. * the subtrees have equal frequency. This minimizes the worst case length.
  21580. */
  21581. function smaller(tree, n, m, depth) {
  21582. var _n2 = n*2;
  21583. var _m2 = m*2;
  21584. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  21585. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  21586. }
  21587. /* ===========================================================================
  21588. * Restore the heap property by moving down the tree starting at node k,
  21589. * exchanging a node with the smallest of its two sons if necessary, stopping
  21590. * when the heap property is re-established (each father smaller than its
  21591. * two sons).
  21592. */
  21593. function pqdownheap(s, tree, k)
  21594. // deflate_state *s;
  21595. // ct_data *tree; /* the tree to restore */
  21596. // int k; /* node to move down */
  21597. {
  21598. var v = s.heap[k];
  21599. var j = k << 1; /* left son of k */
  21600. while (j <= s.heap_len) {
  21601. /* Set j to the smallest of the two sons: */
  21602. if (j < s.heap_len &&
  21603. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  21604. j++;
  21605. }
  21606. /* Exit if v is smaller than both sons */
  21607. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  21608. /* Exchange v with the smallest son */
  21609. s.heap[k] = s.heap[j];
  21610. k = j;
  21611. /* And continue down the tree, setting j to the left son of k */
  21612. j <<= 1;
  21613. }
  21614. s.heap[k] = v;
  21615. }
  21616. // inlined manually
  21617. // var SMALLEST = 1;
  21618. /* ===========================================================================
  21619. * Send the block data compressed using the given Huffman trees
  21620. */
  21621. function compress_block(s, ltree, dtree)
  21622. // deflate_state *s;
  21623. // const ct_data *ltree; /* literal tree */
  21624. // const ct_data *dtree; /* distance tree */
  21625. {
  21626. var dist; /* distance of matched string */
  21627. var lc; /* match length or unmatched char (if dist == 0) */
  21628. var lx = 0; /* running index in l_buf */
  21629. var code; /* the code to send */
  21630. var extra; /* number of extra bits to send */
  21631. if (s.last_lit !== 0) {
  21632. do {
  21633. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  21634. lc = s.pending_buf[s.l_buf + lx];
  21635. lx++;
  21636. if (dist === 0) {
  21637. send_code(s, lc, ltree); /* send a literal byte */
  21638. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  21639. } else {
  21640. /* Here, lc is the match length - MIN_MATCH */
  21641. code = _length_code[lc];
  21642. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  21643. extra = extra_lbits[code];
  21644. if (extra !== 0) {
  21645. lc -= base_length[code];
  21646. send_bits(s, lc, extra); /* send the extra length bits */
  21647. }
  21648. dist--; /* dist is now the match distance - 1 */
  21649. code = d_code(dist);
  21650. //Assert (code < D_CODES, "bad d_code");
  21651. send_code(s, code, dtree); /* send the distance code */
  21652. extra = extra_dbits[code];
  21653. if (extra !== 0) {
  21654. dist -= base_dist[code];
  21655. send_bits(s, dist, extra); /* send the extra distance bits */
  21656. }
  21657. } /* literal or match pair ? */
  21658. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  21659. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  21660. // "pendingBuf overflow");
  21661. } while (lx < s.last_lit);
  21662. }
  21663. send_code(s, END_BLOCK, ltree);
  21664. }
  21665. /* ===========================================================================
  21666. * Construct one Huffman tree and assigns the code bit strings and lengths.
  21667. * Update the total bit length for the current block.
  21668. * IN assertion: the field freq is set for all tree elements.
  21669. * OUT assertions: the fields len and code are set to the optimal bit length
  21670. * and corresponding code. The length opt_len is updated; static_len is
  21671. * also updated if stree is not null. The field max_code is set.
  21672. */
  21673. function build_tree(s, desc)
  21674. // deflate_state *s;
  21675. // tree_desc *desc; /* the tree descriptor */
  21676. {
  21677. var tree = desc.dyn_tree;
  21678. var stree = desc.stat_desc.static_tree;
  21679. var has_stree = desc.stat_desc.has_stree;
  21680. var elems = desc.stat_desc.elems;
  21681. var n, m; /* iterate over heap elements */
  21682. var max_code = -1; /* largest code with non zero frequency */
  21683. var node; /* new node being created */
  21684. /* Construct the initial heap, with least frequent element in
  21685. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  21686. * heap[0] is not used.
  21687. */
  21688. s.heap_len = 0;
  21689. s.heap_max = HEAP_SIZE;
  21690. for (n = 0; n < elems; n++) {
  21691. if (tree[n * 2]/*.Freq*/ !== 0) {
  21692. s.heap[++s.heap_len] = max_code = n;
  21693. s.depth[n] = 0;
  21694. } else {
  21695. tree[n*2 + 1]/*.Len*/ = 0;
  21696. }
  21697. }
  21698. /* The pkzip format requires that at least one distance code exists,
  21699. * and that at least one bit should be sent even if there is only one
  21700. * possible code. So to avoid special checks later on we force at least
  21701. * two codes of non zero frequency.
  21702. */
  21703. while (s.heap_len < 2) {
  21704. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  21705. tree[node * 2]/*.Freq*/ = 1;
  21706. s.depth[node] = 0;
  21707. s.opt_len--;
  21708. if (has_stree) {
  21709. s.static_len -= stree[node*2 + 1]/*.Len*/;
  21710. }
  21711. /* node is 0 or 1 so it does not have extra bits */
  21712. }
  21713. desc.max_code = max_code;
  21714. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  21715. * establish sub-heaps of increasing lengths:
  21716. */
  21717. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  21718. /* Construct the Huffman tree by repeatedly combining the least two
  21719. * frequent nodes.
  21720. */
  21721. node = elems; /* next internal node of the tree */
  21722. do {
  21723. //pqremove(s, tree, n); /* n = node of least frequency */
  21724. /*** pqremove ***/
  21725. n = s.heap[1/*SMALLEST*/];
  21726. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  21727. pqdownheap(s, tree, 1/*SMALLEST*/);
  21728. /***/
  21729. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  21730. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  21731. s.heap[--s.heap_max] = m;
  21732. /* Create a new node father of n and m */
  21733. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  21734. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  21735. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  21736. /* and insert the new node in the heap */
  21737. s.heap[1/*SMALLEST*/] = node++;
  21738. pqdownheap(s, tree, 1/*SMALLEST*/);
  21739. } while (s.heap_len >= 2);
  21740. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  21741. /* At this point, the fields freq and dad are set. We can now
  21742. * generate the bit lengths.
  21743. */
  21744. gen_bitlen(s, desc);
  21745. /* The field len is now set, we can generate the bit codes */
  21746. gen_codes(tree, max_code, s.bl_count);
  21747. }
  21748. /* ===========================================================================
  21749. * Scan a literal or distance tree to determine the frequencies of the codes
  21750. * in the bit length tree.
  21751. */
  21752. function scan_tree(s, tree, max_code)
  21753. // deflate_state *s;
  21754. // ct_data *tree; /* the tree to be scanned */
  21755. // int max_code; /* and its largest code of non zero frequency */
  21756. {
  21757. var n; /* iterates over all tree elements */
  21758. var prevlen = -1; /* last emitted length */
  21759. var curlen; /* length of current code */
  21760. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  21761. var count = 0; /* repeat count of the current code */
  21762. var max_count = 7; /* max repeat count */
  21763. var min_count = 4; /* min repeat count */
  21764. if (nextlen === 0) {
  21765. max_count = 138;
  21766. min_count = 3;
  21767. }
  21768. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  21769. for (n = 0; n <= max_code; n++) {
  21770. curlen = nextlen;
  21771. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  21772. if (++count < max_count && curlen === nextlen) {
  21773. continue;
  21774. } else if (count < min_count) {
  21775. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  21776. } else if (curlen !== 0) {
  21777. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  21778. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  21779. } else if (count <= 10) {
  21780. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  21781. } else {
  21782. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  21783. }
  21784. count = 0;
  21785. prevlen = curlen;
  21786. if (nextlen === 0) {
  21787. max_count = 138;
  21788. min_count = 3;
  21789. } else if (curlen === nextlen) {
  21790. max_count = 6;
  21791. min_count = 3;
  21792. } else {
  21793. max_count = 7;
  21794. min_count = 4;
  21795. }
  21796. }
  21797. }
  21798. /* ===========================================================================
  21799. * Send a literal or distance tree in compressed form, using the codes in
  21800. * bl_tree.
  21801. */
  21802. function send_tree(s, tree, max_code)
  21803. // deflate_state *s;
  21804. // ct_data *tree; /* the tree to be scanned */
  21805. // int max_code; /* and its largest code of non zero frequency */
  21806. {
  21807. var n; /* iterates over all tree elements */
  21808. var prevlen = -1; /* last emitted length */
  21809. var curlen; /* length of current code */
  21810. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  21811. var count = 0; /* repeat count of the current code */
  21812. var max_count = 7; /* max repeat count */
  21813. var min_count = 4; /* min repeat count */
  21814. /* tree[max_code+1].Len = -1; */ /* guard already set */
  21815. if (nextlen === 0) {
  21816. max_count = 138;
  21817. min_count = 3;
  21818. }
  21819. for (n = 0; n <= max_code; n++) {
  21820. curlen = nextlen;
  21821. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  21822. if (++count < max_count && curlen === nextlen) {
  21823. continue;
  21824. } else if (count < min_count) {
  21825. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  21826. } else if (curlen !== 0) {
  21827. if (curlen !== prevlen) {
  21828. send_code(s, curlen, s.bl_tree);
  21829. count--;
  21830. }
  21831. //Assert(count >= 3 && count <= 6, " 3_6?");
  21832. send_code(s, REP_3_6, s.bl_tree);
  21833. send_bits(s, count-3, 2);
  21834. } else if (count <= 10) {
  21835. send_code(s, REPZ_3_10, s.bl_tree);
  21836. send_bits(s, count-3, 3);
  21837. } else {
  21838. send_code(s, REPZ_11_138, s.bl_tree);
  21839. send_bits(s, count-11, 7);
  21840. }
  21841. count = 0;
  21842. prevlen = curlen;
  21843. if (nextlen === 0) {
  21844. max_count = 138;
  21845. min_count = 3;
  21846. } else if (curlen === nextlen) {
  21847. max_count = 6;
  21848. min_count = 3;
  21849. } else {
  21850. max_count = 7;
  21851. min_count = 4;
  21852. }
  21853. }
  21854. }
  21855. /* ===========================================================================
  21856. * Construct the Huffman tree for the bit lengths and return the index in
  21857. * bl_order of the last bit length code to send.
  21858. */
  21859. function build_bl_tree(s) {
  21860. var max_blindex; /* index of last bit length code of non zero freq */
  21861. /* Determine the bit length frequencies for literal and distance trees */
  21862. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  21863. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  21864. /* Build the bit length tree: */
  21865. build_tree(s, s.bl_desc);
  21866. /* opt_len now includes the length of the tree representations, except
  21867. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  21868. */
  21869. /* Determine the number of bit length codes to send. The pkzip format
  21870. * requires that at least 4 bit length codes be sent. (appnote.txt says
  21871. * 3 but the actual value used is 4.)
  21872. */
  21873. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  21874. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  21875. break;
  21876. }
  21877. }
  21878. /* Update opt_len to include the bit length tree and counts */
  21879. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  21880. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  21881. // s->opt_len, s->static_len));
  21882. return max_blindex;
  21883. }
  21884. /* ===========================================================================
  21885. * Send the header for a block using dynamic Huffman trees: the counts, the
  21886. * lengths of the bit length codes, the literal tree and the distance tree.
  21887. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  21888. */
  21889. function send_all_trees(s, lcodes, dcodes, blcodes)
  21890. // deflate_state *s;
  21891. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  21892. {
  21893. var rank; /* index in bl_order */
  21894. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  21895. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  21896. // "too many codes");
  21897. //Tracev((stderr, "\nbl counts: "));
  21898. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  21899. send_bits(s, dcodes-1, 5);
  21900. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  21901. for (rank = 0; rank < blcodes; rank++) {
  21902. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  21903. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  21904. }
  21905. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  21906. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  21907. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  21908. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  21909. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  21910. }
  21911. /* ===========================================================================
  21912. * Check if the data type is TEXT or BINARY, using the following algorithm:
  21913. * - TEXT if the two conditions below are satisfied:
  21914. * a) There are no non-portable control characters belonging to the
  21915. * "black list" (0..6, 14..25, 28..31).
  21916. * b) There is at least one printable character belonging to the
  21917. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  21918. * - BINARY otherwise.
  21919. * - The following partially-portable control characters form a
  21920. * "gray list" that is ignored in this detection algorithm:
  21921. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  21922. * IN assertion: the fields Freq of dyn_ltree are set.
  21923. */
  21924. function detect_data_type(s) {
  21925. /* black_mask is the bit mask of black-listed bytes
  21926. * set bits 0..6, 14..25, and 28..31
  21927. * 0xf3ffc07f = binary 11110011111111111100000001111111
  21928. */
  21929. var black_mask = 0xf3ffc07f;
  21930. var n;
  21931. /* Check for non-textual ("black-listed") bytes. */
  21932. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  21933. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  21934. return Z_BINARY;
  21935. }
  21936. }
  21937. /* Check for textual ("white-listed") bytes. */
  21938. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  21939. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  21940. return Z_TEXT;
  21941. }
  21942. for (n = 32; n < LITERALS; n++) {
  21943. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  21944. return Z_TEXT;
  21945. }
  21946. }
  21947. /* There are no "black-listed" or "white-listed" bytes:
  21948. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  21949. */
  21950. return Z_BINARY;
  21951. }
  21952. var static_init_done = false;
  21953. /* ===========================================================================
  21954. * Initialize the tree data structures for a new zlib stream.
  21955. */
  21956. function _tr_init(s)
  21957. {
  21958. if (!static_init_done) {
  21959. tr_static_init();
  21960. static_init_done = true;
  21961. }
  21962. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  21963. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  21964. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  21965. s.bi_buf = 0;
  21966. s.bi_valid = 0;
  21967. /* Initialize the first block of the first file: */
  21968. init_block(s);
  21969. }
  21970. /* ===========================================================================
  21971. * Send a stored block
  21972. */
  21973. function _tr_stored_block(s, buf, stored_len, last)
  21974. //DeflateState *s;
  21975. //charf *buf; /* input block */
  21976. //ulg stored_len; /* length of input block */
  21977. //int last; /* one if this is the last block for a file */
  21978. {
  21979. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  21980. copy_block(s, buf, stored_len, true); /* with header */
  21981. }
  21982. /* ===========================================================================
  21983. * Send one empty static block to give enough lookahead for inflate.
  21984. * This takes 10 bits, of which 7 may remain in the bit buffer.
  21985. */
  21986. function _tr_align(s) {
  21987. send_bits(s, STATIC_TREES<<1, 3);
  21988. send_code(s, END_BLOCK, static_ltree);
  21989. bi_flush(s);
  21990. }
  21991. /* ===========================================================================
  21992. * Determine the best encoding for the current block: dynamic trees, static
  21993. * trees or store, and output the encoded block to the zip file.
  21994. */
  21995. function _tr_flush_block(s, buf, stored_len, last)
  21996. //DeflateState *s;
  21997. //charf *buf; /* input block, or NULL if too old */
  21998. //ulg stored_len; /* length of input block */
  21999. //int last; /* one if this is the last block for a file */
  22000. {
  22001. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  22002. var max_blindex = 0; /* index of last bit length code of non zero freq */
  22003. /* Build the Huffman trees unless a stored block is forced */
  22004. if (s.level > 0) {
  22005. /* Check if the file is binary or text */
  22006. if (s.strm.data_type === Z_UNKNOWN) {
  22007. s.strm.data_type = detect_data_type(s);
  22008. }
  22009. /* Construct the literal and distance trees */
  22010. build_tree(s, s.l_desc);
  22011. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  22012. // s->static_len));
  22013. build_tree(s, s.d_desc);
  22014. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  22015. // s->static_len));
  22016. /* At this point, opt_len and static_len are the total bit lengths of
  22017. * the compressed block data, excluding the tree representations.
  22018. */
  22019. /* Build the bit length tree for the above two trees, and get the index
  22020. * in bl_order of the last bit length code to send.
  22021. */
  22022. max_blindex = build_bl_tree(s);
  22023. /* Determine the best encoding. Compute the block lengths in bytes. */
  22024. opt_lenb = (s.opt_len+3+7) >>> 3;
  22025. static_lenb = (s.static_len+3+7) >>> 3;
  22026. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  22027. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  22028. // s->last_lit));
  22029. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  22030. } else {
  22031. // Assert(buf != (char*)0, "lost buf");
  22032. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  22033. }
  22034. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  22035. /* 4: two words for the lengths */
  22036. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  22037. * Otherwise we can't have processed more than WSIZE input bytes since
  22038. * the last block flush, because compression would have been
  22039. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  22040. * transform a block into a stored block.
  22041. */
  22042. _tr_stored_block(s, buf, stored_len, last);
  22043. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  22044. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  22045. compress_block(s, static_ltree, static_dtree);
  22046. } else {
  22047. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  22048. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  22049. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  22050. }
  22051. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  22052. /* The above check is made mod 2^32, for files larger than 512 MB
  22053. * and uLong implemented on 32 bits.
  22054. */
  22055. init_block(s);
  22056. if (last) {
  22057. bi_windup(s);
  22058. }
  22059. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  22060. // s->compressed_len-7*last));
  22061. }
  22062. /* ===========================================================================
  22063. * Save the match info and tally the frequency counts. Return true if
  22064. * the current block must be flushed.
  22065. */
  22066. function _tr_tally(s, dist, lc)
  22067. // deflate_state *s;
  22068. // unsigned dist; /* distance of matched string */
  22069. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  22070. {
  22071. //var out_length, in_length, dcode;
  22072. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  22073. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  22074. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  22075. s.last_lit++;
  22076. if (dist === 0) {
  22077. /* lc is the unmatched char */
  22078. s.dyn_ltree[lc*2]/*.Freq*/++;
  22079. } else {
  22080. s.matches++;
  22081. /* Here, lc is the match length - MIN_MATCH */
  22082. dist--; /* dist = match distance - 1 */
  22083. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  22084. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  22085. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  22086. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  22087. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  22088. }
  22089. // (!) This block is disabled in zlib defailts,
  22090. // don't enable it for binary compatibility
  22091. //#ifdef TRUNCATE_BLOCK
  22092. // /* Try to guess if it is profitable to stop the current block here */
  22093. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  22094. // /* Compute an upper bound for the compressed length */
  22095. // out_length = s.last_lit*8;
  22096. // in_length = s.strstart - s.block_start;
  22097. //
  22098. // for (dcode = 0; dcode < D_CODES; dcode++) {
  22099. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  22100. // }
  22101. // out_length >>>= 3;
  22102. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  22103. // // s->last_lit, in_length, out_length,
  22104. // // 100L - out_length*100L/in_length));
  22105. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  22106. // return true;
  22107. // }
  22108. // }
  22109. //#endif
  22110. return (s.last_lit === s.lit_bufsize-1);
  22111. /* We avoid equality with lit_bufsize because of wraparound at 64K
  22112. * on 16 bit machines and because stored blocks are restricted to
  22113. * 64K-1 bytes.
  22114. */
  22115. }
  22116. exports._tr_init = _tr_init;
  22117. exports._tr_stored_block = _tr_stored_block;
  22118. exports._tr_flush_block = _tr_flush_block;
  22119. exports._tr_tally = _tr_tally;
  22120. exports._tr_align = _tr_align;
  22121. },{"../utils/common":65}],77:[function(require,module,exports){
  22122. 'use strict';
  22123. function ZStream() {
  22124. /* next input byte */
  22125. this.input = null; // JS specific, because we have no pointers
  22126. this.next_in = 0;
  22127. /* number of bytes available at input */
  22128. this.avail_in = 0;
  22129. /* total number of input bytes read so far */
  22130. this.total_in = 0;
  22131. /* next output byte should be put there */
  22132. this.output = null; // JS specific, because we have no pointers
  22133. this.next_out = 0;
  22134. /* remaining free space at output */
  22135. this.avail_out = 0;
  22136. /* total number of bytes output so far */
  22137. this.total_out = 0;
  22138. /* last error message, NULL if no error */
  22139. this.msg = ''/*Z_NULL*/;
  22140. /* not visible by applications */
  22141. this.state = null;
  22142. /* best guess about the data type: binary or text */
  22143. this.data_type = 2/*Z_UNKNOWN*/;
  22144. /* adler32 value of the uncompressed data */
  22145. this.adler = 0;
  22146. }
  22147. module.exports = ZStream;
  22148. },{}],78:[function(require,module,exports){
  22149. var MediaStreamType = {
  22150. VIDEO_TYPE: "Video",
  22151. AUDIO_TYPE: "Audio"
  22152. };
  22153. module.exports = MediaStreamType;
  22154. },{}],79:[function(require,module,exports){
  22155. var RTCBrowserType = {
  22156. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  22157. RTC_BROWSER_FIREFOX: "rtc_browser.firefox"
  22158. };
  22159. module.exports = RTCBrowserType;
  22160. },{}],80:[function(require,module,exports){
  22161. var RTCEvents = {
  22162. LASTN_CHANGED: "rtc.lastn_changed",
  22163. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  22164. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  22165. SIMULCAST_LAYER_CHANGED: "rtc.simulcast_layer_changed",
  22166. SIMULCAST_LAYER_CHANGING: "rtc.simulcast_layer_changing",
  22167. SIMULCAST_START: "rtc.simlcast_start",
  22168. SIMULCAST_STOP: "rtc.simlcast_stop"
  22169. };
  22170. module.exports = RTCEvents;
  22171. },{}],81:[function(require,module,exports){
  22172. var Resolutions = {
  22173. "1080": {
  22174. width: 1920,
  22175. height: 1080,
  22176. order: 7
  22177. },
  22178. "fullhd": {
  22179. width: 1920,
  22180. height: 1080,
  22181. order: 7
  22182. },
  22183. "720": {
  22184. width: 1280,
  22185. height: 720,
  22186. order: 6
  22187. },
  22188. "hd": {
  22189. width: 1280,
  22190. height: 720,
  22191. order: 6
  22192. },
  22193. "960": {
  22194. width: 960,
  22195. height: 720,
  22196. order: 5
  22197. },
  22198. "640": {
  22199. width: 640,
  22200. height: 480,
  22201. order: 4
  22202. },
  22203. "vga": {
  22204. width: 640,
  22205. height: 480,
  22206. order: 4
  22207. },
  22208. "360": {
  22209. width: 640,
  22210. height: 360,
  22211. order: 3
  22212. },
  22213. "320": {
  22214. width: 320,
  22215. height: 240,
  22216. order: 2
  22217. },
  22218. "180": {
  22219. width: 320,
  22220. height: 180,
  22221. order: 1
  22222. }
  22223. };
  22224. module.exports = Resolutions;
  22225. },{}],82:[function(require,module,exports){
  22226. var StreamEventTypes = {
  22227. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  22228. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  22229. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  22230. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  22231. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended"
  22232. };
  22233. module.exports = StreamEventTypes;
  22234. },{}],83:[function(require,module,exports){
  22235. var UIEvents = {
  22236. NICKNAME_CHANGED: "UI.nickname_changed",
  22237. SELECTED_ENDPOINT: "UI.selected_endpoint",
  22238. PINNED_ENDPOINT: "UI.pinned_endpoint"
  22239. };
  22240. module.exports = UIEvents;
  22241. },{}],84:[function(require,module,exports){
  22242. var AuthenticationEvents = {
  22243. /**
  22244. * Event callback arguments:
  22245. * function(authenticationEnabled, userIdentity)
  22246. * authenticationEnabled - indicates whether authentication has been enabled
  22247. * in this session
  22248. * userIdentity - if user has been logged in then it contains user name. If
  22249. * contains 'null' or 'undefined' then user is not logged in.
  22250. */
  22251. IDENTITY_UPDATED: "authentication.identity_updated"
  22252. };
  22253. module.exports = AuthenticationEvents;
  22254. },{}],85:[function(require,module,exports){
  22255. var CQEvents = {
  22256. LOCALSTATS_UPDATED: "cq.localstats_updated",
  22257. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  22258. STOP: "cq.stop"
  22259. };
  22260. module.exports = CQEvents;
  22261. },{}],86:[function(require,module,exports){
  22262. var DesktopSharingEventTypes = {
  22263. INIT: "ds.init",
  22264. SWITCHING_DONE: "ds.switching_done",
  22265. NEW_STREAM_CREATED: "ds.new_stream_created"
  22266. };
  22267. module.exports = DesktopSharingEventTypes;
  22268. },{}],87:[function(require,module,exports){
  22269. module.exports = {
  22270. getLanguages : function () {
  22271. var languages = [];
  22272. for(var lang in this)
  22273. {
  22274. if(typeof this[lang] === "string")
  22275. languages.push(this[lang]);
  22276. }
  22277. return languages;
  22278. },
  22279. EN: "en",
  22280. BG: "bg",
  22281. DE: "de"
  22282. }
  22283. },{}],88:[function(require,module,exports){
  22284. var XMPPEvents = {
  22285. CONFERENCE_CERATED: "xmpp.conferenceCreated.jingle",
  22286. CALL_TERMINATED: "xmpp.callterminated.jingle",
  22287. CALL_INCOMING: "xmpp.callincoming.jingle",
  22288. DISPOSE_CONFERENCE: "xmpp.dispoce_confernce",
  22289. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  22290. KICKED: "xmpp.kicked",
  22291. BRIDGE_DOWN: "xmpp.bridge_down",
  22292. USER_ID_CHANGED: "xmpp.user_id_changed",
  22293. CHANGED_STREAMS: "xmpp.changed_streams",
  22294. MUC_JOINED: "xmpp.muc_joined",
  22295. MUC_ENTER: "xmpp.muc_enter",
  22296. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  22297. MUC_LEFT: "xmpp.muc_left",
  22298. MUC_DESTROYED: "xmpp.muc_destroyed",
  22299. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  22300. REMOTE_STATS: "xmpp.remote_stats",
  22301. LOCALROLE_CHANGED: "xmpp.localrole_changed",
  22302. PRESENCE_STATUS: "xmpp.presence_status",
  22303. RESERVATION_ERROR: "xmpp.room_reservation_error",
  22304. SUBJECT_CHANGED: "xmpp.subject_changed",
  22305. MESSAGE_RECEIVED: "xmpp.message_received",
  22306. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  22307. PASSWORD_REQUIRED: "xmpp.password_required",
  22308. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  22309. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  22310. ETHERPAD: "xmpp.etherpad"
  22311. };
  22312. module.exports = XMPPEvents;
  22313. },{}],89:[function(require,module,exports){
  22314. // Copyright Joyent, Inc. and other Node contributors.
  22315. //
  22316. // Permission is hereby granted, free of charge, to any person obtaining a
  22317. // copy of this software and associated documentation files (the
  22318. // "Software"), to deal in the Software without restriction, including
  22319. // without limitation the rights to use, copy, modify, merge, publish,
  22320. // distribute, sublicense, and/or sell copies of the Software, and to permit
  22321. // persons to whom the Software is furnished to do so, subject to the
  22322. // following conditions:
  22323. //
  22324. // The above copyright notice and this permission notice shall be included
  22325. // in all copies or substantial portions of the Software.
  22326. //
  22327. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  22328. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22329. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  22330. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  22331. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  22332. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  22333. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  22334. function EventEmitter() {
  22335. this._events = this._events || {};
  22336. this._maxListeners = this._maxListeners || undefined;
  22337. }
  22338. module.exports = EventEmitter;
  22339. // Backwards-compat with node 0.10.x
  22340. EventEmitter.EventEmitter = EventEmitter;
  22341. EventEmitter.prototype._events = undefined;
  22342. EventEmitter.prototype._maxListeners = undefined;
  22343. // By default EventEmitters will print a warning if more than 10 listeners are
  22344. // added to it. This is a useful default which helps finding memory leaks.
  22345. EventEmitter.defaultMaxListeners = 10;
  22346. // Obviously not all Emitters should be limited to 10. This function allows
  22347. // that to be increased. Set to zero for unlimited.
  22348. EventEmitter.prototype.setMaxListeners = function(n) {
  22349. if (!isNumber(n) || n < 0 || isNaN(n))
  22350. throw TypeError('n must be a positive number');
  22351. this._maxListeners = n;
  22352. return this;
  22353. };
  22354. EventEmitter.prototype.emit = function(type) {
  22355. var er, handler, len, args, i, listeners;
  22356. if (!this._events)
  22357. this._events = {};
  22358. // If there is no 'error' event listener then throw.
  22359. if (type === 'error') {
  22360. if (!this._events.error ||
  22361. (isObject(this._events.error) && !this._events.error.length)) {
  22362. er = arguments[1];
  22363. if (er instanceof Error) {
  22364. throw er; // Unhandled 'error' event
  22365. }
  22366. throw TypeError('Uncaught, unspecified "error" event.');
  22367. }
  22368. }
  22369. handler = this._events[type];
  22370. if (isUndefined(handler))
  22371. return false;
  22372. if (isFunction(handler)) {
  22373. switch (arguments.length) {
  22374. // fast cases
  22375. case 1:
  22376. handler.call(this);
  22377. break;
  22378. case 2:
  22379. handler.call(this, arguments[1]);
  22380. break;
  22381. case 3:
  22382. handler.call(this, arguments[1], arguments[2]);
  22383. break;
  22384. // slower
  22385. default:
  22386. len = arguments.length;
  22387. args = new Array(len - 1);
  22388. for (i = 1; i < len; i++)
  22389. args[i - 1] = arguments[i];
  22390. handler.apply(this, args);
  22391. }
  22392. } else if (isObject(handler)) {
  22393. len = arguments.length;
  22394. args = new Array(len - 1);
  22395. for (i = 1; i < len; i++)
  22396. args[i - 1] = arguments[i];
  22397. listeners = handler.slice();
  22398. len = listeners.length;
  22399. for (i = 0; i < len; i++)
  22400. listeners[i].apply(this, args);
  22401. }
  22402. return true;
  22403. };
  22404. EventEmitter.prototype.addListener = function(type, listener) {
  22405. var m;
  22406. if (!isFunction(listener))
  22407. throw TypeError('listener must be a function');
  22408. if (!this._events)
  22409. this._events = {};
  22410. // To avoid recursion in the case that type === "newListener"! Before
  22411. // adding it to the listeners, first emit "newListener".
  22412. if (this._events.newListener)
  22413. this.emit('newListener', type,
  22414. isFunction(listener.listener) ?
  22415. listener.listener : listener);
  22416. if (!this._events[type])
  22417. // Optimize the case of one listener. Don't need the extra array object.
  22418. this._events[type] = listener;
  22419. else if (isObject(this._events[type]))
  22420. // If we've already got an array, just append.
  22421. this._events[type].push(listener);
  22422. else
  22423. // Adding the second element, need to change to array.
  22424. this._events[type] = [this._events[type], listener];
  22425. // Check for listener leak
  22426. if (isObject(this._events[type]) && !this._events[type].warned) {
  22427. var m;
  22428. if (!isUndefined(this._maxListeners)) {
  22429. m = this._maxListeners;
  22430. } else {
  22431. m = EventEmitter.defaultMaxListeners;
  22432. }
  22433. if (m && m > 0 && this._events[type].length > m) {
  22434. this._events[type].warned = true;
  22435. console.error('(node) warning: possible EventEmitter memory ' +
  22436. 'leak detected. %d listeners added. ' +
  22437. 'Use emitter.setMaxListeners() to increase limit.',
  22438. this._events[type].length);
  22439. if (typeof console.trace === 'function') {
  22440. // not supported in IE 10
  22441. console.trace();
  22442. }
  22443. }
  22444. }
  22445. return this;
  22446. };
  22447. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  22448. EventEmitter.prototype.once = function(type, listener) {
  22449. if (!isFunction(listener))
  22450. throw TypeError('listener must be a function');
  22451. var fired = false;
  22452. function g() {
  22453. this.removeListener(type, g);
  22454. if (!fired) {
  22455. fired = true;
  22456. listener.apply(this, arguments);
  22457. }
  22458. }
  22459. g.listener = listener;
  22460. this.on(type, g);
  22461. return this;
  22462. };
  22463. // emits a 'removeListener' event iff the listener was removed
  22464. EventEmitter.prototype.removeListener = function(type, listener) {
  22465. var list, position, length, i;
  22466. if (!isFunction(listener))
  22467. throw TypeError('listener must be a function');
  22468. if (!this._events || !this._events[type])
  22469. return this;
  22470. list = this._events[type];
  22471. length = list.length;
  22472. position = -1;
  22473. if (list === listener ||
  22474. (isFunction(list.listener) && list.listener === listener)) {
  22475. delete this._events[type];
  22476. if (this._events.removeListener)
  22477. this.emit('removeListener', type, listener);
  22478. } else if (isObject(list)) {
  22479. for (i = length; i-- > 0;) {
  22480. if (list[i] === listener ||
  22481. (list[i].listener && list[i].listener === listener)) {
  22482. position = i;
  22483. break;
  22484. }
  22485. }
  22486. if (position < 0)
  22487. return this;
  22488. if (list.length === 1) {
  22489. list.length = 0;
  22490. delete this._events[type];
  22491. } else {
  22492. list.splice(position, 1);
  22493. }
  22494. if (this._events.removeListener)
  22495. this.emit('removeListener', type, listener);
  22496. }
  22497. return this;
  22498. };
  22499. EventEmitter.prototype.removeAllListeners = function(type) {
  22500. var key, listeners;
  22501. if (!this._events)
  22502. return this;
  22503. // not listening for removeListener, no need to emit
  22504. if (!this._events.removeListener) {
  22505. if (arguments.length === 0)
  22506. this._events = {};
  22507. else if (this._events[type])
  22508. delete this._events[type];
  22509. return this;
  22510. }
  22511. // emit removeListener for all listeners on all events
  22512. if (arguments.length === 0) {
  22513. for (key in this._events) {
  22514. if (key === 'removeListener') continue;
  22515. this.removeAllListeners(key);
  22516. }
  22517. this.removeAllListeners('removeListener');
  22518. this._events = {};
  22519. return this;
  22520. }
  22521. listeners = this._events[type];
  22522. if (isFunction(listeners)) {
  22523. this.removeListener(type, listeners);
  22524. } else {
  22525. // LIFO order
  22526. while (listeners.length)
  22527. this.removeListener(type, listeners[listeners.length - 1]);
  22528. }
  22529. delete this._events[type];
  22530. return this;
  22531. };
  22532. EventEmitter.prototype.listeners = function(type) {
  22533. var ret;
  22534. if (!this._events || !this._events[type])
  22535. ret = [];
  22536. else if (isFunction(this._events[type]))
  22537. ret = [this._events[type]];
  22538. else
  22539. ret = this._events[type].slice();
  22540. return ret;
  22541. };
  22542. EventEmitter.listenerCount = function(emitter, type) {
  22543. var ret;
  22544. if (!emitter._events || !emitter._events[type])
  22545. ret = 0;
  22546. else if (isFunction(emitter._events[type]))
  22547. ret = 1;
  22548. else
  22549. ret = emitter._events[type].length;
  22550. return ret;
  22551. };
  22552. function isFunction(arg) {
  22553. return typeof arg === 'function';
  22554. }
  22555. function isNumber(arg) {
  22556. return typeof arg === 'number';
  22557. }
  22558. function isObject(arg) {
  22559. return typeof arg === 'object' && arg !== null;
  22560. }
  22561. function isUndefined(arg) {
  22562. return arg === void 0;
  22563. }
  22564. },{}]},{},[1])(1)
  22565. });