Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

app.bundle.js 870KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831
  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. // Copyright Joyent, Inc. and other Node contributors.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a
  5. // copy of this software and associated documentation files (the
  6. // "Software"), to deal in the Software without restriction, including
  7. // without limitation the rights to use, copy, modify, merge, publish,
  8. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9. // persons to whom the Software is furnished to do so, subject to the
  10. // following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included
  13. // in all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  16. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  18. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  19. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  20. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  21. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. function EventEmitter() {
  23. this._events = this._events || {};
  24. this._maxListeners = this._maxListeners || undefined;
  25. }
  26. module.exports = EventEmitter;
  27. // Backwards-compat with node 0.10.x
  28. EventEmitter.EventEmitter = EventEmitter;
  29. EventEmitter.prototype._events = undefined;
  30. EventEmitter.prototype._maxListeners = undefined;
  31. // By default EventEmitters will print a warning if more than 10 listeners are
  32. // added to it. This is a useful default which helps finding memory leaks.
  33. EventEmitter.defaultMaxListeners = 10;
  34. // Obviously not all Emitters should be limited to 10. This function allows
  35. // that to be increased. Set to zero for unlimited.
  36. EventEmitter.prototype.setMaxListeners = function(n) {
  37. if (!isNumber(n) || n < 0 || isNaN(n))
  38. throw TypeError('n must be a positive number');
  39. this._maxListeners = n;
  40. return this;
  41. };
  42. EventEmitter.prototype.emit = function(type) {
  43. var er, handler, len, args, i, listeners;
  44. if (!this._events)
  45. this._events = {};
  46. // If there is no 'error' event listener then throw.
  47. if (type === 'error') {
  48. if (!this._events.error ||
  49. (isObject(this._events.error) && !this._events.error.length)) {
  50. er = arguments[1];
  51. if (er instanceof Error) {
  52. throw er; // Unhandled 'error' event
  53. }
  54. throw TypeError('Uncaught, unspecified "error" event.');
  55. }
  56. }
  57. handler = this._events[type];
  58. if (isUndefined(handler))
  59. return false;
  60. if (isFunction(handler)) {
  61. switch (arguments.length) {
  62. // fast cases
  63. case 1:
  64. handler.call(this);
  65. break;
  66. case 2:
  67. handler.call(this, arguments[1]);
  68. break;
  69. case 3:
  70. handler.call(this, arguments[1], arguments[2]);
  71. break;
  72. // slower
  73. default:
  74. len = arguments.length;
  75. args = new Array(len - 1);
  76. for (i = 1; i < len; i++)
  77. args[i - 1] = arguments[i];
  78. handler.apply(this, args);
  79. }
  80. } else if (isObject(handler)) {
  81. len = arguments.length;
  82. args = new Array(len - 1);
  83. for (i = 1; i < len; i++)
  84. args[i - 1] = arguments[i];
  85. listeners = handler.slice();
  86. len = listeners.length;
  87. for (i = 0; i < len; i++)
  88. listeners[i].apply(this, args);
  89. }
  90. return true;
  91. };
  92. EventEmitter.prototype.addListener = function(type, listener) {
  93. var m;
  94. if (!isFunction(listener))
  95. throw TypeError('listener must be a function');
  96. if (!this._events)
  97. this._events = {};
  98. // To avoid recursion in the case that type === "newListener"! Before
  99. // adding it to the listeners, first emit "newListener".
  100. if (this._events.newListener)
  101. this.emit('newListener', type,
  102. isFunction(listener.listener) ?
  103. listener.listener : listener);
  104. if (!this._events[type])
  105. // Optimize the case of one listener. Don't need the extra array object.
  106. this._events[type] = listener;
  107. else if (isObject(this._events[type]))
  108. // If we've already got an array, just append.
  109. this._events[type].push(listener);
  110. else
  111. // Adding the second element, need to change to array.
  112. this._events[type] = [this._events[type], listener];
  113. // Check for listener leak
  114. if (isObject(this._events[type]) && !this._events[type].warned) {
  115. var m;
  116. if (!isUndefined(this._maxListeners)) {
  117. m = this._maxListeners;
  118. } else {
  119. m = EventEmitter.defaultMaxListeners;
  120. }
  121. if (m && m > 0 && this._events[type].length > m) {
  122. this._events[type].warned = true;
  123. console.error('(node) warning: possible EventEmitter memory ' +
  124. 'leak detected. %d listeners added. ' +
  125. 'Use emitter.setMaxListeners() to increase limit.',
  126. this._events[type].length);
  127. if (typeof console.trace === 'function') {
  128. // not supported in IE 10
  129. console.trace();
  130. }
  131. }
  132. }
  133. return this;
  134. };
  135. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  136. EventEmitter.prototype.once = function(type, listener) {
  137. if (!isFunction(listener))
  138. throw TypeError('listener must be a function');
  139. var fired = false;
  140. function g() {
  141. this.removeListener(type, g);
  142. if (!fired) {
  143. fired = true;
  144. listener.apply(this, arguments);
  145. }
  146. }
  147. g.listener = listener;
  148. this.on(type, g);
  149. return this;
  150. };
  151. // emits a 'removeListener' event iff the listener was removed
  152. EventEmitter.prototype.removeListener = function(type, listener) {
  153. var list, position, length, i;
  154. if (!isFunction(listener))
  155. throw TypeError('listener must be a function');
  156. if (!this._events || !this._events[type])
  157. return this;
  158. list = this._events[type];
  159. length = list.length;
  160. position = -1;
  161. if (list === listener ||
  162. (isFunction(list.listener) && list.listener === listener)) {
  163. delete this._events[type];
  164. if (this._events.removeListener)
  165. this.emit('removeListener', type, listener);
  166. } else if (isObject(list)) {
  167. for (i = length; i-- > 0;) {
  168. if (list[i] === listener ||
  169. (list[i].listener && list[i].listener === listener)) {
  170. position = i;
  171. break;
  172. }
  173. }
  174. if (position < 0)
  175. return this;
  176. if (list.length === 1) {
  177. list.length = 0;
  178. delete this._events[type];
  179. } else {
  180. list.splice(position, 1);
  181. }
  182. if (this._events.removeListener)
  183. this.emit('removeListener', type, listener);
  184. }
  185. return this;
  186. };
  187. EventEmitter.prototype.removeAllListeners = function(type) {
  188. var key, listeners;
  189. if (!this._events)
  190. return this;
  191. // not listening for removeListener, no need to emit
  192. if (!this._events.removeListener) {
  193. if (arguments.length === 0)
  194. this._events = {};
  195. else if (this._events[type])
  196. delete this._events[type];
  197. return this;
  198. }
  199. // emit removeListener for all listeners on all events
  200. if (arguments.length === 0) {
  201. for (key in this._events) {
  202. if (key === 'removeListener') continue;
  203. this.removeAllListeners(key);
  204. }
  205. this.removeAllListeners('removeListener');
  206. this._events = {};
  207. return this;
  208. }
  209. listeners = this._events[type];
  210. if (isFunction(listeners)) {
  211. this.removeListener(type, listeners);
  212. } else {
  213. // LIFO order
  214. while (listeners.length)
  215. this.removeListener(type, listeners[listeners.length - 1]);
  216. }
  217. delete this._events[type];
  218. return this;
  219. };
  220. EventEmitter.prototype.listeners = function(type) {
  221. var ret;
  222. if (!this._events || !this._events[type])
  223. ret = [];
  224. else if (isFunction(this._events[type]))
  225. ret = [this._events[type]];
  226. else
  227. ret = this._events[type].slice();
  228. return ret;
  229. };
  230. EventEmitter.listenerCount = function(emitter, type) {
  231. var ret;
  232. if (!emitter._events || !emitter._events[type])
  233. ret = 0;
  234. else if (isFunction(emitter._events[type]))
  235. ret = 1;
  236. else
  237. ret = emitter._events[type].length;
  238. return ret;
  239. };
  240. function isFunction(arg) {
  241. return typeof arg === 'function';
  242. }
  243. function isNumber(arg) {
  244. return typeof arg === 'number';
  245. }
  246. function isObject(arg) {
  247. return typeof arg === 'object' && arg !== null;
  248. }
  249. function isUndefined(arg) {
  250. return arg === void 0;
  251. }
  252. },{}],2:[function(require,module,exports){
  253. /* jshint -W117 */
  254. /* application specific logic */
  255. var APP =
  256. {
  257. init: function () {
  258. this.UI = require("./modules/UI/UI");
  259. this.API = require("./modules/API/API");
  260. this.connectionquality = require("./modules/connectionquality/connectionquality");
  261. this.statistics = require("./modules/statistics/statistics");
  262. this.RTC = require("./modules/RTC/RTC");
  263. this.simulcast = require("./modules/simulcast/simulcast");
  264. this.desktopsharing = require("./modules/desktopsharing/desktopsharing");
  265. this.xmpp = require("./modules/xmpp/xmpp");
  266. this.keyboardshortcut = require("./modules/keyboardshortcut/keyboardshortcut");
  267. this.translation = require("./modules/translation/translation");
  268. }
  269. };
  270. function init() {
  271. APP.RTC.start();
  272. APP.xmpp.start(APP.UI.getCredentials());
  273. APP.statistics.start();
  274. APP.connectionquality.init();
  275. // Set default desktop sharing method
  276. APP.desktopsharing.init();
  277. APP.keyboardshortcut.init();
  278. }
  279. $(document).ready(function () {
  280. APP.init();
  281. APP.translation.init();
  282. if(APP.API.isEnabled())
  283. APP.API.init();
  284. APP.UI.start(init);
  285. });
  286. $(window).bind('beforeunload', function () {
  287. if(APP.API.isEnabled())
  288. APP.API.dispose();
  289. });
  290. module.exports = APP;
  291. },{"./modules/API/API":3,"./modules/RTC/RTC":7,"./modules/UI/UI":9,"./modules/connectionquality/connectionquality":35,"./modules/desktopsharing/desktopsharing":36,"./modules/keyboardshortcut/keyboardshortcut":37,"./modules/simulcast/simulcast":43,"./modules/statistics/statistics":46,"./modules/translation/translation":47,"./modules/xmpp/xmpp":61}],3:[function(require,module,exports){
  292. /**
  293. * Implements API class that communicates with external api class
  294. * and provides interface to access Jitsi Meet features by external
  295. * applications that embed Jitsi Meet
  296. */
  297. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  298. /**
  299. * List of the available commands.
  300. * @type {{
  301. * displayName: inputDisplayNameHandler,
  302. * muteAudio: toggleAudio,
  303. * muteVideo: toggleVideo,
  304. * filmStrip: toggleFilmStrip
  305. * }}
  306. */
  307. var commands =
  308. {
  309. displayName: APP.UI.inputDisplayNameHandler,
  310. muteAudio: APP.UI.toggleAudio,
  311. muteVideo: APP.UI.toggleVideo,
  312. toggleFilmStrip: APP.UI.toggleFilmStrip,
  313. toggleChat: APP.UI.toggleChat,
  314. toggleContactList: APP.UI.toggleContactList
  315. };
  316. /**
  317. * Maps the supported events and their status
  318. * (true it the event is enabled and false if it is disabled)
  319. * @type {{
  320. * incomingMessage: boolean,
  321. * outgoingMessage: boolean,
  322. * displayNameChange: boolean,
  323. * participantJoined: boolean,
  324. * participantLeft: boolean
  325. * }}
  326. */
  327. var events =
  328. {
  329. incomingMessage: false,
  330. outgoingMessage:false,
  331. displayNameChange: false,
  332. participantJoined: false,
  333. participantLeft: false
  334. };
  335. var displayName = {};
  336. /**
  337. * Processes commands from external applicaiton.
  338. * @param message the object with the command
  339. */
  340. function processCommand(message)
  341. {
  342. if(message.action != "execute")
  343. {
  344. console.error("Unknown action of the message");
  345. return;
  346. }
  347. for(var key in message)
  348. {
  349. if(commands[key])
  350. commands[key].apply(null, message[key]);
  351. }
  352. }
  353. /**
  354. * Processes events objects from external applications
  355. * @param event the event
  356. */
  357. function processEvent(event) {
  358. if(!event.action)
  359. {
  360. console.error("Event with no action is received.");
  361. return;
  362. }
  363. var i = 0;
  364. switch(event.action)
  365. {
  366. case "add":
  367. for(; i < event.events.length; i++)
  368. {
  369. events[event.events[i]] = true;
  370. }
  371. break;
  372. case "remove":
  373. for(; i < event.events.length; i++)
  374. {
  375. events[event.events[i]] = false;
  376. }
  377. break;
  378. default:
  379. console.error("Unknown action for event.");
  380. }
  381. }
  382. /**
  383. * Sends message to the external application.
  384. * @param object
  385. */
  386. function sendMessage(object) {
  387. window.parent.postMessage(JSON.stringify(object), "*");
  388. }
  389. /**
  390. * Processes a message event from the external application
  391. * @param event the message event
  392. */
  393. function processMessage(event)
  394. {
  395. var message;
  396. try {
  397. message = JSON.parse(event.data);
  398. } catch (e) {}
  399. if(!message.type)
  400. return;
  401. switch (message.type)
  402. {
  403. case "command":
  404. processCommand(message);
  405. break;
  406. case "event":
  407. processEvent(message);
  408. break;
  409. default:
  410. console.error("Unknown type of the message");
  411. return;
  412. }
  413. }
  414. function setupListeners() {
  415. APP.xmpp.addListener(XMPPEvents.MUC_ENTER, function (from) {
  416. API.triggerEvent("participantJoined", {jid: from});
  417. });
  418. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid) {
  419. if (from != myjid)
  420. API.triggerEvent("incomingMessage",
  421. {"from": from, "nick": nick, "message": txt});
  422. });
  423. APP.xmpp.addListener(XMPPEvents.MUC_LEFT, function (jid) {
  424. API.triggerEvent("participantLeft", {jid: jid});
  425. });
  426. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {
  427. name = displayName[jid];
  428. if(!name || name != newDisplayName) {
  429. API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});
  430. displayName[jid] = newDisplayName;
  431. }
  432. });
  433. APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {
  434. APP.API.triggerEvent("outgoingMessage", {"message": body});
  435. });
  436. }
  437. var API = {
  438. /**
  439. * Check whether the API should be enabled or not.
  440. * @returns {boolean}
  441. */
  442. isEnabled: function () {
  443. var hash = location.hash;
  444. if(hash && hash.indexOf("external") > -1 && window.postMessage)
  445. return true;
  446. return false;
  447. },
  448. /**
  449. * Initializes the APIConnector. Setups message event listeners that will
  450. * receive information from external applications that embed Jitsi Meet.
  451. * It also sends a message to the external application that APIConnector
  452. * is initialized.
  453. */
  454. init: function () {
  455. if (window.addEventListener)
  456. {
  457. window.addEventListener('message',
  458. processMessage, false);
  459. }
  460. else
  461. {
  462. window.attachEvent('onmessage', processMessage);
  463. }
  464. sendMessage({type: "system", loaded: true});
  465. setupListeners();
  466. },
  467. /**
  468. * Checks whether the event is enabled ot not.
  469. * @param name the name of the event.
  470. * @returns {*}
  471. */
  472. isEventEnabled: function (name) {
  473. return events[name];
  474. },
  475. /**
  476. * Sends event object to the external application that has been subscribed
  477. * for that event.
  478. * @param name the name event
  479. * @param object data associated with the event
  480. */
  481. triggerEvent: function (name, object) {
  482. if(this.isEnabled() && this.isEventEnabled(name))
  483. sendMessage({
  484. type: "event", action: "result", event: name, result: object});
  485. },
  486. /**
  487. * Removes the listeners.
  488. */
  489. dispose: function () {
  490. if(window.removeEventListener)
  491. {
  492. window.removeEventListener("message",
  493. processMessage, false);
  494. }
  495. else
  496. {
  497. window.detachEvent('onmessage', processMessage);
  498. }
  499. }
  500. };
  501. module.exports = API;
  502. },{"../../service/xmpp/XMPPEvents":89}],4:[function(require,module,exports){
  503. /* global Strophe, updateLargeVideo, focusedVideoSrc*/
  504. // cache datachannels to avoid garbage collection
  505. // https://code.google.com/p/chromium/issues/detail?id=405545
  506. var RTCEvents = require("../../service/RTC/RTCEvents");
  507. var _dataChannels = [];
  508. var eventEmitter = null;
  509. var DataChannels =
  510. {
  511. /**
  512. * Callback triggered by PeerConnection when new data channel is opened
  513. * on the bridge.
  514. * @param event the event info object.
  515. */
  516. onDataChannel: function (event)
  517. {
  518. var dataChannel = event.channel;
  519. dataChannel.onopen = function () {
  520. console.info("Data channel opened by the Videobridge!", dataChannel);
  521. // Code sample for sending string and/or binary data
  522. // Sends String message to the bridge
  523. //dataChannel.send("Hello bridge!");
  524. // Sends 12 bytes binary message to the bridge
  525. //dataChannel.send(new ArrayBuffer(12));
  526. // when the data channel becomes available, tell the bridge about video
  527. // selections so that it can do adaptive simulcast,
  528. // we want the notification to trigger even if userJid is undefined,
  529. // or null.
  530. var userJid = APP.UI.getLargeVideoState().userResourceJid;
  531. // we want the notification to trigger even if userJid is undefined,
  532. // or null.
  533. onSelectedEndpointChanged(userJid);
  534. };
  535. dataChannel.onerror = function (error) {
  536. console.error("Data Channel Error:", error, dataChannel);
  537. };
  538. dataChannel.onmessage = function (event) {
  539. var data = event.data;
  540. // JSON
  541. var obj;
  542. try {
  543. obj = JSON.parse(data);
  544. }
  545. catch (e) {
  546. console.error(
  547. "Failed to parse data channel message as JSON: ",
  548. data,
  549. dataChannel);
  550. }
  551. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  552. var colibriClass = obj.colibriClass;
  553. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  554. // Endpoint ID from the Videobridge.
  555. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  556. console.info(
  557. "Data channel new dominant speaker event: ",
  558. dominantSpeakerEndpoint);
  559. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  560. }
  561. else if ("InLastNChangeEvent" === colibriClass)
  562. {
  563. var oldValue = obj.oldValue;
  564. var newValue = obj.newValue;
  565. // Make sure that oldValue and newValue are of type boolean.
  566. var type;
  567. if ((type = typeof oldValue) !== 'boolean') {
  568. if (type === 'string') {
  569. oldValue = (oldValue == "true");
  570. } else {
  571. oldValue = new Boolean(oldValue).valueOf();
  572. }
  573. }
  574. if ((type = typeof newValue) !== 'boolean') {
  575. if (type === 'string') {
  576. newValue = (newValue == "true");
  577. } else {
  578. newValue = new Boolean(newValue).valueOf();
  579. }
  580. }
  581. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  582. }
  583. else if ("LastNEndpointsChangeEvent" === colibriClass)
  584. {
  585. // The new/latest list of last-n endpoint IDs.
  586. var lastNEndpoints = obj.lastNEndpoints;
  587. // The list of endpoint IDs which are entering the list of
  588. // last-n at this time i.e. were not in the old list of last-n
  589. // endpoint IDs.
  590. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  591. var stream = obj.stream;
  592. console.log(
  593. "Data channel new last-n event: ",
  594. lastNEndpoints, endpointsEnteringLastN, obj);
  595. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  596. lastNEndpoints, endpointsEnteringLastN, obj);
  597. }
  598. else if ("SimulcastLayersChangedEvent" === colibriClass)
  599. {
  600. eventEmitter.emit(RTCEvents.SIMULCAST_LAYER_CHANGED,
  601. obj.endpointSimulcastLayers);
  602. }
  603. else if ("SimulcastLayersChangingEvent" === colibriClass)
  604. {
  605. eventEmitter.emit(RTCEvents.SIMULCAST_LAYER_CHANGING,
  606. obj.endpointSimulcastLayers);
  607. }
  608. else if ("StartSimulcastLayerEvent" === colibriClass)
  609. {
  610. eventEmitter.emit(RTCEvents.SIMULCAST_START, obj.simulcastLayer);
  611. }
  612. else if ("StopSimulcastLayerEvent" === colibriClass)
  613. {
  614. eventEmitter.emit(RTCEvents.SIMULCAST_STOP, obj.simulcastLayer);
  615. }
  616. else
  617. {
  618. console.debug("Data channel JSON-formatted message: ", obj);
  619. }
  620. }
  621. };
  622. dataChannel.onclose = function ()
  623. {
  624. console.info("The Data Channel closed", dataChannel);
  625. var idx = _dataChannels.indexOf(dataChannel);
  626. if (idx > -1)
  627. _dataChannels = _dataChannels.splice(idx, 1);
  628. };
  629. _dataChannels.push(dataChannel);
  630. },
  631. /**
  632. * Binds "ondatachannel" event listener to given PeerConnection instance.
  633. * @param peerConnection WebRTC peer connection instance.
  634. */
  635. init: function (peerConnection, emitter) {
  636. if(!config.openSctp)
  637. return;
  638. peerConnection.ondatachannel = this.onDataChannel;
  639. eventEmitter = emitter;
  640. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  641. // Although it's not a requirement to open separate channels from both bridge
  642. // and peer as single channel can be used for sending and receiving data.
  643. // So either channel opened by the bridge or the one opened here is enough
  644. // for communication with the bridge.
  645. /*var dataChannelOptions =
  646. {
  647. reliable: true
  648. };
  649. var dataChannel
  650. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  651. // Can be used only when is in open state
  652. dataChannel.onopen = function ()
  653. {
  654. dataChannel.send("My channel !!!");
  655. };
  656. dataChannel.onmessage = function (event)
  657. {
  658. var msgData = event.data;
  659. console.info("Got My Data Channel Message:", msgData, dataChannel);
  660. };*/
  661. },
  662. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  663. handlePinnedEndpointEvent: onPinnedEndpointChanged
  664. };
  665. function onSelectedEndpointChanged(userResource)
  666. {
  667. console.log('selected endpoint changed: ', userResource);
  668. if (_dataChannels && _dataChannels.length != 0)
  669. {
  670. _dataChannels.some(function (dataChannel) {
  671. if (dataChannel.readyState == 'open')
  672. {
  673. console.log('sending selected endpoint changed '
  674. + 'notification to the bridge: ', userResource);
  675. dataChannel.send(JSON.stringify({
  676. 'colibriClass': 'SelectedEndpointChangedEvent',
  677. 'selectedEndpoint':
  678. (!userResource || userResource === null)?
  679. null : userResource
  680. }));
  681. return true;
  682. }
  683. });
  684. }
  685. }
  686. function onPinnedEndpointChanged(userResource)
  687. {
  688. console.log('pinned endpoint changed: ', userResource);
  689. if (_dataChannels && _dataChannels.length != 0)
  690. {
  691. _dataChannels.some(function (dataChannel) {
  692. if (dataChannel.readyState == 'open')
  693. {
  694. dataChannel.send(JSON.stringify({
  695. 'colibriClass': 'PinnedEndpointChangedEvent',
  696. 'pinnedEndpoint':
  697. (!userResource || userResource == null)?
  698. null : userResource
  699. }));
  700. return true;
  701. }
  702. });
  703. }
  704. }
  705. module.exports = DataChannels;
  706. },{"../../service/RTC/RTCEvents":81}],5:[function(require,module,exports){
  707. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  708. function LocalStream(stream, type, eventEmitter, videoType)
  709. {
  710. this.stream = stream;
  711. this.eventEmitter = eventEmitter;
  712. this.type = type;
  713. this.videoType = videoType;
  714. var self = this;
  715. if(type == "audio")
  716. {
  717. this.getTracks = function () {
  718. return self.stream.getAudioTracks();
  719. };
  720. }
  721. else
  722. {
  723. this.getTracks = function () {
  724. return self.stream.getVideoTracks();
  725. };
  726. }
  727. this.stream.onended = function()
  728. {
  729. self.streamEnded();
  730. };
  731. }
  732. LocalStream.prototype.streamEnded = function () {
  733. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  734. }
  735. LocalStream.prototype.getOriginalStream = function()
  736. {
  737. return this.stream;
  738. }
  739. LocalStream.prototype.isAudioStream = function () {
  740. return (this.stream.getAudioTracks() && this.stream.getAudioTracks().length > 0);
  741. };
  742. LocalStream.prototype.mute = function()
  743. {
  744. var ismuted = false;
  745. var tracks = this.getTracks();
  746. for (var idx = 0; idx < tracks.length; idx++) {
  747. ismuted = !tracks[idx].enabled;
  748. tracks[idx].enabled = ismuted;
  749. }
  750. return ismuted;
  751. };
  752. LocalStream.prototype.setMute = function(mute)
  753. {
  754. var tracks = this.getTracks();
  755. for (var idx = 0; idx < tracks.length; idx++) {
  756. tracks[idx].enabled = mute;
  757. }
  758. };
  759. LocalStream.prototype.isMuted = function () {
  760. var tracks = [];
  761. if(this.type == "audio")
  762. {
  763. tracks = this.stream.getAudioTracks();
  764. }
  765. else
  766. {
  767. tracks = this.stream.getVideoTracks();
  768. }
  769. for (var idx = 0; idx < tracks.length; idx++) {
  770. if(tracks[idx].enabled)
  771. return false;
  772. }
  773. return true;
  774. }
  775. LocalStream.prototype.getId = function () {
  776. return this.stream.getTracks()[0].id;
  777. }
  778. module.exports = LocalStream;
  779. },{"../../service/RTC/StreamEventTypes.js":83}],6:[function(require,module,exports){
  780. ////These lines should be uncommented when require works in app.js
  781. var RTCBrowserType = require("../../service/RTC/RTCBrowserType.js");
  782. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  783. /**
  784. * Creates a MediaStream object for the given data, session id and ssrc.
  785. * It is a wrapper class for the MediaStream.
  786. *
  787. * @param data the data object from which we obtain the stream,
  788. * the peerjid, etc.
  789. * @param sid the session id
  790. * @param ssrc the ssrc corresponding to this MediaStream
  791. *
  792. * @constructor
  793. */
  794. function MediaStream(data, sid, ssrc, browser) {
  795. // XXX(gp) to minimize headaches in the future, we should build our
  796. // abstractions around tracks and not streams. ORTC is track based API.
  797. // Mozilla expects m-lines to represent media tracks.
  798. //
  799. // Practically, what I'm saying is that we should have a MediaTrack class
  800. // and not a MediaStream class.
  801. //
  802. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  803. // a track might have an associated RTX and FEC sources.
  804. this.sid = sid;
  805. this.stream = data.stream;
  806. this.peerjid = data.peerjid;
  807. this.ssrc = ssrc;
  808. this.type = (this.stream.getVideoTracks().length > 0)?
  809. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  810. this.videoType = null;
  811. this.muted = false;
  812. if(browser == RTCBrowserType.RTC_BROWSER_FIREFOX)
  813. {
  814. if (!this.getVideoTracks)
  815. this.getVideoTracks = function () { return []; };
  816. if (!this.getAudioTracks)
  817. this.getAudioTracks = function () { return []; };
  818. }
  819. }
  820. MediaStream.prototype.getOriginalStream = function()
  821. {
  822. return this.stream;
  823. }
  824. MediaStream.prototype.setMute = function (value)
  825. {
  826. this.stream.muted = value;
  827. this.muted = value;
  828. }
  829. module.exports = MediaStream;
  830. },{"../../service/RTC/MediaStreamTypes":79,"../../service/RTC/RTCBrowserType.js":80}],7:[function(require,module,exports){
  831. var EventEmitter = require("events");
  832. var RTCUtils = require("./RTCUtils.js");
  833. var LocalStream = require("./LocalStream.js");
  834. var DataChannels = require("./DataChannels");
  835. var MediaStream = require("./MediaStream.js");
  836. var DesktopSharingEventTypes
  837. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  838. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  839. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  840. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  841. var UIEvents = require("../../service/UI/UIEvents");
  842. var eventEmitter = new EventEmitter();
  843. var RTC = {
  844. rtcUtils: null,
  845. localStreams: [],
  846. remoteStreams: {},
  847. localAudio: null,
  848. localVideo: null,
  849. addStreamListener: function (listener, eventType) {
  850. eventEmitter.on(eventType, listener);
  851. },
  852. addListener: function (type, listener) {
  853. eventEmitter.on(type, listener);
  854. },
  855. removeStreamListener: function (listener, eventType) {
  856. if(!(eventType instanceof StreamEventTypes))
  857. throw "Illegal argument";
  858. eventEmitter.removeListener(eventType, listener);
  859. },
  860. createLocalStream: function (stream, type, change) {
  861. var localStream = new LocalStream(stream, type, eventEmitter);
  862. //in firefox we have only one stream object
  863. if(this.localStreams.length == 0 ||
  864. this.localStreams[0].getOriginalStream() != stream)
  865. this.localStreams.push(localStream);
  866. if(type == "audio")
  867. {
  868. this.localAudio = localStream;
  869. }
  870. else
  871. {
  872. this.localVideo = localStream;
  873. }
  874. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  875. if(change)
  876. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  877. eventEmitter.emit(eventType, localStream);
  878. return localStream;
  879. },
  880. removeLocalStream: function (stream) {
  881. for(var i = 0; i < this.localStreams.length; i++)
  882. {
  883. if(this.localStreams[i].getOriginalStream() === stream) {
  884. delete this.localStreams[i];
  885. return;
  886. }
  887. }
  888. },
  889. createRemoteStream: function (data, sid, thessrc) {
  890. var remoteStream = new MediaStream(data, sid, thessrc,
  891. this.getBrowserType());
  892. var jid = data.peerjid || APP.xmpp.myJid();
  893. if(!this.remoteStreams[jid]) {
  894. this.remoteStreams[jid] = {};
  895. }
  896. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  897. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  898. console.debug("ADD remote stream ", remoteStream.type, " ", jid, " ", thessrc);
  899. return remoteStream;
  900. },
  901. getBrowserType: function () {
  902. return this.rtcUtils.browser;
  903. },
  904. getPCConstraints: function () {
  905. return this.rtcUtils.pc_constraints;
  906. },
  907. getUserMediaWithConstraints:function(um, success_callback,
  908. failure_callback, resolution,
  909. bandwidth, fps, desktopStream)
  910. {
  911. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  912. failure_callback, resolution, bandwidth, fps, desktopStream);
  913. },
  914. attachMediaStream: function (element, stream) {
  915. this.rtcUtils.attachMediaStream(element, stream);
  916. },
  917. getStreamID: function (stream) {
  918. return this.rtcUtils.getStreamID(stream);
  919. },
  920. getVideoSrc: function (element) {
  921. return this.rtcUtils.getVideoSrc(element);
  922. },
  923. setVideoSrc: function (element, src) {
  924. this.rtcUtils.setVideoSrc(element, src);
  925. },
  926. dispose: function() {
  927. if (this.rtcUtils) {
  928. this.rtcUtils = null;
  929. }
  930. },
  931. stop: function () {
  932. this.dispose();
  933. },
  934. start: function () {
  935. var self = this;
  936. APP.desktopsharing.addListener(
  937. function (stream, isUsingScreenStream, callback) {
  938. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  939. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  940. APP.xmpp.addListener(XMPPEvents.CHANGED_STREAMS, function (jid, changedStreams) {
  941. for(var i = 0; i < changedStreams.length; i++) {
  942. var type = changedStreams[i].type;
  943. if (type != "audio") {
  944. var peerStreams = self.remoteStreams[jid];
  945. if(!peerStreams)
  946. continue;
  947. var videoStream = peerStreams[MediaStreamType.VIDEO_TYPE];
  948. if(!videoStream)
  949. continue;
  950. videoStream.videoType = changedStreams[i].type;
  951. }
  952. }
  953. });
  954. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  955. DataChannels.init(event.peerconnection, eventEmitter);
  956. });
  957. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  958. DataChannels.handleSelectedEndpointEvent);
  959. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  960. DataChannels.handlePinnedEndpointEvent);
  961. this.rtcUtils = new RTCUtils(this);
  962. this.rtcUtils.obtainAudioAndVideoPermissions();
  963. },
  964. muteRemoteVideoStream: function (jid, value) {
  965. var stream;
  966. if(this.remoteStreams[jid] &&
  967. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE])
  968. {
  969. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  970. }
  971. if(!stream)
  972. return false;
  973. if (value != stream.muted) {
  974. stream.setMute(value);
  975. return true;
  976. }
  977. return false;
  978. },
  979. switchVideoStreams: function (new_stream) {
  980. this.localVideo.stream = new_stream;
  981. this.localStreams = [];
  982. //in firefox we have only one stream object
  983. if (this.localAudio.getOriginalStream() != new_stream)
  984. this.localStreams.push(this.localAudio);
  985. this.localStreams.push(this.localVideo);
  986. },
  987. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  988. var oldStream = this.localVideo.getOriginalStream();
  989. var type = (isUsingScreenStream? "screen" : "video");
  990. this.localVideo = this.createLocalStream(stream, "video", true, type);
  991. // Stop the stream to trigger onended event for old stream
  992. oldStream.stop();
  993. APP.xmpp.switchStreams(stream, oldStream,callback);
  994. },
  995. /**
  996. * Checks if video identified by given src is desktop stream.
  997. * @param videoSrc eg.
  998. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  999. * @returns {boolean}
  1000. */
  1001. isVideoSrcDesktop: function (jid) {
  1002. if(!jid)
  1003. return false;
  1004. var isDesktop = false;
  1005. var stream = null;
  1006. if (APP.xmpp.myJid() &&
  1007. APP.xmpp.myResource() === jid) {
  1008. // local video
  1009. stream = this.localVideo;
  1010. } else {
  1011. var peerStreams = this.remoteStreams[jid];
  1012. if(!peerStreams)
  1013. return false;
  1014. stream = peerStreams[MediaStreamType.VIDEO_TYPE];
  1015. }
  1016. if(stream)
  1017. isDesktop = (stream.videoType === "screen");
  1018. return isDesktop;
  1019. }
  1020. };
  1021. module.exports = RTC;
  1022. },{"../../service/RTC/MediaStreamTypes":79,"../../service/RTC/StreamEventTypes.js":83,"../../service/UI/UIEvents":84,"../../service/desktopsharing/DesktopSharingEventTypes":87,"../../service/xmpp/XMPPEvents":89,"./DataChannels":4,"./LocalStream.js":5,"./MediaStream.js":6,"./RTCUtils.js":8,"events":1}],8:[function(require,module,exports){
  1023. var RTCBrowserType = require("../../service/RTC/RTCBrowserType.js");
  1024. var Resolutions = require("../../service/RTC/Resolutions");
  1025. var currentResolution = null;
  1026. function getPreviousResolution(resolution) {
  1027. if(!Resolutions[resolution])
  1028. return null;
  1029. var order = Resolutions[resolution].order;
  1030. var res = null;
  1031. var resName = null;
  1032. for(var i in Resolutions)
  1033. {
  1034. var tmp = Resolutions[i];
  1035. if(res == null || (res.order < tmp.order && tmp.order < order))
  1036. {
  1037. resName = i;
  1038. res = tmp;
  1039. }
  1040. }
  1041. return resName;
  1042. }
  1043. function setResolutionConstraints(constraints, resolution, isAndroid)
  1044. {
  1045. if (resolution && !constraints.video || isAndroid) {
  1046. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  1047. }
  1048. if(Resolutions[resolution])
  1049. {
  1050. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1051. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1052. }
  1053. else
  1054. {
  1055. if (isAndroid) {
  1056. constraints.video.mandatory.minWidth = 320;
  1057. constraints.video.mandatory.minHeight = 240;
  1058. constraints.video.mandatory.maxFrameRate = 15;
  1059. }
  1060. }
  1061. if (constraints.video.mandatory.minWidth)
  1062. constraints.video.mandatory.maxWidth = constraints.video.mandatory.minWidth;
  1063. if (constraints.video.mandatory.minHeight)
  1064. constraints.video.mandatory.maxHeight = constraints.video.mandatory.minHeight;
  1065. }
  1066. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  1067. {
  1068. var constraints = {audio: false, video: false};
  1069. if (um.indexOf('video') >= 0) {
  1070. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  1071. }
  1072. if (um.indexOf('audio') >= 0) {
  1073. constraints.audio = { mandatory: {}, optional: []};// same behaviour as true
  1074. }
  1075. if (um.indexOf('screen') >= 0) {
  1076. constraints.video = {
  1077. mandatory: {
  1078. chromeMediaSource: "screen",
  1079. googLeakyBucket: true,
  1080. maxWidth: window.screen.width,
  1081. maxHeight: window.screen.height,
  1082. maxFrameRate: 3
  1083. },
  1084. optional: []
  1085. };
  1086. }
  1087. if (um.indexOf('desktop') >= 0) {
  1088. constraints.video = {
  1089. mandatory: {
  1090. chromeMediaSource: "desktop",
  1091. chromeMediaSourceId: desktopStream,
  1092. googLeakyBucket: true,
  1093. maxWidth: window.screen.width,
  1094. maxHeight: window.screen.height,
  1095. maxFrameRate: 3
  1096. },
  1097. optional: []
  1098. };
  1099. }
  1100. if (constraints.audio) {
  1101. // if it is good enough for hangouts...
  1102. constraints.audio.optional.push(
  1103. {googEchoCancellation: true},
  1104. {googAutoGainControl: true},
  1105. {googNoiseSupression: true},
  1106. {googHighpassFilter: true},
  1107. {googNoisesuppression2: true},
  1108. {googEchoCancellation2: true},
  1109. {googAutoGainControl2: true}
  1110. );
  1111. }
  1112. if (constraints.video) {
  1113. constraints.video.optional.push(
  1114. {googNoiseReduction: false} // chrome 37 workaround for issue 3807, reenable in M38
  1115. );
  1116. if (um.indexOf('video') >= 0) {
  1117. constraints.video.optional.push(
  1118. {googLeakyBucket: true}
  1119. );
  1120. }
  1121. }
  1122. if (um.indexOf('video') >= 0) {
  1123. setResolutionConstraints(constraints, resolution, isAndroid);
  1124. }
  1125. if (bandwidth) { // doesn't work currently, see webrtc issue 1846
  1126. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};//same behaviour as true
  1127. constraints.video.optional.push({bandwidth: bandwidth});
  1128. }
  1129. if (fps) { // for some cameras it might be necessary to request 30fps
  1130. // so they choose 30fps mjpg over 10fps yuy2
  1131. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};// same behaviour as true;
  1132. constraints.video.mandatory.minFrameRate = fps;
  1133. }
  1134. return constraints;
  1135. }
  1136. function RTCUtils(RTCService)
  1137. {
  1138. this.service = RTCService;
  1139. if (navigator.mozGetUserMedia) {
  1140. console.log('This appears to be Firefox');
  1141. var version = parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1142. if (version >= 22) {
  1143. this.peerconnection = mozRTCPeerConnection;
  1144. this.browser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  1145. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1146. this.pc_constraints = {};
  1147. this.attachMediaStream = function (element, stream) {
  1148. element[0].mozSrcObject = stream;
  1149. element[0].play();
  1150. };
  1151. this.getStreamID = function (stream) {
  1152. var tracks = stream.getVideoTracks();
  1153. if(!tracks || tracks.length == 0)
  1154. {
  1155. tracks = stream.getAudioTracks();
  1156. }
  1157. return tracks[0].id.replace(/[\{,\}]/g,"");
  1158. };
  1159. this.getVideoSrc = function (element) {
  1160. return element.mozSrcObject;
  1161. };
  1162. this.setVideoSrc = function (element, src) {
  1163. element.mozSrcObject = src;
  1164. };
  1165. RTCSessionDescription = mozRTCSessionDescription;
  1166. RTCIceCandidate = mozRTCIceCandidate;
  1167. }
  1168. } else if (navigator.webkitGetUserMedia) {
  1169. console.log('This appears to be Chrome');
  1170. this.peerconnection = webkitRTCPeerConnection;
  1171. this.browser = RTCBrowserType.RTC_BROWSER_CHROME;
  1172. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1173. this.attachMediaStream = function (element, stream) {
  1174. element.attr('src', webkitURL.createObjectURL(stream));
  1175. };
  1176. this.getStreamID = function (stream) {
  1177. // streams from FF endpoints have the characters '{' and '}'
  1178. // that make jQuery choke.
  1179. return stream.id.replace(/[\{,\}]/g,"");
  1180. };
  1181. this.getVideoSrc = function (element) {
  1182. return element.getAttribute("src");
  1183. };
  1184. this.setVideoSrc = function (element, src) {
  1185. element.setAttribute("src", src);
  1186. };
  1187. // DTLS should now be enabled by default but..
  1188. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  1189. if (navigator.userAgent.indexOf('Android') != -1) {
  1190. this.pc_constraints = {}; // disable DTLS on Android
  1191. }
  1192. if (!webkitMediaStream.prototype.getVideoTracks) {
  1193. webkitMediaStream.prototype.getVideoTracks = function () {
  1194. return this.videoTracks;
  1195. };
  1196. }
  1197. if (!webkitMediaStream.prototype.getAudioTracks) {
  1198. webkitMediaStream.prototype.getAudioTracks = function () {
  1199. return this.audioTracks;
  1200. };
  1201. }
  1202. }
  1203. else
  1204. {
  1205. try { console.log('Browser does not appear to be WebRTC-capable'); } catch (e) { }
  1206. window.location.href = 'unsupported_browser.html';
  1207. return;
  1208. }
  1209. if (this.browser !== RTCBrowserType.RTC_BROWSER_CHROME &&
  1210. config.enableFirefoxSupport !== true) {
  1211. window.location.href = 'unsupported_browser.html';
  1212. return;
  1213. }
  1214. }
  1215. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1216. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1217. desktopStream)
  1218. {
  1219. currentResolution = resolution;
  1220. // Check if we are running on Android device
  1221. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1222. var constraints = getConstraints(
  1223. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1224. var isFF = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
  1225. try {
  1226. if (config.enableSimulcast
  1227. && constraints.video
  1228. && constraints.video.chromeMediaSource !== 'screen'
  1229. && constraints.video.chromeMediaSource !== 'desktop'
  1230. && !isAndroid
  1231. // We currently do not support FF, as it doesn't have multistream support.
  1232. && !isFF) {
  1233. APP.simulcast.getUserMedia(constraints, function (stream) {
  1234. console.log('onUserMediaSuccess');
  1235. success_callback(stream);
  1236. },
  1237. function (error) {
  1238. console.warn('Failed to get access to local media. Error ', error);
  1239. if (failure_callback) {
  1240. failure_callback(error);
  1241. }
  1242. });
  1243. } else {
  1244. this.getUserMedia(constraints,
  1245. function (stream) {
  1246. console.log('onUserMediaSuccess');
  1247. success_callback(stream);
  1248. },
  1249. function (error) {
  1250. console.warn('Failed to get access to local media. Error ',
  1251. error, constraints);
  1252. if (failure_callback) {
  1253. failure_callback(error);
  1254. }
  1255. });
  1256. }
  1257. } catch (e) {
  1258. console.error('GUM failed: ', e);
  1259. if(failure_callback) {
  1260. failure_callback(e);
  1261. }
  1262. }
  1263. };
  1264. /**
  1265. * We ask for audio and video combined stream in order to get permissions and
  1266. * not to ask twice.
  1267. */
  1268. RTCUtils.prototype.obtainAudioAndVideoPermissions = function() {
  1269. var self = this;
  1270. // Get AV
  1271. this.getUserMediaWithConstraints(
  1272. ['audio', 'video'],
  1273. function (stream) {
  1274. self.successCallback(stream);
  1275. },
  1276. function (error) {
  1277. self.errorCallback(error);
  1278. },
  1279. config.resolution || '360');
  1280. }
  1281. RTCUtils.prototype.successCallback = function (stream) {
  1282. console.log('got', stream, stream.getAudioTracks().length,
  1283. stream.getVideoTracks().length);
  1284. this.handleLocalStream(stream);
  1285. };
  1286. RTCUtils.prototype.errorCallback = function (error) {
  1287. var self = this;
  1288. console.error('failed to obtain audio/video stream - trying audio only', error);
  1289. var resolution = getPreviousResolution(currentResolution);
  1290. if(typeof error == "object" && error.constraintName && error.name
  1291. && (error.name == "ConstraintNotSatisfiedError" ||
  1292. error.name == "OverconstrainedError") &&
  1293. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1294. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1295. && resolution != null)
  1296. {
  1297. self.getUserMediaWithConstraints(['audio', 'video'],
  1298. function (stream) {
  1299. return self.successCallback(stream);
  1300. }, function (error) {
  1301. return self.errorCallback(error);
  1302. }, resolution);
  1303. }
  1304. else
  1305. {
  1306. self.getUserMediaWithConstraints(
  1307. ['audio'],
  1308. function (stream) {
  1309. return self.successCallback(stream);
  1310. },
  1311. function (error) {
  1312. console.error('failed to obtain audio/video stream - stop',
  1313. error);
  1314. APP.UI.messageHandler.showError("dialog.error", "Error",
  1315. "dialog.failedpermissions",
  1316. "Failed to obtain permissions to use the local microphone " +
  1317. "and/or camera.");
  1318. }
  1319. );
  1320. }
  1321. }
  1322. RTCUtils.prototype.handleLocalStream = function(stream)
  1323. {
  1324. if(window.webkitMediaStream)
  1325. {
  1326. var audioStream = new webkitMediaStream();
  1327. var videoStream = new webkitMediaStream();
  1328. var audioTracks = stream.getAudioTracks();
  1329. var videoTracks = stream.getVideoTracks();
  1330. for (var i = 0; i < audioTracks.length; i++) {
  1331. audioStream.addTrack(audioTracks[i]);
  1332. }
  1333. this.service.createLocalStream(audioStream, "audio");
  1334. for (i = 0; i < videoTracks.length; i++) {
  1335. videoStream.addTrack(videoTracks[i]);
  1336. }
  1337. this.service.createLocalStream(videoStream, "video");
  1338. }
  1339. else
  1340. {//firefox
  1341. this.service.createLocalStream(stream, "stream");
  1342. }
  1343. };
  1344. module.exports = RTCUtils;
  1345. },{"../../service/RTC/RTCBrowserType.js":80,"../../service/RTC/Resolutions":82}],9:[function(require,module,exports){
  1346. var UI = {};
  1347. var VideoLayout = require("./videolayout/VideoLayout.js");
  1348. var AudioLevels = require("./audio_levels/AudioLevels.js");
  1349. var Prezi = require("./prezi/Prezi.js");
  1350. var Etherpad = require("./etherpad/Etherpad.js");
  1351. var Chat = require("./side_pannels/chat/Chat.js");
  1352. var Toolbar = require("./toolbars/Toolbar");
  1353. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  1354. var BottomToolbar = require("./toolbars/BottomToolbar");
  1355. var ContactList = require("./side_pannels/contactlist/ContactList");
  1356. var Avatar = require("./avatar/Avatar");
  1357. var EventEmitter = require("events");
  1358. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  1359. var Settings = require("./../settings/Settings");
  1360. var PanelToggler = require("./side_pannels/SidePanelToggler");
  1361. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  1362. UI.messageHandler = require("./util/MessageHandler");
  1363. var messageHandler = UI.messageHandler;
  1364. var Authentication = require("./authentication/Authentication");
  1365. var UIUtil = require("./util/UIUtil");
  1366. var NicknameHandler = require("./util/NicknameHandler");
  1367. var CQEvents = require("../../service/connectionquality/CQEvents");
  1368. var DesktopSharingEventTypes
  1369. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1370. var RTCEvents = require("../../service/RTC/RTCEvents");
  1371. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  1372. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  1373. var eventEmitter = new EventEmitter();
  1374. var roomName = null;
  1375. function setupPrezi()
  1376. {
  1377. $("#reloadPresentationLink").click(function()
  1378. {
  1379. Prezi.reloadPresentation();
  1380. });
  1381. }
  1382. function setupChat()
  1383. {
  1384. Chat.init();
  1385. $("#toggle_smileys").click(function() {
  1386. Chat.toggleSmileys();
  1387. });
  1388. }
  1389. function setupToolbars() {
  1390. Toolbar.init(UI);
  1391. Toolbar.setupButtonsFromConfig();
  1392. BottomToolbar.init();
  1393. }
  1394. function streamHandler(stream) {
  1395. switch (stream.type)
  1396. {
  1397. case "audio":
  1398. VideoLayout.changeLocalAudio(stream);
  1399. break;
  1400. case "video":
  1401. VideoLayout.changeLocalVideo(stream);
  1402. break;
  1403. case "stream":
  1404. VideoLayout.changeLocalStream(stream);
  1405. break;
  1406. }
  1407. }
  1408. function onDisposeConference(unload) {
  1409. Toolbar.showAuthenticateButton(false);
  1410. };
  1411. function onDisplayNameChanged(jid, displayName) {
  1412. ContactList.onDisplayNameChange(jid, displayName);
  1413. SettingsMenu.onDisplayNameChange(jid, displayName);
  1414. VideoLayout.onDisplayNameChanged(jid, displayName);
  1415. }
  1416. function registerListeners() {
  1417. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  1418. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  1419. APP.RTC.addStreamListener(function (stream) {
  1420. VideoLayout.onRemoteStreamAdded(stream);
  1421. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  1422. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  1423. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (resourceJid) {
  1424. VideoLayout.onDominantSpeakerChanged(resourceJid);
  1425. });
  1426. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1427. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  1428. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  1429. endpointsEnteringLastN, stream);
  1430. });
  1431. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  1432. function (endpointSimulcastLayers) {
  1433. VideoLayout.onSimulcastLayersChanged(endpointSimulcastLayers);
  1434. });
  1435. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGING,
  1436. function (endpointSimulcastLayers) {
  1437. VideoLayout.onSimulcastLayersChanging(endpointSimulcastLayers);
  1438. });
  1439. APP.statistics.addAudioLevelListener(function(jid, audioLevel)
  1440. {
  1441. var resourceJid;
  1442. if(jid === APP.statistics.LOCAL_JID)
  1443. {
  1444. resourceJid = AudioLevels.LOCAL_LEVEL;
  1445. if(APP.RTC.localAudio.isMuted())
  1446. {
  1447. audioLevel = 0;
  1448. }
  1449. }
  1450. else
  1451. {
  1452. resourceJid = Strophe.getResourceFromJid(jid);
  1453. }
  1454. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  1455. UI.getLargeVideoState().userResourceJid);
  1456. });
  1457. APP.desktopsharing.addListener(function () {
  1458. ToolbarToggler.showDesktopSharingButton();
  1459. }, DesktopSharingEventTypes.INIT);
  1460. APP.desktopsharing.addListener(
  1461. Toolbar.changeDesktopSharingButtonState,
  1462. DesktopSharingEventTypes.SWITCHING_DONE);
  1463. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  1464. VideoLayout.updateLocalConnectionStats);
  1465. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  1466. VideoLayout.updateConnectionStats);
  1467. APP.connectionquality.addListener(CQEvents.STOP,
  1468. VideoLayout.onStatsStop);
  1469. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  1470. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  1471. messageHandler.openMessageDialog(
  1472. 'dialog.serviceUnavailable', 'Service unavailable',
  1473. 'dialog.gracefulShutdown',
  1474. 'Our service is currently down for maintenance.' +
  1475. ' Please try again later.'
  1476. );
  1477. });
  1478. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  1479. messageHandler.openDialog(
  1480. 'Reservation system error',
  1481. 'Error code: ' + code + ', message: ' + msg,
  1482. true, {},
  1483. function (event, value, message, formVals)
  1484. {
  1485. return false;
  1486. }
  1487. );
  1488. });
  1489. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  1490. messageHandler.openMessageDialog("dialog.sessTerminated", "Session Terminated",
  1491. "dialog.kickMessage", "Ouch! You have been kicked out of the meet!");
  1492. });
  1493. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  1494. //FIXME: use Session Terminated from translation, but
  1495. // 'reason' text comes from XMPP packet and is not translated
  1496. messageHandler.openDialog(
  1497. "Session Terminated", reason, true, {},
  1498. function (event, value, message, formVals)
  1499. {
  1500. return false;
  1501. }
  1502. );
  1503. });
  1504. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  1505. messageHandler.showError("dialog.error","Error",
  1506. "dialog.bridgeUnavailable",
  1507. "Jitsi Videobridge is currently unavailable. Please try again later!");
  1508. });
  1509. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  1510. Avatar.setUserAvatar(from, id);
  1511. });
  1512. APP.xmpp.addListener(XMPPEvents.CHANGED_STREAMS, function (jid, changedStreams) {
  1513. for(stream in changedStreams)
  1514. {
  1515. // might need to update the direction if participant just went from sendrecv to recvonly
  1516. if (stream.type === 'video' || stream.type === 'screen') {
  1517. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  1518. switch (stream.direction) {
  1519. case 'sendrecv':
  1520. el.show();
  1521. break;
  1522. case 'recvonly':
  1523. el.hide();
  1524. // FIXME: Check if we have to change large video
  1525. //VideoLayout.updateLargeVideo(el);
  1526. break;
  1527. }
  1528. }
  1529. }
  1530. });
  1531. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  1532. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  1533. APP.xmpp.addListener(XMPPEvents.LOCALROLE_CHANGED, onLocalRoleChange);
  1534. APP.xmpp.addListener(XMPPEvents.MUC_ENTER, onMucEntered);
  1535. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  1536. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  1537. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  1538. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  1539. APP.xmpp.addListener(XMPPEvents.MUC_LEFT, onMucLeft);
  1540. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordReqiured);
  1541. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  1542. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  1543. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED, onAuthenticationRequired);
  1544. }
  1545. /**
  1546. * Mutes/unmutes the local video.
  1547. *
  1548. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  1549. * @param options an object which specifies optional arguments such as the
  1550. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  1551. * specifies whether the method was initiated in response to a user command (in
  1552. * contrast to an automatic decision taken by the application logic)
  1553. */
  1554. function setVideoMute(mute, options) {
  1555. APP.xmpp.setVideoMute(
  1556. mute,
  1557. function (mute) {
  1558. var video = $('#video');
  1559. var communicativeClass = "icon-camera";
  1560. var muteClass = "icon-camera icon-camera-disabled";
  1561. if (mute) {
  1562. video.removeClass(communicativeClass);
  1563. video.addClass(muteClass);
  1564. } else {
  1565. video.removeClass(muteClass);
  1566. video.addClass(communicativeClass);
  1567. }
  1568. },
  1569. options);
  1570. }
  1571. function bindEvents()
  1572. {
  1573. /**
  1574. * Resizes and repositions videos in full screen mode.
  1575. */
  1576. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1577. function () {
  1578. VideoLayout.resizeLargeVideoContainer();
  1579. VideoLayout.positionLarge();
  1580. }
  1581. );
  1582. $(window).resize(function () {
  1583. VideoLayout.resizeLargeVideoContainer();
  1584. VideoLayout.positionLarge();
  1585. });
  1586. }
  1587. UI.start = function (init) {
  1588. document.title = interfaceConfig.APP_NAME;
  1589. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1590. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1591. {
  1592. $("#videoconference_page").hide();
  1593. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1594. setupWelcomePage();
  1595. return;
  1596. }
  1597. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  1598. var leftWatermarkDiv
  1599. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  1600. leftWatermarkDiv.css({display: 'block'});
  1601. leftWatermarkDiv.parent().get(0).href
  1602. = interfaceConfig.JITSI_WATERMARK_LINK;
  1603. }
  1604. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1605. var rightWatermarkDiv
  1606. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  1607. rightWatermarkDiv.css({display: 'block'});
  1608. rightWatermarkDiv.parent().get(0).href
  1609. = interfaceConfig.BRAND_WATERMARK_LINK;
  1610. rightWatermarkDiv.get(0).style.backgroundImage
  1611. = "url(images/rightwatermark.png)";
  1612. }
  1613. if (interfaceConfig.SHOW_POWERED_BY) {
  1614. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  1615. }
  1616. $("#welcome_page").hide();
  1617. VideoLayout.resizeLargeVideoContainer();
  1618. $("#videospace").mousemove(function () {
  1619. return ToolbarToggler.showToolbar();
  1620. });
  1621. // Set the defaults for prompt dialogs.
  1622. jQuery.prompt.setDefaults({persistent: false});
  1623. VideoLayout.init(eventEmitter);
  1624. AudioLevels.init();
  1625. NicknameHandler.init(eventEmitter);
  1626. registerListeners();
  1627. bindEvents();
  1628. setupPrezi();
  1629. setupToolbars();
  1630. setupChat();
  1631. document.title = interfaceConfig.APP_NAME;
  1632. $("#downloadlog").click(function (event) {
  1633. dump(event.target);
  1634. });
  1635. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1636. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1637. {
  1638. $("#videoconference_page").hide();
  1639. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1640. setupWelcomePage();
  1641. return;
  1642. }
  1643. $("#welcome_page").hide();
  1644. document.getElementById('largeVideo').volume = 0;
  1645. if (!$('#settings').is(':visible')) {
  1646. console.log('init');
  1647. init();
  1648. } else {
  1649. loginInfo.onsubmit = function (e) {
  1650. if (e.preventDefault) e.preventDefault();
  1651. $('#settings').hide();
  1652. init();
  1653. };
  1654. }
  1655. toastr.options = {
  1656. "closeButton": true,
  1657. "debug": false,
  1658. "positionClass": "notification-bottom-right",
  1659. "onclick": null,
  1660. "showDuration": "300",
  1661. "hideDuration": "1000",
  1662. "timeOut": "2000",
  1663. "extendedTimeOut": "1000",
  1664. "showEasing": "swing",
  1665. "hideEasing": "linear",
  1666. "showMethod": "fadeIn",
  1667. "hideMethod": "fadeOut",
  1668. "reposition": function() {
  1669. if(PanelToggler.isVisible()) {
  1670. $("#toast-container").addClass("notification-bottom-right-center");
  1671. } else {
  1672. $("#toast-container").removeClass("notification-bottom-right-center");
  1673. }
  1674. },
  1675. "newestOnTop": false
  1676. };
  1677. SettingsMenu.init();
  1678. };
  1679. function chatAddError(errorMessage, originalText)
  1680. {
  1681. return Chat.chatAddError(errorMessage, originalText);
  1682. };
  1683. function chatSetSubject(text)
  1684. {
  1685. return Chat.chatSetSubject(text);
  1686. };
  1687. function updateChatConversation(from, displayName, message) {
  1688. return Chat.updateChatConversation(from, displayName, message);
  1689. };
  1690. function onMucJoined(jid, info) {
  1691. Toolbar.updateRoomUrl(window.location.href);
  1692. document.getElementById('localNick').appendChild(
  1693. document.createTextNode(Strophe.getResourceFromJid(jid) + ' (me)')
  1694. );
  1695. var settings = Settings.getSettings();
  1696. // Add myself to the contact list.
  1697. ContactList.addContact(jid, settings.email || settings.uid);
  1698. // Once we've joined the muc show the toolbar
  1699. ToolbarToggler.showToolbar();
  1700. var displayName = !config.displayJids
  1701. ? info.displayName : Strophe.getResourceFromJid(jid);
  1702. if (displayName)
  1703. onDisplayNameChanged('localVideoContainer', displayName + ' (me)');
  1704. }
  1705. function initEtherpad(name) {
  1706. Etherpad.init(name);
  1707. };
  1708. function onMucLeft(jid) {
  1709. console.log('left.muc', jid);
  1710. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  1711. '>.displayname').html();
  1712. messageHandler.notify(displayName,'notify.somebody', "Somebody",
  1713. 'disconnected',
  1714. 'notify.disconnected', "disconnected");
  1715. // Need to call this with a slight delay, otherwise the element couldn't be
  1716. // found for some reason.
  1717. // XXX(gp) it works fine without the timeout for me (with Chrome 38).
  1718. window.setTimeout(function () {
  1719. var container = document.getElementById(
  1720. 'participant_' + Strophe.getResourceFromJid(jid));
  1721. if (container) {
  1722. ContactList.removeContact(jid);
  1723. VideoLayout.removeConnectionIndicator(jid);
  1724. // hide here, wait for video to close before removing
  1725. $(container).hide();
  1726. VideoLayout.resizeThumbnails();
  1727. }
  1728. }, 10);
  1729. VideoLayout.participantLeft(jid);
  1730. };
  1731. function onLocalRoleChange(jid, info, pres, isModerator)
  1732. {
  1733. console.info("My role changed, new role: " + info.role);
  1734. onModeratorStatusChanged(isModerator);
  1735. VideoLayout.showModeratorIndicator();
  1736. if (isModerator) {
  1737. Authentication.closeAuthenticationWindow();
  1738. messageHandler.notify(null, "notify.me",
  1739. 'Me', 'connected', "notify.moderator",
  1740. 'Moderator rights granted !');
  1741. }
  1742. }
  1743. function onModeratorStatusChanged(isModerator) {
  1744. Toolbar.showSipCallButton(isModerator);
  1745. Toolbar.showRecordingButton(
  1746. isModerator); //&&
  1747. // FIXME:
  1748. // Recording visible if
  1749. // there are at least 2(+ 1 focus) participants
  1750. //Object.keys(connection.emuc.members).length >= 3);
  1751. if (isModerator && config.etherpad_base) {
  1752. Etherpad.init();
  1753. }
  1754. };
  1755. function onPasswordReqiured(callback) {
  1756. // password is required
  1757. Toolbar.lockLockButton();
  1758. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1759. message += APP.translation.translateString(
  1760. "dialog.passwordRequired", null, "Password required");
  1761. message += '</h2>' +
  1762. '<input id="lockKey" type="text" placeholder="password" autofocus>';
  1763. messageHandler.openTwoButtonDialog(null, null, null, message,
  1764. true,
  1765. "dialog.Ok",
  1766. function (e, v, m, f) {},
  1767. function (event) {
  1768. document.getElementById('lockKey').focus();
  1769. },
  1770. function (e, v, m, f) {
  1771. if (v) {
  1772. var lockKey = document.getElementById('lockKey');
  1773. if (lockKey.value !== null) {
  1774. Toolbar.setSharedKey(lockKey.value);
  1775. callback(lockKey.value);
  1776. }
  1777. }
  1778. }
  1779. );
  1780. }
  1781. function onMucEntered(jid, id, displayName) {
  1782. messageHandler.notify(displayName,'notify.somebody', "Somebody",
  1783. 'connected',
  1784. 'notify.connected', "connected");
  1785. // Add Peer's container
  1786. VideoLayout.ensurePeerContainerExists(jid,id);
  1787. }
  1788. function onMucPresenceStatus( jid, info) {
  1789. VideoLayout.setPresenceStatus(
  1790. 'participant_' + Strophe.getResourceFromJid(jid), info.status);
  1791. }
  1792. function onMucRoleChanged(role, displayName) {
  1793. VideoLayout.showModeratorIndicator();
  1794. if (role === 'moderator') {
  1795. var messageKey, messageOptions = {};
  1796. var lDisplayName = displayName;
  1797. if (!lDisplayName) {
  1798. lDisplayName = 'Somebody';
  1799. messageKey = "notify.grantedToUnknown";
  1800. }
  1801. else
  1802. {
  1803. messageKey = "notify.grantedTo";
  1804. messageOptions = {to: displayName};
  1805. }
  1806. messageHandler.notify(
  1807. displayName,'notify.somebody', "Somebody",
  1808. 'connected', messageKey,
  1809. 'Moderator rights granted to ' + lDisplayName + '!',
  1810. messageOptions);
  1811. }
  1812. }
  1813. function onAuthenticationRequired(intervalCallback) {
  1814. Authentication.openAuthenticationDialog(
  1815. roomName, intervalCallback, function () {
  1816. Toolbar.authenticateClicked();
  1817. });
  1818. };
  1819. function onLastNChanged(oldValue, newValue) {
  1820. if (config.muteLocalVideoIfNotInLastN) {
  1821. setVideoMute(!newValue, { 'byUser': false });
  1822. }
  1823. }
  1824. UI.toggleSmileys = function () {
  1825. Chat.toggleSmileys();
  1826. };
  1827. UI.getSettings = function () {
  1828. return Settings.getSettings();
  1829. };
  1830. UI.toggleFilmStrip = function () {
  1831. return BottomToolbar.toggleFilmStrip();
  1832. };
  1833. UI.toggleChat = function () {
  1834. return BottomToolbar.toggleChat();
  1835. };
  1836. UI.toggleContactList = function () {
  1837. return BottomToolbar.toggleContactList();
  1838. };
  1839. UI.inputDisplayNameHandler = function (value) {
  1840. VideoLayout.inputDisplayNameHandler(value);
  1841. };
  1842. UI.getLargeVideoState = function()
  1843. {
  1844. return VideoLayout.getLargeVideoState();
  1845. };
  1846. UI.generateRoomName = function() {
  1847. if(roomName)
  1848. return roomName;
  1849. var roomnode = null;
  1850. var path = window.location.pathname;
  1851. // determinde the room node from the url
  1852. // TODO: just the roomnode or the whole bare jid?
  1853. if (config.getroomnode && typeof config.getroomnode === 'function') {
  1854. // custom function might be responsible for doing the pushstate
  1855. roomnode = config.getroomnode(path);
  1856. } else {
  1857. /* fall back to default strategy
  1858. * this is making assumptions about how the URL->room mapping happens.
  1859. * It currently assumes deployment at root, with a rewrite like the
  1860. * following one (for nginx):
  1861. location ~ ^/([a-zA-Z0-9]+)$ {
  1862. rewrite ^/(.*)$ / break;
  1863. }
  1864. */
  1865. if (path.length > 1) {
  1866. roomnode = path.substr(1).toLowerCase();
  1867. } else {
  1868. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  1869. roomnode = word.toLowerCase();
  1870. window.history.pushState('VideoChat',
  1871. 'Room: ' + word, window.location.pathname + word);
  1872. }
  1873. }
  1874. roomName = roomnode + '@' + config.hosts.muc;
  1875. return roomName;
  1876. };
  1877. UI.connectionIndicatorShowMore = function(id)
  1878. {
  1879. return VideoLayout.connectionIndicators[id].showMore();
  1880. };
  1881. UI.getCredentials = function () {
  1882. var settings = this.getSettings();
  1883. return {
  1884. bosh: document.getElementById('boshURL').value,
  1885. password: document.getElementById('password').value,
  1886. jid: document.getElementById('jid').value,
  1887. email: settings.email,
  1888. displayName: settings.displayName,
  1889. uid: settings.uid
  1890. };
  1891. };
  1892. UI.disableConnect = function () {
  1893. document.getElementById('connect').disabled = true;
  1894. };
  1895. UI.showLoginPopup = function(callback)
  1896. {
  1897. console.log('password is required');
  1898. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1899. message += APP.translation.translateString(
  1900. "dialog.passwordRequired", null, "Password required");
  1901. message += '</h2>' +
  1902. '<input id="passwordrequired.username" type="text" ' +
  1903. 'placeholder="user@domain.net" autofocus>' +
  1904. '<input id="passwordrequired.password" ' +
  1905. 'type="password" placeholder="user password">';
  1906. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  1907. true,
  1908. "dialog.Ok",
  1909. function (e, v, m, f) {
  1910. if (v) {
  1911. var username = document.getElementById('passwordrequired.username');
  1912. var password = document.getElementById('passwordrequired.password');
  1913. if (username.value !== null && password.value != null) {
  1914. callback(username.value, password.value);
  1915. }
  1916. }
  1917. },
  1918. function (event) {
  1919. document.getElementById('passwordrequired.username').focus();
  1920. }
  1921. );
  1922. }
  1923. UI.checkForNicknameAndJoin = function () {
  1924. Authentication.closeAuthenticationDialog();
  1925. Authentication.stopInterval();
  1926. var nick = null;
  1927. if (config.useNicks) {
  1928. nick = window.prompt('Your nickname (optional)');
  1929. }
  1930. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  1931. };
  1932. function dump(elem, filename) {
  1933. elem = elem.parentNode;
  1934. elem.download = filename || 'meetlog.json';
  1935. elem.href = 'data:application/json;charset=utf-8,\n';
  1936. var data = APP.xmpp.populateData();
  1937. var metadata = {};
  1938. metadata.time = new Date();
  1939. metadata.url = window.location.href;
  1940. metadata.ua = navigator.userAgent;
  1941. var log = APP.xmpp.getLogger();
  1942. if (log) {
  1943. metadata.xmpp = log;
  1944. }
  1945. data.metadata = metadata;
  1946. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  1947. return false;
  1948. }
  1949. UI.getRoomName = function () {
  1950. return roomName;
  1951. };
  1952. /**
  1953. * Mutes/unmutes the local video.
  1954. */
  1955. UI.toggleVideo = function () {
  1956. UIUtil.buttonClick("#video", "icon-camera icon-camera-disabled");
  1957. setVideoMute(!APP.RTC.localVideo.isMuted());
  1958. };
  1959. /**
  1960. * Mutes / unmutes audio for the local participant.
  1961. */
  1962. UI.toggleAudio = function() {
  1963. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  1964. };
  1965. /**
  1966. * Sets muted audio state for the local participant.
  1967. */
  1968. UI.setAudioMuted = function (mute) {
  1969. if(!APP.xmpp.setAudioMute(mute, function () {
  1970. VideoLayout.showLocalAudioIndicator(mute);
  1971. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1972. }))
  1973. {
  1974. // We still click the button.
  1975. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1976. return;
  1977. }
  1978. }
  1979. UI.addListener = function (type, listener) {
  1980. eventEmitter.on(type, listener);
  1981. }
  1982. UI.clickOnVideo = function (videoNumber) {
  1983. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  1984. if (remoteVideos.length > videoNumber) {
  1985. remoteVideos[videoNumber].click();
  1986. }
  1987. }
  1988. //Used by torture
  1989. UI.showToolbar = function () {
  1990. return ToolbarToggler.showToolbar();
  1991. }
  1992. //Used by torture
  1993. UI.dockToolbar = function (isDock) {
  1994. return ToolbarToggler.dockToolbar(isDock);
  1995. }
  1996. module.exports = UI;
  1997. },{"../../service/RTC/RTCEvents":81,"../../service/RTC/StreamEventTypes":83,"../../service/connectionquality/CQEvents":86,"../../service/desktopsharing/DesktopSharingEventTypes":87,"../../service/xmpp/XMPPEvents":89,"./../settings/Settings":38,"./audio_levels/AudioLevels.js":10,"./authentication/Authentication":12,"./avatar/Avatar":13,"./etherpad/Etherpad.js":14,"./prezi/Prezi.js":15,"./side_pannels/SidePanelToggler":17,"./side_pannels/chat/Chat.js":18,"./side_pannels/contactlist/ContactList":22,"./side_pannels/settings/SettingsMenu":23,"./toolbars/BottomToolbar":24,"./toolbars/Toolbar":25,"./toolbars/ToolbarToggler":26,"./util/MessageHandler":28,"./util/NicknameHandler":29,"./util/UIUtil":30,"./videolayout/VideoLayout.js":32,"./welcome_page/RoomnameGenerator":33,"./welcome_page/WelcomePage":34,"events":1}],10:[function(require,module,exports){
  1998. var CanvasUtil = require("./CanvasUtils");
  1999. var ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  2000. function initActiveSpeakerAudioLevels() {
  2001. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  2002. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  2003. // Draw a circle.
  2004. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  2005. // Add a shadow around the circle
  2006. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  2007. ASDrawContext.shadowOffsetX = 0;
  2008. ASDrawContext.shadowOffsetY = 0;
  2009. }
  2010. /**
  2011. * The audio Levels plugin.
  2012. */
  2013. var AudioLevels = (function(my) {
  2014. var audioLevelCanvasCache = {};
  2015. my.LOCAL_LEVEL = 'local';
  2016. my.init = function () {
  2017. initActiveSpeakerAudioLevels();
  2018. }
  2019. /**
  2020. * Updates the audio level canvas for the given peerJid. If the canvas
  2021. * didn't exist we create it.
  2022. */
  2023. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  2024. var resourceJid = null;
  2025. var videoSpanId = null;
  2026. if (!peerJid)
  2027. videoSpanId = 'localVideoContainer';
  2028. else {
  2029. resourceJid = Strophe.getResourceFromJid(peerJid);
  2030. videoSpanId = 'participant_' + resourceJid;
  2031. }
  2032. var videoSpan = document.getElementById(videoSpanId);
  2033. if (!videoSpan) {
  2034. if (resourceJid)
  2035. console.error("No video element for jid", resourceJid);
  2036. else
  2037. console.error("No video element for local video.");
  2038. return;
  2039. }
  2040. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  2041. var videoSpaceWidth = $('#remoteVideos').width();
  2042. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  2043. var thumbnailWidth = thumbnailSize[0];
  2044. var thumbnailHeight = thumbnailSize[1];
  2045. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  2046. audioLevelCanvas = document.createElement('canvas');
  2047. audioLevelCanvas.className = "audiolevel";
  2048. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  2049. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  2050. resizeAudioLevelCanvas( audioLevelCanvas,
  2051. thumbnailWidth,
  2052. thumbnailHeight);
  2053. videoSpan.appendChild(audioLevelCanvas);
  2054. } else {
  2055. audioLevelCanvas = audioLevelCanvas.get(0);
  2056. resizeAudioLevelCanvas( audioLevelCanvas,
  2057. thumbnailWidth,
  2058. thumbnailHeight);
  2059. }
  2060. };
  2061. /**
  2062. * Updates the audio level UI for the given resourceJid.
  2063. *
  2064. * @param resourceJid the resource jid indicating the video element for
  2065. * which we draw the audio level
  2066. * @param audioLevel the newAudio level to render
  2067. */
  2068. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  2069. drawAudioLevelCanvas(resourceJid, audioLevel);
  2070. var videoSpanId = getVideoSpanId(resourceJid);
  2071. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  2072. if (!audioLevelCanvas)
  2073. return;
  2074. var drawContext = audioLevelCanvas.getContext('2d');
  2075. var canvasCache = audioLevelCanvasCache[resourceJid];
  2076. drawContext.clearRect (0, 0,
  2077. audioLevelCanvas.width, audioLevelCanvas.height);
  2078. drawContext.drawImage(canvasCache, 0, 0);
  2079. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  2080. if(!APP.xmpp.myJid()) {
  2081. return;
  2082. }
  2083. resourceJid = APP.xmpp.myResource();
  2084. }
  2085. if(resourceJid === largeVideoResourceJid) {
  2086. window.requestAnimationFrame(function () {
  2087. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  2088. });
  2089. }
  2090. };
  2091. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  2092. if($("#activeSpeaker").css("visibility") == "hidden")
  2093. return;
  2094. ASDrawContext.clearRect(0, 0, 300, 300);
  2095. if(audioLevel == 0)
  2096. return;
  2097. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  2098. // Fill the shape.
  2099. ASDrawContext.fill();
  2100. };
  2101. /**
  2102. * Resizes the given audio level canvas to match the given thumbnail size.
  2103. */
  2104. function resizeAudioLevelCanvas(audioLevelCanvas,
  2105. thumbnailWidth,
  2106. thumbnailHeight) {
  2107. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  2108. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  2109. }
  2110. /**
  2111. * Draws the audio level canvas into the cached canvas object.
  2112. *
  2113. * @param resourceJid the resource jid indicating the video element for
  2114. * which we draw the audio level
  2115. * @param audioLevel the newAudio level to render
  2116. */
  2117. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  2118. if (!audioLevelCanvasCache[resourceJid]) {
  2119. var videoSpanId = getVideoSpanId(resourceJid);
  2120. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  2121. /*
  2122. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  2123. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  2124. * error. Since audio levels are frequently updated, the errors have
  2125. * been observed to pile into the console, strain the CPU.
  2126. */
  2127. if (audioLevelCanvasOrig)
  2128. {
  2129. audioLevelCanvasCache[resourceJid]
  2130. = CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  2131. }
  2132. }
  2133. var canvas = audioLevelCanvasCache[resourceJid];
  2134. if (!canvas)
  2135. return;
  2136. var drawContext = canvas.getContext('2d');
  2137. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  2138. var shadowLevel = getShadowLevel(audioLevel);
  2139. if (shadowLevel > 0)
  2140. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  2141. CanvasUtil.drawRoundRectGlow( drawContext,
  2142. interfaceConfig.CANVAS_EXTRA/2, interfaceConfig.CANVAS_EXTRA/2,
  2143. canvas.width - interfaceConfig.CANVAS_EXTRA,
  2144. canvas.height - interfaceConfig.CANVAS_EXTRA,
  2145. interfaceConfig.CANVAS_RADIUS,
  2146. interfaceConfig.SHADOW_COLOR,
  2147. shadowLevel);
  2148. }
  2149. /**
  2150. * Returns the shadow/glow level for the given audio level.
  2151. *
  2152. * @param audioLevel the audio level from which we determine the shadow
  2153. * level
  2154. */
  2155. function getShadowLevel (audioLevel) {
  2156. var shadowLevel = 0;
  2157. if (audioLevel <= 0.3) {
  2158. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  2159. }
  2160. else if (audioLevel <= 0.6) {
  2161. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  2162. }
  2163. else {
  2164. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  2165. }
  2166. return shadowLevel;
  2167. }
  2168. /**
  2169. * Returns the video span id corresponding to the given resourceJid or local
  2170. * user.
  2171. */
  2172. function getVideoSpanId(resourceJid) {
  2173. var videoSpanId = null;
  2174. if (resourceJid === AudioLevels.LOCAL_LEVEL
  2175. || (APP.xmpp.myResource() && resourceJid
  2176. === APP.xmpp.myResource()))
  2177. videoSpanId = 'localVideoContainer';
  2178. else
  2179. videoSpanId = 'participant_' + resourceJid;
  2180. return videoSpanId;
  2181. }
  2182. /**
  2183. * Indicates that the remote video has been resized.
  2184. */
  2185. $(document).bind('remotevideo.resized', function (event, width, height) {
  2186. var resized = false;
  2187. $('#remoteVideos>span>canvas').each(function() {
  2188. var canvas = $(this).get(0);
  2189. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  2190. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  2191. resized = true;
  2192. }
  2193. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  2194. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  2195. resized = true;
  2196. }
  2197. });
  2198. if (resized)
  2199. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  2200. audioLevelCanvasCache[resourceJid].width
  2201. = width + interfaceConfig.CANVAS_EXTRA;
  2202. audioLevelCanvasCache[resourceJid].height
  2203. = height + interfaceConfig.CANVAS_EXTRA;
  2204. });
  2205. });
  2206. return my;
  2207. })(AudioLevels || {});
  2208. module.exports = AudioLevels;
  2209. },{"./CanvasUtils":11}],11:[function(require,module,exports){
  2210. /**
  2211. * Utility class for drawing canvas shapes.
  2212. */
  2213. var CanvasUtil = (function(my) {
  2214. /**
  2215. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  2216. * of the glow.
  2217. *
  2218. * @param drawContext the context of the canvas to draw to
  2219. * @param x the x coordinate of the round rectangle
  2220. * @param y the y coordinate of the round rectangle
  2221. * @param w the width of the round rectangle
  2222. * @param h the height of the round rectangle
  2223. * @param glowColor the color of the glow
  2224. * @param glowWidth the width of the glow
  2225. */
  2226. my.drawRoundRectGlow
  2227. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  2228. // Save the previous state of the context.
  2229. drawContext.save();
  2230. if (w < 2 * r) r = w / 2;
  2231. if (h < 2 * r) r = h / 2;
  2232. // Draw a round rectangle.
  2233. drawContext.beginPath();
  2234. drawContext.moveTo(x+r, y);
  2235. drawContext.arcTo(x+w, y, x+w, y+h, r);
  2236. drawContext.arcTo(x+w, y+h, x, y+h, r);
  2237. drawContext.arcTo(x, y+h, x, y, r);
  2238. drawContext.arcTo(x, y, x+w, y, r);
  2239. drawContext.closePath();
  2240. // Add a shadow around the rectangle
  2241. drawContext.shadowColor = glowColor;
  2242. drawContext.shadowBlur = glowWidth;
  2243. drawContext.shadowOffsetX = 0;
  2244. drawContext.shadowOffsetY = 0;
  2245. // Fill the shape.
  2246. drawContext.fill();
  2247. drawContext.save();
  2248. drawContext.restore();
  2249. // 1) Uncomment this line to use Composite Operation, which is doing the
  2250. // same as the clip function below and is also antialiasing the round
  2251. // border, but is said to be less fast performance wise.
  2252. // drawContext.globalCompositeOperation='destination-out';
  2253. drawContext.beginPath();
  2254. drawContext.moveTo(x+r, y);
  2255. drawContext.arcTo(x+w, y, x+w, y+h, r);
  2256. drawContext.arcTo(x+w, y+h, x, y+h, r);
  2257. drawContext.arcTo(x, y+h, x, y, r);
  2258. drawContext.arcTo(x, y, x+w, y, r);
  2259. drawContext.closePath();
  2260. // 2) Uncomment this line to use Composite Operation, which is doing the
  2261. // same as the clip function below and is also antialiasing the round
  2262. // border, but is said to be less fast performance wise.
  2263. // drawContext.fill();
  2264. // Comment these two lines if choosing to do the same with composite
  2265. // operation above 1 and 2.
  2266. drawContext.clip();
  2267. drawContext.clearRect(0, 0, 277, 200);
  2268. // Restore the previous context state.
  2269. drawContext.restore();
  2270. };
  2271. /**
  2272. * Clones the given canvas.
  2273. *
  2274. * @return the new cloned canvas.
  2275. */
  2276. my.cloneCanvas = function (oldCanvas) {
  2277. /*
  2278. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  2279. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  2280. * levels are frequently updated, the errors have been observed to pile
  2281. * into the console, strain the CPU.
  2282. */
  2283. if (!oldCanvas)
  2284. return oldCanvas;
  2285. //create a new canvas
  2286. var newCanvas = document.createElement('canvas');
  2287. var context = newCanvas.getContext('2d');
  2288. //set dimensions
  2289. newCanvas.width = oldCanvas.width;
  2290. newCanvas.height = oldCanvas.height;
  2291. //apply the old canvas to the new one
  2292. context.drawImage(oldCanvas, 0, 0);
  2293. //return the new canvas
  2294. return newCanvas;
  2295. };
  2296. return my;
  2297. })(CanvasUtil || {});
  2298. module.exports = CanvasUtil;
  2299. },{}],12:[function(require,module,exports){
  2300. /* Initial "authentication required" dialog */
  2301. var authDialog = null;
  2302. /* Loop retry ID that wits for other user to create the room */
  2303. var authRetryId = null;
  2304. var authenticationWindow = null;
  2305. var Authentication = {
  2306. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  2307. // This is the loop that will wait for the room to be created by
  2308. // someone else. 'auth_required.moderator' will bring us back here.
  2309. authRetryId = window.setTimeout(intervalCallback , 5000);
  2310. // Show prompt only if it's not open
  2311. if (authDialog !== null) {
  2312. return;
  2313. }
  2314. // extract room name from 'room@muc.server.net'
  2315. var room = roomName.substr(0, roomName.indexOf('@'));
  2316. var title = APP.translation.generateTranslatonHTML("dialog.Stop",
  2317. "Stop");
  2318. var defMsg = 'Authentication is required to create room:<br/><b>' +
  2319. room +
  2320. '</b></br> You can either authenticate to create the room or ' +
  2321. 'just wait for someone else to do so.';
  2322. var msg = APP.translation.generateTranslatonHTML("dialog.AuthMsg",
  2323. defMsg, {room: room});
  2324. var button = APP.translation.generateTranslatonHTML(
  2325. "dialog.Authenticate", "Authenticate");
  2326. var buttons = {};
  2327. buttons.authenticate = {title: button, value: "authNow"};
  2328. authDialog = APP.UI.messageHandler.openDialog(
  2329. title,
  2330. msg,
  2331. true,
  2332. buttons,
  2333. function (onSubmitEvent, submitValue) {
  2334. // Do not close the dialog yet
  2335. onSubmitEvent.preventDefault();
  2336. // Open login popup
  2337. if (submitValue === 'authNow') {
  2338. callback();
  2339. }
  2340. }
  2341. );
  2342. },
  2343. closeAuthenticationWindow:function () {
  2344. if (authenticationWindow) {
  2345. authenticationWindow.close();
  2346. authenticationWindow = null;
  2347. }
  2348. },
  2349. focusAuthenticationWindow: function () {
  2350. // If auth window exists just bring it to the front
  2351. if (authenticationWindow) {
  2352. authenticationWindow.focus();
  2353. return;
  2354. }
  2355. },
  2356. closeAuthenticationDialog: function () {
  2357. // Close authentication dialog if opened
  2358. if (authDialog) {
  2359. APP.UI.messageHandler.closeDialog();
  2360. authDialog = null;
  2361. }
  2362. },
  2363. createAuthenticationWindow: function (callback, url) {
  2364. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  2365. url, 910, 660,
  2366. // On closed
  2367. function () {
  2368. // Close authentication dialog if opened
  2369. if (authDialog) {
  2370. messageHandler.closeDialog();
  2371. authDialog = null;
  2372. }
  2373. callback();
  2374. authenticationWindow = null;
  2375. });
  2376. return authenticationWindow;
  2377. },
  2378. stopInterval: function () {
  2379. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  2380. if (authRetryId) {
  2381. window.clearTimeout(authRetryId);
  2382. authRetryId = null;
  2383. }
  2384. }
  2385. };
  2386. module.exports = Authentication;
  2387. },{}],13:[function(require,module,exports){
  2388. var Settings = require("../../settings/Settings");
  2389. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  2390. var users = {};
  2391. var activeSpeakerJid;
  2392. function setVisibility(selector, show) {
  2393. if (selector && selector.length > 0) {
  2394. selector.css("visibility", show ? "visible" : "hidden");
  2395. }
  2396. }
  2397. function isUserMuted(jid) {
  2398. // XXX(gp) we may want to rename this method to something like
  2399. // isUserStreaming, for example.
  2400. if (jid && jid != APP.xmpp.myJid()) {
  2401. var resource = Strophe.getResourceFromJid(jid);
  2402. if (!require("../videolayout/VideoLayout").isInLastN(resource)) {
  2403. return true;
  2404. }
  2405. }
  2406. if (!APP.RTC.remoteStreams[jid] || !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  2407. return null;
  2408. }
  2409. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  2410. }
  2411. function getGravatarUrl(id, size) {
  2412. if(id === APP.xmpp.myJid() || !id) {
  2413. id = Settings.getSettings().uid;
  2414. }
  2415. return 'https://www.gravatar.com/avatar/' +
  2416. MD5.hexdigest(id.trim().toLowerCase()) +
  2417. "?d=wavatar&size=" + (size || "30");
  2418. }
  2419. var Avatar = {
  2420. /**
  2421. * Sets the user's avatar in the settings menu(if local user), contact list
  2422. * and thumbnail
  2423. * @param jid jid of the user
  2424. * @param id email or userID to be used as a hash
  2425. */
  2426. setUserAvatar: function (jid, id) {
  2427. if (id) {
  2428. if (users[jid] === id) {
  2429. return;
  2430. }
  2431. users[jid] = id;
  2432. }
  2433. var thumbUrl = getGravatarUrl(users[jid] || jid, 100);
  2434. var contactListUrl = getGravatarUrl(users[jid] || jid);
  2435. var resourceJid = Strophe.getResourceFromJid(jid);
  2436. var thumbnail = $('#participant_' + resourceJid);
  2437. var avatar = $('#avatar_' + resourceJid);
  2438. // set the avatar in the settings menu if it is local user and get the
  2439. // local video container
  2440. if (jid === APP.xmpp.myJid()) {
  2441. $('#avatar').get(0).src = thumbUrl;
  2442. thumbnail = $('#localVideoContainer');
  2443. }
  2444. // set the avatar in the contact list
  2445. var contact = $('#' + resourceJid + '>img');
  2446. if (contact && contact.length > 0) {
  2447. contact.get(0).src = contactListUrl;
  2448. }
  2449. // set the avatar in the thumbnail
  2450. if (avatar && avatar.length > 0) {
  2451. avatar[0].src = thumbUrl;
  2452. } else {
  2453. if (thumbnail && thumbnail.length > 0) {
  2454. avatar = document.createElement('img');
  2455. avatar.id = 'avatar_' + resourceJid;
  2456. avatar.className = 'userAvatar';
  2457. avatar.src = thumbUrl;
  2458. thumbnail.append(avatar);
  2459. }
  2460. }
  2461. //if the user is the current active speaker - update the active speaker
  2462. // avatar
  2463. if (jid === activeSpeakerJid) {
  2464. this.updateActiveSpeakerAvatarSrc(jid);
  2465. }
  2466. },
  2467. /**
  2468. * Hides or shows the user's avatar
  2469. * @param jid jid of the user
  2470. * @param show whether we should show the avatar or not
  2471. * video because there is no dominant speaker and no focused speaker
  2472. */
  2473. showUserAvatar: function (jid, show) {
  2474. if (users[jid]) {
  2475. var resourceJid = Strophe.getResourceFromJid(jid);
  2476. var video = $('#participant_' + resourceJid + '>video');
  2477. var avatar = $('#avatar_' + resourceJid);
  2478. if (jid === APP.xmpp.myJid()) {
  2479. video = $('#localVideoWrapper>video');
  2480. }
  2481. if (show === undefined || show === null) {
  2482. show = isUserMuted(jid);
  2483. }
  2484. //if the user is the currently focused, the dominant speaker or if
  2485. //there is no focused and no dominant speaker and the large video is
  2486. //currently shown
  2487. if (activeSpeakerJid === jid && require("../videolayout/VideoLayout").isLargeVideoOnTop()) {
  2488. setVisibility($("#largeVideo"), !show);
  2489. setVisibility($('#activeSpeaker'), show);
  2490. setVisibility(avatar, false);
  2491. setVisibility(video, false);
  2492. } else {
  2493. if (video && video.length > 0) {
  2494. setVisibility(video, !show);
  2495. setVisibility(avatar, show);
  2496. }
  2497. }
  2498. }
  2499. },
  2500. /**
  2501. * Updates the src of the active speaker avatar
  2502. * @param jid of the current active speaker
  2503. */
  2504. updateActiveSpeakerAvatarSrc: function (jid) {
  2505. if (!jid) {
  2506. jid = APP.xmpp.findJidFromResource(
  2507. require("../videolayout/VideoLayout").getLargeVideoState().userResourceJid);
  2508. }
  2509. var avatar = $("#activeSpeakerAvatar")[0];
  2510. var url = getGravatarUrl(users[jid],
  2511. interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE);
  2512. if (jid === activeSpeakerJid && avatar.src === url) {
  2513. return;
  2514. }
  2515. activeSpeakerJid = jid;
  2516. var isMuted = isUserMuted(jid);
  2517. if (jid && isMuted !== null) {
  2518. avatar.src = url;
  2519. setVisibility($("#largeVideo"), !isMuted);
  2520. Avatar.showUserAvatar(jid, isMuted);
  2521. }
  2522. }
  2523. };
  2524. module.exports = Avatar;
  2525. },{"../../../service/RTC/MediaStreamTypes":79,"../../settings/Settings":38,"../videolayout/VideoLayout":32}],14:[function(require,module,exports){
  2526. /* global $, config,
  2527. setLargeVideoVisible, Util */
  2528. var VideoLayout = require("../videolayout/VideoLayout");
  2529. var Prezi = require("../prezi/Prezi");
  2530. var UIUtil = require("../util/UIUtil");
  2531. var etherpadName = null;
  2532. var etherpadIFrame = null;
  2533. var domain = null;
  2534. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  2535. /**
  2536. * Resizes the etherpad.
  2537. */
  2538. function resize() {
  2539. if ($('#etherpad>iframe').length) {
  2540. var remoteVideos = $('#remoteVideos');
  2541. var availableHeight
  2542. = window.innerHeight - remoteVideos.outerHeight();
  2543. var availableWidth = UIUtil.getAvailableVideoWidth();
  2544. $('#etherpad>iframe').width(availableWidth);
  2545. $('#etherpad>iframe').height(availableHeight);
  2546. }
  2547. }
  2548. /**
  2549. * Shares the Etherpad name with other participants.
  2550. */
  2551. function shareEtherpad() {
  2552. APP.xmpp.addToPresence("etherpad", etherpadName);
  2553. }
  2554. /**
  2555. * Creates the Etherpad button and adds it to the toolbar.
  2556. */
  2557. function enableEtherpadButton() {
  2558. if (!$('#etherpadButton').is(":visible"))
  2559. $('#etherpadButton').css({display: 'inline-block'});
  2560. }
  2561. /**
  2562. * Creates the IFrame for the etherpad.
  2563. */
  2564. function createIFrame() {
  2565. etherpadIFrame = document.createElement('iframe');
  2566. etherpadIFrame.src = domain + etherpadName + options;
  2567. etherpadIFrame.frameBorder = 0;
  2568. etherpadIFrame.scrolling = "no";
  2569. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  2570. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  2571. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  2572. document.getElementById('etherpad').appendChild(etherpadIFrame);
  2573. etherpadIFrame.onload = function() {
  2574. document.domain = document.domain;
  2575. bubbleIframeMouseMove(etherpadIFrame);
  2576. setTimeout(function() {
  2577. // the iframes inside of the etherpad are
  2578. // not yet loaded when the etherpad iframe is loaded
  2579. var outer = etherpadIFrame.
  2580. contentDocument.getElementsByName("ace_outer")[0];
  2581. bubbleIframeMouseMove(outer);
  2582. var inner = outer.
  2583. contentDocument.getElementsByName("ace_inner")[0];
  2584. bubbleIframeMouseMove(inner);
  2585. }, 2000);
  2586. };
  2587. }
  2588. function bubbleIframeMouseMove(iframe){
  2589. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  2590. iframe.contentWindow.onmousemove = function(e){
  2591. if(existingOnMouseMove) existingOnMouseMove(e);
  2592. var evt = document.createEvent("MouseEvents");
  2593. var boundingClientRect = iframe.getBoundingClientRect();
  2594. evt.initMouseEvent(
  2595. "mousemove",
  2596. true, // bubbles
  2597. false, // not cancelable
  2598. window,
  2599. e.detail,
  2600. e.screenX,
  2601. e.screenY,
  2602. e.clientX + boundingClientRect.left,
  2603. e.clientY + boundingClientRect.top,
  2604. e.ctrlKey,
  2605. e.altKey,
  2606. e.shiftKey,
  2607. e.metaKey,
  2608. e.button,
  2609. null // no related element
  2610. );
  2611. iframe.dispatchEvent(evt);
  2612. };
  2613. }
  2614. /**
  2615. * On video selected event.
  2616. */
  2617. $(document).bind('video.selected', function (event, isPresentation) {
  2618. if (config.etherpad_base && etherpadIFrame && etherpadIFrame.style.visibility !== 'hidden')
  2619. Etherpad.toggleEtherpad(isPresentation);
  2620. });
  2621. var Etherpad = {
  2622. /**
  2623. * Initializes the etherpad.
  2624. */
  2625. init: function (name) {
  2626. if (config.etherpad_base && !etherpadName) {
  2627. domain = config.etherpad_base;
  2628. if (!name) {
  2629. // In case we're the focus we generate the name.
  2630. etherpadName = Math.random().toString(36).substring(7) +
  2631. '_' + (new Date().getTime()).toString();
  2632. shareEtherpad();
  2633. }
  2634. else
  2635. etherpadName = name;
  2636. enableEtherpadButton();
  2637. /**
  2638. * Resizes the etherpad, when the window is resized.
  2639. */
  2640. $(window).resize(function () {
  2641. resize();
  2642. });
  2643. }
  2644. },
  2645. /**
  2646. * Opens/hides the Etherpad.
  2647. */
  2648. toggleEtherpad: function (isPresentation) {
  2649. if (!etherpadIFrame)
  2650. createIFrame();
  2651. var largeVideo = null;
  2652. if (Prezi.isPresentationVisible())
  2653. largeVideo = $('#presentation>iframe');
  2654. else
  2655. largeVideo = $('#largeVideo');
  2656. if ($('#etherpad>iframe').css('visibility') === 'hidden') {
  2657. $('#activeSpeaker').css('visibility', 'hidden');
  2658. largeVideo.fadeOut(300, function () {
  2659. if (Prezi.isPresentationVisible()) {
  2660. largeVideo.css({opacity: '0'});
  2661. } else {
  2662. VideoLayout.setLargeVideoVisible(false);
  2663. }
  2664. });
  2665. $('#etherpad>iframe').fadeIn(300, function () {
  2666. document.body.style.background = '#eeeeee';
  2667. $('#etherpad>iframe').css({visibility: 'visible'});
  2668. $('#etherpad').css({zIndex: 2});
  2669. });
  2670. }
  2671. else if ($('#etherpad>iframe')) {
  2672. $('#etherpad>iframe').fadeOut(300, function () {
  2673. $('#etherpad>iframe').css({visibility: 'hidden'});
  2674. $('#etherpad').css({zIndex: 0});
  2675. document.body.style.background = 'black';
  2676. });
  2677. if (!isPresentation) {
  2678. $('#largeVideo').fadeIn(300, function () {
  2679. VideoLayout.setLargeVideoVisible(true);
  2680. });
  2681. }
  2682. }
  2683. resize();
  2684. },
  2685. isVisible: function() {
  2686. var etherpadIframe = $('#etherpad>iframe');
  2687. return etherpadIframe && etherpadIframe.is(':visible');
  2688. }
  2689. };
  2690. module.exports = Etherpad;
  2691. },{"../prezi/Prezi":15,"../util/UIUtil":30,"../videolayout/VideoLayout":32}],15:[function(require,module,exports){
  2692. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  2693. var UIUtil = require("../util/UIUtil");
  2694. var VideoLayout = require("../videolayout/VideoLayout");
  2695. var messageHandler = require("../util/MessageHandler");
  2696. var PreziPlayer = require("./PreziPlayer");
  2697. var preziPlayer = null;
  2698. var Prezi = {
  2699. /**
  2700. * Reloads the current presentation.
  2701. */
  2702. reloadPresentation: function() {
  2703. var iframe = document.getElementById(preziPlayer.options.preziId);
  2704. iframe.src = iframe.src;
  2705. },
  2706. /**
  2707. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  2708. * otherwise.
  2709. */
  2710. isPresentationVisible: function () {
  2711. return ($('#presentation>iframe') != null
  2712. && $('#presentation>iframe').css('opacity') == 1);
  2713. },
  2714. /**
  2715. * Opens the Prezi dialog, from which the user could choose a presentation
  2716. * to load.
  2717. */
  2718. openPreziDialog: function() {
  2719. var myprezi = APP.xmpp.getPrezi();
  2720. if (myprezi) {
  2721. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  2722. "Remove Prezi", "dialog.removePreziMsg",
  2723. "Are you sure you would like to remove your Prezi?",
  2724. false,
  2725. "dialog.Remove",
  2726. function(e,v,m,f) {
  2727. if(v) {
  2728. APP.xmpp.removePreziFromPresence();
  2729. }
  2730. }
  2731. );
  2732. }
  2733. else if (preziPlayer != null) {
  2734. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  2735. "Share a Prezi", "dialog.sharePreziMsg",
  2736. "Another participant is already sharing a Prezi." +
  2737. "This conference allows only one Prezi at a time.",
  2738. false,
  2739. "dialog.Ok",
  2740. function(e,v,m,f) {
  2741. $.prompt.close();
  2742. }
  2743. );
  2744. }
  2745. else {
  2746. var html = APP.translation.generateTranslatonHTML(
  2747. "dialog.sharePreziTitle", "Share a Prezi");
  2748. var cancelButton = APP.translation.generateTranslatonHTML(
  2749. "dialog.Cancel", "Cancel");
  2750. var shareButton = APP.translation.generateTranslatonHTML(
  2751. "dialog.Share", "Share");
  2752. var backButton = APP.translation.generateTranslatonHTML(
  2753. "dialog.Back", "Back");
  2754. var buttons = {};
  2755. var buttons1 = {};
  2756. buttons1.button1 = buttons.button1 = {title: cancelButton, value: false};
  2757. buttons.button2 = {title: shareButton, value: true};
  2758. buttons1.button2 = {title: backButton, value: true};
  2759. var linkError = APP.translation.generateTranslatonHTML(
  2760. "dialog.preziLinkError", "Please provide a correct prezi link.")
  2761. var openPreziState = {
  2762. state0: {
  2763. html: '<h2>' + html + '</h2>' +
  2764. '<input id="preziUrl" type="text" ' +
  2765. 'placeholder="e.g. ' +
  2766. 'http://prezi.com/wz7vhjycl7e6/my-prezi" autofocus>',
  2767. persistent: false,
  2768. buttons: buttons,
  2769. defaultButton: 1,
  2770. submit: function(e,v,m,f){
  2771. e.preventDefault();
  2772. if(v)
  2773. {
  2774. var preziUrl = document.getElementById('preziUrl');
  2775. if (preziUrl.value)
  2776. {
  2777. var urlValue
  2778. = encodeURI(UIUtil.escapeHtml(preziUrl.value));
  2779. if (urlValue.indexOf('http://prezi.com/') != 0
  2780. && urlValue.indexOf('https://prezi.com/') != 0)
  2781. {
  2782. $.prompt.goToState('state1');
  2783. return false;
  2784. }
  2785. else {
  2786. var presIdTmp = urlValue.substring(
  2787. urlValue.indexOf("prezi.com/") + 10);
  2788. if (!isAlphanumeric(presIdTmp)
  2789. || presIdTmp.indexOf('/') < 2) {
  2790. $.prompt.goToState('state1');
  2791. return false;
  2792. }
  2793. else {
  2794. APP.xmpp.addToPresence("prezi", urlValue);
  2795. $.prompt.close();
  2796. }
  2797. }
  2798. }
  2799. }
  2800. else
  2801. $.prompt.close();
  2802. }
  2803. },
  2804. state1: {
  2805. html: '<h2>' + html + '</h2>' +
  2806. linkError,
  2807. persistent: false,
  2808. buttons: buttons1,
  2809. defaultButton: 1,
  2810. submit:function(e,v,m,f) {
  2811. e.preventDefault();
  2812. if(v==0)
  2813. $.prompt.close();
  2814. else
  2815. $.prompt.goToState('state0');
  2816. }
  2817. }
  2818. };
  2819. var focusPreziUrl = function(e) {
  2820. document.getElementById('preziUrl').focus();
  2821. };
  2822. messageHandler.openDialogWithStates(openPreziState, focusPreziUrl, focusPreziUrl);
  2823. }
  2824. }
  2825. };
  2826. /**
  2827. * A new presentation has been added.
  2828. *
  2829. * @param event the event indicating the add of a presentation
  2830. * @param jid the jid from which the presentation was added
  2831. * @param presUrl url of the presentation
  2832. * @param currentSlide the current slide to which we should move
  2833. */
  2834. function presentationAdded(event, jid, presUrl, currentSlide) {
  2835. console.log("presentation added", presUrl);
  2836. var presId = getPresentationId(presUrl);
  2837. var elementId = 'participant_'
  2838. + Strophe.getResourceFromJid(jid)
  2839. + '_' + presId;
  2840. // We explicitly don't specify the peer jid here, because we don't want
  2841. // this video to be dealt with as a peer related one (for example we
  2842. // don't want to show a mute/kick menu for this one, etc.).
  2843. VideoLayout.addRemoteVideoContainer(null, elementId);
  2844. VideoLayout.resizeThumbnails();
  2845. var controlsEnabled = false;
  2846. if (jid === APP.xmpp.myJid())
  2847. controlsEnabled = true;
  2848. setPresentationVisible(true);
  2849. $('#largeVideoContainer').hover(
  2850. function (event) {
  2851. if (Prezi.isPresentationVisible()) {
  2852. var reloadButtonRight = window.innerWidth
  2853. - $('#presentation>iframe').offset().left
  2854. - $('#presentation>iframe').width();
  2855. $('#reloadPresentation').css({ right: reloadButtonRight,
  2856. display:'inline-block'});
  2857. }
  2858. },
  2859. function (event) {
  2860. if (!Prezi.isPresentationVisible())
  2861. $('#reloadPresentation').css({display:'none'});
  2862. else {
  2863. var e = event.toElement || event.relatedTarget;
  2864. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  2865. $('#reloadPresentation').css({display:'none'});
  2866. }
  2867. });
  2868. preziPlayer = new PreziPlayer(
  2869. 'presentation',
  2870. {preziId: presId,
  2871. width: getPresentationWidth(),
  2872. height: getPresentationHeihgt(),
  2873. controls: controlsEnabled,
  2874. debug: true
  2875. });
  2876. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  2877. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  2878. console.log("prezi status", event.value);
  2879. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  2880. if (jid != APP.xmpp.myJid())
  2881. preziPlayer.flyToStep(currentSlide);
  2882. }
  2883. });
  2884. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  2885. console.log("event value", event.value);
  2886. APP.xmpp.addToPresence("preziSlide", event.value);
  2887. });
  2888. $("#" + elementId).css( 'background-image',
  2889. 'url(../images/avatarprezi.png)');
  2890. $("#" + elementId).click(
  2891. function () {
  2892. setPresentationVisible(true);
  2893. }
  2894. );
  2895. };
  2896. /**
  2897. * A presentation has been removed.
  2898. *
  2899. * @param event the event indicating the remove of a presentation
  2900. * @param jid the jid for which the presentation was removed
  2901. * @param the url of the presentation
  2902. */
  2903. function presentationRemoved(event, jid, presUrl) {
  2904. console.log('presentation removed', presUrl);
  2905. var presId = getPresentationId(presUrl);
  2906. setPresentationVisible(false);
  2907. $('#participant_'
  2908. + Strophe.getResourceFromJid(jid)
  2909. + '_' + presId).remove();
  2910. $('#presentation>iframe').remove();
  2911. if (preziPlayer != null) {
  2912. preziPlayer.destroy();
  2913. preziPlayer = null;
  2914. }
  2915. };
  2916. /**
  2917. * Indicates if the given string is an alphanumeric string.
  2918. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  2919. * purpose of checking URIs.
  2920. */
  2921. function isAlphanumeric(unsafeText) {
  2922. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  2923. return regex.test(unsafeText);
  2924. }
  2925. /**
  2926. * Returns the presentation id from the given url.
  2927. */
  2928. function getPresentationId (presUrl) {
  2929. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  2930. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  2931. }
  2932. /**
  2933. * Returns the presentation width.
  2934. */
  2935. function getPresentationWidth() {
  2936. var availableWidth = UIUtil.getAvailableVideoWidth();
  2937. var availableHeight = getPresentationHeihgt();
  2938. var aspectRatio = 16.0 / 9.0;
  2939. if (availableHeight < availableWidth / aspectRatio) {
  2940. availableWidth = Math.floor(availableHeight * aspectRatio);
  2941. }
  2942. return availableWidth;
  2943. }
  2944. /**
  2945. * Returns the presentation height.
  2946. */
  2947. function getPresentationHeihgt() {
  2948. var remoteVideos = $('#remoteVideos');
  2949. return window.innerHeight - remoteVideos.outerHeight();
  2950. }
  2951. /**
  2952. * Resizes the presentation iframe.
  2953. */
  2954. function resize() {
  2955. if ($('#presentation>iframe')) {
  2956. $('#presentation>iframe').width(getPresentationWidth());
  2957. $('#presentation>iframe').height(getPresentationHeihgt());
  2958. }
  2959. }
  2960. /**
  2961. * Shows/hides a presentation.
  2962. */
  2963. function setPresentationVisible(visible) {
  2964. var prezi = $('#presentation>iframe');
  2965. if (visible) {
  2966. // Trigger the video.selected event to indicate a change in the
  2967. // large video.
  2968. $(document).trigger("video.selected", [true]);
  2969. $('#largeVideo').fadeOut(300);
  2970. prezi.fadeIn(300, function() {
  2971. prezi.css({opacity:'1'});
  2972. ToolbarToggler.dockToolbar(true);
  2973. VideoLayout.setLargeVideoVisible(false);
  2974. });
  2975. $('#activeSpeaker').css('visibility', 'hidden');
  2976. }
  2977. else {
  2978. if (prezi.css('opacity') == '1') {
  2979. prezi.fadeOut(300, function () {
  2980. prezi.css({opacity:'0'});
  2981. $('#reloadPresentation').css({display:'none'});
  2982. $('#largeVideo').fadeIn(300, function() {
  2983. VideoLayout.setLargeVideoVisible(true);
  2984. ToolbarToggler.dockToolbar(false);
  2985. });
  2986. });
  2987. }
  2988. }
  2989. }
  2990. /**
  2991. * Presentation has been removed.
  2992. */
  2993. $(document).bind('presentationremoved.muc', presentationRemoved);
  2994. /**
  2995. * Presentation has been added.
  2996. */
  2997. $(document).bind('presentationadded.muc', presentationAdded);
  2998. /*
  2999. * Indicates presentation slide change.
  3000. */
  3001. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  3002. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  3003. preziPlayer.flyToStep(current);
  3004. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  3005. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  3006. preziPlayer.flyToStep(current, i);
  3007. }
  3008. }
  3009. });
  3010. /**
  3011. * On video selected event.
  3012. */
  3013. $(document).bind('video.selected', function (event, isPresentation) {
  3014. if (!isPresentation && $('#presentation>iframe')) {
  3015. setPresentationVisible(false);
  3016. }
  3017. });
  3018. $(window).resize(function () {
  3019. resize();
  3020. });
  3021. module.exports = Prezi;
  3022. },{"../toolbars/ToolbarToggler":26,"../util/MessageHandler":28,"../util/UIUtil":30,"../videolayout/VideoLayout":32,"./PreziPlayer":16}],16:[function(require,module,exports){
  3023. (function() {
  3024. "use strict";
  3025. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  3026. window.PreziPlayer = (function() {
  3027. PreziPlayer.API_VERSION = 1;
  3028. PreziPlayer.CURRENT_STEP = 'currentStep';
  3029. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  3030. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  3031. PreziPlayer.STATUS_LOADING = 'loading';
  3032. PreziPlayer.STATUS_READY = 'ready';
  3033. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  3034. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  3035. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  3036. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  3037. PreziPlayer.EVENT_STATUS = "statusChange";
  3038. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  3039. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  3040. PreziPlayer.domain = "https://prezi.com";
  3041. PreziPlayer.path = "/player/";
  3042. PreziPlayer.players = {};
  3043. PreziPlayer.binded_methods = ['changesHandler'];
  3044. PreziPlayer.createMultiplePlayers = function(optionArray){
  3045. for(var i=0; i<optionArray.length; i++) {
  3046. var optionSet = optionArray[i];
  3047. new PreziPlayer(optionSet.id, optionSet);
  3048. };
  3049. };
  3050. PreziPlayer.messageReceived = function(event){
  3051. var message, item, player;
  3052. try {
  3053. message = JSON.parse(event.data);
  3054. if (message.id && (player = PreziPlayer.players[message.id])) {
  3055. if (player.options.debug === true) {
  3056. if (console && console.log)
  3057. console.log('received', message);
  3058. }
  3059. if (message.type === "changes") {
  3060. player.changesHandler(message);
  3061. }
  3062. for (var i = 0; i < player.callbacks.length; i++) {
  3063. item = player.callbacks[i];
  3064. if (item && message.type === item.event) {
  3065. item.callback(message);
  3066. }
  3067. }
  3068. }
  3069. } catch (e) { }
  3070. };
  3071. function PreziPlayer(id, options) {
  3072. var params, paramString = "", _this = this;
  3073. if (PreziPlayer.players[id]){
  3074. PreziPlayer.players[id].destroy();
  3075. }
  3076. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  3077. var method_name = PreziPlayer.binded_methods[i];
  3078. _this[method_name] = __bind(_this[method_name], _this);
  3079. };
  3080. options = options || {};
  3081. this.options = options;
  3082. this.values = {'status': PreziPlayer.STATUS_LOADING};
  3083. this.values[PreziPlayer.CURRENT_STEP] = 0;
  3084. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  3085. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  3086. this.callbacks = [];
  3087. this.id = id;
  3088. this.embedTo = document.getElementById(id);
  3089. if (!this.embedTo) {
  3090. throw "The element id is not available.";
  3091. }
  3092. this.iframe = document.createElement('iframe');
  3093. params = [
  3094. { name: 'oid', value: options.preziId },
  3095. { name: 'explorable', value: options.explorable ? 1 : 0 },
  3096. { name: 'controls', value: options.controls ? 1 : 0 }
  3097. ];
  3098. for(var i=0; i<params.length; i++) {
  3099. var param = params[i];
  3100. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  3101. };
  3102. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  3103. this.iframe.frameBorder = 0;
  3104. this.iframe.scrolling = "no";
  3105. this.iframe.width = options.width || 640;
  3106. this.iframe.height = options.height || 480;
  3107. this.embedTo.innerHTML = '';
  3108. // JITSI: IN CASE SOMETHING GOES WRONG.
  3109. try {
  3110. this.embedTo.appendChild(this.iframe);
  3111. }
  3112. catch (err) {
  3113. console.log("CATCH ERROR");
  3114. }
  3115. // JITSI: Increase interval from 200 to 500, which fixes prezi
  3116. // crashes for us.
  3117. this.initPollInterval = setInterval(function(){
  3118. _this.sendMessage({'action': 'init'});
  3119. }, 500);
  3120. PreziPlayer.players[id] = this;
  3121. }
  3122. PreziPlayer.prototype.changesHandler = function(message) {
  3123. var key, value, j, item;
  3124. if (this.initPollInterval) {
  3125. clearInterval(this.initPollInterval);
  3126. this.initPollInterval = false;
  3127. }
  3128. for (key in message.data) {
  3129. if (message.data.hasOwnProperty(key)){
  3130. value = message.data[key];
  3131. this.values[key] = value;
  3132. for (j=0; j<this.callbacks.length; j++) {
  3133. item = this.callbacks[j];
  3134. if (item && item.event === key + "Change"){
  3135. item.callback({type: item.event, value: value});
  3136. }
  3137. }
  3138. }
  3139. }
  3140. };
  3141. PreziPlayer.prototype.destroy = function() {
  3142. if (this.initPollInterval) {
  3143. clearInterval(this.initPollInterval);
  3144. this.initPollInterval = false;
  3145. }
  3146. this.embedTo.innerHTML = '';
  3147. };
  3148. PreziPlayer.prototype.sendMessage = function(message) {
  3149. if (this.options.debug === true) {
  3150. if (console && console.log) console.log('sent', message);
  3151. }
  3152. message.version = PreziPlayer.API_VERSION;
  3153. message.id = this.id;
  3154. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  3155. };
  3156. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  3157. PreziPlayer.prototype.flyToNextStep = function() {
  3158. return this.sendMessage({
  3159. 'action': 'present',
  3160. 'data': ['moveToNextStep']
  3161. });
  3162. };
  3163. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  3164. PreziPlayer.prototype.flyToPreviousStep = function() {
  3165. return this.sendMessage({
  3166. 'action': 'present',
  3167. 'data': ['moveToPrevStep']
  3168. });
  3169. };
  3170. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  3171. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  3172. var obj = this;
  3173. // check animation_step
  3174. if (animation_step > 0 &&
  3175. obj.values.animationCountOnSteps &&
  3176. obj.values.animationCountOnSteps[step] <= animation_step) {
  3177. animation_step = obj.values.animationCountOnSteps[step];
  3178. }
  3179. // jump to animation steps by calling flyToNextStep()
  3180. function doAnimationSteps() {
  3181. if (obj.values.isMoving == true) {
  3182. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  3183. return;
  3184. }
  3185. while (animation_step-- > 0) {
  3186. obj.flyToNextStep(); // do the animation steps
  3187. }
  3188. }
  3189. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  3190. // jump to the step
  3191. return this.sendMessage({
  3192. 'action': 'present',
  3193. 'data': ['moveToStep', step]
  3194. });
  3195. };
  3196. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  3197. PreziPlayer.prototype.flyToObject = function(objectId) {
  3198. return this.sendMessage({
  3199. 'action': 'present',
  3200. 'data': ['moveToObject', objectId]
  3201. });
  3202. };
  3203. PreziPlayer.prototype.play = function(defaultDelay) {
  3204. return this.sendMessage({
  3205. 'action': 'present',
  3206. 'data': ['startAutoPlay', defaultDelay]
  3207. });
  3208. };
  3209. PreziPlayer.prototype.stop = function() {
  3210. return this.sendMessage({
  3211. 'action': 'present',
  3212. 'data': ['stopAutoPlay']
  3213. });
  3214. };
  3215. PreziPlayer.prototype.pause = function(defaultDelay) {
  3216. return this.sendMessage({
  3217. 'action': 'present',
  3218. 'data': ['pauseAutoPlay', defaultDelay]
  3219. });
  3220. };
  3221. PreziPlayer.prototype.getCurrentStep = function() {
  3222. return this.values.currentStep;
  3223. };
  3224. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  3225. return this.values.currentAnimationStep;
  3226. };
  3227. PreziPlayer.prototype.getCurrentObject = function() {
  3228. return this.values.currentObject;
  3229. };
  3230. PreziPlayer.prototype.getStatus = function() {
  3231. return this.values.status;
  3232. };
  3233. PreziPlayer.prototype.isPlaying = function() {
  3234. return this.values.isAutoPlaying;
  3235. };
  3236. PreziPlayer.prototype.getStepCount = function() {
  3237. return this.values.stepCount;
  3238. };
  3239. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  3240. return this.values.animationCountOnSteps;
  3241. };
  3242. PreziPlayer.prototype.getTitle = function() {
  3243. return this.values.title;
  3244. };
  3245. PreziPlayer.prototype.setDimensions = function(dims) {
  3246. for (var parameter in dims) {
  3247. this.iframe[parameter] = dims[parameter];
  3248. }
  3249. }
  3250. PreziPlayer.prototype.getDimensions = function() {
  3251. return {
  3252. width: parseInt(this.iframe.width, 10),
  3253. height: parseInt(this.iframe.height, 10)
  3254. }
  3255. }
  3256. PreziPlayer.prototype.on = function(event, callback) {
  3257. this.callbacks.push({
  3258. event: event,
  3259. callback: callback
  3260. });
  3261. };
  3262. PreziPlayer.prototype.off = function(event, callback) {
  3263. var j, item;
  3264. if (event === undefined) {
  3265. this.callbacks = [];
  3266. }
  3267. j = this.callbacks.length;
  3268. while (j--) {
  3269. item = this.callbacks[j];
  3270. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  3271. this.callbacks.splice(j, 1);
  3272. }
  3273. }
  3274. };
  3275. if (window.addEventListener) {
  3276. window.addEventListener('message', PreziPlayer.messageReceived, false);
  3277. } else {
  3278. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  3279. }
  3280. return PreziPlayer;
  3281. })();
  3282. })();
  3283. module.exports = PreziPlayer;
  3284. },{}],17:[function(require,module,exports){
  3285. var Chat = require("./chat/Chat");
  3286. var ContactList = require("./contactlist/ContactList");
  3287. var Settings = require("./../../settings/Settings");
  3288. var SettingsMenu = require("./settings/SettingsMenu");
  3289. var VideoLayout = require("../videolayout/VideoLayout");
  3290. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  3291. var UIUtil = require("../util/UIUtil");
  3292. /**
  3293. * Toggler for the chat, contact list, settings menu, etc..
  3294. */
  3295. var PanelToggler = (function(my) {
  3296. var currentlyOpen = null;
  3297. var buttons = {
  3298. '#chatspace': '#chatBottomButton',
  3299. '#contactlist': '#contactListButton',
  3300. '#settingsmenu': '#settingsButton'
  3301. };
  3302. /**
  3303. * Resizes the video area
  3304. * @param isClosing whether the side panel is going to be closed or is going to open / remain opened
  3305. * @param completeFunction a function to be called when the video space is resized
  3306. */
  3307. var resizeVideoArea = function(isClosing, completeFunction) {
  3308. var videospace = $('#videospace');
  3309. var panelSize = isClosing ? [0, 0] : PanelToggler.getPanelSize();
  3310. var videospaceWidth = window.innerWidth - panelSize[0];
  3311. var videospaceHeight = window.innerHeight;
  3312. var videoSize
  3313. = VideoLayout.getVideoSize(null, null, videospaceWidth, videospaceHeight);
  3314. var videoWidth = videoSize[0];
  3315. var videoHeight = videoSize[1];
  3316. var videoPosition = VideoLayout.getVideoPosition(videoWidth,
  3317. videoHeight,
  3318. videospaceWidth,
  3319. videospaceHeight);
  3320. var horizontalIndent = videoPosition[0];
  3321. var verticalIndent = videoPosition[1];
  3322. var thumbnailSize = VideoLayout.calculateThumbnailSize(videospaceWidth);
  3323. var thumbnailsWidth = thumbnailSize[0];
  3324. var thumbnailsHeight = thumbnailSize[1];
  3325. //for chat
  3326. videospace.animate({
  3327. right: panelSize[0],
  3328. width: videospaceWidth,
  3329. height: videospaceHeight
  3330. },
  3331. {
  3332. queue: false,
  3333. duration: 500,
  3334. complete: completeFunction
  3335. });
  3336. $('#remoteVideos').animate({
  3337. height: thumbnailsHeight
  3338. },
  3339. {
  3340. queue: false,
  3341. duration: 500
  3342. });
  3343. $('#remoteVideos>span').animate({
  3344. height: thumbnailsHeight,
  3345. width: thumbnailsWidth
  3346. },
  3347. {
  3348. queue: false,
  3349. duration: 500,
  3350. complete: function () {
  3351. $(document).trigger(
  3352. "remotevideo.resized",
  3353. [thumbnailsWidth,
  3354. thumbnailsHeight]);
  3355. }
  3356. });
  3357. $('#largeVideoContainer').animate({
  3358. width: videospaceWidth,
  3359. height: videospaceHeight
  3360. },
  3361. {
  3362. queue: false,
  3363. duration: 500
  3364. });
  3365. $('#largeVideo').animate({
  3366. width: videoWidth,
  3367. height: videoHeight,
  3368. top: verticalIndent,
  3369. bottom: verticalIndent,
  3370. left: horizontalIndent,
  3371. right: horizontalIndent
  3372. },
  3373. {
  3374. queue: false,
  3375. duration: 500
  3376. });
  3377. };
  3378. /**
  3379. * Toggles the windows in the side panel
  3380. * @param object the window that should be shown
  3381. * @param selector the selector for the element containing the panel
  3382. * @param onOpenComplete function to be called when the panel is opened
  3383. * @param onOpen function to be called if the window is going to be opened
  3384. * @param onClose function to be called if the window is going to be closed
  3385. */
  3386. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  3387. UIUtil.buttonClick(buttons[selector], "active");
  3388. if (object.isVisible()) {
  3389. $("#toast-container").animate({
  3390. right: '5px'
  3391. },
  3392. {
  3393. queue: false,
  3394. duration: 500
  3395. });
  3396. $(selector).hide("slide", {
  3397. direction: "right",
  3398. queue: false,
  3399. duration: 500
  3400. });
  3401. if(typeof onClose === "function") {
  3402. onClose();
  3403. }
  3404. currentlyOpen = null;
  3405. }
  3406. else {
  3407. // Undock the toolbar when the chat is shown and if we're in a
  3408. // video mode.
  3409. if (VideoLayout.isLargeVideoVisible()) {
  3410. ToolbarToggler.dockToolbar(false);
  3411. }
  3412. if(currentlyOpen) {
  3413. var current = $(currentlyOpen);
  3414. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  3415. current.css('z-index', 4);
  3416. setTimeout(function () {
  3417. current.css('display', 'none');
  3418. current.css('z-index', 5);
  3419. }, 500);
  3420. }
  3421. $("#toast-container").animate({
  3422. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  3423. },
  3424. {
  3425. queue: false,
  3426. duration: 500
  3427. });
  3428. $(selector).show("slide", {
  3429. direction: "right",
  3430. queue: false,
  3431. duration: 500,
  3432. complete: onOpenComplete
  3433. });
  3434. if(typeof onOpen === "function") {
  3435. onOpen();
  3436. }
  3437. currentlyOpen = selector;
  3438. }
  3439. };
  3440. /**
  3441. * Opens / closes the chat area.
  3442. */
  3443. my.toggleChat = function() {
  3444. var chatCompleteFunction = Chat.isVisible() ?
  3445. function() {} : function () {
  3446. Chat.scrollChatToBottom();
  3447. $('#chatspace').trigger('shown');
  3448. };
  3449. resizeVideoArea(Chat.isVisible(), chatCompleteFunction);
  3450. toggle(Chat,
  3451. '#chatspace',
  3452. function () {
  3453. // Request the focus in the nickname field or the chat input field.
  3454. if ($('#nickname').css('visibility') === 'visible') {
  3455. $('#nickinput').focus();
  3456. } else {
  3457. $('#usermsg').focus();
  3458. }
  3459. },
  3460. null,
  3461. Chat.resizeChat,
  3462. null);
  3463. };
  3464. /**
  3465. * Opens / closes the contact list area.
  3466. */
  3467. my.toggleContactList = function () {
  3468. var completeFunction = ContactList.isVisible() ?
  3469. function() {} : function () { $('#contactlist').trigger('shown');};
  3470. resizeVideoArea(ContactList.isVisible(), completeFunction);
  3471. toggle(ContactList,
  3472. '#contactlist',
  3473. null,
  3474. function() {
  3475. ContactList.setVisualNotification(false);
  3476. },
  3477. null);
  3478. };
  3479. /**
  3480. * Opens / closes the settings menu
  3481. */
  3482. my.toggleSettingsMenu = function() {
  3483. resizeVideoArea(SettingsMenu.isVisible(), function (){});
  3484. toggle(SettingsMenu,
  3485. '#settingsmenu',
  3486. null,
  3487. function() {
  3488. var settings = Settings.getSettings();
  3489. $('#setDisplayName').get(0).value = settings.displayName;
  3490. $('#setEmail').get(0).value = settings.email;
  3491. },
  3492. null);
  3493. };
  3494. /**
  3495. * Returns the size of the side panel.
  3496. */
  3497. my.getPanelSize = function () {
  3498. var availableHeight = window.innerHeight;
  3499. var availableWidth = window.innerWidth;
  3500. var panelWidth = 200;
  3501. if (availableWidth * 0.2 < 200) {
  3502. panelWidth = availableWidth * 0.2;
  3503. }
  3504. return [panelWidth, availableHeight];
  3505. };
  3506. my.isVisible = function() {
  3507. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  3508. };
  3509. return my;
  3510. }(PanelToggler || {}));
  3511. module.exports = PanelToggler;
  3512. },{"../toolbars/ToolbarToggler":26,"../util/UIUtil":30,"../videolayout/VideoLayout":32,"./../../settings/Settings":38,"./chat/Chat":18,"./contactlist/ContactList":22,"./settings/SettingsMenu":23}],18:[function(require,module,exports){
  3513. /* global $, Util, nickname:true */
  3514. var Replacement = require("./Replacement");
  3515. var CommandsProcessor = require("./Commands");
  3516. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  3517. var smileys = require("./smileys.json").smileys;
  3518. var NicknameHandler = require("../../util/NicknameHandler");
  3519. var UIUtil = require("../../util/UIUtil");
  3520. var UIEvents = require("../../../../service/UI/UIEvents");
  3521. var notificationInterval = false;
  3522. var unreadMessages = 0;
  3523. /**
  3524. * Shows/hides a visual notification, indicating that a message has arrived.
  3525. */
  3526. function setVisualNotification(show) {
  3527. var unreadMsgElement = document.getElementById('unreadMessages');
  3528. var unreadMsgBottomElement
  3529. = document.getElementById('bottomUnreadMessages');
  3530. var glower = $('#chatButton');
  3531. var bottomGlower = $('#chatBottomButton');
  3532. if (unreadMessages) {
  3533. unreadMsgElement.innerHTML = unreadMessages.toString();
  3534. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  3535. ToolbarToggler.dockToolbar(true);
  3536. var chatButtonElement
  3537. = document.getElementById('chatButton').parentNode;
  3538. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  3539. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  3540. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  3541. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  3542. unreadMsgElement.setAttribute(
  3543. 'style',
  3544. 'top:' + topIndent +
  3545. '; left:' + leftIndent + ';');
  3546. var chatBottomButtonElement
  3547. = document.getElementById('chatBottomButton').parentNode;
  3548. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  3549. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  3550. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  3551. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  3552. unreadMsgBottomElement.setAttribute(
  3553. 'style',
  3554. 'top:' + bottomTopIndent +
  3555. '; left:' + bottomLeftIndent + ';');
  3556. if (!glower.hasClass('icon-chat-simple')) {
  3557. glower.removeClass('icon-chat');
  3558. glower.addClass('icon-chat-simple');
  3559. }
  3560. }
  3561. else {
  3562. unreadMsgElement.innerHTML = '';
  3563. unreadMsgBottomElement.innerHTML = '';
  3564. glower.removeClass('icon-chat-simple');
  3565. glower.addClass('icon-chat');
  3566. }
  3567. if (show && !notificationInterval) {
  3568. notificationInterval = window.setInterval(function () {
  3569. glower.toggleClass('active');
  3570. bottomGlower.toggleClass('active glowing');
  3571. }, 800);
  3572. }
  3573. else if (!show && notificationInterval) {
  3574. window.clearInterval(notificationInterval);
  3575. notificationInterval = false;
  3576. glower.removeClass('active');
  3577. bottomGlower.removeClass('glowing');
  3578. bottomGlower.addClass('active');
  3579. }
  3580. }
  3581. /**
  3582. * Returns the current time in the format it is shown to the user
  3583. * @returns {string}
  3584. */
  3585. function getCurrentTime() {
  3586. var now = new Date();
  3587. var hour = now.getHours();
  3588. var minute = now.getMinutes();
  3589. var second = now.getSeconds();
  3590. if(hour.toString().length === 1) {
  3591. hour = '0'+hour;
  3592. }
  3593. if(minute.toString().length === 1) {
  3594. minute = '0'+minute;
  3595. }
  3596. if(second.toString().length === 1) {
  3597. second = '0'+second;
  3598. }
  3599. return hour+':'+minute+':'+second;
  3600. }
  3601. function toggleSmileys()
  3602. {
  3603. var smileys = $('#smileysContainer');
  3604. if(!smileys.is(':visible')) {
  3605. smileys.show("slide", { direction: "down", duration: 300});
  3606. } else {
  3607. smileys.hide("slide", { direction: "down", duration: 300});
  3608. }
  3609. $('#usermsg').focus();
  3610. }
  3611. function addClickFunction(smiley, number) {
  3612. smiley.onclick = function addSmileyToMessage() {
  3613. var usermsg = $('#usermsg');
  3614. var message = usermsg.val();
  3615. message += smileys['smiley' + number];
  3616. usermsg.val(message);
  3617. usermsg.get(0).setSelectionRange(message.length, message.length);
  3618. toggleSmileys();
  3619. usermsg.focus();
  3620. };
  3621. }
  3622. /**
  3623. * Adds the smileys container to the chat
  3624. */
  3625. function addSmileys() {
  3626. var smileysContainer = document.createElement('div');
  3627. smileysContainer.id = 'smileysContainer';
  3628. for(var i = 1; i <= 21; i++) {
  3629. var smileyContainer = document.createElement('div');
  3630. smileyContainer.id = 'smiley' + i;
  3631. smileyContainer.className = 'smileyContainer';
  3632. var smiley = document.createElement('img');
  3633. smiley.src = 'images/smileys/smiley' + i + '.svg';
  3634. smiley.className = 'smiley';
  3635. addClickFunction(smiley, i);
  3636. smileyContainer.appendChild(smiley);
  3637. smileysContainer.appendChild(smileyContainer);
  3638. }
  3639. $("#chatspace").append(smileysContainer);
  3640. }
  3641. /**
  3642. * Resizes the chat conversation.
  3643. */
  3644. function resizeChatConversation() {
  3645. var msgareaHeight = $('#usermsg').outerHeight();
  3646. var chatspace = $('#chatspace');
  3647. var width = chatspace.width();
  3648. var chat = $('#chatconversation');
  3649. var smileys = $('#smileysarea');
  3650. smileys.height(msgareaHeight);
  3651. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  3652. $('#smileysContainer').css('bottom', msgareaHeight);
  3653. chat.width(width - 10);
  3654. chat.height(window.innerHeight - 15 - msgareaHeight);
  3655. }
  3656. /**
  3657. * Chat related user interface.
  3658. */
  3659. var Chat = (function (my) {
  3660. /**
  3661. * Initializes chat related interface.
  3662. */
  3663. my.init = function () {
  3664. if(NicknameHandler.getNickname())
  3665. Chat.setChatConversationMode(true);
  3666. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  3667. function (nickname) {
  3668. Chat.setChatConversationMode(true);
  3669. });
  3670. $('#nickinput').keydown(function (event) {
  3671. if (event.keyCode === 13) {
  3672. event.preventDefault();
  3673. var val = UIUtil.escapeHtml(this.value);
  3674. this.value = '';
  3675. if (!NicknameHandler.getNickname()) {
  3676. NicknameHandler.setNickname(val);
  3677. return;
  3678. }
  3679. }
  3680. });
  3681. $('#usermsg').keydown(function (event) {
  3682. if (event.keyCode === 13) {
  3683. event.preventDefault();
  3684. var value = this.value;
  3685. $('#usermsg').val('').trigger('autosize.resize');
  3686. this.focus();
  3687. var command = new CommandsProcessor(value);
  3688. if(command.isCommand())
  3689. {
  3690. command.processCommand();
  3691. }
  3692. else
  3693. {
  3694. var message = UIUtil.escapeHtml(value);
  3695. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  3696. }
  3697. }
  3698. });
  3699. var onTextAreaResize = function () {
  3700. resizeChatConversation();
  3701. Chat.scrollChatToBottom();
  3702. };
  3703. $('#usermsg').autosize({callback: onTextAreaResize});
  3704. $("#chatspace").bind("shown",
  3705. function () {
  3706. unreadMessages = 0;
  3707. setVisualNotification(false);
  3708. });
  3709. addSmileys();
  3710. };
  3711. /**
  3712. * Appends the given message to the chat conversation.
  3713. */
  3714. my.updateChatConversation = function (from, displayName, message) {
  3715. var divClassName = '';
  3716. if (APP.xmpp.myJid() === from) {
  3717. divClassName = "localuser";
  3718. }
  3719. else {
  3720. divClassName = "remoteuser";
  3721. if (!Chat.isVisible()) {
  3722. unreadMessages++;
  3723. UIUtil.playSoundNotification('chatNotification');
  3724. setVisualNotification(true);
  3725. }
  3726. }
  3727. // replace links and smileys
  3728. // Strophe already escapes special symbols on sending,
  3729. // so we escape here only tags to avoid double &amp;
  3730. var escMessage = message.replace(/</g, '&lt;').
  3731. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  3732. var escDisplayName = UIUtil.escapeHtml(displayName);
  3733. message = Replacement.processReplacements(escMessage);
  3734. var messageContainer =
  3735. '<div class="chatmessage">'+
  3736. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  3737. '<div class="username ' + divClassName +'">' + escDisplayName +
  3738. '</div>' + '<div class="timestamp">' + getCurrentTime() +
  3739. '</div>' + '<div class="usermessage">' + message + '</div>' +
  3740. '</div>';
  3741. $('#chatconversation').append(messageContainer);
  3742. $('#chatconversation').animate(
  3743. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3744. };
  3745. /**
  3746. * Appends error message to the conversation
  3747. * @param errorMessage the received error message.
  3748. * @param originalText the original message.
  3749. */
  3750. my.chatAddError = function(errorMessage, originalText)
  3751. {
  3752. errorMessage = UIUtil.escapeHtml(errorMessage);
  3753. originalText = UIUtil.escapeHtml(originalText);
  3754. $('#chatconversation').append(
  3755. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  3756. (originalText? (' \"'+ originalText + '\"') : "") +
  3757. ' was not sent.' +
  3758. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  3759. $('#chatconversation').animate(
  3760. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3761. };
  3762. /**
  3763. * Sets the subject to the UI
  3764. * @param subject the subject
  3765. */
  3766. my.chatSetSubject = function(subject)
  3767. {
  3768. if(subject)
  3769. subject = subject.trim();
  3770. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  3771. if(subject === "")
  3772. {
  3773. $("#subject").css({display: "none"});
  3774. }
  3775. else
  3776. {
  3777. $("#subject").css({display: "block"});
  3778. }
  3779. };
  3780. /**
  3781. * Sets the chat conversation mode.
  3782. */
  3783. my.setChatConversationMode = function (isConversationMode) {
  3784. if (isConversationMode) {
  3785. $('#nickname').css({visibility: 'hidden'});
  3786. $('#chatconversation').css({visibility: 'visible'});
  3787. $('#usermsg').css({visibility: 'visible'});
  3788. $('#smileysarea').css({visibility: 'visible'});
  3789. $('#usermsg').focus();
  3790. }
  3791. };
  3792. /**
  3793. * Resizes the chat area.
  3794. */
  3795. my.resizeChat = function () {
  3796. var chatSize = require("../SidePanelToggler").getPanelSize();
  3797. $('#chatspace').width(chatSize[0]);
  3798. $('#chatspace').height(chatSize[1]);
  3799. resizeChatConversation();
  3800. };
  3801. /**
  3802. * Indicates if the chat is currently visible.
  3803. */
  3804. my.isVisible = function () {
  3805. return $('#chatspace').is(":visible");
  3806. };
  3807. /**
  3808. * Shows and hides the window with the smileys
  3809. */
  3810. my.toggleSmileys = toggleSmileys;
  3811. /**
  3812. * Scrolls chat to the bottom.
  3813. */
  3814. my.scrollChatToBottom = function() {
  3815. setTimeout(function () {
  3816. $('#chatconversation').scrollTop(
  3817. $('#chatconversation')[0].scrollHeight);
  3818. }, 5);
  3819. };
  3820. return my;
  3821. }(Chat || {}));
  3822. module.exports = Chat;
  3823. },{"../../../../service/UI/UIEvents":84,"../../toolbars/ToolbarToggler":26,"../../util/NicknameHandler":29,"../../util/UIUtil":30,"../SidePanelToggler":17,"./Commands":19,"./Replacement":20,"./smileys.json":21}],19:[function(require,module,exports){
  3824. var UIUtil = require("../../util/UIUtil");
  3825. /**
  3826. * List with supported commands. The keys are the names of the commands and
  3827. * the value is the function that processes the message.
  3828. * @type {{String: function}}
  3829. */
  3830. var commands = {
  3831. "topic" : processTopic
  3832. };
  3833. /**
  3834. * Extracts the command from the message.
  3835. * @param message the received message
  3836. * @returns {string} the command
  3837. */
  3838. function getCommand(message)
  3839. {
  3840. if(message)
  3841. {
  3842. for(var command in commands)
  3843. {
  3844. if(message.indexOf("/" + command) == 0)
  3845. return command;
  3846. }
  3847. }
  3848. return "";
  3849. };
  3850. /**
  3851. * Processes the data for topic command.
  3852. * @param commandArguments the arguments of the topic command.
  3853. */
  3854. function processTopic(commandArguments)
  3855. {
  3856. var topic = UIUtil.escapeHtml(commandArguments);
  3857. APP.xmpp.setSubject(topic);
  3858. }
  3859. /**
  3860. * Constructs new CommandProccessor instance from a message that
  3861. * handles commands received via chat messages.
  3862. * @param message the message
  3863. * @constructor
  3864. */
  3865. function CommandsProcessor(message)
  3866. {
  3867. var command = getCommand(message);
  3868. /**
  3869. * Returns the name of the command.
  3870. * @returns {String} the command
  3871. */
  3872. this.getCommand = function()
  3873. {
  3874. return command;
  3875. };
  3876. var messageArgument = message.substr(command.length + 2);
  3877. /**
  3878. * Returns the arguments of the command.
  3879. * @returns {string}
  3880. */
  3881. this.getArgument = function()
  3882. {
  3883. return messageArgument;
  3884. };
  3885. }
  3886. /**
  3887. * Checks whether this instance is valid command or not.
  3888. * @returns {boolean}
  3889. */
  3890. CommandsProcessor.prototype.isCommand = function()
  3891. {
  3892. if(this.getCommand())
  3893. return true;
  3894. return false;
  3895. };
  3896. /**
  3897. * Processes the command.
  3898. */
  3899. CommandsProcessor.prototype.processCommand = function()
  3900. {
  3901. if(!this.isCommand())
  3902. return;
  3903. commands[this.getCommand()](this.getArgument());
  3904. };
  3905. module.exports = CommandsProcessor;
  3906. },{"../../util/UIUtil":30}],20:[function(require,module,exports){
  3907. var Smileys = require("./smileys.json");
  3908. /**
  3909. * Processes links and smileys in "body"
  3910. */
  3911. function processReplacements(body)
  3912. {
  3913. //make links clickable
  3914. body = linkify(body);
  3915. //add smileys
  3916. body = smilify(body);
  3917. return body;
  3918. }
  3919. /**
  3920. * Finds and replaces all links in the links in "body"
  3921. * with their <a href=""></a>
  3922. */
  3923. function linkify(inputText)
  3924. {
  3925. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  3926. //URLs starting with http://, https://, or ftp://
  3927. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  3928. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  3929. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  3930. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  3931. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  3932. //Change email addresses to mailto:: links.
  3933. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  3934. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  3935. return replacedText;
  3936. }
  3937. /**
  3938. * Replaces common smiley strings with images
  3939. */
  3940. function smilify(body)
  3941. {
  3942. if(!body) {
  3943. return body;
  3944. }
  3945. var regexs = Smileys["regexs"];
  3946. for(var smiley in regexs) {
  3947. if(regexs.hasOwnProperty(smiley)) {
  3948. body = body.replace(regexs[smiley],
  3949. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  3950. }
  3951. }
  3952. return body;
  3953. }
  3954. module.exports = {
  3955. processReplacements: processReplacements,
  3956. linkify: linkify
  3957. };
  3958. },{"./smileys.json":21}],21:[function(require,module,exports){
  3959. module.exports={
  3960. "smileys": {
  3961. "smiley1": ":)",
  3962. "smiley2": ":(",
  3963. "smiley3": ":D",
  3964. "smiley4": "(y)",
  3965. "smiley5": " :P",
  3966. "smiley6": "(wave)",
  3967. "smiley7": "(blush)",
  3968. "smiley8": "(chuckle)",
  3969. "smiley9": "(shocked)",
  3970. "smiley10": ":*",
  3971. "smiley11": "(n)",
  3972. "smiley12": "(search)",
  3973. "smiley13": " <3",
  3974. "smiley14": "(oops)",
  3975. "smiley15": "(angry)",
  3976. "smiley16": "(angel)",
  3977. "smiley17": "(sick)",
  3978. "smiley18": ";(",
  3979. "smiley19": "(bomb)",
  3980. "smiley20": "(clap)",
  3981. "smiley21": " ;)"
  3982. },
  3983. "regexs": {
  3984. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  3985. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  3986. "smiley1": /(:-\)|:\))/gi,
  3987. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  3988. "smiley5": /(:-P|:P|:-p|:p)/gi,
  3989. "smiley6": /(\(wave\))/gi,
  3990. "smiley7": /(\(blush\))/gi,
  3991. "smiley8": /(\(chuckle\))/gi,
  3992. "smiley9": /(:-0|\(shocked\))/gi,
  3993. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  3994. "smiley11": /(\(n\))/gi,
  3995. "smiley12": /(\(search\))/g,
  3996. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  3997. "smiley14": /(\(oops\))/gi,
  3998. "smiley15": /(\(angry\))/gi,
  3999. "smiley16": /(\(angel\))/gi,
  4000. "smiley17": /(\(sick\))/gi,
  4001. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  4002. "smiley19": /(\(bomb\))/gi,
  4003. "smiley20": /(\(clap\))/gi,
  4004. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  4005. }
  4006. }
  4007. },{}],22:[function(require,module,exports){
  4008. var numberOfContacts = 0;
  4009. var notificationInterval;
  4010. /**
  4011. * Updates the number of participants in the contact list button and sets
  4012. * the glow
  4013. * @param delta indicates whether a new user has joined (1) or someone has
  4014. * left(-1)
  4015. */
  4016. function updateNumberOfParticipants(delta) {
  4017. //when the user is alone we don't show the number of participants
  4018. if(numberOfContacts === 0) {
  4019. $("#numberOfParticipants").text('');
  4020. numberOfContacts += delta;
  4021. } else if(numberOfContacts !== 0 && !ContactList.isVisible()) {
  4022. ContactList.setVisualNotification(true);
  4023. numberOfContacts += delta;
  4024. $("#numberOfParticipants").text(numberOfContacts);
  4025. }
  4026. }
  4027. /**
  4028. * Creates the avatar element.
  4029. *
  4030. * @return the newly created avatar element
  4031. */
  4032. function createAvatar(id) {
  4033. var avatar = document.createElement('img');
  4034. avatar.className = "icon-avatar avatar";
  4035. avatar.src = "https://www.gravatar.com/avatar/" + id + "?d=wavatar&size=30";
  4036. return avatar;
  4037. }
  4038. /**
  4039. * Creates the display name paragraph.
  4040. *
  4041. * @param displayName the display name to set
  4042. */
  4043. function createDisplayNameParagraph(displayName) {
  4044. var p = document.createElement('p');
  4045. p.innerText = displayName;
  4046. return p;
  4047. }
  4048. function stopGlowing(glower) {
  4049. window.clearInterval(notificationInterval);
  4050. notificationInterval = false;
  4051. glower.removeClass('glowing');
  4052. if (!ContactList.isVisible()) {
  4053. glower.removeClass('active');
  4054. }
  4055. }
  4056. /**
  4057. * Contact list.
  4058. */
  4059. var ContactList = {
  4060. /**
  4061. * Indicates if the chat is currently visible.
  4062. *
  4063. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  4064. * otherwise
  4065. */
  4066. isVisible: function () {
  4067. return $('#contactlist').is(":visible");
  4068. },
  4069. /**
  4070. * Adds a contact for the given peerJid if such doesn't yet exist.
  4071. *
  4072. * @param peerJid the peerJid corresponding to the contact
  4073. * @param id the user's email or userId used to get the user's avatar
  4074. */
  4075. ensureAddContact: function (peerJid, id) {
  4076. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4077. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4078. if (!contact || contact.length <= 0)
  4079. ContactList.addContact(peerJid, id);
  4080. },
  4081. /**
  4082. * Adds a contact for the given peer jid.
  4083. *
  4084. * @param peerJid the jid of the contact to add
  4085. * @param id the email or userId of the user
  4086. */
  4087. addContact: function (peerJid, id) {
  4088. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4089. var contactlist = $('#contactlist>ul');
  4090. var newContact = document.createElement('li');
  4091. newContact.id = resourceJid;
  4092. newContact.className = "clickable";
  4093. newContact.onclick = function (event) {
  4094. if (event.currentTarget.className === "clickable") {
  4095. $(ContactList).trigger('contactclicked', [peerJid]);
  4096. }
  4097. };
  4098. newContact.appendChild(createAvatar(id));
  4099. newContact.appendChild(createDisplayNameParagraph("Participant"));
  4100. var clElement = contactlist.get(0);
  4101. if (resourceJid === APP.xmpp.myResource()
  4102. && $('#contactlist>ul .title')[0].nextSibling.nextSibling) {
  4103. clElement.insertBefore(newContact,
  4104. $('#contactlist>ul .title')[0].nextSibling.nextSibling);
  4105. }
  4106. else {
  4107. clElement.appendChild(newContact);
  4108. }
  4109. updateNumberOfParticipants(1);
  4110. },
  4111. /**
  4112. * Removes a contact for the given peer jid.
  4113. *
  4114. * @param peerJid the peerJid corresponding to the contact to remove
  4115. */
  4116. removeContact: function (peerJid) {
  4117. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4118. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4119. if (contact && contact.length > 0) {
  4120. var contactlist = $('#contactlist>ul');
  4121. contactlist.get(0).removeChild(contact.get(0));
  4122. updateNumberOfParticipants(-1);
  4123. }
  4124. },
  4125. setVisualNotification: function (show, stopGlowingIn) {
  4126. var glower = $('#contactListButton');
  4127. if (show && !notificationInterval) {
  4128. notificationInterval = window.setInterval(function () {
  4129. glower.toggleClass('active glowing');
  4130. }, 800);
  4131. }
  4132. else if (!show && notificationInterval) {
  4133. stopGlowing(glower);
  4134. }
  4135. if (stopGlowingIn) {
  4136. setTimeout(function () {
  4137. stopGlowing(glower);
  4138. }, stopGlowingIn);
  4139. }
  4140. },
  4141. setClickable: function (resourceJid, isClickable) {
  4142. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4143. if (isClickable) {
  4144. contact.addClass('clickable');
  4145. } else {
  4146. contact.removeClass('clickable');
  4147. }
  4148. },
  4149. onDisplayNameChange: function (peerJid, displayName) {
  4150. if (peerJid === 'localVideoContainer')
  4151. peerJid = APP.xmpp.myJid();
  4152. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4153. var contactName = $('#contactlist #' + resourceJid + '>p');
  4154. if (contactName && displayName && displayName.length > 0)
  4155. contactName.html(displayName);
  4156. }
  4157. };
  4158. module.exports = ContactList;
  4159. },{}],23:[function(require,module,exports){
  4160. var Avatar = require("../../avatar/Avatar");
  4161. var Settings = require("./../../../settings/Settings");
  4162. var UIUtil = require("../../util/UIUtil");
  4163. var languages = require("../../../../service/translation/languages");
  4164. function generateLanguagesSelectBox()
  4165. {
  4166. var currentLang = APP.translation.getCurrentLanguage();
  4167. var html = "<select id=\"languages_selectbox\">";
  4168. var langArray = languages.getLanguages();
  4169. for(var i = 0; i < langArray.length; i++)
  4170. {
  4171. var lang = langArray[i];
  4172. html += "<option ";
  4173. if(lang === currentLang)
  4174. html += "selected ";
  4175. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  4176. html += "</option>";
  4177. }
  4178. return html + "</select>";
  4179. }
  4180. var SettingsMenu = {
  4181. init: function () {
  4182. $("#updateSettings").before(generateLanguagesSelectBox());
  4183. $('#settingsmenu>input').keyup(function(event){
  4184. if(event.keyCode === 13) {//enter
  4185. SettingsMenu.update();
  4186. }
  4187. });
  4188. $("#updateSettings").click(function () {
  4189. SettingsMenu.update();
  4190. });
  4191. },
  4192. update: function() {
  4193. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  4194. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  4195. if(newDisplayName) {
  4196. var displayName = Settings.setDisplayName(newDisplayName);
  4197. APP.xmpp.addToPresence("displayName", displayName, true);
  4198. }
  4199. var language = $("#languages_selectbox").val();
  4200. APP.translation.setLanguage(language);
  4201. Settings.setLanguage(language);
  4202. APP.xmpp.addToPresence("email", newEmail);
  4203. var email = Settings.setEmail(newEmail);
  4204. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  4205. },
  4206. isVisible: function() {
  4207. return $('#settingsmenu').is(':visible');
  4208. },
  4209. setDisplayName: function(newDisplayName) {
  4210. var displayName = Settings.setDisplayName(newDisplayName);
  4211. $('#setDisplayName').get(0).value = displayName;
  4212. },
  4213. onDisplayNameChange: function(peerJid, newDisplayName) {
  4214. if(peerJid === 'localVideoContainer' ||
  4215. peerJid === APP.xmpp.myJid()) {
  4216. this.setDisplayName(newDisplayName);
  4217. }
  4218. }
  4219. };
  4220. module.exports = SettingsMenu;
  4221. },{"../../../../service/translation/languages":88,"../../avatar/Avatar":13,"../../util/UIUtil":30,"./../../../settings/Settings":38}],24:[function(require,module,exports){
  4222. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4223. var buttonHandlers = {
  4224. "bottom_toolbar_contact_list": function () {
  4225. BottomToolbar.toggleContactList();
  4226. },
  4227. "bottom_toolbar_film_strip": function () {
  4228. BottomToolbar.toggleFilmStrip();
  4229. },
  4230. "bottom_toolbar_chat": function () {
  4231. BottomToolbar.toggleChat();
  4232. }
  4233. };
  4234. var BottomToolbar = (function (my) {
  4235. my.init = function () {
  4236. for(var k in buttonHandlers)
  4237. $("#" + k).click(buttonHandlers[k]);
  4238. };
  4239. my.toggleChat = function() {
  4240. PanelToggler.toggleChat();
  4241. };
  4242. my.toggleContactList = function() {
  4243. PanelToggler.toggleContactList();
  4244. };
  4245. my.toggleFilmStrip = function() {
  4246. var filmstrip = $("#remoteVideos");
  4247. filmstrip.toggleClass("hidden");
  4248. };
  4249. $(document).bind("remotevideo.resized", function (event, width, height) {
  4250. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  4251. $('#bottomToolbar').css({bottom: bottom + 'px'});
  4252. });
  4253. return my;
  4254. }(BottomToolbar || {}));
  4255. module.exports = BottomToolbar;
  4256. },{"../side_pannels/SidePanelToggler":17}],25:[function(require,module,exports){
  4257. /* global APP,$, buttonClick, config, lockRoom,
  4258. setSharedKey, Util */
  4259. var messageHandler = require("../util/MessageHandler");
  4260. var BottomToolbar = require("./BottomToolbar");
  4261. var Prezi = require("../prezi/Prezi");
  4262. var Etherpad = require("../etherpad/Etherpad");
  4263. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4264. var Authentication = require("../authentication/Authentication");
  4265. var UIUtil = require("../util/UIUtil");
  4266. var AuthenticationEvents
  4267. = require("../../../service/authentication/AuthenticationEvents");
  4268. var roomUrl = null;
  4269. var sharedKey = '';
  4270. var UI = null;
  4271. var buttonHandlers =
  4272. {
  4273. "toolbar_button_mute": function () {
  4274. return APP.UI.toggleAudio();
  4275. },
  4276. "toolbar_button_camera": function () {
  4277. return APP.UI.toggleVideo();
  4278. },
  4279. /*"toolbar_button_authentication": function () {
  4280. return Toolbar.authenticateClicked();
  4281. },*/
  4282. "toolbar_button_record": function () {
  4283. return toggleRecording();
  4284. },
  4285. "toolbar_button_security": function () {
  4286. return Toolbar.openLockDialog();
  4287. },
  4288. "toolbar_button_link": function () {
  4289. return Toolbar.openLinkDialog();
  4290. },
  4291. "toolbar_button_chat": function () {
  4292. return BottomToolbar.toggleChat();
  4293. },
  4294. "toolbar_button_prezi": function () {
  4295. return Prezi.openPreziDialog();
  4296. },
  4297. "toolbar_button_etherpad": function () {
  4298. return Etherpad.toggleEtherpad(0);
  4299. },
  4300. "toolbar_button_desktopsharing": function () {
  4301. return APP.desktopsharing.toggleScreenSharing();
  4302. },
  4303. "toolbar_button_fullScreen": function()
  4304. {
  4305. UIUtil.buttonClick("#fullScreen", "icon-full-screen icon-exit-full-screen");
  4306. return Toolbar.toggleFullScreen();
  4307. },
  4308. "toolbar_button_sip": function () {
  4309. return callSipButtonClicked();
  4310. },
  4311. "toolbar_button_settings": function () {
  4312. PanelToggler.toggleSettingsMenu();
  4313. },
  4314. "toolbar_button_hangup": function () {
  4315. return hangup();
  4316. },
  4317. "toolbar_button_login": function () {
  4318. Toolbar.authenticateClicked();
  4319. },
  4320. "toolbar_button_logout": function () {
  4321. // Ask for confirmation
  4322. messageHandler.openTwoButtonDialog(
  4323. "dialog.logoutTitle", "Logout",
  4324. "dialog.logoutQuestion",
  4325. "Are you sure you want to logout and stop the conference ?",
  4326. false, "Yes",
  4327. function (evt, yes) {
  4328. if (yes) {
  4329. APP.xmpp.logout(function (url) {
  4330. if (url) {
  4331. window.location.href = url;
  4332. } else {
  4333. hangup();
  4334. }
  4335. });
  4336. }
  4337. });
  4338. }
  4339. };
  4340. function hangup() {
  4341. APP.xmpp.disposeConference();
  4342. if(config.enableWelcomePage)
  4343. {
  4344. setTimeout(function()
  4345. {
  4346. window.localStorage.welcomePageDisabled = false;
  4347. window.location.pathname = "/";
  4348. }, 10000);
  4349. }
  4350. var title = APP.translation.generateTranslatonHTML(
  4351. "dialog.sessTerminated", "Session Terminated");
  4352. var msg = APP.translation.generateTranslatonHTML(
  4353. "dialog.hungUp","You hung up the call");
  4354. var button = APP.translation.generateTranslatonHTML(
  4355. "dialog.joinAgain", "Join again");
  4356. var buttons = {};
  4357. buttons.joinAgain = {title: button, value: true};
  4358. UI.messageHandler.openDialog(
  4359. title,
  4360. msg,
  4361. true,
  4362. buttons,
  4363. function(event, value, message, formVals)
  4364. {
  4365. window.location.reload();
  4366. return false;
  4367. }
  4368. );
  4369. }
  4370. /**
  4371. * Starts or stops the recording for the conference.
  4372. */
  4373. function toggleRecording() {
  4374. APP.xmpp.toggleRecording(function (callback) {
  4375. var msg = APP.translation.generateTranslatonHTML(
  4376. "dialog.recordingToken", "Enter recording token");
  4377. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  4378. '<h2>' + msg + '</h2>' +
  4379. '<input id="recordingToken" type="text" ' +
  4380. 'placeholder="token" autofocus>',
  4381. false,
  4382. "dialog.Save",
  4383. function (e, v, m, f) {
  4384. if (v) {
  4385. var token = document.getElementById('recordingToken');
  4386. if (token.value) {
  4387. callback(UIUtil.escapeHtml(token.value));
  4388. }
  4389. }
  4390. },
  4391. function (event) {
  4392. document.getElementById('recordingToken').focus();
  4393. },
  4394. function () {
  4395. }
  4396. );
  4397. }, Toolbar.setRecordingButtonState, Toolbar.setRecordingButtonState);
  4398. }
  4399. /**
  4400. * Locks / unlocks the room.
  4401. */
  4402. function lockRoom(lock) {
  4403. var currentSharedKey = '';
  4404. if (lock)
  4405. currentSharedKey = sharedKey;
  4406. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  4407. // password is required
  4408. if (sharedKey)
  4409. {
  4410. console.log('set room password');
  4411. Toolbar.lockLockButton();
  4412. }
  4413. else
  4414. {
  4415. console.log('removed room password');
  4416. Toolbar.unlockLockButton();
  4417. }
  4418. }, function (err) {
  4419. console.warn('setting password failed', err);
  4420. messageHandler.showError("dialog.lockTitle", 'Lock failed',
  4421. "dialog.lockMessage",
  4422. 'Failed to lock conference.',
  4423. err);
  4424. Toolbar.setSharedKey('');
  4425. }, function () {
  4426. console.warn('room passwords not supported');
  4427. messageHandler.showError("dialog.warning", 'Warning',
  4428. "dialog.passwordNotSupported",
  4429. 'Room passwords are currently not supported.');
  4430. Toolbar.setSharedKey('');
  4431. });
  4432. };
  4433. /**
  4434. * Invite participants to conference.
  4435. */
  4436. function inviteParticipants() {
  4437. if (roomUrl === null)
  4438. return;
  4439. var sharedKeyText = "";
  4440. if (sharedKey && sharedKey.length > 0) {
  4441. sharedKeyText =
  4442. "This conference is password protected. Please use the " +
  4443. "following pin when joining:%0D%0A%0D%0A" +
  4444. sharedKey + "%0D%0A%0D%0A";
  4445. }
  4446. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  4447. var subject = "Invitation to a " + interfaceConfig.APP_NAME + " (" + conferenceName + ")";
  4448. var body = "Hey there, I%27d like to invite you to a " + interfaceConfig.APP_NAME +
  4449. " conference I%27ve just set up.%0D%0A%0D%0A" +
  4450. "Please click on the following link in order" +
  4451. " to join the conference.%0D%0A%0D%0A" +
  4452. roomUrl +
  4453. "%0D%0A%0D%0A" +
  4454. sharedKeyText +
  4455. "Note that " + interfaceConfig.APP_NAME + " is currently" +
  4456. " only supported by Chromium," +
  4457. " Google Chrome and Opera, so you need" +
  4458. " to be using one of these browsers.%0D%0A%0D%0A" +
  4459. "Talk to you in a sec!";
  4460. if (window.localStorage.displayname) {
  4461. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  4462. }
  4463. if (interfaceConfig.INVITATION_POWERED_BY) {
  4464. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  4465. }
  4466. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  4467. }
  4468. function callSipButtonClicked()
  4469. {
  4470. var defaultNumber
  4471. = config.defaultSipNumber ? config.defaultSipNumber : '';
  4472. var sipMsg = APP.translation.generateTranslatonHTML(
  4473. "dialog.sipMsg", "Enter SIP number");
  4474. messageHandler.openTwoButtonDialog(null, null, null,
  4475. '<h2>' + sipMsg + '</h2>' +
  4476. '<input id="sipNumber" type="text"' +
  4477. ' value="' + defaultNumber + '" autofocus>',
  4478. false,
  4479. "dialog.Dial",
  4480. function (e, v, m, f) {
  4481. if (v) {
  4482. var numberInput = document.getElementById('sipNumber');
  4483. if (numberInput.value) {
  4484. APP.xmpp.dial(numberInput.value, 'fromnumber',
  4485. UI.getRoomName(), sharedKey);
  4486. }
  4487. }
  4488. },
  4489. function (event) {
  4490. document.getElementById('sipNumber').focus();
  4491. }
  4492. );
  4493. }
  4494. var Toolbar = (function (my) {
  4495. my.init = function (ui) {
  4496. for(var k in buttonHandlers)
  4497. $("#" + k).click(buttonHandlers[k]);
  4498. UI = ui;
  4499. // Update login info
  4500. APP.xmpp.addListener(
  4501. AuthenticationEvents.IDENTITY_UPDATED,
  4502. function (authenticationEnabled, userIdentity) {
  4503. var loggedIn = false;
  4504. if (userIdentity) {
  4505. loggedIn = true;
  4506. }
  4507. //FIXME: XMPP authentication need improvements for "live" login
  4508. if (!APP.xmpp.isExternalAuthEnabled() && !loggedIn)
  4509. {
  4510. authenticationEnabled = false;
  4511. }
  4512. Toolbar.showAuthenticateButton(authenticationEnabled);
  4513. if (authenticationEnabled) {
  4514. Toolbar.setAuthenticatedIdentity(userIdentity);
  4515. Toolbar.showLoginButton(!loggedIn);
  4516. Toolbar.showLogoutButton(loggedIn);
  4517. }
  4518. }
  4519. );
  4520. },
  4521. /**
  4522. * Sets shared key
  4523. * @param sKey the shared key
  4524. */
  4525. my.setSharedKey = function (sKey) {
  4526. sharedKey = sKey;
  4527. };
  4528. my.authenticateClicked = function () {
  4529. Authentication.focusAuthenticationWindow();
  4530. // Get authentication URL
  4531. if (!APP.xmpp.getMUCJoined()) {
  4532. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  4533. // If conference has not been started yet - redirect to login page
  4534. window.location.href = url;
  4535. });
  4536. } else {
  4537. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  4538. // Otherwise - open popup with authentication URL
  4539. var authenticationWindow = Authentication.createAuthenticationWindow(
  4540. function () {
  4541. // On popup closed - retry room allocation
  4542. APP.xmpp.allocateConferenceFocus(
  4543. APP.UI.getRoomName(),
  4544. function () { console.info("AUTH DONE"); }
  4545. );
  4546. }, url);
  4547. if (!authenticationWindow) {
  4548. messageHandler.openMessageDialog(
  4549. null, null, "dialog.popupError",
  4550. "Your browser is blocking popup windows from this site." +
  4551. " Please enable popups in your browser security settings" +
  4552. " and try again.");
  4553. }
  4554. });
  4555. }
  4556. };
  4557. /**
  4558. * Updates the room invite url.
  4559. */
  4560. my.updateRoomUrl = function (newRoomUrl) {
  4561. roomUrl = newRoomUrl;
  4562. // If the invite dialog has been already opened we update the information.
  4563. var inviteLink = document.getElementById('inviteLinkRef');
  4564. if (inviteLink) {
  4565. inviteLink.value = roomUrl;
  4566. inviteLink.select();
  4567. document.getElementById('jqi_state0_buttonInvite').disabled = false;
  4568. }
  4569. };
  4570. /**
  4571. * Disables and enables some of the buttons.
  4572. */
  4573. my.setupButtonsFromConfig = function () {
  4574. if (config.disablePrezi)
  4575. {
  4576. $("#prezi_button").css({display: "none"});
  4577. }
  4578. };
  4579. /**
  4580. * Opens the lock room dialog.
  4581. */
  4582. my.openLockDialog = function () {
  4583. // Only the focus is able to set a shared key.
  4584. if (!APP.xmpp.isModerator()) {
  4585. if (sharedKey) {
  4586. messageHandler.openMessageDialog(null, null,
  4587. "dialog.passwordError",
  4588. "This conversation is currently protected by" +
  4589. " a password. Only the owner of the conference" +
  4590. " could set a password.",
  4591. false,
  4592. "Password");
  4593. } else {
  4594. messageHandler.openMessageDialog(null, null, "dialog.passwordError2",
  4595. "This conversation isn't currently protected by" +
  4596. " a password. Only the owner of the conference" +
  4597. " could set a password.",
  4598. false,
  4599. "Password");
  4600. }
  4601. } else {
  4602. if (sharedKey) {
  4603. messageHandler.openTwoButtonDialog(null, null,
  4604. "dialog.passwordCheck",
  4605. "Are you sure you would like to remove your password?",
  4606. false,
  4607. "dialog.Remove",
  4608. function (e, v) {
  4609. if (v) {
  4610. Toolbar.setSharedKey('');
  4611. lockRoom(false);
  4612. }
  4613. });
  4614. } else {
  4615. var msg = APP.translation.generateTranslatonHTML(
  4616. "dialog.passwordMsg", "Set a password to lock your room");
  4617. var yourPassword = APP.translation.translateString(
  4618. "dialog.yourPassword", null, "your password");
  4619. messageHandler.openTwoButtonDialog(null, null, null,
  4620. '<h2>' + msg + '</h2>' +
  4621. '<input id="lockKey" type="text"' +
  4622. 'placeholder="' + yourPassword + '" autofocus>',
  4623. false,
  4624. "dialog.Save",
  4625. function (e, v) {
  4626. if (v) {
  4627. var lockKey = document.getElementById('lockKey');
  4628. if (lockKey.value) {
  4629. Toolbar.setSharedKey(UIUtil.escapeHtml(lockKey.value));
  4630. lockRoom(true);
  4631. }
  4632. }
  4633. },
  4634. function () {
  4635. document.getElementById('lockKey').focus();
  4636. }
  4637. );
  4638. }
  4639. }
  4640. };
  4641. /**
  4642. * Opens the invite link dialog.
  4643. */
  4644. my.openLinkDialog = function () {
  4645. var inviteLink;
  4646. if (roomUrl === null) {
  4647. inviteLink = "Your conference is currently being created...";
  4648. } else {
  4649. inviteLink = encodeURI(roomUrl);
  4650. }
  4651. messageHandler.openTwoButtonDialog("dialog.shareLink",
  4652. "Share this link with everyone you want to invite", null,
  4653. '<input id="inviteLinkRef" type="text" value="' +
  4654. inviteLink + '" onclick="this.select();" readonly>',
  4655. false,
  4656. "dialog.Invite",
  4657. function (e, v) {
  4658. if (v) {
  4659. if (roomUrl) {
  4660. inviteParticipants();
  4661. }
  4662. }
  4663. },
  4664. function () {
  4665. if (roomUrl) {
  4666. document.getElementById('inviteLinkRef').select();
  4667. } else {
  4668. document.getElementById('jqi_state0_buttonInvite')
  4669. .disabled = true;
  4670. }
  4671. }
  4672. );
  4673. };
  4674. /**
  4675. * Opens the settings dialog.
  4676. */
  4677. my.openSettingsDialog = function () {
  4678. var settings1 = APP.translation.generateTranslatonHTML(
  4679. "dialog.settings1", "Configure your conference");
  4680. var settings2 = APP.translation.generateTranslatonHTML(
  4681. "dialog.settings2", "Participants join muted");
  4682. var settings3 = APP.translation.generateTranslatonHTML(
  4683. "dialog.settings3", "Require nicknames<br/><br/>" +
  4684. "Set a password to lock your room:");
  4685. var yourPassword = APP.translation.translateString(
  4686. "dialog.yourPassword", null, "your password");
  4687. messageHandler.openTwoButtonDialog(null,
  4688. '<h2>' + settings1 + '</h2>' +
  4689. '<input type="checkbox" id="initMuted">' +
  4690. settings2 + '<br/>' +
  4691. '<input type="checkbox" id="requireNicknames">' +
  4692. settings3 +
  4693. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  4694. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  4695. null,
  4696. null,
  4697. false,
  4698. "dialog.Save",
  4699. function () {
  4700. document.getElementById('lockKey').focus();
  4701. },
  4702. function (e, v) {
  4703. if (v) {
  4704. if ($('#initMuted').is(":checked")) {
  4705. // it is checked
  4706. }
  4707. if ($('#requireNicknames').is(":checked")) {
  4708. // it is checked
  4709. }
  4710. /*
  4711. var lockKey = document.getElementById('lockKey');
  4712. if (lockKey.value) {
  4713. setSharedKey(lockKey.value);
  4714. lockRoom(true);
  4715. }
  4716. */
  4717. }
  4718. }
  4719. );
  4720. };
  4721. /**
  4722. * Toggles the application in and out of full screen mode
  4723. * (a.k.a. presentation mode in Chrome).
  4724. */
  4725. my.toggleFullScreen = function () {
  4726. var fsElement = document.documentElement;
  4727. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  4728. //Enter Full Screen
  4729. if (fsElement.mozRequestFullScreen) {
  4730. fsElement.mozRequestFullScreen();
  4731. }
  4732. else {
  4733. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  4734. }
  4735. } else {
  4736. //Exit Full Screen
  4737. if (document.mozCancelFullScreen) {
  4738. document.mozCancelFullScreen();
  4739. } else {
  4740. document.webkitCancelFullScreen();
  4741. }
  4742. }
  4743. };
  4744. /**
  4745. * Unlocks the lock button state.
  4746. */
  4747. my.unlockLockButton = function () {
  4748. if ($("#lockIcon").hasClass("icon-security-locked"))
  4749. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  4750. };
  4751. /**
  4752. * Updates the lock button state to locked.
  4753. */
  4754. my.lockLockButton = function () {
  4755. if ($("#lockIcon").hasClass("icon-security"))
  4756. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  4757. };
  4758. /**
  4759. * Shows or hides authentication button
  4760. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  4761. */
  4762. my.showAuthenticateButton = function (show) {
  4763. if (show) {
  4764. $('#authentication').css({display: "inline"});
  4765. }
  4766. else {
  4767. $('#authentication').css({display: "none"});
  4768. }
  4769. };
  4770. // Shows or hides the 'recording' button.
  4771. my.showRecordingButton = function (show) {
  4772. if (!config.enableRecording) {
  4773. return;
  4774. }
  4775. if (show) {
  4776. $('#recording').css({display: "inline"});
  4777. }
  4778. else {
  4779. $('#recording').css({display: "none"});
  4780. }
  4781. };
  4782. // Sets the state of the recording button
  4783. my.setRecordingButtonState = function (isRecording) {
  4784. if (isRecording) {
  4785. $('#recordButton').removeClass("icon-recEnable");
  4786. $('#recordButton').addClass("icon-recEnable active");
  4787. } else {
  4788. $('#recordButton').removeClass("icon-recEnable active");
  4789. $('#recordButton').addClass("icon-recEnable");
  4790. }
  4791. };
  4792. // Shows or hides SIP calls button
  4793. my.showSipCallButton = function (show) {
  4794. if (APP.xmpp.isSipGatewayEnabled() && show) {
  4795. $('#sipCallButton').css({display: "inline-block"});
  4796. } else {
  4797. $('#sipCallButton').css({display: "none"});
  4798. }
  4799. };
  4800. /**
  4801. * Displays user authenticated identity name(login).
  4802. * @param authIdentity identity name to be displayed.
  4803. */
  4804. my.setAuthenticatedIdentity = function (authIdentity) {
  4805. if (authIdentity) {
  4806. $('#toolbar_auth_identity').css({display: "list-item"});
  4807. $('#toolbar_auth_identity').text(authIdentity);
  4808. } else {
  4809. $('#toolbar_auth_identity').css({display: "none"});
  4810. }
  4811. };
  4812. /**
  4813. * Shows/hides login button.
  4814. * @param show <tt>true</tt> to show
  4815. */
  4816. my.showLoginButton = function (show) {
  4817. if (show) {
  4818. $('#toolbar_button_login').css({display: "list-item"});
  4819. } else {
  4820. $('#toolbar_button_login').css({display: "none"});
  4821. }
  4822. };
  4823. /**
  4824. * Shows/hides logout button.
  4825. * @param show <tt>true</tt> to show
  4826. */
  4827. my.showLogoutButton = function (show) {
  4828. if (show) {
  4829. $('#toolbar_button_logout').css({display: "list-item"});
  4830. } else {
  4831. $('#toolbar_button_logout').css({display: "none"});
  4832. }
  4833. };
  4834. /**
  4835. * Sets the state of the button. The button has blue glow if desktop
  4836. * streaming is active.
  4837. * @param active the state of the desktop streaming.
  4838. */
  4839. my.changeDesktopSharingButtonState = function (active) {
  4840. var button = $("#desktopsharing > a");
  4841. if (active)
  4842. {
  4843. button.addClass("glow");
  4844. }
  4845. else
  4846. {
  4847. button.removeClass("glow");
  4848. }
  4849. };
  4850. return my;
  4851. }(Toolbar || {}));
  4852. module.exports = Toolbar;
  4853. },{"../../../service/authentication/AuthenticationEvents":85,"../authentication/Authentication":12,"../etherpad/Etherpad":14,"../prezi/Prezi":15,"../side_pannels/SidePanelToggler":17,"../util/MessageHandler":28,"../util/UIUtil":30,"./BottomToolbar":24}],26:[function(require,module,exports){
  4854. /* global $, interfaceConfig, Moderator, DesktopStreaming.showDesktopSharingButton */
  4855. var toolbarTimeoutObject,
  4856. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  4857. function showDesktopSharingButton() {
  4858. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  4859. $('#desktopsharing').css({display: "inline"});
  4860. } else {
  4861. $('#desktopsharing').css({display: "none"});
  4862. }
  4863. }
  4864. /**
  4865. * Hides the toolbar.
  4866. */
  4867. function hideToolbar() {
  4868. var header = $("#header"),
  4869. bottomToolbar = $("#bottomToolbar");
  4870. var isToolbarHover = false;
  4871. header.find('*').each(function () {
  4872. var id = $(this).attr('id');
  4873. if ($("#" + id + ":hover").length > 0) {
  4874. isToolbarHover = true;
  4875. }
  4876. });
  4877. if ($("#bottomToolbar:hover").length > 0) {
  4878. isToolbarHover = true;
  4879. }
  4880. clearTimeout(toolbarTimeoutObject);
  4881. toolbarTimeoutObject = null;
  4882. if (!isToolbarHover) {
  4883. header.hide("slide", { direction: "up", duration: 300});
  4884. $('#subject').animate({top: "-=40"}, 300);
  4885. if ($("#remoteVideos").hasClass("hidden")) {
  4886. bottomToolbar.hide(
  4887. "slide", {direction: "right", duration: 300});
  4888. }
  4889. }
  4890. else {
  4891. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4892. }
  4893. }
  4894. var ToolbarToggler = {
  4895. /**
  4896. * Shows the main toolbar.
  4897. */
  4898. showToolbar: function () {
  4899. var header = $("#header"),
  4900. bottomToolbar = $("#bottomToolbar");
  4901. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  4902. header.show("slide", { direction: "up", duration: 300});
  4903. $('#subject').animate({top: "+=40"}, 300);
  4904. if (!bottomToolbar.is(":visible")) {
  4905. bottomToolbar.show(
  4906. "slide", {direction: "right", duration: 300});
  4907. }
  4908. if (toolbarTimeoutObject) {
  4909. clearTimeout(toolbarTimeoutObject);
  4910. toolbarTimeoutObject = null;
  4911. }
  4912. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4913. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  4914. }
  4915. if (APP.xmpp.isModerator())
  4916. {
  4917. // TODO: Enable settings functionality.
  4918. // Need to uncomment the settings button in index.html.
  4919. // $('#settingsButton').css({visibility:"visible"});
  4920. }
  4921. // Show/hide desktop sharing button
  4922. showDesktopSharingButton();
  4923. },
  4924. /**
  4925. * Docks/undocks the toolbar.
  4926. *
  4927. * @param isDock indicates what operation to perform
  4928. */
  4929. dockToolbar: function (isDock) {
  4930. if (isDock) {
  4931. // First make sure the toolbar is shown.
  4932. if (!$('#header').is(':visible')) {
  4933. this.showToolbar();
  4934. }
  4935. // Then clear the time out, to dock the toolbar.
  4936. if (toolbarTimeoutObject) {
  4937. clearTimeout(toolbarTimeoutObject);
  4938. toolbarTimeoutObject = null;
  4939. }
  4940. }
  4941. else {
  4942. if (!$('#header').is(':visible')) {
  4943. this.showToolbar();
  4944. }
  4945. else {
  4946. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4947. }
  4948. }
  4949. },
  4950. showDesktopSharingButton: showDesktopSharingButton
  4951. };
  4952. module.exports = ToolbarToggler;
  4953. },{}],27:[function(require,module,exports){
  4954. var JitsiPopover = (function () {
  4955. /**
  4956. * Constructs new JitsiPopover and attaches it to the element
  4957. * @param element jquery selector
  4958. * @param options the options for the popover.
  4959. * @constructor
  4960. */
  4961. function JitsiPopover(element, options)
  4962. {
  4963. this.options = {
  4964. skin: "white",
  4965. content: ""
  4966. };
  4967. if(options)
  4968. {
  4969. if(options.skin)
  4970. this.options.skin = options.skin;
  4971. if(options.content)
  4972. this.options.content = options.content;
  4973. }
  4974. this.elementIsHovered = false;
  4975. this.popoverIsHovered = false;
  4976. this.popoverShown = false;
  4977. element.data("jitsi_popover", this);
  4978. this.element = element;
  4979. this.template = ' <div class="jitsipopover ' + this.options.skin +
  4980. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  4981. '<div class="jitsiPopupmenuPadding"></div></div>';
  4982. var self = this;
  4983. this.element.on("mouseenter", function () {
  4984. self.elementIsHovered = true;
  4985. self.show();
  4986. }).on("mouseleave", function () {
  4987. self.elementIsHovered = false;
  4988. setTimeout(function () {
  4989. self.hide();
  4990. }, 10);
  4991. });
  4992. }
  4993. /**
  4994. * Shows the popover
  4995. */
  4996. JitsiPopover.prototype.show = function () {
  4997. this.createPopover();
  4998. this.popoverShown = true;
  4999. };
  5000. /**
  5001. * Hides the popover
  5002. */
  5003. JitsiPopover.prototype.hide = function () {
  5004. if(!this.elementIsHovered && !this.popoverIsHovered && this.popoverShown)
  5005. {
  5006. this.forceHide();
  5007. }
  5008. };
  5009. /**
  5010. * Hides the popover
  5011. */
  5012. JitsiPopover.prototype.forceHide = function () {
  5013. $(".jitsipopover").remove();
  5014. this.popoverShown = false;
  5015. };
  5016. /**
  5017. * Creates the popover html
  5018. */
  5019. JitsiPopover.prototype.createPopover = function () {
  5020. $("body").append(this.template);
  5021. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  5022. var self = this;
  5023. $(".jitsipopover").on("mouseenter", function () {
  5024. self.popoverIsHovered = true;
  5025. }).on("mouseleave", function () {
  5026. self.popoverIsHovered = false;
  5027. self.hide();
  5028. });
  5029. this.refreshPosition();
  5030. };
  5031. /**
  5032. * Refreshes the position of the popover
  5033. */
  5034. JitsiPopover.prototype.refreshPosition = function () {
  5035. $(".jitsipopover").position({
  5036. my: "bottom",
  5037. at: "top",
  5038. collision: "fit",
  5039. of: this.element,
  5040. using: function (position, elements) {
  5041. var calcLeft = elements.target.left - elements.element.left + elements.target.width/2;
  5042. $(".jitsipopover").css({top: position.top, left: position.left, display: "table"});
  5043. $(".jitsipopover > .arrow").css({left: calcLeft});
  5044. $(".jitsipopover > .jitsiPopupmenuPadding").css({left: calcLeft - 50});
  5045. }
  5046. });
  5047. };
  5048. /**
  5049. * Updates the content of popover.
  5050. * @param content new content
  5051. */
  5052. JitsiPopover.prototype.updateContent = function (content) {
  5053. this.options.content = content;
  5054. if(!this.popoverShown)
  5055. return;
  5056. $(".jitsipopover").remove();
  5057. this.createPopover();
  5058. };
  5059. return JitsiPopover;
  5060. })();
  5061. module.exports = JitsiPopover;
  5062. },{}],28:[function(require,module,exports){
  5063. /* global $, jQuery */
  5064. var messageHandler = (function(my) {
  5065. /**
  5066. * Shows a message to the user.
  5067. *
  5068. * @param titleString the title of the message
  5069. * @param messageString the text of the message
  5070. */
  5071. my.openMessageDialog = function(titleKey, titleString,
  5072. messageKey, messageString) {
  5073. var title = null;
  5074. if(titleKey)
  5075. {
  5076. title = APP.translation.generateTranslatonHTML(titleKey,
  5077. titleString);
  5078. }
  5079. var message = APP.translation.generateTranslatonHTML(messageKey,
  5080. messageString);
  5081. $.prompt(message,
  5082. {
  5083. title: title,
  5084. persistent: false
  5085. }
  5086. );
  5087. };
  5088. /**
  5089. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  5090. *
  5091. * @param titleString the title of the message
  5092. * @param msgString the text of the message
  5093. * @param persistent boolean value which determines whether the message is persistent or not
  5094. * @param leftButton the fist button's text
  5095. * @param submitFunction function to be called on submit
  5096. * @param loadedFunction function to be called after the prompt is fully loaded
  5097. * @param closeFunction function to be called after the prompt is closed
  5098. */
  5099. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  5100. persistent, leftButtonKey, submitFunction, loadedFunction,
  5101. closeFunction)
  5102. {
  5103. var leftButton = APP.translation.generateTranslatonHTML(leftButtonKey);
  5104. var buttons = {};
  5105. buttons.button1 = {title: leftButton, value: true};
  5106. var cancelButton = APP.translation.generateTranslatonHTML("dialog.Cancel",
  5107. "Cancel");
  5108. buttons.button2 = {title: cancelButton, value: false};
  5109. var message = msgString, title = titleString;
  5110. if(titleKey)
  5111. {
  5112. title = APP.translation.generateTranslatonHTML(titleKey, titleString);
  5113. }
  5114. if(msgKey) {
  5115. message = APP.translation.generateTranslatonHTML(msgKey, msgString);
  5116. }
  5117. $.prompt(message, {
  5118. title: title,
  5119. persistent: false,
  5120. buttons: buttons,
  5121. defaultButton: 1,
  5122. loaded: loadedFunction,
  5123. submit: submitFunction,
  5124. close: closeFunction
  5125. });
  5126. };
  5127. /**
  5128. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  5129. *
  5130. * @param titleString the title of the message
  5131. * @param msgString the text of the message
  5132. * @param persistent boolean value which determines whether the message is persistent or not
  5133. * @param buttons object with the buttons. The keys must be the name of the button and value is the value
  5134. * that will be passed to submitFunction
  5135. * @param submitFunction function to be called on submit
  5136. * @param loadedFunction function to be called after the prompt is fully loaded
  5137. */
  5138. my.openDialog = function (titleString, msgString, persistent, buttons,
  5139. submitFunction, loadedFunction) {
  5140. var args = {
  5141. title: titleString,
  5142. persistent: persistent,
  5143. buttons: buttons,
  5144. defaultButton: 1,
  5145. loaded: loadedFunction,
  5146. submit: submitFunction
  5147. };
  5148. if (persistent) {
  5149. args.closeText = '';
  5150. }
  5151. return $.prompt(msgString, args);
  5152. };
  5153. /**
  5154. * Closes currently opened dialog.
  5155. */
  5156. my.closeDialog = function () {
  5157. $.prompt.close();
  5158. };
  5159. /**
  5160. * Shows a dialog with different states to the user.
  5161. *
  5162. * @param statesObject object containing all the states of the dialog
  5163. * @param loadedFunction function to be called after the prompt is fully loaded
  5164. * @param stateChangedFunction function to be called when the state of the dialog is changed
  5165. */
  5166. my.openDialogWithStates = function(statesObject, loadedFunction, stateChangedFunction) {
  5167. var myPrompt = $.prompt(statesObject);
  5168. myPrompt.on('impromptu:loaded', loadedFunction);
  5169. myPrompt.on('impromptu:statechanged', stateChangedFunction);
  5170. };
  5171. /**
  5172. * Opens new popup window for given <tt>url</tt> centered over current
  5173. * window.
  5174. *
  5175. * @param url the URL to be displayed in the popup window
  5176. * @param w the width of the popup window
  5177. * @param h the height of the popup window
  5178. * @param onPopupClosed optional callback function called when popup window
  5179. * has been closed.
  5180. *
  5181. * @returns popup window object if opened successfully or undefined
  5182. * in case we failed to open it(popup blocked)
  5183. */
  5184. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  5185. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  5186. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  5187. var popup = window.open(
  5188. url, '_blank',
  5189. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  5190. if (popup && onPopupClosed) {
  5191. var pollTimer = window.setInterval(function () {
  5192. if (popup.closed !== false) {
  5193. window.clearInterval(pollTimer);
  5194. onPopupClosed();
  5195. }
  5196. }, 200);
  5197. }
  5198. return popup;
  5199. };
  5200. /**
  5201. * Shows a dialog prompting the user to send an error report.
  5202. *
  5203. * @param titleString the title of the message
  5204. * @param msgString the text of the message
  5205. * @param error the error that is being reported
  5206. */
  5207. my.openReportDialog = function(titleKey, titleString, msgKey,
  5208. msgString, error) {
  5209. my.openMessageDialog(titleKey, titleString, msgKey, msgString);
  5210. console.log(error);
  5211. //FIXME send the error to the server
  5212. };
  5213. /**
  5214. * Shows an error dialog to the user.
  5215. * @param title the title of the message
  5216. * @param message the text of the messafe
  5217. */
  5218. my.showError = function(titleKey, title, msgKey, message) {
  5219. if(!titleKey) {
  5220. title = "Oops!";
  5221. titleKey = "dialog.oops";
  5222. }
  5223. if(!msgKey)
  5224. {
  5225. message = "There was some kind of error";
  5226. msgKey = "dialog.defaultError";
  5227. }
  5228. messageHandler.openMessageDialog(titleKey, title, msgKey, message);
  5229. };
  5230. my.notify = function(displayName, displayNameKey, displayNameDefault,
  5231. cls, messageKey, messageDefault, messageArguments) {
  5232. var displayNameSpan = '<span class="nickname" ';
  5233. if(displayName)
  5234. {
  5235. displayNameSpan += ">" + displayName;
  5236. }
  5237. else
  5238. {
  5239. displayNameSpan += "data-i18n='" + displayNameKey +
  5240. "'>" + APP.translation.translateString(displayNameKey, null,
  5241. {defaultValue: displayNameDefault});
  5242. }
  5243. displayNameSpan += "</span>";
  5244. var lMessageArguments = messageArguments;
  5245. if(!messageArguments)
  5246. lMessageArguments = {};
  5247. lMessageArguments.defaultValue = messageDefault;
  5248. toastr.info(
  5249. displayNameSpan + '<br>' +
  5250. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  5251. (messageArguments?
  5252. " i18n-options='" + JSON.stringify(messageArguments) + "'"
  5253. : "") + ">" +
  5254. APP.translation.translateString(messageKey, null,
  5255. lMessageArguments) +
  5256. '</span>');
  5257. };
  5258. return my;
  5259. }(messageHandler || {}));
  5260. module.exports = messageHandler;
  5261. },{}],29:[function(require,module,exports){
  5262. var UIEvents = require("../../../service/UI/UIEvents");
  5263. var nickname = null;
  5264. var eventEmitter = null;
  5265. var NickanameHandler = {
  5266. init: function (emitter) {
  5267. eventEmitter = emitter;
  5268. var storedDisplayName = window.localStorage.displayname;
  5269. if (storedDisplayName) {
  5270. nickname = storedDisplayName;
  5271. }
  5272. },
  5273. setNickname: function (newNickname) {
  5274. if (!newNickname || nickname === newNickname)
  5275. return;
  5276. nickname = newNickname;
  5277. window.localStorage.displayname = nickname;
  5278. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  5279. },
  5280. getNickname: function () {
  5281. return nickname;
  5282. },
  5283. addListener: function (type, listener) {
  5284. eventEmitter.on(type, listener);
  5285. }
  5286. };
  5287. module.exports = NickanameHandler;
  5288. },{"../../../service/UI/UIEvents":84}],30:[function(require,module,exports){
  5289. /**
  5290. * Created by hristo on 12/22/14.
  5291. */
  5292. module.exports = {
  5293. /**
  5294. * Returns the available video width.
  5295. */
  5296. getAvailableVideoWidth: function () {
  5297. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5298. var rightPanelWidth
  5299. = PanelToggler.isVisible() ? PanelToggler.getPanelSize()[0] : 0;
  5300. return window.innerWidth - rightPanelWidth;
  5301. },
  5302. /**
  5303. * Changes the style class of the element given by id.
  5304. */
  5305. buttonClick: function(id, classname) {
  5306. $(id).toggleClass(classname); // add the class to the clicked element
  5307. },
  5308. /**
  5309. * Returns the text width for the given element.
  5310. *
  5311. * @param el the element
  5312. */
  5313. getTextWidth: function (el) {
  5314. return (el.clientWidth + 1);
  5315. },
  5316. /**
  5317. * Returns the text height for the given element.
  5318. *
  5319. * @param el the element
  5320. */
  5321. getTextHeight: function (el) {
  5322. return (el.clientHeight + 1);
  5323. },
  5324. /**
  5325. * Plays the sound given by id.
  5326. *
  5327. * @param id the identifier of the audio element.
  5328. */
  5329. playSoundNotification: function (id) {
  5330. document.getElementById(id).play();
  5331. },
  5332. /**
  5333. * Escapes the given text.
  5334. */
  5335. escapeHtml: function (unsafeText) {
  5336. return $('<div/>').text(unsafeText).html();
  5337. },
  5338. imageToGrayScale: function (canvas) {
  5339. var context = canvas.getContext('2d');
  5340. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  5341. var pixels = imgData.data;
  5342. for (var i = 0, n = pixels.length; i < n; i += 4) {
  5343. var grayscale
  5344. = pixels[i] * .3 + pixels[i+1] * .59 + pixels[i+2] * .11;
  5345. pixels[i ] = grayscale; // red
  5346. pixels[i+1] = grayscale; // green
  5347. pixels[i+2] = grayscale; // blue
  5348. // pixels[i+3] is alpha
  5349. }
  5350. // redraw the image in black & white
  5351. context.putImageData(imgData, 0, 0);
  5352. },
  5353. setTooltip: function (element, key, position) {
  5354. element.setAttribute("data-i18n", "[data-content]" + key);
  5355. element.setAttribute("data-toggle", "popover");
  5356. element.setAttribute("data-placement", position);
  5357. element.setAttribute("data-html", true);
  5358. element.setAttribute("data-container", "body");
  5359. }
  5360. };
  5361. },{"../side_pannels/SidePanelToggler":17}],31:[function(require,module,exports){
  5362. var JitsiPopover = require("../util/JitsiPopover");
  5363. /**
  5364. * Constructs new connection indicator.
  5365. * @param videoContainer the video container associated with the indicator.
  5366. * @constructor
  5367. */
  5368. function ConnectionIndicator(videoContainer, jid, VideoLayout)
  5369. {
  5370. this.videoContainer = videoContainer;
  5371. this.bandwidth = null;
  5372. this.packetLoss = null;
  5373. this.bitrate = null;
  5374. this.showMoreValue = false;
  5375. this.resolution = null;
  5376. this.transport = [];
  5377. this.popover = null;
  5378. this.jid = jid;
  5379. this.create();
  5380. this.videoLayout = VideoLayout;
  5381. }
  5382. /**
  5383. * Values for the connection quality
  5384. * @type {{98: string,
  5385. * 81: string,
  5386. * 64: string,
  5387. * 47: string,
  5388. * 30: string,
  5389. * 0: string}}
  5390. */
  5391. ConnectionIndicator.connectionQualityValues = {
  5392. 98: "18px", //full
  5393. 81: "15px",//4 bars
  5394. 64: "11px",//3 bars
  5395. 47: "7px",//2 bars
  5396. 30: "3px",//1 bar
  5397. 0: "0px"//empty
  5398. };
  5399. ConnectionIndicator.getIP = function(value)
  5400. {
  5401. return value.substring(0, value.lastIndexOf(":"));
  5402. };
  5403. ConnectionIndicator.getPort = function(value)
  5404. {
  5405. return value.substring(value.lastIndexOf(":") + 1, value.length);
  5406. };
  5407. ConnectionIndicator.getStringFromArray = function (array) {
  5408. var res = "";
  5409. for(var i = 0; i < array.length; i++)
  5410. {
  5411. res += (i === 0? "" : ", ") + array[i];
  5412. }
  5413. return res;
  5414. };
  5415. /**
  5416. * Generates the html content.
  5417. * @returns {string} the html content.
  5418. */
  5419. ConnectionIndicator.prototype.generateText = function () {
  5420. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  5421. var translate = APP.translation.translateString;
  5422. if(this.bitrate === null)
  5423. {
  5424. downloadBitrate = "N/A";
  5425. uploadBitrate = "N/A";
  5426. }
  5427. else
  5428. {
  5429. downloadBitrate =
  5430. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  5431. uploadBitrate =
  5432. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  5433. }
  5434. if(this.packetLoss === null)
  5435. {
  5436. packetLoss = "N/A";
  5437. }
  5438. else
  5439. {
  5440. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  5441. (this.packetLoss.download !== null? this.packetLoss.download : "N/A") +
  5442. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  5443. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") + "%";
  5444. }
  5445. var resolutionValue = null;
  5446. if(this.resolution && this.jid != null)
  5447. {
  5448. var keys = Object.keys(this.resolution);
  5449. if(keys.length == 1)
  5450. {
  5451. for(var ssrc in this.resolution)
  5452. {
  5453. resolutionValue = this.resolution[ssrc];
  5454. }
  5455. }
  5456. else if(keys.length > 1)
  5457. {
  5458. var displayedSsrc = APP.simulcast.getReceivingSSRC(this.jid);
  5459. resolutionValue = this.resolution[displayedSsrc];
  5460. }
  5461. }
  5462. if(this.jid === null)
  5463. {
  5464. resolution = "";
  5465. if(this.resolution === null || !Object.keys(this.resolution) ||
  5466. Object.keys(this.resolution).length === 0)
  5467. {
  5468. resolution = "N/A";
  5469. }
  5470. else
  5471. for(i in this.resolution)
  5472. {
  5473. resolutionValue = this.resolution[i];
  5474. if(resolutionValue)
  5475. {
  5476. if(resolutionValue.height &&
  5477. resolutionValue.width)
  5478. {
  5479. resolution += (resolution === ""? "" : ", ") +
  5480. resolutionValue.width + "x" +
  5481. resolutionValue.height;
  5482. }
  5483. }
  5484. }
  5485. }
  5486. else if(!resolutionValue ||
  5487. !resolutionValue.height ||
  5488. !resolutionValue.width)
  5489. {
  5490. resolution = "N/A";
  5491. }
  5492. else
  5493. {
  5494. resolution = resolutionValue.width + "x" + resolutionValue.height;
  5495. }
  5496. var result = "<table style='width:100%'>" +
  5497. "<tr>" +
  5498. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  5499. translate("connectionindicator.bitrate") + "</span></td>" +
  5500. "<td><span class='jitsipopover_green'>&darr;</span>" +
  5501. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  5502. uploadBitrate + "</td>" +
  5503. "</tr><tr>" +
  5504. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  5505. translate("connectionindicator.packetloss") + "</span></td>" +
  5506. "<td>" + packetLoss + "</td>" +
  5507. "</tr><tr>" +
  5508. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  5509. translate("connectionindicator.resolution") + "</span></td>" +
  5510. "<td>" + resolution + "</td></tr></table>";
  5511. if(this.videoContainer.id == "localVideoContainer") {
  5512. result += "<div class=\"jitsipopover_showmore\" " +
  5513. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  5514. this.videoContainer.id + "')\" data-i18n='connectionindicator." +
  5515. (this.showMoreValue ? "less" : "more") + "'>" +
  5516. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  5517. "</div><br />";
  5518. }
  5519. if(this.showMoreValue)
  5520. {
  5521. var downloadBandwidth, uploadBandwidth, transport;
  5522. if(this.bandwidth === null)
  5523. {
  5524. downloadBandwidth = "N/A";
  5525. uploadBandwidth = "N/A";
  5526. }
  5527. else
  5528. {
  5529. downloadBandwidth = this.bandwidth.download?
  5530. this.bandwidth.download + " Kbps" :
  5531. "N/A";
  5532. uploadBandwidth = this.bandwidth.upload?
  5533. this.bandwidth.upload + " Kbps" :
  5534. "N/A";
  5535. }
  5536. if(!this.transport || this.transport.length === 0)
  5537. {
  5538. transport = "<tr>" +
  5539. "<td><span class='jitsipopover_blue' " +
  5540. "data-i18n='connectionindicator.address'>" +
  5541. translate("connectionindicator.address") + "</span></td>" +
  5542. "<td> N/A</td></tr>";
  5543. }
  5544. else
  5545. {
  5546. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  5547. for(i = 0; i < this.transport.length; i++)
  5548. {
  5549. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  5550. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  5551. var localIP =
  5552. ConnectionIndicator.getIP(this.transport[i].localip);
  5553. var localPort =
  5554. ConnectionIndicator.getPort(this.transport[i].localip);
  5555. if(data.remoteIP.indexOf(ip) == -1)
  5556. {
  5557. data.remoteIP.push(ip);
  5558. }
  5559. if(data.remotePort.indexOf(port) == -1)
  5560. {
  5561. data.remotePort.push(port);
  5562. }
  5563. if(data.localIP.indexOf(localIP) == -1)
  5564. {
  5565. data.localIP.push(localIP);
  5566. }
  5567. if(data.localPort.indexOf(localPort) == -1)
  5568. {
  5569. data.localPort.push(localPort);
  5570. }
  5571. }
  5572. var local_address_key = "connectionindicator." +
  5573. (data.localIP.length > 1? "localaddresses" : "localaddress");
  5574. var remote_address_key = "connectionindicator." +
  5575. (data.remoteIP.length > 1? "remoteaddresses" : "remoteaddress");
  5576. var localTransport =
  5577. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5578. local_address_key +"'>" +
  5579. translate(local_address_key) + "</span></td><td> " +
  5580. ConnectionIndicator.getStringFromArray(data.localIP) +
  5581. "</td></tr>";
  5582. transport =
  5583. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5584. remote_address_key + "'>" +
  5585. translate(remote_address_key) + "</span></td><td> " +
  5586. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  5587. "</td></tr>";
  5588. var key_remote = "connectionindicator.",
  5589. key_local = "connectionindicator.";
  5590. if(this.transport.length > 1)
  5591. {
  5592. key_remote += "remoteports";
  5593. key_local += "localports";
  5594. }
  5595. else
  5596. {
  5597. key_remote += "remoteport";
  5598. key_local += "localport";
  5599. }
  5600. transport += "<tr>" +
  5601. "<td>" +
  5602. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  5603. "'>" +
  5604. translate(key_remote) + "</span></td><td>";
  5605. localTransport += "<tr>" +
  5606. "<td>" +
  5607. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  5608. "'>" +
  5609. translate(key_local) + "</span></td><td>";
  5610. transport +=
  5611. ConnectionIndicator.getStringFromArray(data.remotePort);
  5612. localTransport +=
  5613. ConnectionIndicator.getStringFromArray(data.localPort);
  5614. transport += "</td></tr>";
  5615. transport += localTransport + "</td></tr>";
  5616. transport +="<tr>" +
  5617. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  5618. translate("connectionindicator.transport") + "</span></td>" +
  5619. "<td>" + this.transport[0].type + "</td></tr>";
  5620. }
  5621. result += "<table style='width:100%'>" +
  5622. "<tr>" +
  5623. "<td>" +
  5624. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  5625. translate("connectionindicator.bandwidth") + "</span>" +
  5626. "</td><td>" +
  5627. "<span class='jitsipopover_green'>&darr;</span>" +
  5628. downloadBandwidth +
  5629. " <span class='jitsipopover_orange'>&uarr;</span>" +
  5630. uploadBandwidth + "</td></tr>";
  5631. result += transport + "</table>";
  5632. }
  5633. return result;
  5634. };
  5635. /**
  5636. * Shows or hide the additional information.
  5637. */
  5638. ConnectionIndicator.prototype.showMore = function () {
  5639. this.showMoreValue = !this.showMoreValue;
  5640. this.updatePopoverData();
  5641. };
  5642. function createIcon(classes)
  5643. {
  5644. var icon = document.createElement("span");
  5645. for(var i in classes)
  5646. {
  5647. icon.classList.add(classes[i]);
  5648. }
  5649. icon.appendChild(
  5650. document.createElement("i")).classList.add("icon-connection");
  5651. return icon;
  5652. }
  5653. /**
  5654. * Creates the indicator
  5655. */
  5656. ConnectionIndicator.prototype.create = function () {
  5657. this.connectionIndicatorContainer = document.createElement("div");
  5658. this.connectionIndicatorContainer.className = "connectionindicator";
  5659. this.connectionIndicatorContainer.style.display = "none";
  5660. this.videoContainer.appendChild(this.connectionIndicatorContainer);
  5661. this.popover = new JitsiPopover(
  5662. $("#" + this.videoContainer.id + " > .connectionindicator"),
  5663. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  5664. APP.translation.translateString("connectionindicator.na") + "</div>",
  5665. skin: "black"});
  5666. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  5667. createIcon(["connection", "connection_empty"]));
  5668. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  5669. createIcon(["connection", "connection_full"]));
  5670. };
  5671. /**
  5672. * Removes the indicator
  5673. */
  5674. ConnectionIndicator.prototype.remove = function()
  5675. {
  5676. this.connectionIndicatorContainer.remove();
  5677. this.popover.forceHide();
  5678. };
  5679. /**
  5680. * Updates the data of the indicator
  5681. * @param percent the percent of connection quality
  5682. * @param object the statistics data.
  5683. */
  5684. ConnectionIndicator.prototype.updateConnectionQuality =
  5685. function (percent, object) {
  5686. if(percent === null)
  5687. {
  5688. this.connectionIndicatorContainer.style.display = "none";
  5689. this.popover.forceHide();
  5690. return;
  5691. }
  5692. else
  5693. {
  5694. if(this.connectionIndicatorContainer.style.display == "none") {
  5695. this.connectionIndicatorContainer.style.display = "block";
  5696. this.videoLayout.updateMutePosition(this.videoContainer.id);
  5697. }
  5698. }
  5699. this.bandwidth = object.bandwidth;
  5700. this.bitrate = object.bitrate;
  5701. this.packetLoss = object.packetLoss;
  5702. this.transport = object.transport;
  5703. if(object.resolution)
  5704. {
  5705. this.resolution = object.resolution;
  5706. }
  5707. for(var quality in ConnectionIndicator.connectionQualityValues)
  5708. {
  5709. if(percent >= quality)
  5710. {
  5711. this.fullIcon.style.width =
  5712. ConnectionIndicator.connectionQualityValues[quality];
  5713. }
  5714. }
  5715. this.updatePopoverData();
  5716. };
  5717. /**
  5718. * Updates the resolution
  5719. * @param resolution the new resolution
  5720. */
  5721. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  5722. this.resolution = resolution;
  5723. this.updatePopoverData();
  5724. };
  5725. /**
  5726. * Updates the content of the popover
  5727. */
  5728. ConnectionIndicator.prototype.updatePopoverData = function () {
  5729. this.popover.updateContent(
  5730. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  5731. APP.translation.translateElement($(".connection_info"));
  5732. };
  5733. /**
  5734. * Hides the popover
  5735. */
  5736. ConnectionIndicator.prototype.hide = function () {
  5737. this.popover.forceHide();
  5738. };
  5739. /**
  5740. * Hides the indicator
  5741. */
  5742. ConnectionIndicator.prototype.hideIndicator = function () {
  5743. this.connectionIndicatorContainer.style.display = "none";
  5744. if(this.popover)
  5745. this.popover.forceHide();
  5746. };
  5747. module.exports = ConnectionIndicator;
  5748. },{"../util/JitsiPopover":27}],32:[function(require,module,exports){
  5749. var AudioLevels = require("../audio_levels/AudioLevels");
  5750. var Avatar = require("../avatar/Avatar");
  5751. var Chat = require("../side_pannels/chat/Chat");
  5752. var ContactList = require("../side_pannels/contactlist/ContactList");
  5753. var UIUtil = require("../util/UIUtil");
  5754. var ConnectionIndicator = require("./ConnectionIndicator");
  5755. var NicknameHandler = require("../util/NicknameHandler");
  5756. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  5757. var UIEvents = require("../../../service/UI/UIEvents");
  5758. var currentDominantSpeaker = null;
  5759. var lastNCount = config.channelLastN;
  5760. var localLastNCount = config.channelLastN;
  5761. var localLastNSet = [];
  5762. var lastNEndpointsCache = [];
  5763. var lastNPickupJid = null;
  5764. var largeVideoState = {
  5765. updateInProgress: false,
  5766. newSrc: ''
  5767. };
  5768. var eventEmitter = null;
  5769. /**
  5770. * Currently focused video "src"(displayed in large video).
  5771. * @type {String}
  5772. */
  5773. var focusedVideoInfo = null;
  5774. /**
  5775. * Indicates if we have muted our audio before the conference has started.
  5776. * @type {boolean}
  5777. */
  5778. var preMuted = false;
  5779. var mutedAudios = {};
  5780. var flipXLocalVideo = true;
  5781. var currentVideoWidth = null;
  5782. var currentVideoHeight = null;
  5783. var localVideoSrc = null;
  5784. function videoactive( videoelem) {
  5785. if (videoelem.attr('id').indexOf('mixedmslabel') === -1) {
  5786. // ignore mixedmslabela0 and v0
  5787. videoelem.show();
  5788. VideoLayout.resizeThumbnails();
  5789. var videoParent = videoelem.parent();
  5790. var parentResourceJid = null;
  5791. if (videoParent)
  5792. parentResourceJid
  5793. = VideoLayout.getPeerContainerResourceJid(videoParent[0]);
  5794. // Update the large video to the last added video only if there's no
  5795. // current dominant, focused speaker or prezi playing or update it to
  5796. // the current dominant speaker.
  5797. if ((!focusedVideoInfo &&
  5798. !VideoLayout.getDominantSpeakerResourceJid() &&
  5799. !require("../prezi/Prezi").isPresentationVisible()) ||
  5800. (parentResourceJid &&
  5801. VideoLayout.getDominantSpeakerResourceJid() === parentResourceJid)) {
  5802. VideoLayout.updateLargeVideo(
  5803. APP.RTC.getVideoSrc(videoelem[0]),
  5804. 1,
  5805. parentResourceJid);
  5806. }
  5807. VideoLayout.showModeratorIndicator();
  5808. }
  5809. }
  5810. function waitForRemoteVideo(selector, ssrc, stream, jid) {
  5811. // XXX(gp) so, every call to this function is *always* preceded by a call
  5812. // to the RTC.attachMediaStream() function but that call is *not* followed
  5813. // by an update to the videoSrcToSsrc map!
  5814. //
  5815. // The above way of doing things results in video SRCs that don't correspond
  5816. // to any SSRC for a short period of time (to be more precise, for as long
  5817. // the waitForRemoteVideo takes to complete). This causes problems (see
  5818. // bellow).
  5819. //
  5820. // I'm wondering why we need to do that; i.e. why call RTC.attachMediaStream()
  5821. // a second time in here and only then update the videoSrcToSsrc map? Why
  5822. // not simply update the videoSrcToSsrc map when the RTC.attachMediaStream()
  5823. // is called the first time? I actually do that in the lastN changed event
  5824. // handler because the "orphan" video SRC is causing troubles there. The
  5825. // purpose of this method would then be to fire the "videoactive.jingle".
  5826. //
  5827. // Food for though I guess :-)
  5828. if (selector.removed || !selector.parent().is(":visible")) {
  5829. console.warn("Media removed before had started", selector);
  5830. return;
  5831. }
  5832. if (stream.id === 'mixedmslabel') return;
  5833. if (selector[0].currentTime > 0) {
  5834. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  5835. APP.RTC.attachMediaStream(selector, videoStream); // FIXME: why do i have to do this for FF?
  5836. videoactive(selector);
  5837. } else {
  5838. setTimeout(function () {
  5839. waitForRemoteVideo(selector, ssrc, stream, jid);
  5840. }, 250);
  5841. }
  5842. }
  5843. /**
  5844. * Returns an array of the video horizontal and vertical indents,
  5845. * so that if fits its parent.
  5846. *
  5847. * @return an array with 2 elements, the horizontal indent and the vertical
  5848. * indent
  5849. */
  5850. function getCameraVideoPosition(videoWidth,
  5851. videoHeight,
  5852. videoSpaceWidth,
  5853. videoSpaceHeight) {
  5854. // Parent height isn't completely calculated when we position the video in
  5855. // full screen mode and this is why we use the screen height in this case.
  5856. // Need to think it further at some point and implement it properly.
  5857. var isFullScreen = document.fullScreen ||
  5858. document.mozFullScreen ||
  5859. document.webkitIsFullScreen;
  5860. if (isFullScreen)
  5861. videoSpaceHeight = window.innerHeight;
  5862. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  5863. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  5864. return [horizontalIndent, verticalIndent];
  5865. }
  5866. /**
  5867. * Returns an array of the video horizontal and vertical indents.
  5868. * Centers horizontally and top aligns vertically.
  5869. *
  5870. * @return an array with 2 elements, the horizontal indent and the vertical
  5871. * indent
  5872. */
  5873. function getDesktopVideoPosition(videoWidth,
  5874. videoHeight,
  5875. videoSpaceWidth,
  5876. videoSpaceHeight) {
  5877. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  5878. var verticalIndent = 0;// Top aligned
  5879. return [horizontalIndent, verticalIndent];
  5880. }
  5881. /**
  5882. * Returns an array of the video dimensions, so that it covers the screen.
  5883. * It leaves no empty areas, but some parts of the video might not be visible.
  5884. *
  5885. * @return an array with 2 elements, the video width and the video height
  5886. */
  5887. function getCameraVideoSize(videoWidth,
  5888. videoHeight,
  5889. videoSpaceWidth,
  5890. videoSpaceHeight) {
  5891. if (!videoWidth)
  5892. videoWidth = currentVideoWidth;
  5893. if (!videoHeight)
  5894. videoHeight = currentVideoHeight;
  5895. var aspectRatio = videoWidth / videoHeight;
  5896. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  5897. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  5898. if (availableWidth / aspectRatio < videoSpaceHeight) {
  5899. availableHeight = videoSpaceHeight;
  5900. availableWidth = availableHeight * aspectRatio;
  5901. }
  5902. if (availableHeight * aspectRatio < videoSpaceWidth) {
  5903. availableWidth = videoSpaceWidth;
  5904. availableHeight = availableWidth / aspectRatio;
  5905. }
  5906. return [availableWidth, availableHeight];
  5907. }
  5908. /**
  5909. * Sets the display name for the given video span id.
  5910. */
  5911. function setDisplayName(videoSpanId, displayName) {
  5912. var nameSpan = $('#' + videoSpanId + '>span.displayname');
  5913. var defaultLocalDisplayName = interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME;
  5914. // If we already have a display name for this video.
  5915. if (nameSpan.length > 0) {
  5916. var nameSpanElement = nameSpan.get(0);
  5917. if (nameSpanElement.id === 'localDisplayName' &&
  5918. $('#localDisplayName').text() !== displayName) {
  5919. if (displayName && displayName.length > 0)
  5920. $('#localDisplayName').html(displayName + ' (me)');
  5921. else
  5922. $('#localDisplayName').text(defaultLocalDisplayName);
  5923. } else {
  5924. if (displayName && displayName.length > 0)
  5925. $('#' + videoSpanId + '_name').html(displayName);
  5926. else
  5927. $('#' + videoSpanId + '_name').text(interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  5928. }
  5929. } else {
  5930. var editButton = null;
  5931. nameSpan = document.createElement('span');
  5932. nameSpan.className = 'displayname';
  5933. $('#' + videoSpanId)[0].appendChild(nameSpan);
  5934. if (videoSpanId === 'localVideoContainer') {
  5935. editButton = createEditDisplayNameButton();
  5936. nameSpan.innerText = defaultLocalDisplayName;
  5937. }
  5938. else {
  5939. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  5940. }
  5941. if (displayName && displayName.length > 0) {
  5942. nameSpan.innerText = displayName;
  5943. }
  5944. if (!editButton) {
  5945. nameSpan.id = videoSpanId + '_name';
  5946. } else {
  5947. nameSpan.id = 'localDisplayName';
  5948. $('#' + videoSpanId)[0].appendChild(editButton);
  5949. //translates popover of edit button
  5950. APP.translation.translateElement($("a.displayname"));
  5951. var editableText = document.createElement('input');
  5952. editableText.className = 'displayname';
  5953. editableText.type = 'text';
  5954. editableText.id = 'editDisplayName';
  5955. if (displayName && displayName.length) {
  5956. editableText.value
  5957. = displayName.substring(0, displayName.indexOf(' (me)'));
  5958. }
  5959. editableText.setAttribute('style', 'display:none;');
  5960. editableText.setAttribute('placeholder', 'ex. Jane Pink');
  5961. $('#' + videoSpanId)[0].appendChild(editableText);
  5962. $('#localVideoContainer .displayname')
  5963. .bind("click", function (e) {
  5964. e.preventDefault();
  5965. e.stopPropagation();
  5966. $('#localDisplayName').hide();
  5967. $('#editDisplayName').show();
  5968. $('#editDisplayName').focus();
  5969. $('#editDisplayName').select();
  5970. $('#editDisplayName').one("focusout", function (e) {
  5971. VideoLayout.inputDisplayNameHandler(this.value);
  5972. });
  5973. $('#editDisplayName').on('keydown', function (e) {
  5974. if (e.keyCode === 13) {
  5975. e.preventDefault();
  5976. VideoLayout.inputDisplayNameHandler(this.value);
  5977. }
  5978. });
  5979. });
  5980. }
  5981. }
  5982. }
  5983. /**
  5984. * Gets the selector of video thumbnail container for the user identified by
  5985. * given <tt>userJid</tt>
  5986. * @param resourceJid user's Jid for whom we want to get the video container.
  5987. */
  5988. function getParticipantContainer(resourceJid)
  5989. {
  5990. if (!resourceJid)
  5991. return null;
  5992. if (resourceJid === APP.xmpp.myResource())
  5993. return $("#localVideoContainer");
  5994. else
  5995. return $("#participant_" + resourceJid);
  5996. }
  5997. /**
  5998. * Sets the size and position of the given video element.
  5999. *
  6000. * @param video the video element to position
  6001. * @param width the desired video width
  6002. * @param height the desired video height
  6003. * @param horizontalIndent the left and right indent
  6004. * @param verticalIndent the top and bottom indent
  6005. */
  6006. function positionVideo(video,
  6007. width,
  6008. height,
  6009. horizontalIndent,
  6010. verticalIndent) {
  6011. video.width(width);
  6012. video.height(height);
  6013. video.css({ top: verticalIndent + 'px',
  6014. bottom: verticalIndent + 'px',
  6015. left: horizontalIndent + 'px',
  6016. right: horizontalIndent + 'px'});
  6017. }
  6018. /**
  6019. * Adds the remote video menu element for the given <tt>jid</tt> in the
  6020. * given <tt>parentElement</tt>.
  6021. *
  6022. * @param jid the jid indicating the video for which we're adding a menu.
  6023. * @param parentElement the parent element where this menu will be added
  6024. */
  6025. function addRemoteVideoMenu(jid, parentElement) {
  6026. var spanElement = document.createElement('span');
  6027. spanElement.className = 'remotevideomenu';
  6028. parentElement.appendChild(spanElement);
  6029. var menuElement = document.createElement('i');
  6030. menuElement.className = 'fa fa-angle-down';
  6031. menuElement.title = 'Remote user controls';
  6032. spanElement.appendChild(menuElement);
  6033. // <ul class="popupmenu">
  6034. // <li><a href="#">Mute</a></li>
  6035. // <li><a href="#">Eject</a></li>
  6036. // </ul>
  6037. var popupmenuElement = document.createElement('ul');
  6038. popupmenuElement.className = 'popupmenu';
  6039. popupmenuElement.id
  6040. = 'remote_popupmenu_' + Strophe.getResourceFromJid(jid);
  6041. spanElement.appendChild(popupmenuElement);
  6042. var muteMenuItem = document.createElement('li');
  6043. var muteLinkItem = document.createElement('a');
  6044. var mutedIndicator = "<i style='float:left;' class='icon-mic-disabled'></i>";
  6045. if (!mutedAudios[jid]) {
  6046. muteLinkItem.innerHTML = mutedIndicator +
  6047. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  6048. muteLinkItem.className = 'mutelink';
  6049. }
  6050. else {
  6051. muteLinkItem.innerHTML = mutedIndicator +
  6052. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  6053. muteLinkItem.className = 'mutelink disabled';
  6054. }
  6055. muteLinkItem.onclick = function(){
  6056. if ($(this).attr('disabled') != undefined) {
  6057. event.preventDefault();
  6058. }
  6059. var isMute = mutedAudios[jid] == true;
  6060. APP.xmpp.setMute(jid, !isMute);
  6061. popupmenuElement.setAttribute('style', 'display:none;');
  6062. if (isMute) {
  6063. this.innerHTML = mutedIndicator +
  6064. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  6065. this.className = 'mutelink disabled';
  6066. }
  6067. else {
  6068. this.innerHTML = mutedIndicator +
  6069. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  6070. this.className = 'mutelink';
  6071. }
  6072. };
  6073. muteMenuItem.appendChild(muteLinkItem);
  6074. popupmenuElement.appendChild(muteMenuItem);
  6075. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  6076. var ejectMenuItem = document.createElement('li');
  6077. var ejectLinkItem = document.createElement('a');
  6078. var ejectText = "<div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.kick'>&nbsp;</div>";
  6079. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  6080. ejectLinkItem.onclick = function(){
  6081. APP.xmpp.eject(jid);
  6082. popupmenuElement.setAttribute('style', 'display:none;');
  6083. };
  6084. ejectMenuItem.appendChild(ejectLinkItem);
  6085. popupmenuElement.appendChild(ejectMenuItem);
  6086. var paddingSpan = document.createElement('span');
  6087. paddingSpan.className = 'popupmenuPadding';
  6088. popupmenuElement.appendChild(paddingSpan);
  6089. APP.translation.translateElement($("#" + popupmenuElement.id + " > li > a > div"));
  6090. }
  6091. /**
  6092. * Removes remote video menu element from video element identified by
  6093. * given <tt>videoElementId</tt>.
  6094. *
  6095. * @param videoElementId the id of local or remote video element.
  6096. */
  6097. function removeRemoteVideoMenu(videoElementId) {
  6098. var menuSpan = $('#' + videoElementId + '>span.remotevideomenu');
  6099. if (menuSpan.length) {
  6100. menuSpan.remove();
  6101. }
  6102. }
  6103. /**
  6104. * Updates the data for the indicator
  6105. * @param id the id of the indicator
  6106. * @param percent the percent for connection quality
  6107. * @param object the data
  6108. */
  6109. function updateStatsIndicator(id, percent, object) {
  6110. if(VideoLayout.connectionIndicators[id])
  6111. VideoLayout.connectionIndicators[id].updateConnectionQuality(percent, object);
  6112. }
  6113. /**
  6114. * Returns an array of the video dimensions, so that it keeps it's aspect
  6115. * ratio and fits available area with it's larger dimension. This method
  6116. * ensures that whole video will be visible and can leave empty areas.
  6117. *
  6118. * @return an array with 2 elements, the video width and the video height
  6119. */
  6120. function getDesktopVideoSize(videoWidth,
  6121. videoHeight,
  6122. videoSpaceWidth,
  6123. videoSpaceHeight) {
  6124. if (!videoWidth)
  6125. videoWidth = currentVideoWidth;
  6126. if (!videoHeight)
  6127. videoHeight = currentVideoHeight;
  6128. var aspectRatio = videoWidth / videoHeight;
  6129. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  6130. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  6131. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  6132. if (availableWidth / aspectRatio >= videoSpaceHeight)
  6133. {
  6134. availableHeight = videoSpaceHeight;
  6135. availableWidth = availableHeight * aspectRatio;
  6136. }
  6137. if (availableHeight * aspectRatio >= videoSpaceWidth)
  6138. {
  6139. availableWidth = videoSpaceWidth;
  6140. availableHeight = availableWidth / aspectRatio;
  6141. }
  6142. return [availableWidth, availableHeight];
  6143. }
  6144. /**
  6145. * Creates the edit display name button.
  6146. *
  6147. * @returns the edit button
  6148. */
  6149. function createEditDisplayNameButton() {
  6150. var editButton = document.createElement('a');
  6151. editButton.className = 'displayname';
  6152. UIUtil.setTooltip(editButton,
  6153. "videothumbnail.editnickname",
  6154. "top");
  6155. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  6156. return editButton;
  6157. }
  6158. /**
  6159. * Creates the element indicating the moderator(owner) of the conference.
  6160. *
  6161. * @param parentElement the parent element where the owner indicator will
  6162. * be added
  6163. */
  6164. function createModeratorIndicatorElement(parentElement) {
  6165. var moderatorIndicator = document.createElement('i');
  6166. moderatorIndicator.className = 'fa fa-star';
  6167. parentElement.appendChild(moderatorIndicator);
  6168. UIUtil.setTooltip(parentElement,
  6169. "videothumbnail.moderator",
  6170. "top");
  6171. }
  6172. var VideoLayout = (function (my) {
  6173. my.connectionIndicators = {};
  6174. // By default we use camera
  6175. my.getVideoSize = getCameraVideoSize;
  6176. my.getVideoPosition = getCameraVideoPosition;
  6177. my.init = function (emitter) {
  6178. // Listen for large video size updates
  6179. document.getElementById('largeVideo')
  6180. .addEventListener('loadedmetadata', function (e) {
  6181. currentVideoWidth = this.videoWidth;
  6182. currentVideoHeight = this.videoHeight;
  6183. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  6184. });
  6185. eventEmitter = emitter;
  6186. };
  6187. my.isInLastN = function(resource) {
  6188. return lastNCount < 0 // lastN is disabled, return true
  6189. || (lastNCount > 0 && lastNEndpointsCache.length == 0) // lastNEndpoints cache not built yet, return true
  6190. || (lastNEndpointsCache && lastNEndpointsCache.indexOf(resource) !== -1);
  6191. };
  6192. my.changeLocalStream = function (stream) {
  6193. VideoLayout.changeLocalVideo(stream);
  6194. };
  6195. my.changeLocalAudio = function(stream) {
  6196. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  6197. document.getElementById('localAudio').autoplay = true;
  6198. document.getElementById('localAudio').volume = 0;
  6199. if (preMuted) {
  6200. if(!APP.UI.setAudioMuted(true))
  6201. {
  6202. preMuted = mute;
  6203. }
  6204. preMuted = false;
  6205. }
  6206. };
  6207. my.changeLocalVideo = function(stream) {
  6208. var flipX = true;
  6209. if(stream.videoType == "screen")
  6210. flipX = false;
  6211. var localVideo = document.createElement('video');
  6212. localVideo.id = 'localVideo_' +
  6213. APP.RTC.getStreamID(stream.getOriginalStream());
  6214. localVideo.autoplay = true;
  6215. localVideo.volume = 0; // is it required if audio is separated ?
  6216. localVideo.oncontextmenu = function () { return false; };
  6217. var localVideoContainer = document.getElementById('localVideoWrapper');
  6218. localVideoContainer.appendChild(localVideo);
  6219. // Set default display name.
  6220. setDisplayName('localVideoContainer');
  6221. if(!VideoLayout.connectionIndicators["localVideoContainer"]) {
  6222. VideoLayout.connectionIndicators["localVideoContainer"]
  6223. = new ConnectionIndicator($("#localVideoContainer")[0], null, VideoLayout);
  6224. }
  6225. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  6226. var localVideoSelector = $('#' + localVideo.id);
  6227. function localVideoClick(event) {
  6228. event.stopPropagation();
  6229. VideoLayout.handleVideoThumbClicked(
  6230. APP.RTC.getVideoSrc(localVideo),
  6231. false,
  6232. APP.xmpp.myResource());
  6233. }
  6234. // Add click handler to both video and video wrapper elements in case
  6235. // there's no video.
  6236. localVideoSelector.click(localVideoClick);
  6237. $('#localVideoContainer').click(localVideoClick);
  6238. // Add hover handler
  6239. $('#localVideoContainer').hover(
  6240. function() {
  6241. VideoLayout.showDisplayName('localVideoContainer', true);
  6242. },
  6243. function() {
  6244. if (!VideoLayout.isLargeVideoVisible()
  6245. || APP.RTC.getVideoSrc(localVideo) !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  6246. VideoLayout.showDisplayName('localVideoContainer', false);
  6247. }
  6248. );
  6249. // Add stream ended handler
  6250. stream.getOriginalStream().onended = function () {
  6251. localVideoContainer.removeChild(localVideo);
  6252. VideoLayout.updateRemovedVideo(APP.RTC.getVideoSrc(localVideo));
  6253. };
  6254. // Flip video x axis if needed
  6255. flipXLocalVideo = flipX;
  6256. if (flipX) {
  6257. localVideoSelector.addClass("flipVideoX");
  6258. }
  6259. // Attach WebRTC stream
  6260. var videoStream = APP.simulcast.getLocalVideoStream();
  6261. APP.RTC.attachMediaStream(localVideoSelector, videoStream);
  6262. localVideoSrc = APP.RTC.getVideoSrc(localVideo);
  6263. var myResourceJid = APP.xmpp.myResource();
  6264. VideoLayout.updateLargeVideo(localVideoSrc, 0,
  6265. myResourceJid);
  6266. };
  6267. /**
  6268. * Checks if removed video is currently displayed and tries to display
  6269. * another one instead.
  6270. * @param removedVideoSrc src stream identifier of the video.
  6271. */
  6272. my.updateRemovedVideo = function(removedVideoSrc) {
  6273. if (removedVideoSrc === APP.RTC.getVideoSrc($('#largeVideo')[0])) {
  6274. // this is currently displayed as large
  6275. // pick the last visible video in the row
  6276. // if nobody else is left, this picks the local video
  6277. var pick
  6278. = $('#remoteVideos>span[id!="mixedstream"]:visible:last>video')
  6279. .get(0);
  6280. if (!pick) {
  6281. console.info("Last visible video no longer exists");
  6282. pick = $('#remoteVideos>span[id!="mixedstream"]>video').get(0);
  6283. if (!pick || !APP.RTC.getVideoSrc(pick)) {
  6284. // Try local video
  6285. console.info("Fallback to local video...");
  6286. pick = $('#remoteVideos>span>span>video').get(0);
  6287. }
  6288. }
  6289. // mute if localvideo
  6290. if (pick) {
  6291. var container = pick.parentNode;
  6292. var jid = null;
  6293. if(container)
  6294. {
  6295. if(container.id == "localVideoWrapper")
  6296. {
  6297. jid = APP.xmpp.myResource();
  6298. }
  6299. else
  6300. {
  6301. jid = VideoLayout.getPeerContainerResourceJid(container);
  6302. }
  6303. }
  6304. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(pick), pick.volume, jid);
  6305. } else {
  6306. console.warn("Failed to elect large video");
  6307. }
  6308. }
  6309. };
  6310. my.onRemoteStreamAdded = function (stream) {
  6311. var container;
  6312. var remotes = document.getElementById('remoteVideos');
  6313. if (stream.peerjid) {
  6314. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  6315. container = document.getElementById(
  6316. 'participant_' + Strophe.getResourceFromJid(stream.peerjid));
  6317. } else {
  6318. var id = stream.getOriginalStream().id;
  6319. if (id !== 'mixedmslabel'
  6320. // FIXME: default stream is added always with new focus
  6321. // (to be investigated)
  6322. && id !== 'default') {
  6323. console.error('can not associate stream',
  6324. id,
  6325. 'with a participant');
  6326. // We don't want to add it here since it will cause troubles
  6327. return;
  6328. }
  6329. // FIXME: for the mixed ms we dont need a video -- currently
  6330. container = document.createElement('span');
  6331. container.id = 'mixedstream';
  6332. container.className = 'videocontainer';
  6333. remotes.appendChild(container);
  6334. UIUtil.playSoundNotification('userJoined');
  6335. }
  6336. if (container) {
  6337. VideoLayout.addRemoteStreamElement( container,
  6338. stream.sid,
  6339. stream.getOriginalStream(),
  6340. stream.peerjid,
  6341. stream.ssrc);
  6342. }
  6343. }
  6344. my.getLargeVideoState = function () {
  6345. return largeVideoState;
  6346. };
  6347. /**
  6348. * Updates the large video with the given new video source.
  6349. */
  6350. my.updateLargeVideo = function(newSrc, vol, resourceJid) {
  6351. console.log('hover in', newSrc);
  6352. if (APP.RTC.getVideoSrc($('#largeVideo')[0]) !== newSrc) {
  6353. $('#activeSpeaker').css('visibility', 'hidden');
  6354. // Due to the simulcast the localVideoSrc may have changed when the
  6355. // fadeOut event triggers. In that case the getJidFromVideoSrc and
  6356. // isVideoSrcDesktop methods will not function correctly.
  6357. //
  6358. // Also, again due to the simulcast, the updateLargeVideo method can
  6359. // be called multiple times almost simultaneously. Therefore, we
  6360. // store the state here and update only once.
  6361. largeVideoState.newSrc = newSrc;
  6362. largeVideoState.isVisible = $('#largeVideo').is(':visible');
  6363. largeVideoState.isDesktop = APP.RTC.isVideoSrcDesktop(resourceJid);
  6364. if(largeVideoState.userResourceJid) {
  6365. largeVideoState.oldResourceJid = largeVideoState.userResourceJid;
  6366. } else {
  6367. largeVideoState.oldResourceJid = null;
  6368. }
  6369. largeVideoState.userResourceJid = resourceJid;
  6370. // Screen stream is already rotated
  6371. largeVideoState.flipX = (newSrc === localVideoSrc) && flipXLocalVideo;
  6372. var userChanged = false;
  6373. if (largeVideoState.oldResourceJid !== largeVideoState.userResourceJid) {
  6374. userChanged = true;
  6375. // we want the notification to trigger even if userJid is undefined,
  6376. // or null.
  6377. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT,
  6378. largeVideoState.userResourceJid);
  6379. }
  6380. if (!largeVideoState.updateInProgress) {
  6381. largeVideoState.updateInProgress = true;
  6382. var doUpdate = function () {
  6383. Avatar.updateActiveSpeakerAvatarSrc(
  6384. APP.xmpp.findJidFromResource(
  6385. largeVideoState.userResourceJid));
  6386. if (!userChanged && largeVideoState.preload &&
  6387. largeVideoState.preload !== null &&
  6388. APP.RTC.getVideoSrc($(largeVideoState.preload)[0]) === newSrc)
  6389. {
  6390. console.info('Switching to preloaded video');
  6391. var attributes = $('#largeVideo').prop("attributes");
  6392. // loop through largeVideo attributes and apply them on
  6393. // preload.
  6394. $.each(attributes, function () {
  6395. if (this.name !== 'id' && this.name !== 'src') {
  6396. largeVideoState.preload.attr(this.name, this.value);
  6397. }
  6398. });
  6399. largeVideoState.preload.appendTo($('#largeVideoContainer'));
  6400. $('#largeVideo').attr('id', 'previousLargeVideo');
  6401. largeVideoState.preload.attr('id', 'largeVideo');
  6402. $('#previousLargeVideo').remove();
  6403. largeVideoState.preload.on('loadedmetadata', function (e) {
  6404. currentVideoWidth = this.videoWidth;
  6405. currentVideoHeight = this.videoHeight;
  6406. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  6407. });
  6408. largeVideoState.preload = null;
  6409. largeVideoState.preload_ssrc = 0;
  6410. } else {
  6411. APP.RTC.setVideoSrc($('#largeVideo')[0], largeVideoState.newSrc);
  6412. }
  6413. var videoTransform = document.getElementById('largeVideo')
  6414. .style.webkitTransform;
  6415. if (largeVideoState.flipX && videoTransform !== 'scaleX(-1)') {
  6416. document.getElementById('largeVideo').style.webkitTransform
  6417. = "scaleX(-1)";
  6418. }
  6419. else if (!largeVideoState.flipX && videoTransform === 'scaleX(-1)') {
  6420. document.getElementById('largeVideo').style.webkitTransform
  6421. = "none";
  6422. }
  6423. // Change the way we'll be measuring and positioning large video
  6424. VideoLayout.getVideoSize = largeVideoState.isDesktop
  6425. ? getDesktopVideoSize
  6426. : getCameraVideoSize;
  6427. VideoLayout.getVideoPosition = largeVideoState.isDesktop
  6428. ? getDesktopVideoPosition
  6429. : getCameraVideoPosition;
  6430. // Only if the large video is currently visible.
  6431. // Disable previous dominant speaker video.
  6432. if (largeVideoState.oldResourceJid) {
  6433. VideoLayout.enableDominantSpeaker(
  6434. largeVideoState.oldResourceJid,
  6435. false);
  6436. }
  6437. // Enable new dominant speaker in the remote videos section.
  6438. if (largeVideoState.userResourceJid) {
  6439. VideoLayout.enableDominantSpeaker(
  6440. largeVideoState.userResourceJid,
  6441. true);
  6442. }
  6443. if (userChanged && largeVideoState.isVisible) {
  6444. // using "this" should be ok because we're called
  6445. // from within the fadeOut event.
  6446. $(this).fadeIn(300);
  6447. }
  6448. if(userChanged) {
  6449. Avatar.showUserAvatar(
  6450. APP.xmpp.findJidFromResource(
  6451. largeVideoState.oldResourceJid));
  6452. }
  6453. largeVideoState.updateInProgress = false;
  6454. };
  6455. if (userChanged) {
  6456. $('#largeVideo').fadeOut(300, doUpdate);
  6457. } else {
  6458. doUpdate();
  6459. }
  6460. }
  6461. } else {
  6462. Avatar.showUserAvatar(
  6463. APP.xmpp.findJidFromResource(
  6464. largeVideoState.userResourceJid));
  6465. }
  6466. };
  6467. my.handleVideoThumbClicked = function(videoSrc,
  6468. noPinnedEndpointChangedEvent,
  6469. resourceJid) {
  6470. // Restore style for previously focused video
  6471. var oldContainer = null;
  6472. if(focusedVideoInfo) {
  6473. var focusResourceJid = focusedVideoInfo.resourceJid;
  6474. oldContainer = getParticipantContainer(focusResourceJid);
  6475. }
  6476. if (oldContainer) {
  6477. oldContainer.removeClass("videoContainerFocused");
  6478. }
  6479. // Unlock current focused.
  6480. if (focusedVideoInfo && focusedVideoInfo.src === videoSrc)
  6481. {
  6482. focusedVideoInfo = null;
  6483. var dominantSpeakerVideo = null;
  6484. // Enable the currently set dominant speaker.
  6485. if (currentDominantSpeaker) {
  6486. dominantSpeakerVideo
  6487. = $('#participant_' + currentDominantSpeaker + '>video')
  6488. .get(0);
  6489. if (dominantSpeakerVideo) {
  6490. VideoLayout.updateLargeVideo(
  6491. APP.RTC.getVideoSrc(dominantSpeakerVideo),
  6492. 1,
  6493. currentDominantSpeaker);
  6494. }
  6495. }
  6496. if (!noPinnedEndpointChangedEvent) {
  6497. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  6498. }
  6499. return;
  6500. }
  6501. // Lock new video
  6502. focusedVideoInfo = {
  6503. src: videoSrc,
  6504. resourceJid: resourceJid
  6505. };
  6506. // Update focused/pinned interface.
  6507. if (resourceJid)
  6508. {
  6509. var container = getParticipantContainer(resourceJid);
  6510. container.addClass("videoContainerFocused");
  6511. if (!noPinnedEndpointChangedEvent) {
  6512. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  6513. }
  6514. }
  6515. if ($('#largeVideo').attr('src') === videoSrc &&
  6516. VideoLayout.isLargeVideoOnTop()) {
  6517. return;
  6518. }
  6519. // Triggers a "video.selected" event. The "false" parameter indicates
  6520. // this isn't a prezi.
  6521. $(document).trigger("video.selected", [false]);
  6522. VideoLayout.updateLargeVideo(videoSrc, 1, resourceJid);
  6523. $('audio').each(function (idx, el) {
  6524. if (el.id.indexOf('mixedmslabel') !== -1) {
  6525. el.volume = 0;
  6526. el.volume = 1;
  6527. }
  6528. });
  6529. };
  6530. /**
  6531. * Positions the large video.
  6532. *
  6533. * @param videoWidth the stream video width
  6534. * @param videoHeight the stream video height
  6535. */
  6536. my.positionLarge = function (videoWidth, videoHeight) {
  6537. var videoSpaceWidth = $('#videospace').width();
  6538. var videoSpaceHeight = window.innerHeight;
  6539. var videoSize = VideoLayout.getVideoSize(videoWidth,
  6540. videoHeight,
  6541. videoSpaceWidth,
  6542. videoSpaceHeight);
  6543. var largeVideoWidth = videoSize[0];
  6544. var largeVideoHeight = videoSize[1];
  6545. var videoPosition = VideoLayout.getVideoPosition(largeVideoWidth,
  6546. largeVideoHeight,
  6547. videoSpaceWidth,
  6548. videoSpaceHeight);
  6549. var horizontalIndent = videoPosition[0];
  6550. var verticalIndent = videoPosition[1];
  6551. positionVideo($('#largeVideo'),
  6552. largeVideoWidth,
  6553. largeVideoHeight,
  6554. horizontalIndent, verticalIndent);
  6555. };
  6556. /**
  6557. * Shows/hides the large video.
  6558. */
  6559. my.setLargeVideoVisible = function(isVisible) {
  6560. var resourceJid = largeVideoState.userResourceJid;
  6561. if (isVisible) {
  6562. $('#largeVideo').css({visibility: 'visible'});
  6563. $('.watermark').css({visibility: 'visible'});
  6564. VideoLayout.enableDominantSpeaker(resourceJid, true);
  6565. }
  6566. else {
  6567. $('#largeVideo').css({visibility: 'hidden'});
  6568. $('#activeSpeaker').css('visibility', 'hidden');
  6569. $('.watermark').css({visibility: 'hidden'});
  6570. VideoLayout.enableDominantSpeaker(resourceJid, false);
  6571. if(focusedVideoInfo) {
  6572. var focusResourceJid = focusedVideoInfo.resourceJid;
  6573. var oldContainer = getParticipantContainer(focusResourceJid);
  6574. if (oldContainer && oldContainer.length > 0) {
  6575. oldContainer.removeClass("videoContainerFocused");
  6576. }
  6577. focusedVideoInfo = null;
  6578. if(focusResourceJid) {
  6579. Avatar.showUserAvatar(
  6580. APP.xmpp.findJidFromResource(focusResourceJid));
  6581. }
  6582. }
  6583. }
  6584. };
  6585. /**
  6586. * Indicates if the large video is currently visible.
  6587. *
  6588. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  6589. */
  6590. my.isLargeVideoVisible = function() {
  6591. return $('#largeVideo').is(':visible');
  6592. };
  6593. my.isLargeVideoOnTop = function () {
  6594. var Etherpad = require("../etherpad/Etherpad");
  6595. var Prezi = require("../prezi/Prezi");
  6596. return !Prezi.isPresentationVisible() && !Etherpad.isVisible();
  6597. };
  6598. /**
  6599. * Checks if container for participant identified by given peerJid exists
  6600. * in the document and creates it eventually.
  6601. *
  6602. * @param peerJid peer Jid to check.
  6603. * @param userId user email or id for setting the avatar
  6604. *
  6605. * @return Returns <tt>true</tt> if the peer container exists,
  6606. * <tt>false</tt> - otherwise
  6607. */
  6608. my.ensurePeerContainerExists = function(peerJid, userId) {
  6609. ContactList.ensureAddContact(peerJid, userId);
  6610. var resourceJid = Strophe.getResourceFromJid(peerJid);
  6611. var videoSpanId = 'participant_' + resourceJid;
  6612. if (!$('#' + videoSpanId).length) {
  6613. var container =
  6614. VideoLayout.addRemoteVideoContainer(peerJid, videoSpanId, userId);
  6615. Avatar.setUserAvatar(peerJid, userId);
  6616. // Set default display name.
  6617. setDisplayName(videoSpanId);
  6618. VideoLayout.connectionIndicators[videoSpanId] =
  6619. new ConnectionIndicator(container, peerJid, VideoLayout);
  6620. var nickfield = document.createElement('span');
  6621. nickfield.className = "nick";
  6622. nickfield.appendChild(document.createTextNode(resourceJid));
  6623. container.appendChild(nickfield);
  6624. // In case this is not currently in the last n we don't show it.
  6625. if (localLastNCount
  6626. && localLastNCount > 0
  6627. && $('#remoteVideos>span').length >= localLastNCount + 2) {
  6628. showPeerContainer(resourceJid, 'hide');
  6629. }
  6630. else
  6631. VideoLayout.resizeThumbnails();
  6632. }
  6633. };
  6634. my.addRemoteVideoContainer = function(peerJid, spanId) {
  6635. var container = document.createElement('span');
  6636. container.id = spanId;
  6637. container.className = 'videocontainer';
  6638. var remotes = document.getElementById('remoteVideos');
  6639. remotes.appendChild(container);
  6640. // If the peerJid is null then this video span couldn't be directly
  6641. // associated with a participant (this could happen in the case of prezi).
  6642. if (APP.xmpp.isModerator() && peerJid !== null)
  6643. addRemoteVideoMenu(peerJid, container);
  6644. AudioLevels.updateAudioLevelCanvas(peerJid, VideoLayout);
  6645. return container;
  6646. };
  6647. /**
  6648. * Creates an audio or video stream element.
  6649. */
  6650. my.createStreamElement = function (sid, stream) {
  6651. var isVideo = stream.getVideoTracks().length > 0;
  6652. var element = isVideo
  6653. ? document.createElement('video')
  6654. : document.createElement('audio');
  6655. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_')
  6656. + sid + '_' + APP.RTC.getStreamID(stream);
  6657. element.id = id;
  6658. element.autoplay = true;
  6659. element.oncontextmenu = function () { return false; };
  6660. return element;
  6661. };
  6662. my.addRemoteStreamElement
  6663. = function (container, sid, stream, peerJid, thessrc) {
  6664. var newElementId = null;
  6665. var isVideo = stream.getVideoTracks().length > 0;
  6666. if (container) {
  6667. var streamElement = VideoLayout.createStreamElement(sid, stream);
  6668. newElementId = streamElement.id;
  6669. container.appendChild(streamElement);
  6670. var sel = $('#' + newElementId);
  6671. sel.hide();
  6672. // If the container is currently visible we attach the stream.
  6673. if (!isVideo
  6674. || (container.offsetParent !== null && isVideo)) {
  6675. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  6676. APP.RTC.attachMediaStream(sel, videoStream);
  6677. if (isVideo)
  6678. waitForRemoteVideo(sel, thessrc, stream, peerJid);
  6679. }
  6680. stream.onended = function () {
  6681. console.log('stream ended', this);
  6682. VideoLayout.removeRemoteStreamElement(
  6683. stream, isVideo, container);
  6684. // NOTE(gp) it seems that under certain circumstances, the
  6685. // onended event is not fired and thus the contact list is not
  6686. // updated.
  6687. //
  6688. // The onended event of a stream should be fired when the SSRCs
  6689. // corresponding to that stream are removed from the SDP; but
  6690. // this doesn't seem to always be the case, resulting in ghost
  6691. // contacts.
  6692. //
  6693. // In an attempt to fix the ghost contacts problem, I'm moving
  6694. // the removeContact() method call in app.js, inside the
  6695. // 'muc.left' event handler.
  6696. //if (peerJid)
  6697. // ContactList.removeContact(peerJid);
  6698. };
  6699. // Add click handler.
  6700. container.onclick = function (event) {
  6701. /*
  6702. * FIXME It turns out that videoThumb may not exist (if there is
  6703. * no actual video).
  6704. */
  6705. var videoThumb = $('#' + container.id + '>video').get(0);
  6706. if (videoThumb) {
  6707. VideoLayout.handleVideoThumbClicked(
  6708. APP.RTC.getVideoSrc(videoThumb),
  6709. false,
  6710. Strophe.getResourceFromJid(peerJid));
  6711. }
  6712. event.stopPropagation();
  6713. event.preventDefault();
  6714. return false;
  6715. };
  6716. // Add hover handler
  6717. $(container).hover(
  6718. function() {
  6719. VideoLayout.showDisplayName(container.id, true);
  6720. },
  6721. function() {
  6722. var videoSrc = null;
  6723. if ($('#' + container.id + '>video')
  6724. && $('#' + container.id + '>video').length > 0) {
  6725. videoSrc = APP.RTC.getVideoSrc($('#' + container.id + '>video').get(0));
  6726. }
  6727. // If the video has been "pinned" by the user we want to
  6728. // keep the display name on place.
  6729. if (!VideoLayout.isLargeVideoVisible()
  6730. || videoSrc !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  6731. VideoLayout.showDisplayName(container.id, false);
  6732. }
  6733. );
  6734. }
  6735. return newElementId;
  6736. };
  6737. /**
  6738. * Removes the remote stream element corresponding to the given stream and
  6739. * parent container.
  6740. *
  6741. * @param stream the stream
  6742. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  6743. * @param container
  6744. */
  6745. my.removeRemoteStreamElement = function (stream, isVideo, container) {
  6746. if (!container)
  6747. return;
  6748. var select = null;
  6749. var removedVideoSrc = null;
  6750. if (isVideo) {
  6751. select = $('#' + container.id + '>video');
  6752. removedVideoSrc = APP.RTC.getVideoSrc(select.get(0));
  6753. }
  6754. else
  6755. select = $('#' + container.id + '>audio');
  6756. // Mark video as removed to cancel waiting loop(if video is removed
  6757. // before has started)
  6758. select.removed = true;
  6759. select.remove();
  6760. var audioCount = $('#' + container.id + '>audio').length;
  6761. var videoCount = $('#' + container.id + '>video').length;
  6762. if (!audioCount && !videoCount) {
  6763. console.log("Remove whole user", container.id);
  6764. if(VideoLayout.connectionIndicators[container.id])
  6765. VideoLayout.connectionIndicators[container.id].remove();
  6766. // Remove whole container
  6767. container.remove();
  6768. UIUtil.playSoundNotification('userLeft');
  6769. VideoLayout.resizeThumbnails();
  6770. }
  6771. if (removedVideoSrc)
  6772. VideoLayout.updateRemovedVideo(removedVideoSrc);
  6773. };
  6774. /**
  6775. * Show/hide peer container for the given resourceJid.
  6776. */
  6777. function showPeerContainer(resourceJid, state) {
  6778. var peerContainer = $('#participant_' + resourceJid);
  6779. if (!peerContainer)
  6780. return;
  6781. var isHide = state === 'hide';
  6782. var resizeThumbnails = false;
  6783. if (!isHide) {
  6784. if (!peerContainer.is(':visible')) {
  6785. resizeThumbnails = true;
  6786. peerContainer.show();
  6787. }
  6788. var jid = APP.xmpp.findJidFromResource(resourceJid);
  6789. if (state == 'show')
  6790. {
  6791. // peerContainer.css('-webkit-filter', '');
  6792. Avatar.showUserAvatar(jid, false);
  6793. }
  6794. else // if (state == 'avatar')
  6795. {
  6796. // peerContainer.css('-webkit-filter', 'grayscale(100%)');
  6797. Avatar.showUserAvatar(jid, true);
  6798. }
  6799. }
  6800. else if (peerContainer.is(':visible') && isHide)
  6801. {
  6802. resizeThumbnails = true;
  6803. peerContainer.hide();
  6804. if(VideoLayout.connectionIndicators['participant_' + resourceJid])
  6805. VideoLayout.connectionIndicators['participant_' + resourceJid].hide();
  6806. }
  6807. if (resizeThumbnails) {
  6808. VideoLayout.resizeThumbnails();
  6809. }
  6810. // We want to be able to pin a participant from the contact list, even
  6811. // if he's not in the lastN set!
  6812. // ContactList.setClickable(resourceJid, !isHide);
  6813. };
  6814. my.inputDisplayNameHandler = function (name) {
  6815. NicknameHandler.setNickname(name);
  6816. if (!$('#localDisplayName').is(":visible")) {
  6817. if (NicknameHandler.getNickname())
  6818. $('#localDisplayName').text(NicknameHandler.getNickname() + " (me)");
  6819. else
  6820. $('#localDisplayName')
  6821. .text(interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  6822. $('#localDisplayName').show();
  6823. }
  6824. $('#editDisplayName').hide();
  6825. };
  6826. /**
  6827. * Shows/hides the display name on the remote video.
  6828. * @param videoSpanId the identifier of the video span element
  6829. * @param isShow indicates if the display name should be shown or hidden
  6830. */
  6831. my.showDisplayName = function(videoSpanId, isShow) {
  6832. var nameSpan = $('#' + videoSpanId + '>span.displayname').get(0);
  6833. if (isShow) {
  6834. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  6835. nameSpan.setAttribute("style", "display:inline-block;");
  6836. }
  6837. else {
  6838. if (nameSpan)
  6839. nameSpan.setAttribute("style", "display:none;");
  6840. }
  6841. };
  6842. /**
  6843. * Shows the presence status message for the given video.
  6844. */
  6845. my.setPresenceStatus = function (videoSpanId, statusMsg) {
  6846. if (!$('#' + videoSpanId).length) {
  6847. // No container
  6848. return;
  6849. }
  6850. var statusSpan = $('#' + videoSpanId + '>span.status');
  6851. if (!statusSpan.length) {
  6852. //Add status span
  6853. statusSpan = document.createElement('span');
  6854. statusSpan.className = 'status';
  6855. statusSpan.id = videoSpanId + '_status';
  6856. $('#' + videoSpanId)[0].appendChild(statusSpan);
  6857. statusSpan = $('#' + videoSpanId + '>span.status');
  6858. }
  6859. // Display status
  6860. if (statusMsg && statusMsg.length) {
  6861. $('#' + videoSpanId + '_status').text(statusMsg);
  6862. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  6863. }
  6864. else {
  6865. // Hide
  6866. statusSpan.get(0).setAttribute("style", "display:none;");
  6867. }
  6868. };
  6869. /**
  6870. * Shows a visual indicator for the moderator of the conference.
  6871. */
  6872. my.showModeratorIndicator = function () {
  6873. var isModerator = APP.xmpp.isModerator();
  6874. if (isModerator) {
  6875. var indicatorSpan = $('#localVideoContainer .focusindicator');
  6876. if (indicatorSpan.children().length === 0)
  6877. {
  6878. createModeratorIndicatorElement(indicatorSpan[0]);
  6879. //translates text in focus indicator
  6880. APP.translation.translateElement($('#localVideoContainer .focusindicator'));
  6881. }
  6882. }
  6883. var members = APP.xmpp.getMembers();
  6884. Object.keys(members).forEach(function (jid) {
  6885. if (Strophe.getResourceFromJid(jid) === 'focus') {
  6886. // Skip server side focus
  6887. return;
  6888. }
  6889. var resourceJid = Strophe.getResourceFromJid(jid);
  6890. var videoSpanId = 'participant_' + resourceJid;
  6891. var videoContainer = document.getElementById(videoSpanId);
  6892. if (!videoContainer) {
  6893. console.error("No video container for " + jid);
  6894. return;
  6895. }
  6896. var member = members[jid];
  6897. if (member.role === 'moderator') {
  6898. // Remove menu if peer is moderator
  6899. var menuSpan = $('#' + videoSpanId + '>span.remotevideomenu');
  6900. if (menuSpan.length) {
  6901. removeRemoteVideoMenu(videoSpanId);
  6902. }
  6903. // Show moderator indicator
  6904. var indicatorSpan
  6905. = $('#' + videoSpanId + ' .focusindicator');
  6906. if (!indicatorSpan || indicatorSpan.length === 0) {
  6907. indicatorSpan = document.createElement('span');
  6908. indicatorSpan.className = 'focusindicator';
  6909. videoContainer.appendChild(indicatorSpan);
  6910. createModeratorIndicatorElement(indicatorSpan);
  6911. //translates text in focus indicators
  6912. APP.translation.translateElement($('#' + videoSpanId + ' .focusindicator'));
  6913. }
  6914. } else if (isModerator) {
  6915. // We are moderator, but user is not - add menu
  6916. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  6917. addRemoteVideoMenu(
  6918. jid,
  6919. document.getElementById('participant_' + resourceJid));
  6920. }
  6921. }
  6922. });
  6923. };
  6924. /**
  6925. * Shows video muted indicator over small videos.
  6926. */
  6927. my.showVideoIndicator = function(videoSpanId, isMuted) {
  6928. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  6929. if (isMuted === 'false') {
  6930. if (videoMutedSpan.length > 0) {
  6931. videoMutedSpan.remove();
  6932. }
  6933. }
  6934. else {
  6935. if(videoMutedSpan.length == 0) {
  6936. videoMutedSpan = document.createElement('span');
  6937. videoMutedSpan.className = 'videoMuted';
  6938. $('#' + videoSpanId)[0].appendChild(videoMutedSpan);
  6939. var mutedIndicator = document.createElement('i');
  6940. mutedIndicator.className = 'icon-camera-disabled';
  6941. UIUtil.setTooltip(mutedIndicator,
  6942. "videothumbnail.videomute",
  6943. "top");
  6944. videoMutedSpan.appendChild(mutedIndicator);
  6945. //translate texts for muted indicator
  6946. APP.translation.translateElement($('#' + videoSpanId + " > span > i"));
  6947. }
  6948. VideoLayout.updateMutePosition(videoSpanId);
  6949. }
  6950. };
  6951. my.updateMutePosition = function (videoSpanId) {
  6952. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  6953. var connectionIndicator = $('#' + videoSpanId + '>div.connectionindicator');
  6954. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  6955. if(connectionIndicator.length > 0
  6956. && connectionIndicator[0].style.display != "none") {
  6957. audioMutedSpan.css({right: "23px"});
  6958. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  6959. }
  6960. else
  6961. {
  6962. audioMutedSpan.css({right: "0px"});
  6963. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  6964. }
  6965. }
  6966. /**
  6967. * Shows audio muted indicator over small videos.
  6968. * @param {string} isMuted
  6969. */
  6970. my.showAudioIndicator = function(videoSpanId, isMuted) {
  6971. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  6972. if (isMuted === 'false') {
  6973. if (audioMutedSpan.length > 0) {
  6974. audioMutedSpan.popover('hide');
  6975. audioMutedSpan.remove();
  6976. }
  6977. }
  6978. else {
  6979. if(audioMutedSpan.length == 0 ) {
  6980. audioMutedSpan = document.createElement('span');
  6981. audioMutedSpan.className = 'audioMuted';
  6982. UIUtil.setTooltip(audioMutedSpan,
  6983. "videothumbnail.mute",
  6984. "top");
  6985. $('#' + videoSpanId)[0].appendChild(audioMutedSpan);
  6986. APP.translation.translateElement($('#' + videoSpanId + " > span"));
  6987. var mutedIndicator = document.createElement('i');
  6988. mutedIndicator.className = 'icon-mic-disabled';
  6989. audioMutedSpan.appendChild(mutedIndicator);
  6990. }
  6991. VideoLayout.updateMutePosition(videoSpanId);
  6992. }
  6993. };
  6994. /*
  6995. * Shows or hides the audio muted indicator over the local thumbnail video.
  6996. * @param {boolean} isMuted
  6997. */
  6998. my.showLocalAudioIndicator = function(isMuted) {
  6999. VideoLayout.showAudioIndicator('localVideoContainer', isMuted.toString());
  7000. };
  7001. /**
  7002. * Resizes the large video container.
  7003. */
  7004. my.resizeLargeVideoContainer = function () {
  7005. Chat.resizeChat();
  7006. var availableHeight = window.innerHeight;
  7007. var availableWidth = UIUtil.getAvailableVideoWidth();
  7008. if (availableWidth < 0 || availableHeight < 0) return;
  7009. $('#videospace').width(availableWidth);
  7010. $('#videospace').height(availableHeight);
  7011. $('#largeVideoContainer').width(availableWidth);
  7012. $('#largeVideoContainer').height(availableHeight);
  7013. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  7014. var top = availableHeight / 2 - avatarSize / 4 * 3;
  7015. $('#activeSpeaker').css('top', top);
  7016. VideoLayout.resizeThumbnails();
  7017. };
  7018. /**
  7019. * Resizes thumbnails.
  7020. */
  7021. my.resizeThumbnails = function() {
  7022. var videoSpaceWidth = $('#remoteVideos').width();
  7023. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  7024. var width = thumbnailSize[0];
  7025. var height = thumbnailSize[1];
  7026. // size videos so that while keeping AR and max height, we have a
  7027. // nice fit
  7028. $('#remoteVideos').height(height);
  7029. $('#remoteVideos>span').width(width);
  7030. $('#remoteVideos>span').height(height);
  7031. $('.userAvatar').css('left', (width - height) / 2);
  7032. $(document).trigger("remotevideo.resized", [width, height]);
  7033. };
  7034. /**
  7035. * Enables the dominant speaker UI.
  7036. *
  7037. * @param resourceJid the jid indicating the video element to
  7038. * activate/deactivate
  7039. * @param isEnable indicates if the dominant speaker should be enabled or
  7040. * disabled
  7041. */
  7042. my.enableDominantSpeaker = function(resourceJid, isEnable) {
  7043. var videoSpanId = null;
  7044. var videoContainerId = null;
  7045. if (resourceJid
  7046. === APP.xmpp.myResource()) {
  7047. videoSpanId = 'localVideoWrapper';
  7048. videoContainerId = 'localVideoContainer';
  7049. }
  7050. else {
  7051. videoSpanId = 'participant_' + resourceJid;
  7052. videoContainerId = videoSpanId;
  7053. }
  7054. var displayName = resourceJid;
  7055. var nameSpan = $('#' + videoContainerId + '>span.displayname');
  7056. if (nameSpan.length > 0)
  7057. displayName = nameSpan.html();
  7058. console.log("UI enable dominant speaker",
  7059. displayName,
  7060. resourceJid,
  7061. isEnable);
  7062. videoSpan = document.getElementById(videoContainerId);
  7063. if (!videoSpan) {
  7064. return;
  7065. }
  7066. var video = $('#' + videoSpanId + '>video');
  7067. if (video && video.length > 0) {
  7068. if (isEnable) {
  7069. var isLargeVideoVisible = VideoLayout.isLargeVideoOnTop();
  7070. VideoLayout.showDisplayName(videoContainerId, isLargeVideoVisible);
  7071. if (!videoSpan.classList.contains("dominantspeaker"))
  7072. videoSpan.classList.add("dominantspeaker");
  7073. }
  7074. else {
  7075. VideoLayout.showDisplayName(videoContainerId, false);
  7076. if (videoSpan.classList.contains("dominantspeaker"))
  7077. videoSpan.classList.remove("dominantspeaker");
  7078. }
  7079. Avatar.showUserAvatar(
  7080. APP.xmpp.findJidFromResource(resourceJid));
  7081. }
  7082. };
  7083. /**
  7084. * Calculates the thumbnail size.
  7085. *
  7086. * @param videoSpaceWidth the width of the video space
  7087. */
  7088. my.calculateThumbnailSize = function (videoSpaceWidth) {
  7089. // Calculate the available height, which is the inner window height minus
  7090. // 39px for the header minus 2px for the delimiter lines on the top and
  7091. // bottom of the large video, minus the 36px space inside the remoteVideos
  7092. // container used for highlighting shadow.
  7093. var availableHeight = 100;
  7094. var numvids = $('#remoteVideos>span:visible').length;
  7095. if (localLastNCount && localLastNCount > 0) {
  7096. numvids = Math.min(localLastNCount + 1, numvids);
  7097. }
  7098. // Remove the 3px borders arround videos and border around the remote
  7099. // videos area and the 4 pixels between the local video and the others
  7100. //TODO: Find out where the 4 pixels come from and remove them
  7101. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  7102. var availableWidth = availableWinWidth / numvids;
  7103. var aspectRatio = 16.0 / 9.0;
  7104. var maxHeight = Math.min(160, availableHeight);
  7105. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  7106. if (availableHeight < availableWidth / aspectRatio) {
  7107. availableWidth = Math.floor(availableHeight * aspectRatio);
  7108. }
  7109. return [availableWidth, availableHeight];
  7110. };
  7111. /**
  7112. * Updates the remote video menu.
  7113. *
  7114. * @param jid the jid indicating the video for which we're adding a menu.
  7115. * @param isMuted indicates the current mute state
  7116. */
  7117. my.updateRemoteVideoMenu = function(jid, isMuted) {
  7118. var muteMenuItem
  7119. = $('#remote_popupmenu_'
  7120. + Strophe.getResourceFromJid(jid)
  7121. + '>li>a.mutelink');
  7122. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  7123. if (muteMenuItem.length) {
  7124. var muteLink = muteMenuItem.get(0);
  7125. if (isMuted === 'true') {
  7126. muteLink.innerHTML = mutedIndicator + ' Muted';
  7127. muteLink.className = 'mutelink disabled';
  7128. }
  7129. else {
  7130. muteLink.innerHTML = mutedIndicator + ' Mute';
  7131. muteLink.className = 'mutelink';
  7132. }
  7133. }
  7134. };
  7135. /**
  7136. * Returns the current dominant speaker resource jid.
  7137. */
  7138. my.getDominantSpeakerResourceJid = function () {
  7139. return currentDominantSpeaker;
  7140. };
  7141. /**
  7142. * Returns the corresponding resource jid to the given peer container
  7143. * DOM element.
  7144. *
  7145. * @return the corresponding resource jid to the given peer container
  7146. * DOM element
  7147. */
  7148. my.getPeerContainerResourceJid = function (containerElement) {
  7149. var i = containerElement.id.indexOf('participant_');
  7150. if (i >= 0)
  7151. return containerElement.id.substring(i + 12);
  7152. };
  7153. /**
  7154. * On contact list item clicked.
  7155. */
  7156. $(ContactList).bind('contactclicked', function(event, jid) {
  7157. if (!jid) {
  7158. return;
  7159. }
  7160. var resource = Strophe.getResourceFromJid(jid);
  7161. var videoContainer = $("#participant_" + resource);
  7162. if (videoContainer.length > 0) {
  7163. var videoThumb = $('video', videoContainer).get(0);
  7164. // It is not always the case that a videoThumb exists (if there is
  7165. // no actual video).
  7166. if (videoThumb) {
  7167. if (videoThumb.src && videoThumb.src != '') {
  7168. // We have a video src, great! Let's update the large video
  7169. // now.
  7170. VideoLayout.handleVideoThumbClicked(
  7171. videoThumb.src,
  7172. false,
  7173. Strophe.getResourceFromJid(jid));
  7174. } else {
  7175. // If we don't have a video src for jid, there's absolutely
  7176. // no point in calling handleVideoThumbClicked; Quite
  7177. // simply, it won't work because it needs an src to attach
  7178. // to the large video.
  7179. //
  7180. // Instead, we trigger the pinned endpoint changed event to
  7181. // let the bridge adjust its lastN set for myjid and store
  7182. // the pinned user in the lastNPickupJid variable to be
  7183. // picked up later by the lastN changed event handler.
  7184. lastNPickupJid = jid;
  7185. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  7186. Strophe.getResourceFromJid(jid));
  7187. }
  7188. } else if (jid == APP.xmpp.myJid()) {
  7189. $("#localVideoContainer").click();
  7190. }
  7191. }
  7192. });
  7193. /**
  7194. * On audio muted event.
  7195. */
  7196. $(document).bind('audiomuted.muc', function (event, jid, isMuted) {
  7197. /*
  7198. // FIXME: but focus can not mute in this case ? - check
  7199. if (jid === xmpp.myJid()) {
  7200. // The local mute indicator is controlled locally
  7201. return;
  7202. }*/
  7203. var videoSpanId = null;
  7204. if (jid === APP.xmpp.myJid()) {
  7205. videoSpanId = 'localVideoContainer';
  7206. } else {
  7207. VideoLayout.ensurePeerContainerExists(jid);
  7208. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  7209. }
  7210. mutedAudios[jid] = isMuted;
  7211. if (APP.xmpp.isModerator()) {
  7212. VideoLayout.updateRemoteVideoMenu(jid, isMuted);
  7213. }
  7214. if (videoSpanId)
  7215. VideoLayout.showAudioIndicator(videoSpanId, isMuted);
  7216. });
  7217. /**
  7218. * On video muted event.
  7219. */
  7220. $(document).bind('videomuted.muc', function (event, jid, value) {
  7221. var isMuted = (value === "true");
  7222. if(!APP.RTC.muteRemoteVideoStream(jid, isMuted))
  7223. return;
  7224. Avatar.showUserAvatar(jid, isMuted);
  7225. var videoSpanId = null;
  7226. if (jid === APP.xmpp.myJid()) {
  7227. videoSpanId = 'localVideoContainer';
  7228. } else {
  7229. VideoLayout.ensurePeerContainerExists(jid);
  7230. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  7231. }
  7232. if (videoSpanId)
  7233. VideoLayout.showVideoIndicator(videoSpanId, value);
  7234. });
  7235. /**
  7236. * Display name changed.
  7237. */
  7238. my.onDisplayNameChanged =
  7239. function (jid, displayName, status) {
  7240. if (jid === 'localVideoContainer'
  7241. || jid === APP.xmpp.myJid()) {
  7242. setDisplayName('localVideoContainer',
  7243. displayName);
  7244. } else {
  7245. VideoLayout.ensurePeerContainerExists(jid);
  7246. setDisplayName(
  7247. 'participant_' + Strophe.getResourceFromJid(jid),
  7248. displayName,
  7249. status);
  7250. }
  7251. };
  7252. /**
  7253. * On dominant speaker changed event.
  7254. */
  7255. my.onDominantSpeakerChanged = function (resourceJid) {
  7256. // We ignore local user events.
  7257. if (resourceJid
  7258. === APP.xmpp.myResource())
  7259. return;
  7260. // Update the current dominant speaker.
  7261. if (resourceJid !== currentDominantSpeaker) {
  7262. var oldSpeakerVideoSpanId = "participant_" + currentDominantSpeaker,
  7263. newSpeakerVideoSpanId = "participant_" + resourceJid;
  7264. if($("#" + oldSpeakerVideoSpanId + ">span.displayname").text() ===
  7265. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME) {
  7266. setDisplayName(oldSpeakerVideoSpanId, null);
  7267. }
  7268. if($("#" + newSpeakerVideoSpanId + ">span.displayname").text() ===
  7269. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME) {
  7270. setDisplayName(newSpeakerVideoSpanId,
  7271. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  7272. }
  7273. currentDominantSpeaker = resourceJid;
  7274. } else {
  7275. return;
  7276. }
  7277. // Obtain container for new dominant speaker.
  7278. var container = document.getElementById(
  7279. 'participant_' + resourceJid);
  7280. // Local video will not have container found, but that's ok
  7281. // since we don't want to switch to local video.
  7282. if (container && !focusedVideoInfo)
  7283. {
  7284. var video = container.getElementsByTagName("video");
  7285. // Update the large video if the video source is already available,
  7286. // otherwise wait for the "videoactive.jingle" event.
  7287. if (video.length && video[0].currentTime > 0)
  7288. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(video[0]), resourceJid);
  7289. }
  7290. };
  7291. /**
  7292. * On last N change event.
  7293. *
  7294. * @param lastNEndpoints the list of last N endpoints
  7295. * @param endpointsEnteringLastN the list currently entering last N
  7296. * endpoints
  7297. */
  7298. my.onLastNEndpointsChanged = function ( lastNEndpoints,
  7299. endpointsEnteringLastN,
  7300. stream) {
  7301. if (lastNCount !== lastNEndpoints.length)
  7302. lastNCount = lastNEndpoints.length;
  7303. lastNEndpointsCache = lastNEndpoints;
  7304. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  7305. //
  7306. // If LastN drops to, say, 2, because of adaptivity, then E should see
  7307. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  7308. // so E sees them. C is only in E's local LastN set.
  7309. //
  7310. // If F starts talking and LastN = 3, then E should see thumbnails for
  7311. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  7312. // enters E's local LastN ejecting C.
  7313. // Increase the local LastN set size, if necessary.
  7314. if (lastNCount > localLastNCount) {
  7315. localLastNCount = lastNCount;
  7316. }
  7317. // Update the local LastN set preserving the order in which the
  7318. // endpoints appeared in the LastN/local LastN set.
  7319. var nextLocalLastNSet = lastNEndpoints.slice(0);
  7320. for (var i = 0; i < localLastNSet.length; i++) {
  7321. if (nextLocalLastNSet.length >= localLastNCount) {
  7322. break;
  7323. }
  7324. var resourceJid = localLastNSet[i];
  7325. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  7326. nextLocalLastNSet.push(resourceJid);
  7327. }
  7328. }
  7329. localLastNSet = nextLocalLastNSet;
  7330. var updateLargeVideo = false;
  7331. // Handle LastN/local LastN changes.
  7332. $('#remoteVideos>span').each(function( index, element ) {
  7333. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  7334. var isReceived = true;
  7335. if (resourceJid
  7336. && lastNEndpoints.indexOf(resourceJid) < 0
  7337. && localLastNSet.indexOf(resourceJid) < 0) {
  7338. console.log("Remove from last N", resourceJid);
  7339. showPeerContainer(resourceJid, 'hide');
  7340. isReceived = false;
  7341. } else if (resourceJid
  7342. && $('#participant_' + resourceJid).is(':visible')
  7343. && lastNEndpoints.indexOf(resourceJid) < 0
  7344. && localLastNSet.indexOf(resourceJid) >= 0) {
  7345. showPeerContainer(resourceJid, 'avatar');
  7346. isReceived = false;
  7347. }
  7348. if (!isReceived) {
  7349. // resourceJid has dropped out of the server side lastN set, so
  7350. // it is no longer being received. If resourceJid was being
  7351. // displayed in the large video we have to switch to another
  7352. // user.
  7353. var largeVideoResource = largeVideoState.userResourceJid;
  7354. if (!updateLargeVideo && resourceJid === largeVideoResource) {
  7355. updateLargeVideo = true;
  7356. }
  7357. }
  7358. });
  7359. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  7360. endpointsEnteringLastN = lastNEndpoints;
  7361. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  7362. endpointsEnteringLastN.forEach(function (resourceJid) {
  7363. var isVisible = $('#participant_' + resourceJid).is(':visible');
  7364. showPeerContainer(resourceJid, 'show');
  7365. if (!isVisible) {
  7366. console.log("Add to last N", resourceJid);
  7367. var jid = APP.xmpp.findJidFromResource(resourceJid);
  7368. var mediaStream = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  7369. var sel = $('#participant_' + resourceJid + '>video');
  7370. var videoStream = APP.simulcast.getReceivingVideoStream(
  7371. mediaStream.stream);
  7372. APP.RTC.attachMediaStream(sel, videoStream);
  7373. if (lastNPickupJid == mediaStream.peerjid) {
  7374. // Clean up the lastN pickup jid.
  7375. lastNPickupJid = null;
  7376. // Don't fire the events again, they've already
  7377. // been fired in the contact list click handler.
  7378. VideoLayout.handleVideoThumbClicked(
  7379. $(sel).attr('src'),
  7380. false,
  7381. Strophe.getResourceFromJid(mediaStream.peerjid));
  7382. updateLargeVideo = false;
  7383. }
  7384. waitForRemoteVideo(sel, mediaStream.ssrc, mediaStream.stream, resourceJid);
  7385. }
  7386. })
  7387. }
  7388. // The endpoint that was being shown in the large video has dropped out
  7389. // of the lastN set and there was no lastN pickup jid. We need to update
  7390. // the large video now.
  7391. if (updateLargeVideo) {
  7392. var resource, container, src;
  7393. var myResource
  7394. = APP.xmpp.myResource();
  7395. // Find out which endpoint to show in the large video.
  7396. for (var i = 0; i < lastNEndpoints.length; i++) {
  7397. resource = lastNEndpoints[i];
  7398. if (!resource || resource === myResource)
  7399. continue;
  7400. container = $("#participant_" + resource);
  7401. if (container.length == 0)
  7402. continue;
  7403. src = $('video', container).attr('src');
  7404. if (!src)
  7405. continue;
  7406. // videoSrcToSsrc needs to be update for this call to succeed.
  7407. VideoLayout.updateLargeVideo(src);
  7408. break;
  7409. }
  7410. }
  7411. };
  7412. my.onSimulcastLayersChanging = function (endpointSimulcastLayers) {
  7413. endpointSimulcastLayers.forEach(function (esl) {
  7414. var resource = esl.endpoint;
  7415. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7416. // then ignore the event (= do not preload anything).
  7417. //
  7418. // The bridge could probably stop sending this message if it's for
  7419. // an endpoint that's not in lastN.
  7420. if (lastNCount != -1
  7421. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7422. return;
  7423. }
  7424. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7425. // Get session and stream from primary ssrc.
  7426. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7427. var sid = res.sid;
  7428. var electedStream = res.stream;
  7429. if (sid && electedStream) {
  7430. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7431. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7432. var preload = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC)) == largeVideoState.userResourceJid);
  7433. if (preload) {
  7434. if (largeVideoState.preload)
  7435. {
  7436. $(largeVideoState.preload).remove();
  7437. }
  7438. console.info('Preloading remote video');
  7439. largeVideoState.preload = $('<video autoplay></video>');
  7440. // ssrcs are unique in an rtp session
  7441. largeVideoState.preload_ssrc = primarySSRC;
  7442. APP.RTC.attachMediaStream(largeVideoState.preload, electedStream)
  7443. }
  7444. } else {
  7445. console.error('Could not find a stream or a session.', sid, electedStream);
  7446. }
  7447. });
  7448. };
  7449. /**
  7450. * On simulcast layers changed event.
  7451. */
  7452. my.onSimulcastLayersChanged = function (endpointSimulcastLayers) {
  7453. endpointSimulcastLayers.forEach(function (esl) {
  7454. var resource = esl.endpoint;
  7455. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7456. // then ignore the event (= do not change large video/thumbnail
  7457. // SRCs).
  7458. //
  7459. // Note that even if we ignore the "changed" event in this event
  7460. // handler, the bridge must continue sending these events because
  7461. // the simulcast code in simulcast.js uses it to know what's going
  7462. // to be streamed by the bridge when/if the endpoint gets back into
  7463. // the lastN set.
  7464. if (lastNCount != -1
  7465. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7466. return;
  7467. }
  7468. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7469. // Get session and stream from primary ssrc.
  7470. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7471. var sid = res.sid;
  7472. var electedStream = res.stream;
  7473. if (sid && electedStream) {
  7474. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7475. console.info('Switching simulcast substream.');
  7476. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7477. var msidParts = msid.split(' ');
  7478. var selRemoteVideo = $(['#', 'remoteVideo_', sid, '_', msidParts[0]].join(''));
  7479. var updateLargeVideo = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC))
  7480. == largeVideoState.userResourceJid);
  7481. var updateFocusedVideoSrc = (focusedVideoInfo && focusedVideoInfo.src && focusedVideoInfo.src != '' &&
  7482. (APP.RTC.getVideoSrc(selRemoteVideo[0]) == focusedVideoInfo.src));
  7483. var electedStreamUrl;
  7484. if (largeVideoState.preload_ssrc == primarySSRC)
  7485. {
  7486. APP.RTC.setVideoSrc(selRemoteVideo[0], APP.RTC.getVideoSrc(largeVideoState.preload[0]));
  7487. }
  7488. else
  7489. {
  7490. if (largeVideoState.preload
  7491. && largeVideoState.preload != null) {
  7492. $(largeVideoState.preload).remove();
  7493. }
  7494. largeVideoState.preload_ssrc = 0;
  7495. APP.RTC.attachMediaStream(selRemoteVideo, electedStream);
  7496. }
  7497. var jid = APP.xmpp.getJidFromSSRC(primarySSRC);
  7498. if (updateLargeVideo) {
  7499. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(selRemoteVideo[0]), null,
  7500. Strophe.getResourceFromJid(jid));
  7501. }
  7502. if (updateFocusedVideoSrc) {
  7503. focusedVideoInfo.src = APP.RTC.getVideoSrc(selRemoteVideo[0]);
  7504. }
  7505. var videoId;
  7506. if(resource == APP.xmpp.myResource())
  7507. {
  7508. videoId = "localVideoContainer";
  7509. }
  7510. else
  7511. {
  7512. videoId = "participant_" + resource;
  7513. }
  7514. var connectionIndicator = VideoLayout.connectionIndicators[videoId];
  7515. if(connectionIndicator)
  7516. connectionIndicator.updatePopoverData();
  7517. } else {
  7518. console.error('Could not find a stream or a sid.', sid, electedStream);
  7519. }
  7520. });
  7521. };
  7522. /**
  7523. * Updates local stats
  7524. * @param percent
  7525. * @param object
  7526. */
  7527. my.updateLocalConnectionStats = function (percent, object) {
  7528. var resolution = null;
  7529. if(object.resolution !== null)
  7530. {
  7531. resolution = object.resolution;
  7532. object.resolution = resolution[APP.xmpp.myJid()];
  7533. delete resolution[APP.xmpp.myJid()];
  7534. }
  7535. updateStatsIndicator("localVideoContainer", percent, object);
  7536. for(var jid in resolution)
  7537. {
  7538. if(resolution[jid] === null)
  7539. continue;
  7540. var id = 'participant_' + Strophe.getResourceFromJid(jid);
  7541. if(VideoLayout.connectionIndicators[id])
  7542. {
  7543. VideoLayout.connectionIndicators[id].updateResolution(resolution[jid]);
  7544. }
  7545. }
  7546. };
  7547. /**
  7548. * Updates remote stats.
  7549. * @param jid the jid associated with the stats
  7550. * @param percent the connection quality percent
  7551. * @param object the stats data
  7552. */
  7553. my.updateConnectionStats = function (jid, percent, object) {
  7554. var resourceJid = Strophe.getResourceFromJid(jid);
  7555. var videoSpanId = 'participant_' + resourceJid;
  7556. updateStatsIndicator(videoSpanId, percent, object);
  7557. };
  7558. /**
  7559. * Removes the connection
  7560. * @param jid
  7561. */
  7562. my.removeConnectionIndicator = function (jid) {
  7563. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7564. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].remove();
  7565. };
  7566. /**
  7567. * Hides the connection indicator
  7568. * @param jid
  7569. */
  7570. my.hideConnectionIndicator = function (jid) {
  7571. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7572. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].hide();
  7573. };
  7574. /**
  7575. * Hides all the indicators
  7576. */
  7577. my.onStatsStop = function () {
  7578. for(var indicator in VideoLayout.connectionIndicators)
  7579. {
  7580. VideoLayout.connectionIndicators[indicator].hideIndicator();
  7581. }
  7582. };
  7583. my.participantLeft = function (jid) {
  7584. // Unlock large video
  7585. if (focusedVideoInfo && focusedVideoInfo.jid === jid)
  7586. {
  7587. console.info("Focused video owner has left the conference");
  7588. focusedVideoInfo = null;
  7589. }
  7590. }
  7591. return my;
  7592. }(VideoLayout || {}));
  7593. module.exports = VideoLayout;
  7594. },{"../../../service/RTC/MediaStreamTypes":79,"../../../service/UI/UIEvents":84,"../audio_levels/AudioLevels":10,"../avatar/Avatar":13,"../etherpad/Etherpad":14,"../prezi/Prezi":15,"../side_pannels/chat/Chat":18,"../side_pannels/contactlist/ContactList":22,"../util/NicknameHandler":29,"../util/UIUtil":30,"./ConnectionIndicator":31}],33:[function(require,module,exports){
  7595. //var nouns = [
  7596. //];
  7597. var pluralNouns = [
  7598. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  7599. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  7600. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  7601. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  7602. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  7603. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  7604. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  7605. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  7606. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  7607. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  7608. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  7609. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  7610. ];
  7611. //var places = [
  7612. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  7613. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  7614. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  7615. // "Bridge"
  7616. //];
  7617. var verbs = [
  7618. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  7619. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  7620. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  7621. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  7622. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  7623. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  7624. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  7625. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  7626. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  7627. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  7628. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  7629. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  7630. ];
  7631. var adverbs = [
  7632. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  7633. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  7634. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  7635. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  7636. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  7637. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  7638. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  7639. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  7640. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  7641. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  7642. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  7643. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  7644. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  7645. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  7646. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly", "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  7647. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  7648. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  7649. ];
  7650. var adjectives = [
  7651. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  7652. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  7653. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  7654. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  7655. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  7656. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  7657. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  7658. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  7659. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  7660. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  7661. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  7662. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  7663. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  7664. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  7665. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  7666. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  7667. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  7668. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  7669. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  7670. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  7671. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  7672. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  7673. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  7674. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  7675. "Zealous"
  7676. ];
  7677. //var pronouns = [
  7678. //];
  7679. //var conjunctions = [
  7680. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  7681. //];
  7682. /*
  7683. * Maps a string (category name) to the array of words from that category.
  7684. */
  7685. var CATEGORIES =
  7686. {
  7687. //"_NOUN_": nouns,
  7688. "_PLURALNOUN_": pluralNouns,
  7689. //"_PLACE_": places,
  7690. "_VERB_": verbs,
  7691. "_ADVERB_": adverbs,
  7692. "_ADJECTIVE_": adjectives
  7693. //"_PRONOUN_": pronouns,
  7694. //"_CONJUNCTION_": conjunctions,
  7695. };
  7696. var PATTERNS = [
  7697. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  7698. // BeautifulFungiOrSpaghetti
  7699. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  7700. // AmazinglyScaryToy
  7701. //"_ADVERB__ADJECTIVE__NOUN_",
  7702. // NeitherTrashNorRifle
  7703. //"Neither_NOUN_Nor_NOUN_",
  7704. //"Either_NOUN_Or_NOUN_",
  7705. // EitherCopulateOrInvestigate
  7706. //"Either_VERB_Or_VERB_",
  7707. //"Neither_VERB_Nor_VERB_",
  7708. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  7709. //"The_ADVERB__ADJECTIVE__NOUN_",
  7710. //"The_ADVERB__ADJECTIVE__NOUN_s",
  7711. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  7712. // WolvesComputeBadly
  7713. //"_PLURALNOUN__VERB__ADVERB_",
  7714. // UniteFacilitateAndMerge
  7715. //"_VERB__VERB_And_VERB_",
  7716. //NastyWitchesAtThePub
  7717. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  7718. ];
  7719. /*
  7720. * Returns a random element from the array 'arr'
  7721. */
  7722. function randomElement(arr)
  7723. {
  7724. return arr[Math.floor(Math.random() * arr.length)];
  7725. }
  7726. /*
  7727. * Returns true if the string 's' contains one of the
  7728. * template strings.
  7729. */
  7730. function hasTemplate(s)
  7731. {
  7732. for (var template in CATEGORIES){
  7733. if (s.indexOf(template) >= 0){
  7734. return true;
  7735. }
  7736. }
  7737. }
  7738. /**
  7739. * Generates new room name.
  7740. */
  7741. var RoomNameGenerator = {
  7742. generateRoomWithoutSeparator: function()
  7743. {
  7744. // Note that if more than one pattern is available, the choice of 'name' won't be random (names from patterns
  7745. // with fewer options will have higher probability of being chosen that names from patterns with more options).
  7746. var name = randomElement(PATTERNS);
  7747. var word;
  7748. while (hasTemplate(name)){
  7749. for (var template in CATEGORIES){
  7750. word = randomElement(CATEGORIES[template]);
  7751. name = name.replace(template, word);
  7752. }
  7753. }
  7754. return name;
  7755. }
  7756. }
  7757. module.exports = RoomNameGenerator;
  7758. },{}],34:[function(require,module,exports){
  7759. var animateTimeout, updateTimeout;
  7760. var RoomNameGenerator = require("./RoomnameGenerator");
  7761. function enter_room()
  7762. {
  7763. var val = $("#enter_room_field").val();
  7764. if(!val) {
  7765. val = $("#enter_room_field").attr("room_name");
  7766. }
  7767. if (val) {
  7768. window.location.pathname = "/" + val;
  7769. }
  7770. }
  7771. function animate(word) {
  7772. var currentVal = $("#enter_room_field").attr("placeholder");
  7773. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  7774. animateTimeout = setTimeout(function() {
  7775. animate(word.substring(1, word.length))
  7776. }, 70);
  7777. }
  7778. function update_roomname()
  7779. {
  7780. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  7781. $("#enter_room_field").attr("room_name", word);
  7782. $("#enter_room_field").attr("placeholder", "");
  7783. clearTimeout(animateTimeout);
  7784. animate(word);
  7785. updateTimeout = setTimeout(update_roomname, 10000);
  7786. }
  7787. function setupWelcomePage()
  7788. {
  7789. $("#videoconference_page").hide();
  7790. $("#domain_name").text(
  7791. window.location.protocol + "//" + window.location.host + "/");
  7792. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  7793. var leftWatermarkDiv
  7794. = $("#welcome_page_header div[class='watermark leftwatermark']");
  7795. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  7796. {
  7797. leftWatermarkDiv.css({display: 'block'});
  7798. leftWatermarkDiv.parent().get(0).href
  7799. = interfaceConfig.JITSI_WATERMARK_LINK;
  7800. }
  7801. }
  7802. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  7803. var rightWatermarkDiv
  7804. = $("#welcome_page_header div[class='watermark rightwatermark']");
  7805. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  7806. rightWatermarkDiv.css({display: 'block'});
  7807. rightWatermarkDiv.parent().get(0).href
  7808. = interfaceConfig.BRAND_WATERMARK_LINK;
  7809. rightWatermarkDiv.get(0).style.backgroundImage
  7810. = "url(images/rightwatermark.png)";
  7811. }
  7812. }
  7813. if (interfaceConfig.SHOW_POWERED_BY) {
  7814. $("#welcome_page_header>a[class='poweredby']")
  7815. .css({display: 'block'});
  7816. }
  7817. $("#enter_room_button").click(function()
  7818. {
  7819. enter_room();
  7820. });
  7821. $("#enter_room_field").keydown(function (event) {
  7822. if (event.keyCode === 13 /* enter */) {
  7823. enter_room();
  7824. }
  7825. });
  7826. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  7827. var updateTimeout;
  7828. var animateTimeout;
  7829. $("#reload_roomname").click(function () {
  7830. clearTimeout(updateTimeout);
  7831. clearTimeout(animateTimeout);
  7832. update_roomname();
  7833. });
  7834. $("#reload_roomname").show();
  7835. update_roomname();
  7836. }
  7837. $("#disable_welcome").click(function () {
  7838. window.localStorage.welcomePageDisabled
  7839. = $("#disable_welcome").is(":checked");
  7840. });
  7841. }
  7842. module.exports = setupWelcomePage;
  7843. },{"./RoomnameGenerator":33}],35:[function(require,module,exports){
  7844. var EventEmitter = require("events");
  7845. var eventEmitter = new EventEmitter();
  7846. var CQEvents = require("../../service/connectionquality/CQEvents");
  7847. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7848. /**
  7849. * local stats
  7850. * @type {{}}
  7851. */
  7852. var stats = {};
  7853. /**
  7854. * remote stats
  7855. * @type {{}}
  7856. */
  7857. var remoteStats = {};
  7858. /**
  7859. * Interval for sending statistics to other participants
  7860. * @type {null}
  7861. */
  7862. var sendIntervalId = null;
  7863. /**
  7864. * Start statistics sending.
  7865. */
  7866. function startSendingStats() {
  7867. sendStats();
  7868. sendIntervalId = setInterval(sendStats, 10000);
  7869. }
  7870. /**
  7871. * Sends statistics to other participants
  7872. */
  7873. function sendStats() {
  7874. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  7875. }
  7876. /**
  7877. * Converts statistics to format for sending through XMPP
  7878. * @param stats the statistics
  7879. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  7880. */
  7881. function convertToMUCStats(stats) {
  7882. return {
  7883. "bitrate_download": stats.bitrate.download,
  7884. "bitrate_upload": stats.bitrate.upload,
  7885. "packetLoss_total": stats.packetLoss.total,
  7886. "packetLoss_download": stats.packetLoss.download,
  7887. "packetLoss_upload": stats.packetLoss.upload
  7888. };
  7889. }
  7890. /**
  7891. * Converts statitistics to format used by VideoLayout
  7892. * @param stats
  7893. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  7894. */
  7895. function parseMUCStats(stats) {
  7896. return {
  7897. bitrate: {
  7898. download: stats.bitrate_download,
  7899. upload: stats.bitrate_upload
  7900. },
  7901. packetLoss: {
  7902. total: stats.packetLoss_total,
  7903. download: stats.packetLoss_download,
  7904. upload: stats.packetLoss_upload
  7905. }
  7906. };
  7907. }
  7908. var ConnectionQuality = {
  7909. init: function () {
  7910. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  7911. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  7912. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  7913. },
  7914. /**
  7915. * Updates the local statistics
  7916. * @param data new statistics
  7917. */
  7918. updateLocalStats: function (data) {
  7919. stats = data;
  7920. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  7921. if (sendIntervalId == null) {
  7922. startSendingStats();
  7923. }
  7924. },
  7925. /**
  7926. * Updates remote statistics
  7927. * @param jid the jid associated with the statistics
  7928. * @param data the statistics
  7929. */
  7930. updateRemoteStats: function (jid, data) {
  7931. if (data == null || data.packetLoss_total == null) {
  7932. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  7933. return;
  7934. }
  7935. remoteStats[jid] = parseMUCStats(data);
  7936. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  7937. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  7938. },
  7939. /**
  7940. * Stops statistics sending.
  7941. */
  7942. stopSendingStats: function () {
  7943. clearInterval(sendIntervalId);
  7944. sendIntervalId = null;
  7945. //notify UI about stopping statistics gathering
  7946. eventEmitter.emit(CQEvents.STOP);
  7947. },
  7948. /**
  7949. * Returns the local statistics.
  7950. */
  7951. getStats: function () {
  7952. return stats;
  7953. },
  7954. addListener: function (type, listener) {
  7955. eventEmitter.on(type, listener);
  7956. }
  7957. };
  7958. module.exports = ConnectionQuality;
  7959. },{"../../service/connectionquality/CQEvents":86,"../../service/xmpp/XMPPEvents":89,"events":1}],36:[function(require,module,exports){
  7960. /* global $, alert, changeLocalVideo, chrome, config, getConferenceHandler, getUserMediaWithConstraints */
  7961. /**
  7962. * Indicates that desktop stream is currently in use(for toggle purpose).
  7963. * @type {boolean}
  7964. */
  7965. var isUsingScreenStream = false;
  7966. /**
  7967. * Indicates that switch stream operation is in progress and prevent from triggering new events.
  7968. * @type {boolean}
  7969. */
  7970. var switchInProgress = false;
  7971. /**
  7972. * Method used to get screen sharing stream.
  7973. *
  7974. * @type {function (stream_callback, failure_callback}
  7975. */
  7976. var obtainDesktopStream = null;
  7977. /**
  7978. * Flag used to cache desktop sharing enabled state. Do not use directly as it can be <tt>null</tt>.
  7979. * @type {null|boolean}
  7980. */
  7981. var _desktopSharingEnabled = null;
  7982. var EventEmitter = require("events");
  7983. var eventEmitter = new EventEmitter();
  7984. var DesktopSharingEventTypes = require("../../service/desktopsharing/DesktopSharingEventTypes");
  7985. /**
  7986. * Method obtains desktop stream from WebRTC 'screen' source.
  7987. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  7988. */
  7989. function obtainWebRTCScreen(streamCallback, failCallback) {
  7990. APP.RTC.getUserMediaWithConstraints(
  7991. ['screen'],
  7992. streamCallback,
  7993. failCallback
  7994. );
  7995. }
  7996. /**
  7997. * Constructs inline install URL for Chrome desktop streaming extension.
  7998. * The 'chromeExtensionId' must be defined in config.js.
  7999. * @returns {string}
  8000. */
  8001. function getWebStoreInstallUrl()
  8002. {
  8003. return "https://chrome.google.com/webstore/detail/" + config.chromeExtensionId;
  8004. }
  8005. /**
  8006. * Checks whether extension update is required.
  8007. * @param minVersion minimal required version
  8008. * @param extVersion current extension version
  8009. * @returns {boolean}
  8010. */
  8011. function isUpdateRequired(minVersion, extVersion)
  8012. {
  8013. try
  8014. {
  8015. var s1 = minVersion.split('.');
  8016. var s2 = extVersion.split('.');
  8017. var len = Math.max(s1.length, s2.length);
  8018. for (var i = 0; i < len; i++)
  8019. {
  8020. var n1 = 0,
  8021. n2 = 0;
  8022. if (i < s1.length)
  8023. n1 = parseInt(s1[i]);
  8024. if (i < s2.length)
  8025. n2 = parseInt(s2[i]);
  8026. if (isNaN(n1) || isNaN(n2))
  8027. {
  8028. return true;
  8029. }
  8030. else if (n1 !== n2)
  8031. {
  8032. return n1 > n2;
  8033. }
  8034. }
  8035. // will happen if boths version has identical numbers in
  8036. // their components (even if one of them is longer, has more components)
  8037. return false;
  8038. }
  8039. catch (e)
  8040. {
  8041. console.error("Failed to parse extension version", e);
  8042. APP.UI.messageHandler.showError("dialog.error", 'Error',
  8043. "dialod.detectext",
  8044. 'Error when trying to detect desktopsharing extension.');
  8045. return true;
  8046. }
  8047. }
  8048. function checkExtInstalled(isInstalledCallback) {
  8049. if (!chrome.runtime) {
  8050. // No API, so no extension for sure
  8051. isInstalledCallback(false);
  8052. return;
  8053. }
  8054. chrome.runtime.sendMessage(
  8055. config.chromeExtensionId,
  8056. { getVersion: true },
  8057. function (response) {
  8058. if (!response || !response.version) {
  8059. // Communication failure - assume that no endpoint exists
  8060. console.warn("Extension not installed?: " + chrome.runtime.lastError);
  8061. isInstalledCallback(false);
  8062. } else {
  8063. // Check installed extension version
  8064. var extVersion = response.version;
  8065. console.log('Extension version is: ' + extVersion);
  8066. var updateRequired = isUpdateRequired(config.minChromeExtVersion, extVersion);
  8067. if (updateRequired) {
  8068. alert(
  8069. 'Jitsi Desktop Streamer requires update. ' +
  8070. 'Changes will take effect after next Chrome restart.');
  8071. }
  8072. isInstalledCallback(!updateRequired);
  8073. }
  8074. }
  8075. );
  8076. }
  8077. function doGetStreamFromExtension(streamCallback, failCallback) {
  8078. // Sends 'getStream' msg to the extension. Extension id must be defined in the config.
  8079. chrome.runtime.sendMessage(
  8080. config.chromeExtensionId,
  8081. { getStream: true, sources: config.desktopSharingSources },
  8082. function (response) {
  8083. if (!response) {
  8084. failCallback(chrome.runtime.lastError);
  8085. return;
  8086. }
  8087. console.log("Response from extension: " + response);
  8088. if (response.streamId) {
  8089. APP.RTC.getUserMediaWithConstraints(
  8090. ['desktop'],
  8091. function (stream) {
  8092. streamCallback(stream);
  8093. },
  8094. failCallback,
  8095. null, null, null,
  8096. response.streamId);
  8097. } else {
  8098. failCallback("Extension failed to get the stream");
  8099. }
  8100. }
  8101. );
  8102. }
  8103. /**
  8104. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop' stream for returned stream token.
  8105. */
  8106. function obtainScreenFromExtension(streamCallback, failCallback) {
  8107. checkExtInstalled(
  8108. function (isInstalled) {
  8109. if (isInstalled) {
  8110. doGetStreamFromExtension(streamCallback, failCallback);
  8111. } else {
  8112. chrome.webstore.install(
  8113. getWebStoreInstallUrl(),
  8114. function (arg) {
  8115. console.log("Extension installed successfully", arg);
  8116. // We need to reload the page in order to get the access to chrome.runtime
  8117. window.location.reload(false);
  8118. },
  8119. function (arg) {
  8120. console.log("Failed to install the extension", arg);
  8121. failCallback(arg);
  8122. APP.UI.messageHandler.showError("dialog.error", 'Error',
  8123. "dialog.failtoinstall",
  8124. 'Failed to install desktop sharing extension');
  8125. }
  8126. );
  8127. }
  8128. }
  8129. );
  8130. }
  8131. /**
  8132. * Call this method to toggle desktop sharing feature.
  8133. * @param method pass "ext" to use chrome extension for desktop capture(chrome extension required),
  8134. * pass "webrtc" to use WebRTC "screen" desktop source('chrome://flags/#enable-usermedia-screen-capture'
  8135. * must be enabled), pass any other string or nothing in order to disable this feature completely.
  8136. */
  8137. function setDesktopSharing(method) {
  8138. // Check if we are running chrome
  8139. if (!navigator.webkitGetUserMedia) {
  8140. obtainDesktopStream = null;
  8141. console.info("Desktop sharing disabled");
  8142. } else if (method == "ext") {
  8143. obtainDesktopStream = obtainScreenFromExtension;
  8144. console.info("Using Chrome extension for desktop sharing");
  8145. } else if (method == "webrtc") {
  8146. obtainDesktopStream = obtainWebRTCScreen;
  8147. console.info("Using Chrome WebRTC for desktop sharing");
  8148. }
  8149. // Reset enabled cache
  8150. _desktopSharingEnabled = null;
  8151. }
  8152. /**
  8153. * Initializes <link rel=chrome-webstore-item /> with extension id set in config.js to support inline installs.
  8154. * Host site must be selected as main website of published extension.
  8155. */
  8156. function initInlineInstalls()
  8157. {
  8158. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  8159. }
  8160. function getSwitchStreamFailed(error) {
  8161. console.error("Failed to obtain the stream to switch to", error);
  8162. switchInProgress = false;
  8163. }
  8164. function streamSwitchDone() {
  8165. switchInProgress = false;
  8166. eventEmitter.emit(
  8167. DesktopSharingEventTypes.SWITCHING_DONE,
  8168. isUsingScreenStream);
  8169. }
  8170. function newStreamCreated(stream)
  8171. {
  8172. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  8173. stream, isUsingScreenStream, streamSwitchDone);
  8174. }
  8175. module.exports = {
  8176. isUsingScreenStream: function () {
  8177. return isUsingScreenStream;
  8178. },
  8179. /**
  8180. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available and enabled.
  8181. */
  8182. isDesktopSharingEnabled: function () {
  8183. if (_desktopSharingEnabled === null) {
  8184. if (obtainDesktopStream === obtainScreenFromExtension) {
  8185. // Parse chrome version
  8186. var userAgent = navigator.userAgent.toLowerCase();
  8187. // We can assume that user agent is chrome, because it's enforced when 'ext' streaming method is set
  8188. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  8189. console.log("Chrome version" + userAgent, ver);
  8190. _desktopSharingEnabled = ver >= 34;
  8191. } else {
  8192. _desktopSharingEnabled = obtainDesktopStream === obtainWebRTCScreen;
  8193. }
  8194. }
  8195. return _desktopSharingEnabled;
  8196. },
  8197. init: function () {
  8198. setDesktopSharing(config.desktopSharing);
  8199. // Initialize Chrome extension inline installs
  8200. if (config.chromeExtensionId) {
  8201. initInlineInstalls();
  8202. }
  8203. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  8204. },
  8205. addListener: function(listener, type)
  8206. {
  8207. eventEmitter.on(type, listener);
  8208. },
  8209. removeListener: function (listener,type) {
  8210. eventEmitter.removeListener(type, listener);
  8211. },
  8212. /*
  8213. * Toggles screen sharing.
  8214. */
  8215. toggleScreenSharing: function () {
  8216. if (switchInProgress || !obtainDesktopStream) {
  8217. console.warn("Switch in progress or no method defined");
  8218. return;
  8219. }
  8220. switchInProgress = true;
  8221. if (!isUsingScreenStream)
  8222. {
  8223. // Switch to desktop stream
  8224. obtainDesktopStream(
  8225. function (stream) {
  8226. // We now use screen stream
  8227. isUsingScreenStream = true;
  8228. // Hook 'ended' event to restore camera when screen stream stops
  8229. stream.addEventListener('ended',
  8230. function (e) {
  8231. if (!switchInProgress && isUsingScreenStream) {
  8232. toggleScreenSharing();
  8233. }
  8234. }
  8235. );
  8236. newStreamCreated(stream);
  8237. },
  8238. getSwitchStreamFailed);
  8239. } else {
  8240. // Disable screen stream
  8241. APP.RTC.getUserMediaWithConstraints(
  8242. ['video'],
  8243. function (stream) {
  8244. // We are now using camera stream
  8245. isUsingScreenStream = false;
  8246. newStreamCreated(stream);
  8247. },
  8248. getSwitchStreamFailed, config.resolution || '360'
  8249. );
  8250. }
  8251. }
  8252. };
  8253. },{"../../service/desktopsharing/DesktopSharingEventTypes":87,"events":1}],37:[function(require,module,exports){
  8254. //maps keycode to character, id of popover for given function and function
  8255. var shortcuts = {
  8256. 67: {
  8257. character: "C",
  8258. id: "toggleChatPopover",
  8259. function: APP.UI.toggleChat
  8260. },
  8261. 70: {
  8262. character: "F",
  8263. id: "filmstripPopover",
  8264. function: APP.UI.toggleFilmStrip
  8265. },
  8266. 77: {
  8267. character: "M",
  8268. id: "mutePopover",
  8269. function: APP.UI.toggleAudio
  8270. },
  8271. 84: {
  8272. character: "T",
  8273. function: function() {
  8274. if(!APP.RTC.localAudio.isMuted()) {
  8275. APP.UI.toggleAudio();
  8276. }
  8277. }
  8278. },
  8279. 86: {
  8280. character: "V",
  8281. id: "toggleVideoPopover",
  8282. function: APP.UI.toggleVideo
  8283. }
  8284. };
  8285. var KeyboardShortcut = {
  8286. init: function () {
  8287. window.onkeyup = function(e) {
  8288. var keycode = e.which;
  8289. if(!($(":focus").is("input[type=text]") ||
  8290. $(":focus").is("input[type=password]") ||
  8291. $(":focus").is("textarea"))) {
  8292. if (typeof shortcuts[keycode] === "object") {
  8293. shortcuts[keycode].function();
  8294. }
  8295. else if (keycode >= "0".charCodeAt(0) &&
  8296. keycode <= "9".charCodeAt(0)) {
  8297. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  8298. }
  8299. //esc while the smileys are visible hides them
  8300. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  8301. APP.UI.toggleSmileys();
  8302. }
  8303. };
  8304. window.onkeydown = function(e) {
  8305. if(!($(":focus").is("input[type=text]") ||
  8306. $(":focus").is("input[type=password]") ||
  8307. $(":focus").is("textarea"))) {
  8308. if(e.which === "T".charCodeAt(0)) {
  8309. if(APP.RTC.localAudio.isMuted()) {
  8310. APP.UI.toggleAudio();
  8311. }
  8312. }
  8313. }
  8314. };
  8315. var self = this;
  8316. $('body').popover({ selector: '[data-toggle=popover]',
  8317. trigger: 'click hover',
  8318. content: function() {
  8319. return this.getAttribute("content") +
  8320. self.getShortcut(this.getAttribute("shortcut"));
  8321. }
  8322. });
  8323. },
  8324. /**
  8325. *
  8326. * @param id indicates the popover associated with the shortcut
  8327. * @returns {string} the keyboard shortcut used for the id given
  8328. */
  8329. getShortcut: function (id) {
  8330. for (var keycode in shortcuts) {
  8331. if (shortcuts.hasOwnProperty(keycode)) {
  8332. if (shortcuts[keycode].id === id) {
  8333. return " (" + shortcuts[keycode].character + ")";
  8334. }
  8335. }
  8336. }
  8337. return "";
  8338. }
  8339. };
  8340. module.exports = KeyboardShortcut;
  8341. },{}],38:[function(require,module,exports){
  8342. var email = '';
  8343. var displayName = '';
  8344. var userId;
  8345. var language = null;
  8346. function supportsLocalStorage() {
  8347. try {
  8348. return 'localStorage' in window && window.localStorage !== null;
  8349. } catch (e) {
  8350. console.log("localstorage is not supported");
  8351. return false;
  8352. }
  8353. }
  8354. function generateUniqueId() {
  8355. function _p8() {
  8356. return (Math.random().toString(16) + "000000000").substr(2, 8);
  8357. }
  8358. return _p8() + _p8() + _p8() + _p8();
  8359. }
  8360. if (supportsLocalStorage()) {
  8361. if (!window.localStorage.jitsiMeetId) {
  8362. window.localStorage.jitsiMeetId = generateUniqueId();
  8363. console.log("generated id", window.localStorage.jitsiMeetId);
  8364. }
  8365. userId = window.localStorage.jitsiMeetId || '';
  8366. email = window.localStorage.email || '';
  8367. displayName = window.localStorage.displayname || '';
  8368. language = window.localStorage.language;
  8369. } else {
  8370. console.log("local storage is not supported");
  8371. userId = generateUniqueId();
  8372. }
  8373. var Settings =
  8374. {
  8375. setDisplayName: function (newDisplayName) {
  8376. displayName = newDisplayName;
  8377. window.localStorage.displayname = displayName;
  8378. return displayName;
  8379. },
  8380. setEmail: function (newEmail)
  8381. {
  8382. email = newEmail;
  8383. window.localStorage.email = newEmail;
  8384. return email;
  8385. },
  8386. getSettings: function () {
  8387. return {
  8388. email: email,
  8389. displayName: displayName,
  8390. uid: userId,
  8391. language: language
  8392. };
  8393. },
  8394. setLanguage: function (lang) {
  8395. language = lang;
  8396. window.localStorage.language = lang;
  8397. }
  8398. };
  8399. module.exports = Settings;
  8400. },{}],39:[function(require,module,exports){
  8401. /**
  8402. *
  8403. * @constructor
  8404. */
  8405. function SimulcastLogger(name, lvl) {
  8406. this.name = name;
  8407. this.lvl = lvl;
  8408. }
  8409. SimulcastLogger.prototype.log = function (text) {
  8410. if (this.lvl) {
  8411. console.log(text);
  8412. }
  8413. };
  8414. SimulcastLogger.prototype.info = function (text) {
  8415. if (this.lvl > 1) {
  8416. console.info(text);
  8417. }
  8418. };
  8419. SimulcastLogger.prototype.fine = function (text) {
  8420. if (this.lvl > 2) {
  8421. console.log(text);
  8422. }
  8423. };
  8424. SimulcastLogger.prototype.error = function (text) {
  8425. console.error(text);
  8426. };
  8427. module.exports = SimulcastLogger;
  8428. },{}],40:[function(require,module,exports){
  8429. var SimulcastLogger = require("./SimulcastLogger");
  8430. var SimulcastUtils = require("./SimulcastUtils");
  8431. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  8432. function SimulcastReceiver() {
  8433. this.simulcastUtils = new SimulcastUtils();
  8434. this.logger = new SimulcastLogger('SimulcastReceiver', 1);
  8435. }
  8436. SimulcastReceiver.prototype._remoteVideoSourceCache = '';
  8437. SimulcastReceiver.prototype._remoteMaps = {
  8438. msid2Quality: {},
  8439. ssrc2Msid: {},
  8440. msid2ssrc: {},
  8441. receivingVideoStreams: {}
  8442. };
  8443. SimulcastReceiver.prototype._cacheRemoteVideoSources = function (lines) {
  8444. this._remoteVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  8445. };
  8446. SimulcastReceiver.prototype._restoreRemoteVideoSources = function (lines) {
  8447. this.simulcastUtils._replaceVideoSources(lines, this._remoteVideoSourceCache);
  8448. };
  8449. SimulcastReceiver.prototype._ensureGoogConference = function (lines) {
  8450. var sb;
  8451. this.logger.info('Ensuring x-google-conference flag...')
  8452. if (this.simulcastUtils._indexOfArray('a=x-google-flag:conference', lines) === this.simulcastUtils._emptyCompoundIndex) {
  8453. // TODO(gp) do that for the audio as well as suggested by fippo.
  8454. // Add the google conference flag
  8455. sb = this.simulcastUtils._getVideoSources(lines);
  8456. sb = ['a=x-google-flag:conference'].concat(sb);
  8457. this.simulcastUtils._replaceVideoSources(lines, sb);
  8458. }
  8459. };
  8460. SimulcastReceiver.prototype._restoreSimulcastGroups = function (sb) {
  8461. this._restoreRemoteVideoSources(sb);
  8462. };
  8463. /**
  8464. * Restores the simulcast groups of the remote description. In
  8465. * transformRemoteDescription we remove those in order for the set remote
  8466. * description to succeed. The focus needs the signal the groups to new
  8467. * participants.
  8468. *
  8469. * @param desc
  8470. * @returns {*}
  8471. */
  8472. SimulcastReceiver.prototype.reverseTransformRemoteDescription = function (desc) {
  8473. var sb;
  8474. if (!this.simulcastUtils.isValidDescription(desc)) {
  8475. return desc;
  8476. }
  8477. if (config.enableSimulcast) {
  8478. sb = desc.sdp.split('\r\n');
  8479. this._restoreSimulcastGroups(sb);
  8480. desc = new RTCSessionDescription({
  8481. type: desc.type,
  8482. sdp: sb.join('\r\n')
  8483. });
  8484. }
  8485. return desc;
  8486. };
  8487. SimulcastUtils.prototype._ensureOrder = function (lines) {
  8488. var videoSources, sb;
  8489. videoSources = this.parseMedia(lines, ['video'])[0];
  8490. sb = this._compileVideoSources(videoSources);
  8491. this._replaceVideoSources(lines, sb);
  8492. };
  8493. SimulcastReceiver.prototype._updateRemoteMaps = function (lines) {
  8494. var remoteVideoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0],
  8495. videoSource, quality;
  8496. // (re) initialize the remote maps.
  8497. this._remoteMaps.msid2Quality = {};
  8498. this._remoteMaps.ssrc2Msid = {};
  8499. this._remoteMaps.msid2ssrc = {};
  8500. var self = this;
  8501. if (remoteVideoSources.groups && remoteVideoSources.groups.length !== 0) {
  8502. remoteVideoSources.groups.forEach(function (group) {
  8503. if (group.semantics === 'SIM' && group.ssrcs && group.ssrcs.length !== 0) {
  8504. quality = 0;
  8505. group.ssrcs.forEach(function (ssrc) {
  8506. videoSource = remoteVideoSources.sources[ssrc];
  8507. self._remoteMaps.msid2Quality[videoSource.msid] = quality++;
  8508. self._remoteMaps.ssrc2Msid[videoSource.ssrc] = videoSource.msid;
  8509. self._remoteMaps.msid2ssrc[videoSource.msid] = videoSource.ssrc;
  8510. });
  8511. }
  8512. });
  8513. }
  8514. };
  8515. SimulcastReceiver.prototype._setReceivingVideoStream = function (resource, ssrc) {
  8516. this._remoteMaps.receivingVideoStreams[resource] = ssrc;
  8517. };
  8518. /**
  8519. * Returns a stream with single video track, the one currently being
  8520. * received by this endpoint.
  8521. *
  8522. * @param stream the remote simulcast stream.
  8523. * @returns {webkitMediaStream}
  8524. */
  8525. SimulcastReceiver.prototype.getReceivingVideoStream = function (stream) {
  8526. var tracks, i, electedTrack, msid, quality = 0, receivingTrackId;
  8527. var self = this;
  8528. if (config.enableSimulcast) {
  8529. stream.getVideoTracks().some(function (track) {
  8530. return Object.keys(self._remoteMaps.receivingVideoStreams).some(function (resource) {
  8531. var ssrc = self._remoteMaps.receivingVideoStreams[resource];
  8532. var msid = self._remoteMaps.ssrc2Msid[ssrc];
  8533. if (msid == [stream.id, track.id].join(' ')) {
  8534. electedTrack = track;
  8535. return true;
  8536. }
  8537. });
  8538. });
  8539. if (!electedTrack) {
  8540. // we don't have an elected track, choose by initial quality.
  8541. tracks = stream.getVideoTracks();
  8542. for (i = 0; i < tracks.length; i++) {
  8543. msid = [stream.id, tracks[i].id].join(' ');
  8544. if (this._remoteMaps.msid2Quality[msid] === quality) {
  8545. electedTrack = tracks[i];
  8546. break;
  8547. }
  8548. }
  8549. // TODO(gp) if the initialQuality could not be satisfied, lower
  8550. // the requirement and try again.
  8551. }
  8552. }
  8553. return (electedTrack)
  8554. ? new webkitMediaStream([electedTrack])
  8555. : stream;
  8556. };
  8557. SimulcastReceiver.prototype.getReceivingSSRC = function (jid) {
  8558. var resource = Strophe.getResourceFromJid(jid);
  8559. var ssrc = this._remoteMaps.receivingVideoStreams[resource];
  8560. // If we haven't receiving a "changed" event yet, then we must be receiving
  8561. // low quality (that the sender always streams).
  8562. if(!ssrc)
  8563. {
  8564. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  8565. var remoteStream = remoteStreamObject.getOriginalStream();
  8566. var tracks = remoteStream.getVideoTracks();
  8567. if (tracks) {
  8568. for (var k = 0; k < tracks.length; k++) {
  8569. var track = tracks[k];
  8570. var msid = [remoteStream.id, track.id].join(' ');
  8571. var _ssrc = this._remoteMaps.msid2ssrc[msid];
  8572. var quality = this._remoteMaps.msid2Quality[msid];
  8573. if (quality == 0) {
  8574. ssrc = _ssrc;
  8575. }
  8576. }
  8577. }
  8578. }
  8579. return ssrc;
  8580. };
  8581. SimulcastReceiver.prototype.getReceivingVideoStreamBySSRC = function (ssrc)
  8582. {
  8583. var sid, electedStream;
  8584. var i, j, k;
  8585. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  8586. if(jid && APP.RTC.remoteStreams[jid])
  8587. {
  8588. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  8589. var remoteStream = remoteStreamObject.getOriginalStream();
  8590. var tracks = remoteStream.getVideoTracks();
  8591. if (tracks) {
  8592. for (k = 0; k < tracks.length; k++) {
  8593. var track = tracks[k];
  8594. var msid = [remoteStream.id, track.id].join(' ');
  8595. var tmp = this._remoteMaps.msid2ssrc[msid];
  8596. if (tmp == ssrc) {
  8597. electedStream = new webkitMediaStream([track]);
  8598. sid = remoteStreamObject.sid;
  8599. // stream found, stop.
  8600. break;
  8601. }
  8602. }
  8603. }
  8604. }
  8605. else
  8606. {
  8607. console.debug(APP.RTC.remoteStreams, jid, ssrc);
  8608. }
  8609. return {
  8610. sid: sid,
  8611. stream: electedStream
  8612. };
  8613. };
  8614. /**
  8615. * Gets the fully qualified msid (stream.id + track.id) associated to the
  8616. * SSRC.
  8617. *
  8618. * @param ssrc
  8619. * @returns {*}
  8620. */
  8621. SimulcastReceiver.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  8622. return this._remoteMaps.ssrc2Msid[ssrc];
  8623. };
  8624. /**
  8625. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  8626. * either gets confused and thinks this is an FID group or, if an FID group
  8627. * is already present, it fails to set the remote description.
  8628. *
  8629. * @param desc
  8630. * @returns {*}
  8631. */
  8632. SimulcastReceiver.prototype.transformRemoteDescription = function (desc) {
  8633. if (desc && desc.sdp) {
  8634. var sb = desc.sdp.split('\r\n');
  8635. this._updateRemoteMaps(sb);
  8636. this._cacheRemoteVideoSources(sb);
  8637. // NOTE(gp) this needs to be called after updateRemoteMaps because we
  8638. // need the simulcast group in the _updateRemoteMaps() method.
  8639. this.simulcastUtils._removeSimulcastGroup(sb);
  8640. if (desc.sdp.indexOf('a=ssrc-group:SIM') !== -1) {
  8641. // We don't need the goog conference flag if we're not doing
  8642. // simulcast.
  8643. this._ensureGoogConference(sb);
  8644. }
  8645. desc = new RTCSessionDescription({
  8646. type: desc.type,
  8647. sdp: sb.join('\r\n')
  8648. });
  8649. this.logger.fine(['Transformed remote description', desc.sdp].join(' '));
  8650. }
  8651. return desc;
  8652. };
  8653. module.exports = SimulcastReceiver;
  8654. },{"../../service/RTC/MediaStreamTypes":79,"./SimulcastLogger":39,"./SimulcastUtils":42}],41:[function(require,module,exports){
  8655. var SimulcastLogger = require("./SimulcastLogger");
  8656. var SimulcastUtils = require("./SimulcastUtils");
  8657. function SimulcastSender() {
  8658. this.simulcastUtils = new SimulcastUtils();
  8659. this.logger = new SimulcastLogger('SimulcastSender', 1);
  8660. }
  8661. SimulcastSender.prototype.displayedLocalVideoStream = null;
  8662. SimulcastSender.prototype._generateGuid = (function () {
  8663. function s4() {
  8664. return Math.floor((1 + Math.random()) * 0x10000)
  8665. .toString(16)
  8666. .substring(1);
  8667. }
  8668. return function () {
  8669. return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
  8670. s4() + '-' + s4() + s4() + s4();
  8671. };
  8672. }());
  8673. // Returns a random integer between min (included) and max (excluded)
  8674. // Using Math.round() gives a non-uniform distribution!
  8675. SimulcastSender.prototype._generateRandomSSRC = function () {
  8676. var min = 0, max = 0xffffffff;
  8677. return Math.floor(Math.random() * (max - min)) + min;
  8678. };
  8679. SimulcastSender.prototype.getLocalVideoStream = function () {
  8680. return (this.displayedLocalVideoStream != null)
  8681. ? this.displayedLocalVideoStream
  8682. // in case we have no simulcast at all, i.e. we didn't perform the GUM
  8683. : APP.RTC.localVideo.getOriginalStream();
  8684. };
  8685. function NativeSimulcastSender() {
  8686. SimulcastSender.call(this); // call the super constructor.
  8687. }
  8688. NativeSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8689. NativeSimulcastSender.prototype._localExplosionMap = {};
  8690. NativeSimulcastSender.prototype._isUsingScreenStream = false;
  8691. NativeSimulcastSender.prototype._localVideoSourceCache = '';
  8692. NativeSimulcastSender.prototype.reset = function () {
  8693. this._localExplosionMap = {};
  8694. this._isUsingScreenStream = APP.desktopsharing.isUsingScreenStream();
  8695. };
  8696. NativeSimulcastSender.prototype._cacheLocalVideoSources = function (lines) {
  8697. this._localVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  8698. };
  8699. NativeSimulcastSender.prototype._restoreLocalVideoSources = function (lines) {
  8700. this.simulcastUtils._replaceVideoSources(lines, this._localVideoSourceCache);
  8701. };
  8702. NativeSimulcastSender.prototype._appendSimulcastGroup = function (lines) {
  8703. var videoSources, ssrcGroup, simSSRC, numOfSubs = 2, i, sb, msid;
  8704. this.logger.info('Appending simulcast group...');
  8705. // Get the primary SSRC information.
  8706. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8707. // Start building the SIM SSRC group.
  8708. ssrcGroup = ['a=ssrc-group:SIM'];
  8709. // The video source buffer.
  8710. sb = [];
  8711. // Create the simulcast sub-streams.
  8712. for (i = 0; i < numOfSubs; i++) {
  8713. // TODO(gp) prevent SSRC collision.
  8714. simSSRC = this._generateRandomSSRC();
  8715. ssrcGroup.push(simSSRC);
  8716. if (videoSources.base) {
  8717. sb.splice.apply(sb, [sb.length, 0].concat(
  8718. [["a=ssrc:", simSSRC, " cname:", videoSources.base.cname].join(''),
  8719. ["a=ssrc:", simSSRC, " msid:", videoSources.base.msid].join('')]
  8720. ));
  8721. }
  8722. this.logger.info(['Generated substream ', i, ' with SSRC ', simSSRC, '.'].join(''));
  8723. }
  8724. // Add the group sim layers.
  8725. sb.splice(0, 0, ssrcGroup.join(' '))
  8726. this.simulcastUtils._replaceVideoSources(lines, sb);
  8727. };
  8728. // Does the actual patching.
  8729. NativeSimulcastSender.prototype._ensureSimulcastGroup = function (lines) {
  8730. this.logger.info('Ensuring simulcast group...');
  8731. if (this.simulcastUtils._indexOfArray('a=ssrc-group:SIM', lines) === this.simulcastUtils._emptyCompoundIndex) {
  8732. this._appendSimulcastGroup(lines);
  8733. this._cacheLocalVideoSources(lines);
  8734. } else {
  8735. // verify that the ssrcs participating in the SIM group are present
  8736. // in the SDP (needed for presence).
  8737. this._restoreLocalVideoSources(lines);
  8738. }
  8739. };
  8740. /**
  8741. * Produces a single stream with multiple tracks for local video sources.
  8742. *
  8743. * @param lines
  8744. * @private
  8745. */
  8746. NativeSimulcastSender.prototype._explodeSimulcastSenderSources = function (lines) {
  8747. var sb, msid, sid, tid, videoSources, self;
  8748. this.logger.info('Exploding local video sources...');
  8749. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8750. self = this;
  8751. if (videoSources.groups && videoSources.groups.length !== 0) {
  8752. videoSources.groups.forEach(function (group) {
  8753. if (group.semantics === 'SIM') {
  8754. group.ssrcs.forEach(function (ssrc) {
  8755. // Get the msid for this ssrc..
  8756. if (self._localExplosionMap[ssrc]) {
  8757. // .. either from the explosion map..
  8758. msid = self._localExplosionMap[ssrc];
  8759. } else {
  8760. // .. or generate a new one (msid).
  8761. sid = videoSources.sources[ssrc].msid
  8762. .substring(0, videoSources.sources[ssrc].msid.indexOf(' '));
  8763. tid = self._generateGuid();
  8764. msid = [sid, tid].join(' ');
  8765. self._localExplosionMap[ssrc] = msid;
  8766. }
  8767. // Assign it to the source object.
  8768. videoSources.sources[ssrc].msid = msid;
  8769. // TODO(gp) Change the msid of associated sources.
  8770. });
  8771. }
  8772. });
  8773. }
  8774. sb = this.simulcastUtils._compileVideoSources(videoSources);
  8775. this.simulcastUtils._replaceVideoSources(lines, sb);
  8776. };
  8777. /**
  8778. * GUM for simulcast.
  8779. *
  8780. * @param constraints
  8781. * @param success
  8782. * @param err
  8783. */
  8784. NativeSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8785. // There's nothing special to do for native simulcast, so just do a normal GUM.
  8786. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8787. success(hqStream);
  8788. }, err);
  8789. };
  8790. /**
  8791. * Prepares the local description for public usage (i.e. to be signaled
  8792. * through Jingle to the focus).
  8793. *
  8794. * @param desc
  8795. * @returns {RTCSessionDescription}
  8796. */
  8797. NativeSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8798. var sb;
  8799. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  8800. return desc;
  8801. }
  8802. sb = desc.sdp.split('\r\n');
  8803. this._explodeSimulcastSenderSources(sb);
  8804. desc = new RTCSessionDescription({
  8805. type: desc.type,
  8806. sdp: sb.join('\r\n')
  8807. });
  8808. this.logger.fine(['Exploded local video sources', desc.sdp].join(' '));
  8809. return desc;
  8810. };
  8811. /**
  8812. * Ensures that the simulcast group is present in the answer, _if_ native
  8813. * simulcast is enabled,
  8814. *
  8815. * @param desc
  8816. * @returns {*}
  8817. */
  8818. NativeSimulcastSender.prototype.transformAnswer = function (desc) {
  8819. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  8820. return desc;
  8821. }
  8822. var sb = desc.sdp.split('\r\n');
  8823. // Even if we have enabled native simulcasting previously
  8824. // (with a call to SLD with an appropriate SDP, for example),
  8825. // createAnswer seems to consistently generate incomplete SDP
  8826. // with missing SSRCS.
  8827. //
  8828. // So, subsequent calls to SLD will have missing SSRCS and presence
  8829. // won't have the complete list of SRCs.
  8830. this._ensureSimulcastGroup(sb);
  8831. desc = new RTCSessionDescription({
  8832. type: desc.type,
  8833. sdp: sb.join('\r\n')
  8834. });
  8835. this.logger.fine(['Transformed answer', desc.sdp].join(' '));
  8836. return desc;
  8837. };
  8838. /**
  8839. *
  8840. *
  8841. * @param desc
  8842. * @returns {*}
  8843. */
  8844. NativeSimulcastSender.prototype.transformLocalDescription = function (desc) {
  8845. return desc;
  8846. };
  8847. NativeSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  8848. // Nothing to do here, native simulcast does that auto-magically.
  8849. };
  8850. NativeSimulcastSender.prototype.constructor = NativeSimulcastSender;
  8851. function SimpleSimulcastSender() {
  8852. SimulcastSender.call(this);
  8853. }
  8854. SimpleSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8855. SimpleSimulcastSender.prototype.localStream = null;
  8856. SimpleSimulcastSender.prototype._localMaps = {
  8857. msids: [],
  8858. msid2ssrc: {}
  8859. };
  8860. /**
  8861. * Groups local video sources together in the ssrc-group:SIM group.
  8862. *
  8863. * @param lines
  8864. * @private
  8865. */
  8866. SimpleSimulcastSender.prototype._groupLocalVideoSources = function (lines) {
  8867. var sb, videoSources, ssrcs = [], ssrc;
  8868. this.logger.info('Grouping local video sources...');
  8869. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8870. for (ssrc in videoSources.sources) {
  8871. // jitsi-meet destroys/creates streams at various places causing
  8872. // the original local stream ids to change. The only thing that
  8873. // remains unchanged is the trackid.
  8874. this._localMaps.msid2ssrc[videoSources.sources[ssrc].msid.split(' ')[1]] = ssrc;
  8875. }
  8876. var self = this;
  8877. // TODO(gp) add only "free" sources.
  8878. this._localMaps.msids.forEach(function (msid) {
  8879. ssrcs.push(self._localMaps.msid2ssrc[msid]);
  8880. });
  8881. if (!videoSources.groups) {
  8882. videoSources.groups = [];
  8883. }
  8884. videoSources.groups.push({
  8885. 'semantics': 'SIM',
  8886. 'ssrcs': ssrcs
  8887. });
  8888. sb = this.simulcastUtils._compileVideoSources(videoSources);
  8889. this.simulcastUtils._replaceVideoSources(lines, sb);
  8890. };
  8891. /**
  8892. * GUM for simulcast.
  8893. *
  8894. * @param constraints
  8895. * @param success
  8896. * @param err
  8897. */
  8898. SimpleSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8899. // TODO(gp) what if we request a resolution not supported by the hardware?
  8900. // TODO(gp) make the lq stream configurable; although this wouldn't work with native simulcast
  8901. var lqConstraints = {
  8902. audio: false,
  8903. video: {
  8904. mandatory: {
  8905. maxWidth: 320,
  8906. maxHeight: 180,
  8907. maxFrameRate: 15
  8908. }
  8909. }
  8910. };
  8911. this.logger.info('HQ constraints: ', constraints);
  8912. this.logger.info('LQ constraints: ', lqConstraints);
  8913. // NOTE(gp) if we request the lq stream first webkitGetUserMedia
  8914. // fails randomly. Tested with Chrome 37. As fippo suggested, the
  8915. // reason appears to be that Chrome only acquires the cam once and
  8916. // then downscales the picture (https://code.google.com/p/chromium/issues/detail?id=346616#c11)
  8917. var self = this;
  8918. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8919. self.localStream = hqStream;
  8920. // reset local maps.
  8921. self._localMaps.msids = [];
  8922. self._localMaps.msid2ssrc = {};
  8923. // add hq trackid to local map
  8924. self._localMaps.msids.push(hqStream.getVideoTracks()[0].id);
  8925. navigator.webkitGetUserMedia(lqConstraints, function (lqStream) {
  8926. self.displayedLocalVideoStream = lqStream;
  8927. // NOTE(gp) The specification says Array.forEach() will visit
  8928. // the array elements in numeric order, and that it doesn't
  8929. // visit elements that don't exist.
  8930. // add lq trackid to local map
  8931. self._localMaps.msids.splice(0, 0, lqStream.getVideoTracks()[0].id);
  8932. self.localStream.addTrack(lqStream.getVideoTracks()[0]);
  8933. success(self.localStream);
  8934. }, err);
  8935. }, err);
  8936. };
  8937. /**
  8938. * Prepares the local description for public usage (i.e. to be signaled
  8939. * through Jingle to the focus).
  8940. *
  8941. * @param desc
  8942. * @returns {RTCSessionDescription}
  8943. */
  8944. SimpleSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8945. var sb;
  8946. if (!this.simulcastUtils.isValidDescription(desc)) {
  8947. return desc;
  8948. }
  8949. sb = desc.sdp.split('\r\n');
  8950. this._groupLocalVideoSources(sb);
  8951. desc = new RTCSessionDescription({
  8952. type: desc.type,
  8953. sdp: sb.join('\r\n')
  8954. });
  8955. this.logger.fine('Grouped local video sources');
  8956. this.logger.fine(desc.sdp);
  8957. return desc;
  8958. };
  8959. /**
  8960. * Ensures that the simulcast group is present in the answer, _if_ native
  8961. * simulcast is enabled,
  8962. *
  8963. * @param desc
  8964. * @returns {*}
  8965. */
  8966. SimpleSimulcastSender.prototype.transformAnswer = function (desc) {
  8967. return desc;
  8968. };
  8969. /**
  8970. *
  8971. *
  8972. * @param desc
  8973. * @returns {*}
  8974. */
  8975. SimpleSimulcastSender.prototype.transformLocalDescription = function (desc) {
  8976. var sb = desc.sdp.split('\r\n');
  8977. this.simulcastUtils._removeSimulcastGroup(sb);
  8978. desc = new RTCSessionDescription({
  8979. type: desc.type,
  8980. sdp: sb.join('\r\n')
  8981. });
  8982. this.logger.fine('Transformed local description');
  8983. this.logger.fine(desc.sdp);
  8984. return desc;
  8985. };
  8986. SimpleSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  8987. var trackid;
  8988. var self = this;
  8989. this.logger.log(['Requested to', enabled ? 'enable' : 'disable', ssrc].join(' '));
  8990. if (Object.keys(this._localMaps.msid2ssrc).some(function (tid) {
  8991. // Search for the track id that corresponds to the ssrc
  8992. if (self._localMaps.msid2ssrc[tid] == ssrc) {
  8993. trackid = tid;
  8994. return true;
  8995. }
  8996. }) && self.localStream.getVideoTracks().some(function (track) {
  8997. // Start/stop the track that corresponds to the track id
  8998. if (track.id === trackid) {
  8999. track.enabled = enabled;
  9000. return true;
  9001. }
  9002. })) {
  9003. this.logger.log([trackid, enabled ? 'enabled' : 'disabled'].join(' '));
  9004. $(document).trigger(enabled
  9005. ? 'simulcastlayerstarted'
  9006. : 'simulcastlayerstopped');
  9007. } else {
  9008. this.logger.error("I don't have a local stream with SSRC " + ssrc);
  9009. }
  9010. };
  9011. SimpleSimulcastSender.prototype.constructor = SimpleSimulcastSender;
  9012. function NoSimulcastSender() {
  9013. SimulcastSender.call(this);
  9014. }
  9015. NoSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  9016. /**
  9017. * GUM for simulcast.
  9018. *
  9019. * @param constraints
  9020. * @param success
  9021. * @param err
  9022. */
  9023. NoSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  9024. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  9025. success(hqStream);
  9026. }, err);
  9027. };
  9028. /**
  9029. * Prepares the local description for public usage (i.e. to be signaled
  9030. * through Jingle to the focus).
  9031. *
  9032. * @param desc
  9033. * @returns {RTCSessionDescription}
  9034. */
  9035. NoSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  9036. return desc;
  9037. };
  9038. /**
  9039. * Ensures that the simulcast group is present in the answer, _if_ native
  9040. * simulcast is enabled,
  9041. *
  9042. * @param desc
  9043. * @returns {*}
  9044. */
  9045. NoSimulcastSender.prototype.transformAnswer = function (desc) {
  9046. return desc;
  9047. };
  9048. /**
  9049. *
  9050. *
  9051. * @param desc
  9052. * @returns {*}
  9053. */
  9054. NoSimulcastSender.prototype.transformLocalDescription = function (desc) {
  9055. return desc;
  9056. };
  9057. NoSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  9058. };
  9059. NoSimulcastSender.prototype.constructor = NoSimulcastSender;
  9060. module.exports = {
  9061. "native": NativeSimulcastSender,
  9062. "no": NoSimulcastSender
  9063. }
  9064. },{"./SimulcastLogger":39,"./SimulcastUtils":42}],42:[function(require,module,exports){
  9065. var SimulcastLogger = require("./SimulcastLogger");
  9066. /**
  9067. *
  9068. * @constructor
  9069. */
  9070. function SimulcastUtils() {
  9071. this.logger = new SimulcastLogger("SimulcastUtils", 1);
  9072. }
  9073. /**
  9074. *
  9075. * @type {{}}
  9076. * @private
  9077. */
  9078. SimulcastUtils.prototype._emptyCompoundIndex = {};
  9079. /**
  9080. *
  9081. * @param lines
  9082. * @param videoSources
  9083. * @private
  9084. */
  9085. SimulcastUtils.prototype._replaceVideoSources = function (lines, videoSources) {
  9086. var i, inVideo = false, index = -1, howMany = 0;
  9087. this.logger.info('Replacing video sources...');
  9088. for (i = 0; i < lines.length; i++) {
  9089. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  9090. // Out of video.
  9091. break;
  9092. }
  9093. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  9094. // In video.
  9095. inVideo = true;
  9096. }
  9097. if (inVideo && (lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:'
  9098. || lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:')) {
  9099. if (index === -1) {
  9100. index = i;
  9101. }
  9102. howMany++;
  9103. }
  9104. }
  9105. // efficiency baby ;)
  9106. lines.splice.apply(lines,
  9107. [index, howMany].concat(videoSources));
  9108. };
  9109. SimulcastUtils.prototype.isValidDescription = function (desc)
  9110. {
  9111. return desc && desc != null
  9112. && desc.type && desc.type != ''
  9113. && desc.sdp && desc.sdp != '';
  9114. };
  9115. SimulcastUtils.prototype._getVideoSources = function (lines) {
  9116. var i, inVideo = false, sb = [];
  9117. this.logger.info('Getting video sources...');
  9118. for (i = 0; i < lines.length; i++) {
  9119. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  9120. // Out of video.
  9121. break;
  9122. }
  9123. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  9124. // In video.
  9125. inVideo = true;
  9126. }
  9127. if (inVideo && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  9128. // In SSRC.
  9129. sb.push(lines[i]);
  9130. }
  9131. if (inVideo && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  9132. sb.push(lines[i]);
  9133. }
  9134. }
  9135. return sb;
  9136. };
  9137. SimulcastUtils.prototype.parseMedia = function (lines, mediatypes) {
  9138. var i, res = [], type, cur_media, idx, ssrcs, cur_ssrc, ssrc,
  9139. ssrc_attribute, group, semantics, skip = true;
  9140. this.logger.info('Parsing media sources...');
  9141. for (i = 0; i < lines.length; i++) {
  9142. if (lines[i].substring(0, 'm='.length) === 'm=') {
  9143. type = lines[i]
  9144. .substr('m='.length, lines[i].indexOf(' ') - 'm='.length);
  9145. skip = mediatypes !== undefined && mediatypes.indexOf(type) === -1;
  9146. if (!skip) {
  9147. cur_media = {
  9148. 'type': type,
  9149. 'sources': {},
  9150. 'groups': []
  9151. };
  9152. res.push(cur_media);
  9153. }
  9154. } else if (!skip && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  9155. idx = lines[i].indexOf(' ');
  9156. ssrc = lines[i].substring('a=ssrc:'.length, idx);
  9157. if (cur_media.sources[ssrc] === undefined) {
  9158. cur_ssrc = {'ssrc': ssrc};
  9159. cur_media.sources[ssrc] = cur_ssrc;
  9160. }
  9161. ssrc_attribute = lines[i].substr(idx + 1).split(':', 2)[0];
  9162. cur_ssrc[ssrc_attribute] = lines[i].substr(idx + 1).split(':', 2)[1];
  9163. if (cur_media.base === undefined) {
  9164. cur_media.base = cur_ssrc;
  9165. }
  9166. } else if (!skip && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  9167. idx = lines[i].indexOf(' ');
  9168. semantics = lines[i].substr(0, idx).substr('a=ssrc-group:'.length);
  9169. ssrcs = lines[i].substr(idx).trim().split(' ');
  9170. group = {
  9171. 'semantics': semantics,
  9172. 'ssrcs': ssrcs
  9173. };
  9174. cur_media.groups.push(group);
  9175. } else if (!skip && (lines[i].substring(0, 'a=sendrecv'.length) === 'a=sendrecv' ||
  9176. lines[i].substring(0, 'a=recvonly'.length) === 'a=recvonly' ||
  9177. lines[i].substring(0, 'a=sendonly'.length) === 'a=sendonly' ||
  9178. lines[i].substring(0, 'a=inactive'.length) === 'a=inactive')) {
  9179. cur_media.direction = lines[i].substring('a='.length);
  9180. }
  9181. }
  9182. return res;
  9183. };
  9184. /**
  9185. * The _indexOfArray() method returns the first a CompoundIndex at which a
  9186. * given element can be found in the array, or _emptyCompoundIndex if it is
  9187. * not present.
  9188. *
  9189. * Example:
  9190. *
  9191. * _indexOfArray('3', [ 'this is line 1', 'this is line 2', 'this is line 3' ])
  9192. *
  9193. * returns {row: 2, column: 14}
  9194. *
  9195. * @param needle
  9196. * @param haystack
  9197. * @param start
  9198. * @returns {}
  9199. * @private
  9200. */
  9201. SimulcastUtils.prototype._indexOfArray = function (needle, haystack, start) {
  9202. var length = haystack.length, idx, i;
  9203. if (!start) {
  9204. start = 0;
  9205. }
  9206. for (i = start; i < length; i++) {
  9207. idx = haystack[i].indexOf(needle);
  9208. if (idx !== -1) {
  9209. return {row: i, column: idx};
  9210. }
  9211. }
  9212. return this._emptyCompoundIndex;
  9213. };
  9214. SimulcastUtils.prototype._removeSimulcastGroup = function (lines) {
  9215. var i;
  9216. for (i = lines.length - 1; i >= 0; i--) {
  9217. if (lines[i].indexOf('a=ssrc-group:SIM') !== -1) {
  9218. lines.splice(i, 1);
  9219. }
  9220. }
  9221. };
  9222. SimulcastUtils.prototype._compileVideoSources = function (videoSources) {
  9223. var sb = [], ssrc, addedSSRCs = [];
  9224. this.logger.info('Compiling video sources...');
  9225. // Add the groups
  9226. if (videoSources.groups && videoSources.groups.length !== 0) {
  9227. videoSources.groups.forEach(function (group) {
  9228. if (group.ssrcs && group.ssrcs.length !== 0) {
  9229. sb.push([['a=ssrc-group:', group.semantics].join(''), group.ssrcs.join(' ')].join(' '));
  9230. // if (group.semantics !== 'SIM') {
  9231. group.ssrcs.forEach(function (ssrc) {
  9232. addedSSRCs.push(ssrc);
  9233. sb.splice.apply(sb, [sb.length, 0].concat([
  9234. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  9235. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  9236. });
  9237. //}
  9238. }
  9239. });
  9240. }
  9241. // Then add any free sources.
  9242. if (videoSources.sources) {
  9243. for (ssrc in videoSources.sources) {
  9244. if (addedSSRCs.indexOf(ssrc) === -1) {
  9245. sb.splice.apply(sb, [sb.length, 0].concat([
  9246. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  9247. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  9248. }
  9249. }
  9250. }
  9251. return sb;
  9252. };
  9253. module.exports = SimulcastUtils;
  9254. },{"./SimulcastLogger":39}],43:[function(require,module,exports){
  9255. /*jslint plusplus: true */
  9256. /*jslint nomen: true*/
  9257. var SimulcastSender = require("./SimulcastSender");
  9258. var NoSimulcastSender = SimulcastSender["no"];
  9259. var NativeSimulcastSender = SimulcastSender["native"];
  9260. var SimulcastReceiver = require("./SimulcastReceiver");
  9261. var SimulcastUtils = require("./SimulcastUtils");
  9262. var RTCEvents = require("../../service/RTC/RTCEvents");
  9263. /**
  9264. *
  9265. * @constructor
  9266. */
  9267. function SimulcastManager() {
  9268. // Create the simulcast utilities.
  9269. this.simulcastUtils = new SimulcastUtils();
  9270. // Create remote simulcast.
  9271. this.simulcastReceiver = new SimulcastReceiver();
  9272. // Initialize local simulcast.
  9273. // TODO(gp) move into SimulcastManager.prototype.getUserMedia and take into
  9274. // account constraints.
  9275. if (!config.enableSimulcast) {
  9276. this.simulcastSender = new NoSimulcastSender();
  9277. } else {
  9278. var isChromium = window.chrome,
  9279. vendorName = window.navigator.vendor;
  9280. if(isChromium !== null && isChromium !== undefined
  9281. /* skip opera */
  9282. && vendorName === "Google Inc."
  9283. /* skip Chromium as suggested by fippo */
  9284. && !window.navigator.appVersion.match(/Chromium\//) ) {
  9285. var ver = parseInt(window.navigator.appVersion.match(/Chrome\/(\d+)\./)[1], 10);
  9286. if (ver > 37) {
  9287. this.simulcastSender = new NativeSimulcastSender();
  9288. } else {
  9289. this.simulcastSender = new NoSimulcastSender();
  9290. }
  9291. } else {
  9292. this.simulcastSender = new NoSimulcastSender();
  9293. }
  9294. }
  9295. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  9296. function (endpointSimulcastLayers) {
  9297. endpointSimulcastLayers.forEach(function (esl) {
  9298. var ssrc = esl.simulcastLayer.primarySSRC;
  9299. simulcast._setReceivingVideoStream(esl.endpoint, ssrc);
  9300. });
  9301. });
  9302. APP.RTC.addListener(RTCEvents.SIMULCAST_START, function (simulcastLayer) {
  9303. var ssrc = simulcastLayer.primarySSRC;
  9304. simulcast._setLocalVideoStreamEnabled(ssrc, true);
  9305. });
  9306. APP.RTC.addListener(RTCEvents.SIMULCAST_STOP, function (simulcastLayer) {
  9307. var ssrc = simulcastLayer.primarySSRC;
  9308. simulcast._setLocalVideoStreamEnabled(ssrc, false);
  9309. });
  9310. }
  9311. /**
  9312. * Restores the simulcast groups of the remote description. In
  9313. * transformRemoteDescription we remove those in order for the set remote
  9314. * description to succeed. The focus needs the signal the groups to new
  9315. * participants.
  9316. *
  9317. * @param desc
  9318. * @returns {*}
  9319. */
  9320. SimulcastManager.prototype.reverseTransformRemoteDescription = function (desc) {
  9321. return this.simulcastReceiver.reverseTransformRemoteDescription(desc);
  9322. };
  9323. /**
  9324. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  9325. * either gets confused and thinks this is an FID group or, if an FID group
  9326. * is already present, it fails to set the remote description.
  9327. *
  9328. * @param desc
  9329. * @returns {*}
  9330. */
  9331. SimulcastManager.prototype.transformRemoteDescription = function (desc) {
  9332. return this.simulcastReceiver.transformRemoteDescription(desc);
  9333. };
  9334. /**
  9335. * Gets the fully qualified msid (stream.id + track.id) associated to the
  9336. * SSRC.
  9337. *
  9338. * @param ssrc
  9339. * @returns {*}
  9340. */
  9341. SimulcastManager.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  9342. return this.simulcastReceiver.getRemoteVideoStreamIdBySSRC(ssrc);
  9343. };
  9344. /**
  9345. * Returns a stream with single video track, the one currently being
  9346. * received by this endpoint.
  9347. *
  9348. * @param stream the remote simulcast stream.
  9349. * @returns {webkitMediaStream}
  9350. */
  9351. SimulcastManager.prototype.getReceivingVideoStream = function (stream) {
  9352. return this.simulcastReceiver.getReceivingVideoStream(stream);
  9353. };
  9354. /**
  9355. *
  9356. *
  9357. * @param desc
  9358. * @returns {*}
  9359. */
  9360. SimulcastManager.prototype.transformLocalDescription = function (desc) {
  9361. return this.simulcastSender.transformLocalDescription(desc);
  9362. };
  9363. /**
  9364. *
  9365. * @returns {*}
  9366. */
  9367. SimulcastManager.prototype.getLocalVideoStream = function() {
  9368. return this.simulcastSender.getLocalVideoStream();
  9369. };
  9370. /**
  9371. * GUM for simulcast.
  9372. *
  9373. * @param constraints
  9374. * @param success
  9375. * @param err
  9376. */
  9377. SimulcastManager.prototype.getUserMedia = function (constraints, success, err) {
  9378. this.simulcastSender.getUserMedia(constraints, success, err);
  9379. };
  9380. /**
  9381. * Prepares the local description for public usage (i.e. to be signaled
  9382. * through Jingle to the focus).
  9383. *
  9384. * @param desc
  9385. * @returns {RTCSessionDescription}
  9386. */
  9387. SimulcastManager.prototype.reverseTransformLocalDescription = function (desc) {
  9388. return this.simulcastSender.reverseTransformLocalDescription(desc);
  9389. };
  9390. /**
  9391. * Ensures that the simulcast group is present in the answer, _if_ native
  9392. * simulcast is enabled,
  9393. *
  9394. * @param desc
  9395. * @returns {*}
  9396. */
  9397. SimulcastManager.prototype.transformAnswer = function (desc) {
  9398. return this.simulcastSender.transformAnswer(desc);
  9399. };
  9400. SimulcastManager.prototype.getReceivingSSRC = function (jid) {
  9401. return this.simulcastReceiver.getReceivingSSRC(jid);
  9402. };
  9403. SimulcastManager.prototype.getReceivingVideoStreamBySSRC = function (msid) {
  9404. return this.simulcastReceiver.getReceivingVideoStreamBySSRC(msid);
  9405. };
  9406. /**
  9407. *
  9408. * @param lines
  9409. * @param mediatypes
  9410. * @returns {*}
  9411. */
  9412. SimulcastManager.prototype.parseMedia = function(lines, mediatypes) {
  9413. var sb = lines.sdp.split('\r\n');
  9414. return this.simulcastUtils.parseMedia(sb, mediatypes);
  9415. };
  9416. SimulcastManager.prototype._setReceivingVideoStream = function(resource, ssrc) {
  9417. this.simulcastReceiver._setReceivingVideoStream(resource, ssrc);
  9418. };
  9419. SimulcastManager.prototype._setLocalVideoStreamEnabled = function(ssrc, enabled) {
  9420. this.simulcastSender._setLocalVideoStreamEnabled(ssrc, enabled);
  9421. };
  9422. SimulcastManager.prototype.resetSender = function() {
  9423. if (typeof this.simulcastSender.reset === 'function'){
  9424. this.simulcastSender.reset();
  9425. }
  9426. };
  9427. var simulcast = new SimulcastManager();
  9428. module.exports = simulcast;
  9429. },{"../../service/RTC/RTCEvents":81,"./SimulcastReceiver":40,"./SimulcastSender":41,"./SimulcastUtils":42}],44:[function(require,module,exports){
  9430. /**
  9431. * Provides statistics for the local stream.
  9432. */
  9433. /**
  9434. * Size of the webaudio analizer buffer.
  9435. * @type {number}
  9436. */
  9437. var WEBAUDIO_ANALIZER_FFT_SIZE = 2048;
  9438. /**
  9439. * Value of the webaudio analizer smoothing time parameter.
  9440. * @type {number}
  9441. */
  9442. var WEBAUDIO_ANALIZER_SMOOTING_TIME = 0.8;
  9443. /**
  9444. * Converts time domain data array to audio level.
  9445. * @param array the time domain data array.
  9446. * @returns {number} the audio level
  9447. */
  9448. function timeDomainDataToAudioLevel(samples) {
  9449. var maxVolume = 0;
  9450. var length = samples.length;
  9451. for (var i = 0; i < length; i++) {
  9452. if (maxVolume < samples[i])
  9453. maxVolume = samples[i];
  9454. }
  9455. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  9456. };
  9457. /**
  9458. * Animates audio level change
  9459. * @param newLevel the new audio level
  9460. * @param lastLevel the last audio level
  9461. * @returns {Number} the audio level to be set
  9462. */
  9463. function animateLevel(newLevel, lastLevel)
  9464. {
  9465. var value = 0;
  9466. var diff = lastLevel - newLevel;
  9467. if(diff > 0.2)
  9468. {
  9469. value = lastLevel - 0.2;
  9470. }
  9471. else if(diff < -0.4)
  9472. {
  9473. value = lastLevel + 0.4;
  9474. }
  9475. else
  9476. {
  9477. value = newLevel;
  9478. }
  9479. return parseFloat(value.toFixed(3));
  9480. }
  9481. /**
  9482. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  9483. *
  9484. * @param stream the local stream
  9485. * @param interval stats refresh interval given in ms.
  9486. * @param {function(LocalStatsCollector)} updateCallback the callback called on stats
  9487. * update.
  9488. * @constructor
  9489. */
  9490. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  9491. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  9492. this.stream = stream;
  9493. this.intervalId = null;
  9494. this.intervalMilis = interval;
  9495. this.eventEmitter = eventEmitter;
  9496. this.audioLevel = 0;
  9497. this.statisticsService = statisticsService;
  9498. }
  9499. /**
  9500. * Starts the collecting the statistics.
  9501. */
  9502. LocalStatsCollector.prototype.start = function () {
  9503. if (config.disableAudioLevels || !window.AudioContext)
  9504. return;
  9505. var context = new AudioContext();
  9506. var analyser = context.createAnalyser();
  9507. analyser.smoothingTimeConstant = WEBAUDIO_ANALIZER_SMOOTING_TIME;
  9508. analyser.fftSize = WEBAUDIO_ANALIZER_FFT_SIZE;
  9509. var source = context.createMediaStreamSource(this.stream);
  9510. source.connect(analyser);
  9511. var self = this;
  9512. this.intervalId = setInterval(
  9513. function () {
  9514. var array = new Uint8Array(analyser.frequencyBinCount);
  9515. analyser.getByteTimeDomainData(array);
  9516. var audioLevel = timeDomainDataToAudioLevel(array);
  9517. if(audioLevel != self.audioLevel) {
  9518. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  9519. self.eventEmitter.emit(
  9520. "statistics.audioLevel",
  9521. self.statisticsService.LOCAL_JID,
  9522. self.audioLevel);
  9523. }
  9524. },
  9525. this.intervalMilis
  9526. );
  9527. };
  9528. /**
  9529. * Stops collecting the statistics.
  9530. */
  9531. LocalStatsCollector.prototype.stop = function () {
  9532. if (this.intervalId) {
  9533. clearInterval(this.intervalId);
  9534. this.intervalId = null;
  9535. }
  9536. };
  9537. module.exports = LocalStatsCollector;
  9538. },{}],45:[function(require,module,exports){
  9539. /* global ssrc2jid */
  9540. /* jshint -W117 */
  9541. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  9542. /**
  9543. * Calculates packet lost percent using the number of lost packets and the
  9544. * number of all packet.
  9545. * @param lostPackets the number of lost packets
  9546. * @param totalPackets the number of all packets.
  9547. * @returns {number} packet loss percent
  9548. */
  9549. function calculatePacketLoss(lostPackets, totalPackets) {
  9550. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  9551. return 0;
  9552. return Math.round((lostPackets/totalPackets)*100);
  9553. }
  9554. function getStatValue(item, name) {
  9555. if(!keyMap[APP.RTC.getBrowserType()][name])
  9556. throw "The property isn't supported!";
  9557. var key = keyMap[APP.RTC.getBrowserType()][name];
  9558. return APP.RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_CHROME? item.stat(key) : item[key];
  9559. }
  9560. /**
  9561. * Peer statistics data holder.
  9562. * @constructor
  9563. */
  9564. function PeerStats()
  9565. {
  9566. this.ssrc2Loss = {};
  9567. this.ssrc2AudioLevel = {};
  9568. this.ssrc2bitrate = {};
  9569. this.ssrc2resolution = {};
  9570. }
  9571. /**
  9572. * The bandwidth
  9573. * @type {{}}
  9574. */
  9575. PeerStats.bandwidth = {};
  9576. /**
  9577. * The bit rate
  9578. * @type {{}}
  9579. */
  9580. PeerStats.bitrate = {};
  9581. /**
  9582. * The packet loss rate
  9583. * @type {{}}
  9584. */
  9585. PeerStats.packetLoss = null;
  9586. /**
  9587. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  9588. * represented by this instance.
  9589. * @param ssrc audio or video RTP stream SSRC.
  9590. * @param lossRate new packet loss rate value to be set.
  9591. */
  9592. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  9593. {
  9594. this.ssrc2Loss[ssrc] = lossRate;
  9595. };
  9596. /**
  9597. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  9598. * represented by this instance.
  9599. * @param ssrc audio or video RTP stream SSRC.
  9600. * @param resolution new resolution value to be set.
  9601. */
  9602. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  9603. {
  9604. if(resolution === null && this.ssrc2resolution[ssrc])
  9605. {
  9606. delete this.ssrc2resolution[ssrc];
  9607. }
  9608. else if(resolution !== null)
  9609. this.ssrc2resolution[ssrc] = resolution;
  9610. };
  9611. /**
  9612. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  9613. * represented by this instance.
  9614. * @param ssrc audio or video RTP stream SSRC.
  9615. * @param bitrate new bitrate value to be set.
  9616. */
  9617. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  9618. {
  9619. if(this.ssrc2bitrate[ssrc])
  9620. {
  9621. this.ssrc2bitrate[ssrc].download += bitrate.download;
  9622. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  9623. }
  9624. else {
  9625. this.ssrc2bitrate[ssrc] = bitrate;
  9626. }
  9627. };
  9628. /**
  9629. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  9630. * the stream which belongs to the peer represented by this instance.
  9631. * @param ssrc RTP stream SSRC for which current audio level value will be
  9632. * updated.
  9633. * @param audioLevel the new audio level value to be set. Value is truncated to
  9634. * fit the range from 0 to 1.
  9635. */
  9636. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  9637. {
  9638. // Range limit 0 - 1
  9639. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  9640. };
  9641. function formatAudioLevel(audioLevel) {
  9642. return Math.min(Math.max(audioLevel, 0), 1);
  9643. }
  9644. /**
  9645. * Array with the transport information.
  9646. * @type {Array}
  9647. */
  9648. PeerStats.transport = [];
  9649. /**
  9650. * <tt>StatsCollector</tt> registers for stats updates of given
  9651. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  9652. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  9653. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  9654. * instance as an event source.
  9655. *
  9656. * @param peerconnection webRTC peer connection object.
  9657. * @param interval stats refresh interval given in ms.
  9658. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  9659. * called on stats update.
  9660. * @constructor
  9661. */
  9662. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  9663. {
  9664. this.peerconnection = peerconnection;
  9665. this.baselineAudioLevelsReport = null;
  9666. this.currentAudioLevelsReport = null;
  9667. this.currentStatsReport = null;
  9668. this.baselineStatsReport = null;
  9669. this.audioLevelsIntervalId = null;
  9670. this.eventEmitter = eventEmitter;
  9671. /**
  9672. * Gather PeerConnection stats once every this many milliseconds.
  9673. */
  9674. this.GATHER_INTERVAL = 15000;
  9675. /**
  9676. * Log stats via the focus once every this many milliseconds.
  9677. */
  9678. this.LOG_INTERVAL = 60000;
  9679. /**
  9680. * Gather stats and store them in this.statsToBeLogged.
  9681. */
  9682. this.gatherStatsIntervalId = null;
  9683. /**
  9684. * Send the stats already saved in this.statsToBeLogged to be logged via
  9685. * the focus.
  9686. */
  9687. this.logStatsIntervalId = null;
  9688. /**
  9689. * Stores the statistics which will be send to the focus to be logged.
  9690. */
  9691. this.statsToBeLogged =
  9692. {
  9693. timestamps: [],
  9694. stats: {}
  9695. };
  9696. // Updates stats interval
  9697. this.audioLevelsIntervalMilis = audioLevelsInterval;
  9698. this.statsIntervalId = null;
  9699. this.statsIntervalMilis = statsInterval;
  9700. // Map of jids to PeerStats
  9701. this.jid2stats = {};
  9702. }
  9703. module.exports = StatsCollector;
  9704. /**
  9705. * Stops stats updates.
  9706. */
  9707. StatsCollector.prototype.stop = function () {
  9708. if (this.audioLevelsIntervalId) {
  9709. clearInterval(this.audioLevelsIntervalId);
  9710. this.audioLevelsIntervalId = null;
  9711. }
  9712. if (this.statsIntervalId)
  9713. {
  9714. clearInterval(this.statsIntervalId);
  9715. this.statsIntervalId = null;
  9716. }
  9717. if(this.logStatsIntervalId)
  9718. {
  9719. clearInterval(this.logStatsIntervalId);
  9720. this.logStatsIntervalId = null;
  9721. }
  9722. if(this.gatherStatsIntervalId)
  9723. {
  9724. clearInterval(this.gatherStatsIntervalId);
  9725. this.gatherStatsIntervalId = null;
  9726. }
  9727. };
  9728. /**
  9729. * Callback passed to <tt>getStats</tt> method.
  9730. * @param error an error that occurred on <tt>getStats</tt> call.
  9731. */
  9732. StatsCollector.prototype.errorCallback = function (error)
  9733. {
  9734. console.error("Get stats error", error);
  9735. this.stop();
  9736. };
  9737. /**
  9738. * Starts stats updates.
  9739. */
  9740. StatsCollector.prototype.start = function ()
  9741. {
  9742. var self = this;
  9743. if(!config.disableAudioLevels) {
  9744. console.debug("set audio levels interval");
  9745. this.audioLevelsIntervalId = setInterval(
  9746. function () {
  9747. // Interval updates
  9748. self.peerconnection.getStats(
  9749. function (report) {
  9750. var results = null;
  9751. if (!report || !report.result ||
  9752. typeof report.result != 'function') {
  9753. results = report;
  9754. }
  9755. else {
  9756. results = report.result();
  9757. }
  9758. //console.error("Got interval report", results);
  9759. self.currentAudioLevelsReport = results;
  9760. self.processAudioLevelReport();
  9761. self.baselineAudioLevelsReport =
  9762. self.currentAudioLevelsReport;
  9763. },
  9764. self.errorCallback
  9765. );
  9766. },
  9767. self.audioLevelsIntervalMilis
  9768. );
  9769. }
  9770. if(!config.disableStats) {
  9771. console.debug("set stats interval");
  9772. this.statsIntervalId = setInterval(
  9773. function () {
  9774. // Interval updates
  9775. self.peerconnection.getStats(
  9776. function (report) {
  9777. var results = null;
  9778. if (!report || !report.result ||
  9779. typeof report.result != 'function') {
  9780. //firefox
  9781. results = report;
  9782. }
  9783. else {
  9784. //chrome
  9785. results = report.result();
  9786. }
  9787. //console.error("Got interval report", results);
  9788. self.currentStatsReport = results;
  9789. try {
  9790. self.processStatsReport();
  9791. }
  9792. catch (e) {
  9793. console.error("Unsupported key:" + e, e);
  9794. }
  9795. self.baselineStatsReport = self.currentStatsReport;
  9796. },
  9797. self.errorCallback
  9798. );
  9799. },
  9800. self.statsIntervalMilis
  9801. );
  9802. }
  9803. if (config.logStats) {
  9804. this.gatherStatsIntervalId = setInterval(
  9805. function () {
  9806. self.peerconnection.getStats(
  9807. function (report) {
  9808. self.addStatsToBeLogged(report.result());
  9809. },
  9810. function () {
  9811. }
  9812. );
  9813. },
  9814. this.GATHER_INTERVAL
  9815. );
  9816. this.logStatsIntervalId = setInterval(
  9817. function() { self.logStats(); },
  9818. this.LOG_INTERVAL);
  9819. }
  9820. };
  9821. /**
  9822. * Checks whether a certain record should be included in the logged statistics.
  9823. */
  9824. function acceptStat(reportId, reportType, statName) {
  9825. if (reportType == "googCandidatePair" && statName == "googChannelId")
  9826. return false;
  9827. if (reportType == "ssrc") {
  9828. if (statName == "googTrackId" ||
  9829. statName == "transportId" ||
  9830. statName == "ssrc")
  9831. return false;
  9832. }
  9833. return true;
  9834. }
  9835. /**
  9836. * Checks whether a certain record should be included in the logged statistics.
  9837. */
  9838. function acceptReport(id, type) {
  9839. if (id.substring(0, 15) == "googCertificate" ||
  9840. id.substring(0, 9) == "googTrack" ||
  9841. id.substring(0, 20) == "googLibjingleSession")
  9842. return false;
  9843. if (type == "googComponent")
  9844. return false;
  9845. return true;
  9846. }
  9847. /**
  9848. * Converts the stats to the format used for logging, and saves the data in
  9849. * this.statsToBeLogged.
  9850. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  9851. */
  9852. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  9853. var self = this;
  9854. var num_records = this.statsToBeLogged.timestamps.length;
  9855. this.statsToBeLogged.timestamps.push(new Date().getTime());
  9856. reports.map(function (report) {
  9857. if (!acceptReport(report.id, report.type))
  9858. return;
  9859. var stat = self.statsToBeLogged.stats[report.id];
  9860. if (!stat) {
  9861. stat = self.statsToBeLogged.stats[report.id] = {};
  9862. }
  9863. stat.type = report.type;
  9864. report.names().map(function (name) {
  9865. if (!acceptStat(report.id, report.type, name))
  9866. return;
  9867. var values = stat[name];
  9868. if (!values) {
  9869. values = stat[name] = [];
  9870. }
  9871. while (values.length < num_records) {
  9872. values.push(null);
  9873. }
  9874. values.push(report.stat(name));
  9875. });
  9876. });
  9877. };
  9878. StatsCollector.prototype.logStats = function () {
  9879. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  9880. return;
  9881. // Reset the stats
  9882. this.statsToBeLogged.stats = {};
  9883. this.statsToBeLogged.timestamps = [];
  9884. };
  9885. var keyMap = {};
  9886. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  9887. "ssrc": "ssrc",
  9888. "packetsReceived": "packetsReceived",
  9889. "packetsLost": "packetsLost",
  9890. "packetsSent": "packetsSent",
  9891. "bytesReceived": "bytesReceived",
  9892. "bytesSent": "bytesSent"
  9893. };
  9894. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  9895. "receiveBandwidth": "googAvailableReceiveBandwidth",
  9896. "sendBandwidth": "googAvailableSendBandwidth",
  9897. "remoteAddress": "googRemoteAddress",
  9898. "transportType": "googTransportType",
  9899. "localAddress": "googLocalAddress",
  9900. "activeConnection": "googActiveConnection",
  9901. "ssrc": "ssrc",
  9902. "packetsReceived": "packetsReceived",
  9903. "packetsSent": "packetsSent",
  9904. "packetsLost": "packetsLost",
  9905. "bytesReceived": "bytesReceived",
  9906. "bytesSent": "bytesSent",
  9907. "googFrameHeightReceived": "googFrameHeightReceived",
  9908. "googFrameWidthReceived": "googFrameWidthReceived",
  9909. "googFrameHeightSent": "googFrameHeightSent",
  9910. "googFrameWidthSent": "googFrameWidthSent",
  9911. "audioInputLevel": "audioInputLevel",
  9912. "audioOutputLevel": "audioOutputLevel"
  9913. };
  9914. /**
  9915. * Stats processing logic.
  9916. */
  9917. StatsCollector.prototype.processStatsReport = function () {
  9918. if (!this.baselineStatsReport) {
  9919. return;
  9920. }
  9921. for (var idx in this.currentStatsReport) {
  9922. var now = this.currentStatsReport[idx];
  9923. try {
  9924. if (getStatValue(now, 'receiveBandwidth') ||
  9925. getStatValue(now, 'sendBandwidth')) {
  9926. PeerStats.bandwidth = {
  9927. "download": Math.round(
  9928. (getStatValue(now, 'receiveBandwidth')) / 1000),
  9929. "upload": Math.round(
  9930. (getStatValue(now, 'sendBandwidth')) / 1000)
  9931. };
  9932. }
  9933. }
  9934. catch(e){/*not supported*/}
  9935. if(now.type == 'googCandidatePair')
  9936. {
  9937. var ip, type, localIP, active;
  9938. try {
  9939. ip = getStatValue(now, 'remoteAddress');
  9940. type = getStatValue(now, "transportType");
  9941. localIP = getStatValue(now, "localAddress");
  9942. active = getStatValue(now, "activeConnection");
  9943. }
  9944. catch(e){/*not supported*/}
  9945. if(!ip || !type || !localIP || active != "true")
  9946. continue;
  9947. var addressSaved = false;
  9948. for(var i = 0; i < PeerStats.transport.length; i++)
  9949. {
  9950. if(PeerStats.transport[i].ip == ip &&
  9951. PeerStats.transport[i].type == type &&
  9952. PeerStats.transport[i].localip == localIP)
  9953. {
  9954. addressSaved = true;
  9955. }
  9956. }
  9957. if(addressSaved)
  9958. continue;
  9959. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  9960. continue;
  9961. }
  9962. if(now.type == "candidatepair")
  9963. {
  9964. if(now.state == "succeeded")
  9965. continue;
  9966. var local = this.currentStatsReport[now.localCandidateId];
  9967. var remote = this.currentStatsReport[now.remoteCandidateId];
  9968. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  9969. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  9970. }
  9971. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  9972. now.type != "inboundrtp") {
  9973. continue;
  9974. }
  9975. var before = this.baselineStatsReport[idx];
  9976. if (!before) {
  9977. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  9978. continue;
  9979. }
  9980. var ssrc = getStatValue(now, 'ssrc');
  9981. if(!ssrc)
  9982. continue;
  9983. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  9984. if (!jid && (Date.now() - now.timestamp) < 3000) {
  9985. console.warn("No jid for ssrc: " + ssrc);
  9986. continue;
  9987. }
  9988. var jidStats = this.jid2stats[jid];
  9989. if (!jidStats) {
  9990. jidStats = new PeerStats();
  9991. this.jid2stats[jid] = jidStats;
  9992. }
  9993. var isDownloadStream = true;
  9994. var key = 'packetsReceived';
  9995. if (!getStatValue(now, key))
  9996. {
  9997. isDownloadStream = false;
  9998. key = 'packetsSent';
  9999. if (!getStatValue(now, key))
  10000. {
  10001. console.warn("No packetsReceived nor packetSent stat found");
  10002. continue;
  10003. }
  10004. }
  10005. var packetsNow = getStatValue(now, key);
  10006. if(!packetsNow || packetsNow < 0)
  10007. packetsNow = 0;
  10008. var packetsBefore = getStatValue(before, key);
  10009. if(!packetsBefore || packetsBefore < 0)
  10010. packetsBefore = 0;
  10011. var packetRate = packetsNow - packetsBefore;
  10012. if(!packetRate || packetRate < 0)
  10013. packetRate = 0;
  10014. var currentLoss = getStatValue(now, 'packetsLost');
  10015. if(!currentLoss || currentLoss < 0)
  10016. currentLoss = 0;
  10017. var previousLoss = getStatValue(before, 'packetsLost');
  10018. if(!previousLoss || previousLoss < 0)
  10019. previousLoss = 0;
  10020. var lossRate = currentLoss - previousLoss;
  10021. if(!lossRate || lossRate < 0)
  10022. lossRate = 0;
  10023. var packetsTotal = (packetRate + lossRate);
  10024. jidStats.setSsrcLoss(ssrc,
  10025. {"packetsTotal": packetsTotal,
  10026. "packetsLost": lossRate,
  10027. "isDownloadStream": isDownloadStream});
  10028. var bytesReceived = 0, bytesSent = 0;
  10029. if(getStatValue(now, "bytesReceived"))
  10030. {
  10031. bytesReceived = getStatValue(now, "bytesReceived") -
  10032. getStatValue(before, "bytesReceived");
  10033. }
  10034. if(getStatValue(now, "bytesSent"))
  10035. {
  10036. bytesSent = getStatValue(now, "bytesSent") -
  10037. getStatValue(before, "bytesSent");
  10038. }
  10039. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  10040. if(bytesReceived <= 0 || time <= 0)
  10041. {
  10042. bytesReceived = 0;
  10043. }
  10044. else
  10045. {
  10046. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  10047. }
  10048. if(bytesSent <= 0 || time <= 0)
  10049. {
  10050. bytesSent = 0;
  10051. }
  10052. else
  10053. {
  10054. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  10055. }
  10056. jidStats.setSsrcBitrate(ssrc, {
  10057. "download": bytesReceived,
  10058. "upload": bytesSent});
  10059. var resolution = {height: null, width: null};
  10060. try {
  10061. if (getStatValue(now, "googFrameHeightReceived") &&
  10062. getStatValue(now, "googFrameWidthReceived")) {
  10063. resolution.height = getStatValue(now, "googFrameHeightReceived");
  10064. resolution.width = getStatValue(now, "googFrameWidthReceived");
  10065. }
  10066. else if (getStatValue(now, "googFrameHeightSent") &&
  10067. getStatValue(now, "googFrameWidthSent")) {
  10068. resolution.height = getStatValue(now, "googFrameHeightSent");
  10069. resolution.width = getStatValue(now, "googFrameWidthSent");
  10070. }
  10071. }
  10072. catch(e){/*not supported*/}
  10073. if(resolution.height && resolution.width)
  10074. {
  10075. jidStats.setSsrcResolution(ssrc, resolution);
  10076. }
  10077. else
  10078. {
  10079. jidStats.setSsrcResolution(ssrc, null);
  10080. }
  10081. }
  10082. var self = this;
  10083. // Jid stats
  10084. var totalPackets = {download: 0, upload: 0};
  10085. var lostPackets = {download: 0, upload: 0};
  10086. var bitrateDownload = 0;
  10087. var bitrateUpload = 0;
  10088. var resolutions = {};
  10089. Object.keys(this.jid2stats).forEach(
  10090. function (jid)
  10091. {
  10092. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  10093. function (ssrc)
  10094. {
  10095. var type = "upload";
  10096. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  10097. type = "download";
  10098. totalPackets[type] +=
  10099. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  10100. lostPackets[type] +=
  10101. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  10102. }
  10103. );
  10104. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  10105. function (ssrc) {
  10106. bitrateDownload +=
  10107. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  10108. bitrateUpload +=
  10109. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  10110. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  10111. }
  10112. );
  10113. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  10114. }
  10115. );
  10116. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  10117. PeerStats.packetLoss = {
  10118. total:
  10119. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  10120. totalPackets.download + totalPackets.upload),
  10121. download:
  10122. calculatePacketLoss(lostPackets.download, totalPackets.download),
  10123. upload:
  10124. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  10125. };
  10126. this.eventEmitter.emit("statistics.connectionstats",
  10127. {
  10128. "bitrate": PeerStats.bitrate,
  10129. "packetLoss": PeerStats.packetLoss,
  10130. "bandwidth": PeerStats.bandwidth,
  10131. "resolution": resolutions,
  10132. "transport": PeerStats.transport
  10133. });
  10134. PeerStats.transport = [];
  10135. };
  10136. /**
  10137. * Stats processing logic.
  10138. */
  10139. StatsCollector.prototype.processAudioLevelReport = function ()
  10140. {
  10141. if (!this.baselineAudioLevelsReport)
  10142. {
  10143. return;
  10144. }
  10145. for (var idx in this.currentAudioLevelsReport)
  10146. {
  10147. var now = this.currentAudioLevelsReport[idx];
  10148. if (now.type != 'ssrc')
  10149. {
  10150. continue;
  10151. }
  10152. var before = this.baselineAudioLevelsReport[idx];
  10153. if (!before)
  10154. {
  10155. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  10156. continue;
  10157. }
  10158. var ssrc = getStatValue(now, 'ssrc');
  10159. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  10160. if (!jid && (Date.now() - now.timestamp) < 3000)
  10161. {
  10162. console.warn("No jid for ssrc: " + ssrc);
  10163. continue;
  10164. }
  10165. var jidStats = this.jid2stats[jid];
  10166. if (!jidStats)
  10167. {
  10168. jidStats = new PeerStats();
  10169. this.jid2stats[jid] = jidStats;
  10170. }
  10171. // Audio level
  10172. var audioLevel = null;
  10173. try {
  10174. audioLevel = getStatValue(now, 'audioInputLevel');
  10175. if (!audioLevel)
  10176. audioLevel = getStatValue(now, 'audioOutputLevel');
  10177. }
  10178. catch(e) {/*not supported*/
  10179. console.warn("Audio Levels are not available in the statistics.");
  10180. clearInterval(this.audioLevelsIntervalId);
  10181. return;
  10182. }
  10183. if (audioLevel)
  10184. {
  10185. // TODO: can't find specs about what this value really is,
  10186. // but it seems to vary between 0 and around 32k.
  10187. audioLevel = audioLevel / 32767;
  10188. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  10189. if(jid != APP.xmpp.myJid())
  10190. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  10191. }
  10192. }
  10193. };
  10194. },{"../../service/RTC/RTCBrowserType":80}],46:[function(require,module,exports){
  10195. /**
  10196. * Created by hristo on 8/4/14.
  10197. */
  10198. var LocalStats = require("./LocalStatsCollector.js");
  10199. var RTPStats = require("./RTPStatsCollector.js");
  10200. var EventEmitter = require("events");
  10201. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  10202. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10203. var eventEmitter = new EventEmitter();
  10204. var localStats = null;
  10205. var rtpStats = null;
  10206. function stopLocal()
  10207. {
  10208. if(localStats)
  10209. {
  10210. localStats.stop();
  10211. localStats = null;
  10212. }
  10213. }
  10214. function stopRemote()
  10215. {
  10216. if(rtpStats)
  10217. {
  10218. rtpStats.stop();
  10219. eventEmitter.emit("statistics.stop");
  10220. rtpStats = null;
  10221. }
  10222. }
  10223. function startRemoteStats (peerconnection) {
  10224. if(rtpStats)
  10225. {
  10226. rtpStats.stop();
  10227. rtpStats = null;
  10228. }
  10229. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  10230. rtpStats.start();
  10231. }
  10232. function onStreamCreated(stream)
  10233. {
  10234. if(stream.getOriginalStream().getAudioTracks().length === 0)
  10235. return;
  10236. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  10237. eventEmitter);
  10238. localStats.start();
  10239. }
  10240. function onDisposeConference(onUnload) {
  10241. stopRemote();
  10242. if(onUnload) {
  10243. stopLocal();
  10244. eventEmitter.removeAllListeners();
  10245. }
  10246. }
  10247. var statistics =
  10248. {
  10249. /**
  10250. * Indicates that this audio level is for local jid.
  10251. * @type {string}
  10252. */
  10253. LOCAL_JID: 'local',
  10254. addAudioLevelListener: function(listener)
  10255. {
  10256. eventEmitter.on("statistics.audioLevel", listener);
  10257. },
  10258. removeAudioLevelListener: function(listener)
  10259. {
  10260. eventEmitter.removeListener("statistics.audioLevel", listener);
  10261. },
  10262. addConnectionStatsListener: function(listener)
  10263. {
  10264. eventEmitter.on("statistics.connectionstats", listener);
  10265. },
  10266. removeConnectionStatsListener: function(listener)
  10267. {
  10268. eventEmitter.removeListener("statistics.connectionstats", listener);
  10269. },
  10270. addRemoteStatsStopListener: function(listener)
  10271. {
  10272. eventEmitter.on("statistics.stop", listener);
  10273. },
  10274. removeRemoteStatsStopListener: function(listener)
  10275. {
  10276. eventEmitter.removeListener("statistics.stop", listener);
  10277. },
  10278. stop: function () {
  10279. stopLocal();
  10280. stopRemote();
  10281. if(eventEmitter)
  10282. {
  10283. eventEmitter.removeAllListeners();
  10284. }
  10285. },
  10286. stopRemoteStatistics: function()
  10287. {
  10288. stopRemote();
  10289. },
  10290. start: function () {
  10291. APP.RTC.addStreamListener(onStreamCreated,
  10292. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  10293. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  10294. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  10295. startRemoteStats(event.peerconnection);
  10296. });
  10297. }
  10298. };
  10299. module.exports = statistics;
  10300. },{"../../service/RTC/StreamEventTypes.js":83,"../../service/xmpp/XMPPEvents":89,"./LocalStatsCollector.js":44,"./RTPStatsCollector.js":45,"events":1}],47:[function(require,module,exports){
  10301. var i18n = require("i18next-client");
  10302. var languages = require("../../service/translation/languages");
  10303. var Settings = require("../settings/Settings");
  10304. var DEFAULT_LANG = languages.EN;
  10305. var initialized = false;
  10306. var waitingForInit = [];
  10307. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  10308. return value.replace("__app__", interfaceConfig.APP_NAME);
  10309. });
  10310. var defaultOptions = {
  10311. detectLngQS: "lang",
  10312. useCookie: false,
  10313. fallbackLng: DEFAULT_LANG,
  10314. shortcutFunction: 'defaultValue',
  10315. load: "unspecific",
  10316. resGetPath: 'lang/__ns__-__lng__.json',
  10317. ns: {
  10318. namespaces: ['main', 'languages'],
  10319. defaultNs: 'main'
  10320. },
  10321. lngWhitelist : languages.getLanguages(),
  10322. fallbackOnNull: true,
  10323. fallbackOnEmpty: true,
  10324. useDataAttrOptions: true,
  10325. app: interfaceConfig.APP_NAME,
  10326. getAsync: true,
  10327. customLoad: function(lng, ns, options, done) {
  10328. var resPath = "lang/__ns__-__lng__.json";
  10329. if(lng === languages.EN)
  10330. resPath = "lang/__ns__.json";
  10331. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  10332. initialized = false;
  10333. i18n.functions.ajax({
  10334. url: url,
  10335. success: function(data, status, xhr) {
  10336. i18n.functions.log('loaded: ' + url);
  10337. done(null, data);
  10338. },
  10339. error : function(xhr, status, error) {
  10340. if ((status && status == 200) ||
  10341. (xhr && xhr.status && xhr.status == 200)) {
  10342. // file loaded but invalid json, stop waste time !
  10343. i18n.functions.error('There is a typo in: ' + url);
  10344. } else if ((status && status == 404) ||
  10345. (xhr && xhr.status && xhr.status == 404)) {
  10346. i18n.functions.log('Does not exist: ' + url);
  10347. } else {
  10348. var theStatus = status ? status :
  10349. ((xhr && xhr.status) ? xhr.status : null);
  10350. i18n.functions.log(theStatus + ' when loading ' + url);
  10351. }
  10352. done(error, {});
  10353. },
  10354. dataType: "json",
  10355. async : options.getAsync
  10356. });
  10357. }
  10358. // options for caching
  10359. // useLocalStorage: true,
  10360. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  10361. };
  10362. function initCompleted(t)
  10363. {
  10364. initialized = true;
  10365. $("[data-i18n]").i18n();
  10366. for(var i = 0; i < waitingForInit.length; i++)
  10367. {
  10368. var obj = waitingForInit[i];
  10369. obj.callback(i18n.t(obj.key));
  10370. }
  10371. waitingForInit = [];
  10372. }
  10373. function checkForParameter() {
  10374. var query = window.location.search.substring(1);
  10375. var vars = query.split("&");
  10376. for (var i=0;i<vars.length;i++) {
  10377. var pair = vars[i].split("=");
  10378. if(pair[0] == "lang")
  10379. {
  10380. return pair[1];
  10381. }
  10382. }
  10383. return null;
  10384. }
  10385. module.exports = {
  10386. init: function (lang) {
  10387. initialized = false;
  10388. var options = defaultOptions;
  10389. if(!lang)
  10390. {
  10391. lang = checkForParameter();
  10392. if(!lang)
  10393. {
  10394. var settings = Settings.getSettings();
  10395. if(settings)
  10396. lang = settings.language;
  10397. }
  10398. }
  10399. if(lang) {
  10400. options.lng = lang;
  10401. }
  10402. i18n.init(options, initCompleted);
  10403. },
  10404. translateString: function (key, cb, options) {
  10405. if(!cb)
  10406. return i18n.t(key, options);
  10407. if(initialized)
  10408. {
  10409. cb(i18n.t(key, options));
  10410. }
  10411. else
  10412. {
  10413. waitingForInit.push({"callback": cb, "key": key});
  10414. }
  10415. },
  10416. setLanguage: function (lang) {
  10417. initialized = false;
  10418. if(!lang)
  10419. lang = DEFAULT_LANG;
  10420. i18n.setLng(lang, defaultOptions, initCompleted);
  10421. },
  10422. getCurrentLanguage: function () {
  10423. return i18n.lng();
  10424. },
  10425. translateElement: function (selector) {
  10426. selector.i18n();
  10427. },
  10428. generateTranslatonHTML: function (key, defaultString, options) {
  10429. var str = "<span data-i18n=\"" + key + "\"";
  10430. if(options)
  10431. {
  10432. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  10433. }
  10434. str += ">";
  10435. if(!options)
  10436. options = {};
  10437. if(defaultString)
  10438. {
  10439. options.defaultValue = defaultString;
  10440. }
  10441. str += this.translateString(key, null, options);
  10442. str += "</span>";
  10443. return str;
  10444. }
  10445. };
  10446. },{"../../service/translation/languages":88,"../settings/Settings":38,"i18next-client":62}],48:[function(require,module,exports){
  10447. /* jshint -W117 */
  10448. var TraceablePeerConnection = require("./TraceablePeerConnection");
  10449. var SDPDiffer = require("./SDPDiffer");
  10450. var SDPUtil = require("./SDPUtil");
  10451. var SDP = require("./SDP");
  10452. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  10453. // Jingle stuff
  10454. function JingleSession(me, sid, connection, service) {
  10455. this.me = me;
  10456. this.sid = sid;
  10457. this.connection = connection;
  10458. this.initiator = null;
  10459. this.responder = null;
  10460. this.isInitiator = null;
  10461. this.peerjid = null;
  10462. this.state = null;
  10463. this.localSDP = null;
  10464. this.remoteSDP = null;
  10465. this.relayedStreams = [];
  10466. this.startTime = null;
  10467. this.stopTime = null;
  10468. this.media_constraints = null;
  10469. this.pc_constraints = null;
  10470. this.ice_config = {};
  10471. this.drip_container = [];
  10472. this.service = service;
  10473. this.usetrickle = true;
  10474. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  10475. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  10476. this.hadstuncandidate = false;
  10477. this.hadturncandidate = false;
  10478. this.lasticecandidate = false;
  10479. this.statsinterval = null;
  10480. this.reason = null;
  10481. this.addssrc = [];
  10482. this.removessrc = [];
  10483. this.pendingop = null;
  10484. this.switchstreams = false;
  10485. this.wait = true;
  10486. this.localStreamsSSRC = null;
  10487. /**
  10488. * The indicator which determines whether the (local) video has been muted
  10489. * in response to a user command in contrast to an automatic decision made
  10490. * by the application logic.
  10491. */
  10492. this.videoMuteByUser = false;
  10493. }
  10494. //TODO: this array must be removed when firefox implement multistream support
  10495. JingleSession.notReceivedSSRCs = [];
  10496. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  10497. var self = this;
  10498. if (this.state !== null) {
  10499. console.error('attempt to initiate on session ' + this.sid +
  10500. 'in state ' + this.state);
  10501. return;
  10502. }
  10503. this.isInitiator = isInitiator;
  10504. this.state = 'pending';
  10505. this.initiator = isInitiator ? this.me : peerjid;
  10506. this.responder = !isInitiator ? this.me : peerjid;
  10507. this.peerjid = peerjid;
  10508. this.hadstuncandidate = false;
  10509. this.hadturncandidate = false;
  10510. this.lasticecandidate = false;
  10511. this.peerconnection
  10512. = new TraceablePeerConnection(
  10513. this.connection.jingle.ice_config,
  10514. this.connection.jingle.pc_constraints );
  10515. this.peerconnection.onicecandidate = function (event) {
  10516. self.sendIceCandidate(event.candidate);
  10517. };
  10518. this.peerconnection.onaddstream = function (event) {
  10519. console.log("REMOTE STREAM ADDED: " + event.stream + " - " + event.stream.id);
  10520. self.remoteStreamAdded(event);
  10521. };
  10522. this.peerconnection.onremovestream = function (event) {
  10523. // Remove the stream from remoteStreams
  10524. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  10525. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  10526. };
  10527. this.peerconnection.onsignalingstatechange = function (event) {
  10528. if (!(self && self.peerconnection)) return;
  10529. };
  10530. this.peerconnection.oniceconnectionstatechange = function (event) {
  10531. if (!(self && self.peerconnection)) return;
  10532. switch (self.peerconnection.iceConnectionState) {
  10533. case 'connected':
  10534. this.startTime = new Date();
  10535. break;
  10536. case 'disconnected':
  10537. this.stopTime = new Date();
  10538. break;
  10539. }
  10540. onIceConnectionStateChange(self.sid, self);
  10541. };
  10542. // add any local and relayed stream
  10543. APP.RTC.localStreams.forEach(function(stream) {
  10544. self.peerconnection.addStream(stream.getOriginalStream());
  10545. });
  10546. this.relayedStreams.forEach(function(stream) {
  10547. self.peerconnection.addStream(stream);
  10548. });
  10549. };
  10550. function onIceConnectionStateChange(sid, session) {
  10551. switch (session.peerconnection.iceConnectionState) {
  10552. case 'checking':
  10553. session.timeChecking = (new Date()).getTime();
  10554. session.firstconnect = true;
  10555. break;
  10556. case 'completed': // on caller side
  10557. case 'connected':
  10558. if (session.firstconnect) {
  10559. session.firstconnect = false;
  10560. var metadata = {};
  10561. metadata.setupTime
  10562. = (new Date()).getTime() - session.timeChecking;
  10563. session.peerconnection.getStats(function (res) {
  10564. if(res && res.result) {
  10565. res.result().forEach(function (report) {
  10566. if (report.type == 'googCandidatePair' &&
  10567. report.stat('googActiveConnection') == 'true') {
  10568. metadata.localCandidateType
  10569. = report.stat('googLocalCandidateType');
  10570. metadata.remoteCandidateType
  10571. = report.stat('googRemoteCandidateType');
  10572. // log pair as well so we can get nice pie
  10573. // charts
  10574. metadata.candidatePair
  10575. = report.stat('googLocalCandidateType') +
  10576. ';' +
  10577. report.stat('googRemoteCandidateType');
  10578. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  10579. {
  10580. metadata.ipv6 = true;
  10581. }
  10582. }
  10583. });
  10584. }
  10585. });
  10586. }
  10587. break;
  10588. }
  10589. }
  10590. JingleSession.prototype.accept = function () {
  10591. var self = this;
  10592. this.state = 'active';
  10593. var pranswer = this.peerconnection.localDescription;
  10594. if (!pranswer || pranswer.type != 'pranswer') {
  10595. return;
  10596. }
  10597. console.log('going from pranswer to answer');
  10598. if (this.usetrickle) {
  10599. // remove candidates already sent from session-accept
  10600. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  10601. for (var i = 0; i < lines.length; i++) {
  10602. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  10603. }
  10604. }
  10605. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  10606. // FIXME: change any inactive to sendrecv or whatever they were originally
  10607. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  10608. }
  10609. pranswer = APP.simulcast.reverseTransformLocalDescription(pranswer);
  10610. var prsdp = new SDP(pranswer.sdp);
  10611. var accept = $iq({to: this.peerjid,
  10612. type: 'set'})
  10613. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10614. action: 'session-accept',
  10615. initiator: this.initiator,
  10616. responder: this.responder,
  10617. sid: this.sid });
  10618. prsdp.toJingle(accept, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10619. var sdp = this.peerconnection.localDescription.sdp;
  10620. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  10621. // FIXME: change any inactive to sendrecv or whatever they were originally
  10622. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  10623. }
  10624. var self = this;
  10625. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  10626. function () {
  10627. //console.log('setLocalDescription success');
  10628. self.setLocalDescription();
  10629. self.connection.sendIQ(accept,
  10630. function () {
  10631. var ack = {};
  10632. ack.source = 'answer';
  10633. $(document).trigger('ack.jingle', [self.sid, ack]);
  10634. },
  10635. function (stanza) {
  10636. var error = ($(stanza).find('error').length) ? {
  10637. code: $(stanza).find('error').attr('code'),
  10638. reason: $(stanza).find('error :first')[0].tagName
  10639. }:{};
  10640. error.source = 'answer';
  10641. JingleSession.onJingleError(self.sid, error);
  10642. },
  10643. 10000);
  10644. },
  10645. function (e) {
  10646. console.error('setLocalDescription failed', e);
  10647. }
  10648. );
  10649. };
  10650. JingleSession.prototype.terminate = function (reason) {
  10651. this.state = 'ended';
  10652. this.reason = reason;
  10653. this.peerconnection.close();
  10654. if (this.statsinterval !== null) {
  10655. window.clearInterval(this.statsinterval);
  10656. this.statsinterval = null;
  10657. }
  10658. };
  10659. JingleSession.prototype.active = function () {
  10660. return this.state == 'active';
  10661. };
  10662. JingleSession.prototype.sendIceCandidate = function (candidate) {
  10663. var self = this;
  10664. if (candidate && !this.lasticecandidate) {
  10665. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  10666. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  10667. if (!(ice && jcand)) {
  10668. console.error('failed to get ice && jcand');
  10669. return;
  10670. }
  10671. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10672. if (jcand.type === 'srflx') {
  10673. this.hadstuncandidate = true;
  10674. } else if (jcand.type === 'relay') {
  10675. this.hadturncandidate = true;
  10676. }
  10677. if (this.usetrickle) {
  10678. if (this.usedrip) {
  10679. if (this.drip_container.length === 0) {
  10680. // start 20ms callout
  10681. window.setTimeout(function () {
  10682. if (self.drip_container.length === 0) return;
  10683. self.sendIceCandidates(self.drip_container);
  10684. self.drip_container = [];
  10685. }, 20);
  10686. }
  10687. this.drip_container.push(candidate);
  10688. return;
  10689. } else {
  10690. self.sendIceCandidate([candidate]);
  10691. }
  10692. }
  10693. } else {
  10694. //console.log('sendIceCandidate: last candidate.');
  10695. if (!this.usetrickle) {
  10696. //console.log('should send full offer now...');
  10697. var init = $iq({to: this.peerjid,
  10698. type: 'set'})
  10699. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10700. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  10701. initiator: this.initiator,
  10702. sid: this.sid});
  10703. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  10704. var self = this;
  10705. var sendJingle = function (ssrc) {
  10706. if(!ssrc)
  10707. ssrc = {};
  10708. self.localSDP.toJingle(init, self.initiator == self.me ? 'initiator' : 'responder', ssrc);
  10709. self.connection.sendIQ(init,
  10710. function () {
  10711. //console.log('session initiate ack');
  10712. var ack = {};
  10713. ack.source = 'offer';
  10714. $(document).trigger('ack.jingle', [self.sid, ack]);
  10715. },
  10716. function (stanza) {
  10717. self.state = 'error';
  10718. self.peerconnection.close();
  10719. var error = ($(stanza).find('error').length) ? {
  10720. code: $(stanza).find('error').attr('code'),
  10721. reason: $(stanza).find('error :first')[0].tagName,
  10722. }:{};
  10723. error.source = 'offer';
  10724. JingleSession.onJingleError(self.sid, error);
  10725. },
  10726. 10000);
  10727. }
  10728. sendJingle();
  10729. }
  10730. this.lasticecandidate = true;
  10731. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  10732. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  10733. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  10734. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  10735. }
  10736. }
  10737. };
  10738. JingleSession.prototype.sendIceCandidates = function (candidates) {
  10739. console.log('sendIceCandidates', candidates);
  10740. var cand = $iq({to: this.peerjid, type: 'set'})
  10741. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10742. action: 'transport-info',
  10743. initiator: this.initiator,
  10744. sid: this.sid});
  10745. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  10746. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  10747. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  10748. if (cands.length > 0) {
  10749. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  10750. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10751. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  10752. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  10753. }).c('transport', ice);
  10754. for (var i = 0; i < cands.length; i++) {
  10755. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  10756. }
  10757. // add fingerprint
  10758. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  10759. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  10760. tmp.required = true;
  10761. cand.c(
  10762. 'fingerprint',
  10763. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  10764. .t(tmp.fingerprint);
  10765. delete tmp.fingerprint;
  10766. cand.attrs(tmp);
  10767. cand.up();
  10768. }
  10769. cand.up(); // transport
  10770. cand.up(); // content
  10771. }
  10772. }
  10773. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  10774. //console.log('was this the last candidate', this.lasticecandidate);
  10775. this.connection.sendIQ(cand,
  10776. function () {
  10777. var ack = {};
  10778. ack.source = 'transportinfo';
  10779. $(document).trigger('ack.jingle', [this.sid, ack]);
  10780. },
  10781. function (stanza) {
  10782. var error = ($(stanza).find('error').length) ? {
  10783. code: $(stanza).find('error').attr('code'),
  10784. reason: $(stanza).find('error :first')[0].tagName,
  10785. }:{};
  10786. error.source = 'transportinfo';
  10787. JingleSession.onJingleError(this.sid, error);
  10788. },
  10789. 10000);
  10790. };
  10791. JingleSession.prototype.sendOffer = function () {
  10792. //console.log('sendOffer...');
  10793. var self = this;
  10794. this.peerconnection.createOffer(function (sdp) {
  10795. self.createdOffer(sdp);
  10796. },
  10797. function (e) {
  10798. console.error('createOffer failed', e);
  10799. },
  10800. this.media_constraints
  10801. );
  10802. };
  10803. JingleSession.prototype.createdOffer = function (sdp) {
  10804. //console.log('createdOffer', sdp);
  10805. var self = this;
  10806. this.localSDP = new SDP(sdp.sdp);
  10807. //this.localSDP.mangle();
  10808. var sendJingle = function () {
  10809. var init = $iq({to: this.peerjid,
  10810. type: 'set'})
  10811. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10812. action: 'session-initiate',
  10813. initiator: this.initiator,
  10814. sid: this.sid});
  10815. self.localSDP.toJingle(init, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10816. self.connection.sendIQ(init,
  10817. function () {
  10818. var ack = {};
  10819. ack.source = 'offer';
  10820. $(document).trigger('ack.jingle', [self.sid, ack]);
  10821. },
  10822. function (stanza) {
  10823. self.state = 'error';
  10824. self.peerconnection.close();
  10825. var error = ($(stanza).find('error').length) ? {
  10826. code: $(stanza).find('error').attr('code'),
  10827. reason: $(stanza).find('error :first')[0].tagName,
  10828. }:{};
  10829. error.source = 'offer';
  10830. JingleSession.onJingleError(self.sid, error);
  10831. },
  10832. 10000);
  10833. }
  10834. sdp.sdp = this.localSDP.raw;
  10835. this.peerconnection.setLocalDescription(sdp,
  10836. function () {
  10837. if(self.usetrickle)
  10838. {
  10839. sendJingle();
  10840. }
  10841. self.setLocalDescription();
  10842. //console.log('setLocalDescription success');
  10843. },
  10844. function (e) {
  10845. console.error('setLocalDescription failed', e);
  10846. }
  10847. );
  10848. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  10849. for (var i = 0; i < cands.length; i++) {
  10850. var cand = SDPUtil.parse_icecandidate(cands[i]);
  10851. if (cand.type == 'srflx') {
  10852. this.hadstuncandidate = true;
  10853. } else if (cand.type == 'relay') {
  10854. this.hadturncandidate = true;
  10855. }
  10856. }
  10857. };
  10858. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  10859. //console.log('setting remote description... ', desctype);
  10860. this.remoteSDP = new SDP('');
  10861. this.remoteSDP.fromJingle(elem);
  10862. if (this.peerconnection.remoteDescription !== null) {
  10863. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  10864. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  10865. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  10866. for (var i = 0; i < pranswer.media.length; i++) {
  10867. // make sure we have ice ufrag and pwd
  10868. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  10869. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  10870. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  10871. } else {
  10872. console.warn('no ice ufrag?');
  10873. }
  10874. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  10875. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  10876. } else {
  10877. console.warn('no ice pwd?');
  10878. }
  10879. }
  10880. // copy over candidates
  10881. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  10882. for (var j = 0; j < lines.length; j++) {
  10883. this.remoteSDP.media[i] += lines[j] + '\r\n';
  10884. }
  10885. }
  10886. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  10887. }
  10888. }
  10889. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  10890. this.peerconnection.setRemoteDescription(remotedesc,
  10891. function () {
  10892. //console.log('setRemoteDescription success');
  10893. },
  10894. function (e) {
  10895. console.error('setRemoteDescription error', e);
  10896. JingleSession.onJingleFatalError(self, e);
  10897. }
  10898. );
  10899. };
  10900. JingleSession.prototype.addIceCandidate = function (elem) {
  10901. var self = this;
  10902. if (this.peerconnection.signalingState == 'closed') {
  10903. return;
  10904. }
  10905. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  10906. console.log('trickle ice candidate arriving before session accept...');
  10907. // create a PRANSWER for setRemoteDescription
  10908. if (!this.remoteSDP) {
  10909. var cobbled = 'v=0\r\n' +
  10910. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  10911. 's=-\r\n' +
  10912. 't=0 0\r\n';
  10913. // first, take some things from the local description
  10914. for (var i = 0; i < this.localSDP.media.length; i++) {
  10915. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  10916. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  10917. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  10918. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  10919. }
  10920. cobbled += 'a=inactive\r\n';
  10921. }
  10922. this.remoteSDP = new SDP(cobbled);
  10923. }
  10924. // then add things like ice and dtls from remote candidate
  10925. elem.each(function () {
  10926. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  10927. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10928. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10929. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  10930. var tmp = $(this).find('transport');
  10931. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  10932. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  10933. tmp = $(this).find('transport>fingerprint');
  10934. if (tmp.length) {
  10935. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  10936. } else {
  10937. console.log('no dtls fingerprint (webrtc issue #1718?)');
  10938. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  10939. }
  10940. break;
  10941. }
  10942. }
  10943. }
  10944. });
  10945. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  10946. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  10947. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  10948. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  10949. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  10950. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  10951. }).length == this.remoteSDP.media.length;
  10952. if (iscomplete) {
  10953. console.log('setting pranswer');
  10954. try {
  10955. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  10956. function() {
  10957. },
  10958. function(e) {
  10959. console.log('setRemoteDescription pranswer failed', e.toString());
  10960. });
  10961. } catch (e) {
  10962. console.error('setting pranswer failed', e);
  10963. }
  10964. } else {
  10965. //console.log('not yet setting pranswer');
  10966. }
  10967. }
  10968. // operate on each content element
  10969. elem.each(function () {
  10970. // would love to deactivate this, but firefox still requires it
  10971. var idx = -1;
  10972. var i;
  10973. for (i = 0; i < self.remoteSDP.media.length; i++) {
  10974. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10975. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10976. idx = i;
  10977. break;
  10978. }
  10979. }
  10980. if (idx == -1) { // fall back to localdescription
  10981. for (i = 0; i < self.localSDP.media.length; i++) {
  10982. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10983. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10984. idx = i;
  10985. break;
  10986. }
  10987. }
  10988. }
  10989. var name = $(this).attr('name');
  10990. // TODO: check ice-pwd and ice-ufrag?
  10991. $(this).find('transport>candidate').each(function () {
  10992. var line, candidate;
  10993. line = SDPUtil.candidateFromJingle(this);
  10994. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  10995. sdpMid: name,
  10996. candidate: line});
  10997. try {
  10998. self.peerconnection.addIceCandidate(candidate);
  10999. } catch (e) {
  11000. console.error('addIceCandidate failed', e.toString(), line);
  11001. }
  11002. });
  11003. });
  11004. };
  11005. JingleSession.prototype.sendAnswer = function (provisional) {
  11006. //console.log('createAnswer', provisional);
  11007. var self = this;
  11008. this.peerconnection.createAnswer(
  11009. function (sdp) {
  11010. self.createdAnswer(sdp, provisional);
  11011. },
  11012. function (e) {
  11013. console.error('createAnswer failed', e);
  11014. },
  11015. this.media_constraints
  11016. );
  11017. };
  11018. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  11019. //console.log('createAnswer callback');
  11020. var self = this;
  11021. this.localSDP = new SDP(sdp.sdp);
  11022. //this.localSDP.mangle();
  11023. this.usepranswer = provisional === true;
  11024. if (this.usetrickle) {
  11025. if (this.usepranswer) {
  11026. sdp.type = 'pranswer';
  11027. for (var i = 0; i < this.localSDP.media.length; i++) {
  11028. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  11029. }
  11030. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  11031. }
  11032. }
  11033. var self = this;
  11034. var sendJingle = function (ssrcs) {
  11035. var accept = $iq({to: self.peerjid,
  11036. type: 'set'})
  11037. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11038. action: 'session-accept',
  11039. initiator: self.initiator,
  11040. responder: self.responder,
  11041. sid: self.sid });
  11042. var publicLocalDesc = APP.simulcast.reverseTransformLocalDescription(sdp);
  11043. var publicLocalSDP = new SDP(publicLocalDesc.sdp);
  11044. publicLocalSDP.toJingle(accept, self.initiator == self.me ? 'initiator' : 'responder', ssrcs);
  11045. self.connection.sendIQ(accept,
  11046. function () {
  11047. var ack = {};
  11048. ack.source = 'answer';
  11049. $(document).trigger('ack.jingle', [self.sid, ack]);
  11050. },
  11051. function (stanza) {
  11052. var error = ($(stanza).find('error').length) ? {
  11053. code: $(stanza).find('error').attr('code'),
  11054. reason: $(stanza).find('error :first')[0].tagName,
  11055. }:{};
  11056. error.source = 'answer';
  11057. JingleSession.onJingleError(self.sid, error);
  11058. },
  11059. 10000);
  11060. }
  11061. sdp.sdp = this.localSDP.raw;
  11062. this.peerconnection.setLocalDescription(sdp,
  11063. function () {
  11064. //console.log('setLocalDescription success');
  11065. if (self.usetrickle && !self.usepranswer) {
  11066. sendJingle();
  11067. }
  11068. self.setLocalDescription();
  11069. },
  11070. function (e) {
  11071. console.error('setLocalDescription failed', e);
  11072. }
  11073. );
  11074. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  11075. for (var j = 0; j < cands.length; j++) {
  11076. var cand = SDPUtil.parse_icecandidate(cands[j]);
  11077. if (cand.type == 'srflx') {
  11078. this.hadstuncandidate = true;
  11079. } else if (cand.type == 'relay') {
  11080. this.hadturncandidate = true;
  11081. }
  11082. }
  11083. };
  11084. JingleSession.prototype.sendTerminate = function (reason, text) {
  11085. var self = this,
  11086. term = $iq({to: this.peerjid,
  11087. type: 'set'})
  11088. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11089. action: 'session-terminate',
  11090. initiator: this.initiator,
  11091. sid: this.sid})
  11092. .c('reason')
  11093. .c(reason || 'success');
  11094. if (text) {
  11095. term.up().c('text').t(text);
  11096. }
  11097. this.connection.sendIQ(term,
  11098. function () {
  11099. self.peerconnection.close();
  11100. self.peerconnection = null;
  11101. self.terminate();
  11102. var ack = {};
  11103. ack.source = 'terminate';
  11104. $(document).trigger('ack.jingle', [self.sid, ack]);
  11105. },
  11106. function (stanza) {
  11107. var error = ($(stanza).find('error').length) ? {
  11108. code: $(stanza).find('error').attr('code'),
  11109. reason: $(stanza).find('error :first')[0].tagName,
  11110. }:{};
  11111. $(document).trigger('ack.jingle', [self.sid, error]);
  11112. },
  11113. 10000);
  11114. if (this.statsinterval !== null) {
  11115. window.clearInterval(this.statsinterval);
  11116. this.statsinterval = null;
  11117. }
  11118. };
  11119. JingleSession.prototype.addSource = function (elem, fromJid) {
  11120. var self = this;
  11121. // FIXME: dirty waiting
  11122. if (!this.peerconnection.localDescription)
  11123. {
  11124. console.warn("addSource - localDescription not ready yet")
  11125. setTimeout(function()
  11126. {
  11127. self.addSource(elem, fromJid);
  11128. },
  11129. 200
  11130. );
  11131. return;
  11132. }
  11133. console.log('addssrc', new Date().getTime());
  11134. console.log('ice', this.peerconnection.iceConnectionState);
  11135. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11136. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  11137. $(elem).each(function (idx, content) {
  11138. var name = $(content).attr('name');
  11139. var lines = '';
  11140. tmp = $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  11141. var semantics = this.getAttribute('semantics');
  11142. var ssrcs = $(this).find('>source').map(function () {
  11143. return this.getAttribute('ssrc');
  11144. }).get();
  11145. if (ssrcs.length != 0) {
  11146. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  11147. }
  11148. });
  11149. tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  11150. tmp.each(function () {
  11151. var ssrc = $(this).attr('ssrc');
  11152. if(mySdp.containsSSRC(ssrc)){
  11153. /**
  11154. * This happens when multiple participants change their streams at the same time and
  11155. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  11156. * addssrc are scheduled for update IQ. See
  11157. */
  11158. console.warn("Got add stream request for my own ssrc: "+ssrc);
  11159. return;
  11160. }
  11161. $(this).find('>parameter').each(function () {
  11162. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  11163. if ($(this).attr('value') && $(this).attr('value').length)
  11164. lines += ':' + $(this).attr('value');
  11165. lines += '\r\n';
  11166. });
  11167. });
  11168. sdp.media.forEach(function(media, idx) {
  11169. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  11170. return;
  11171. sdp.media[idx] += lines;
  11172. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  11173. self.addssrc[idx] += lines;
  11174. });
  11175. sdp.raw = sdp.session + sdp.media.join('');
  11176. });
  11177. this.modifySources();
  11178. };
  11179. JingleSession.prototype.removeSource = function (elem, fromJid) {
  11180. var self = this;
  11181. // FIXME: dirty waiting
  11182. if (!this.peerconnection.localDescription)
  11183. {
  11184. console.warn("removeSource - localDescription not ready yet")
  11185. setTimeout(function()
  11186. {
  11187. self.removeSource(elem, fromJid);
  11188. },
  11189. 200
  11190. );
  11191. return;
  11192. }
  11193. console.log('removessrc', new Date().getTime());
  11194. console.log('ice', this.peerconnection.iceConnectionState);
  11195. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11196. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  11197. $(elem).each(function (idx, content) {
  11198. var name = $(content).attr('name');
  11199. var lines = '';
  11200. tmp = $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  11201. var semantics = this.getAttribute('semantics');
  11202. var ssrcs = $(this).find('>source').map(function () {
  11203. return this.getAttribute('ssrc');
  11204. }).get();
  11205. if (ssrcs.length != 0) {
  11206. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  11207. }
  11208. });
  11209. tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  11210. tmp.each(function () {
  11211. var ssrc = $(this).attr('ssrc');
  11212. // This should never happen, but can be useful for bug detection
  11213. if(mySdp.containsSSRC(ssrc)){
  11214. console.error("Got remove stream request for my own ssrc: "+ssrc);
  11215. return;
  11216. }
  11217. $(this).find('>parameter').each(function () {
  11218. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  11219. if ($(this).attr('value') && $(this).attr('value').length)
  11220. lines += ':' + $(this).attr('value');
  11221. lines += '\r\n';
  11222. });
  11223. });
  11224. sdp.media.forEach(function(media, idx) {
  11225. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  11226. return;
  11227. sdp.media[idx] += lines;
  11228. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  11229. self.removessrc[idx] += lines;
  11230. });
  11231. sdp.raw = sdp.session + sdp.media.join('');
  11232. });
  11233. this.modifySources();
  11234. };
  11235. JingleSession.prototype.modifySources = function (successCallback) {
  11236. var self = this;
  11237. if (this.peerconnection.signalingState == 'closed') return;
  11238. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  11239. // There is nothing to do since scheduled job might have been executed by another succeeding call
  11240. this.setLocalDescription();
  11241. if(successCallback){
  11242. successCallback();
  11243. }
  11244. return;
  11245. }
  11246. // FIXME: this is a big hack
  11247. // https://code.google.com/p/webrtc/issues/detail?id=2688
  11248. // ^ has been fixed.
  11249. if (!(this.peerconnection.signalingState == 'stable' && this.peerconnection.iceConnectionState == 'connected')) {
  11250. console.warn('modifySources not yet', this.peerconnection.signalingState, this.peerconnection.iceConnectionState);
  11251. this.wait = true;
  11252. window.setTimeout(function() { self.modifySources(successCallback); }, 250);
  11253. return;
  11254. }
  11255. if (this.wait) {
  11256. window.setTimeout(function() { self.modifySources(successCallback); }, 2500);
  11257. this.wait = false;
  11258. return;
  11259. }
  11260. // Reset switch streams flag
  11261. this.switchstreams = false;
  11262. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11263. // add sources
  11264. this.addssrc.forEach(function(lines, idx) {
  11265. sdp.media[idx] += lines;
  11266. });
  11267. this.addssrc = [];
  11268. // remove sources
  11269. this.removessrc.forEach(function(lines, idx) {
  11270. lines = lines.split('\r\n');
  11271. lines.pop(); // remove empty last element;
  11272. lines.forEach(function(line) {
  11273. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  11274. });
  11275. });
  11276. this.removessrc = [];
  11277. // FIXME:
  11278. // this was a hack for the situation when only one peer exists
  11279. // in the conference.
  11280. // check if still required and remove
  11281. if (sdp.media[0])
  11282. sdp.media[0] = sdp.media[0].replace('a=recvonly', 'a=sendrecv');
  11283. if (sdp.media[1])
  11284. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11285. sdp.raw = sdp.session + sdp.media.join('');
  11286. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  11287. function() {
  11288. if(self.signalingState == 'closed') {
  11289. console.error("createAnswer attempt on closed state");
  11290. return;
  11291. }
  11292. self.peerconnection.createAnswer(
  11293. function(modifiedAnswer) {
  11294. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  11295. if (self.pendingop !== null) {
  11296. var sdp = new SDP(modifiedAnswer.sdp);
  11297. if (sdp.media.length > 1) {
  11298. switch(self.pendingop) {
  11299. case 'mute':
  11300. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  11301. break;
  11302. case 'unmute':
  11303. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11304. break;
  11305. }
  11306. sdp.raw = sdp.session + sdp.media.join('');
  11307. modifiedAnswer.sdp = sdp.raw;
  11308. }
  11309. self.pendingop = null;
  11310. }
  11311. // FIXME: pushing down an answer while ice connection state
  11312. // is still checking is bad...
  11313. //console.log(self.peerconnection.iceConnectionState);
  11314. // trying to work around another chrome bug
  11315. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  11316. self.peerconnection.setLocalDescription(modifiedAnswer,
  11317. function() {
  11318. //console.log('modified setLocalDescription ok');
  11319. self.setLocalDescription();
  11320. if(successCallback){
  11321. successCallback();
  11322. }
  11323. },
  11324. function(error) {
  11325. console.error('modified setLocalDescription failed', error);
  11326. }
  11327. );
  11328. },
  11329. function(error) {
  11330. console.error('modified answer failed', error);
  11331. }
  11332. );
  11333. },
  11334. function(error) {
  11335. console.error('modify failed', error);
  11336. }
  11337. );
  11338. };
  11339. /**
  11340. * Switches video streams.
  11341. * @param new_stream new stream that will be used as video of this session.
  11342. * @param oldStream old video stream of this session.
  11343. * @param success_callback callback executed after successful stream switch.
  11344. */
  11345. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback) {
  11346. var self = this;
  11347. // Remember SDP to figure out added/removed SSRCs
  11348. var oldSdp = null;
  11349. if(self.peerconnection) {
  11350. if(self.peerconnection.localDescription) {
  11351. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  11352. }
  11353. self.peerconnection.removeStream(oldStream, true);
  11354. self.peerconnection.addStream(new_stream);
  11355. }
  11356. APP.RTC.switchVideoStreams(new_stream, oldStream);
  11357. // Conference is not active
  11358. if(!oldSdp || !self.peerconnection) {
  11359. success_callback();
  11360. return;
  11361. }
  11362. self.switchstreams = true;
  11363. self.modifySources(function() {
  11364. console.log('modify sources done');
  11365. success_callback();
  11366. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  11367. console.log("SDPs", oldSdp, newSdp);
  11368. self.notifyMySSRCUpdate(oldSdp, newSdp);
  11369. });
  11370. };
  11371. /**
  11372. * Figures out added/removed ssrcs and send update IQs.
  11373. * @param old_sdp SDP object for old description.
  11374. * @param new_sdp SDP object for new description.
  11375. */
  11376. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  11377. if (!(this.peerconnection.signalingState == 'stable' &&
  11378. this.peerconnection.iceConnectionState == 'connected')){
  11379. console.log("Too early to send updates");
  11380. return;
  11381. }
  11382. // send source-remove IQ.
  11383. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  11384. var remove = $iq({to: this.peerjid, type: 'set'})
  11385. .c('jingle', {
  11386. xmlns: 'urn:xmpp:jingle:1',
  11387. action: 'source-remove',
  11388. initiator: this.initiator,
  11389. sid: this.sid
  11390. }
  11391. );
  11392. var removed = sdpDiffer.toJingle(remove);
  11393. if (removed) {
  11394. this.connection.sendIQ(remove,
  11395. function (res) {
  11396. console.info('got remove result', res);
  11397. },
  11398. function (err) {
  11399. console.error('got remove error', err);
  11400. }
  11401. );
  11402. } else {
  11403. console.log('removal not necessary');
  11404. }
  11405. // send source-add IQ.
  11406. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  11407. var add = $iq({to: this.peerjid, type: 'set'})
  11408. .c('jingle', {
  11409. xmlns: 'urn:xmpp:jingle:1',
  11410. action: 'source-add',
  11411. initiator: this.initiator,
  11412. sid: this.sid
  11413. }
  11414. );
  11415. var added = sdpDiffer.toJingle(add);
  11416. if (added) {
  11417. this.connection.sendIQ(add,
  11418. function (res) {
  11419. console.info('got add result', res);
  11420. },
  11421. function (err) {
  11422. console.error('got add error', err);
  11423. }
  11424. );
  11425. } else {
  11426. console.log('addition not necessary');
  11427. }
  11428. };
  11429. /**
  11430. * Determines whether the (local) video is mute i.e. all video tracks are
  11431. * disabled.
  11432. *
  11433. * @return <tt>true</tt> if the (local) video is mute i.e. all video tracks are
  11434. * disabled; otherwise, <tt>false</tt>
  11435. */
  11436. JingleSession.prototype.isVideoMute = function () {
  11437. var tracks = APP.RTC.localVideo.getVideoTracks();
  11438. var mute = true;
  11439. for (var i = 0; i < tracks.length; ++i) {
  11440. if (tracks[i].enabled) {
  11441. mute = false;
  11442. break;
  11443. }
  11444. }
  11445. return mute;
  11446. };
  11447. /**
  11448. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  11449. *
  11450. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  11451. * tracks; otherwise, <tt>false</tt>
  11452. * @param callback a function to be invoked with <tt>mute</tt> after all video
  11453. * tracks have been enabled/disabled. The function may, optionally, return
  11454. * another function which is to be invoked after the whole mute/unmute operation
  11455. * has completed successfully.
  11456. * @param options an object which specifies optional arguments such as the
  11457. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  11458. * specifies whether the method was initiated in response to a user command (in
  11459. * contrast to an automatic decision made by the application logic)
  11460. */
  11461. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  11462. var byUser;
  11463. if (options) {
  11464. byUser = options.byUser;
  11465. if (typeof byUser === 'undefined') {
  11466. byUser = true;
  11467. }
  11468. } else {
  11469. byUser = true;
  11470. }
  11471. // The user's command to mute the (local) video takes precedence over any
  11472. // automatic decision made by the application logic.
  11473. if (byUser) {
  11474. this.videoMuteByUser = mute;
  11475. } else if (this.videoMuteByUser) {
  11476. return;
  11477. }
  11478. var self = this;
  11479. var localCallback = function (mute) {
  11480. self.connection.emuc.addVideoInfoToPresence(mute);
  11481. self.connection.emuc.sendPresence();
  11482. return callback(mute)
  11483. };
  11484. if (mute == APP.RTC.localVideo.isMuted())
  11485. {
  11486. // Even if no change occurs, the specified callback is to be executed.
  11487. // The specified callback may, optionally, return a successCallback
  11488. // which is to be executed as well.
  11489. var successCallback = localCallback(mute);
  11490. if (successCallback) {
  11491. successCallback();
  11492. }
  11493. } else {
  11494. APP.RTC.localVideo.setMute(!mute);
  11495. this.hardMuteVideo(mute);
  11496. this.modifySources(localCallback(mute));
  11497. }
  11498. };
  11499. // SDP-based mute by going recvonly/sendrecv
  11500. // FIXME: should probably black out the screen as well
  11501. JingleSession.prototype.toggleVideoMute = function (callback) {
  11502. this.service.setVideoMute(APP.RTC.localVideo.isMuted(), callback);
  11503. };
  11504. JingleSession.prototype.hardMuteVideo = function (muted) {
  11505. this.pendingop = muted ? 'mute' : 'unmute';
  11506. };
  11507. JingleSession.prototype.sendMute = function (muted, content) {
  11508. var info = $iq({to: this.peerjid,
  11509. type: 'set'})
  11510. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11511. action: 'session-info',
  11512. initiator: this.initiator,
  11513. sid: this.sid });
  11514. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11515. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  11516. if (content) {
  11517. info.attrs({'name': content});
  11518. }
  11519. this.connection.send(info);
  11520. };
  11521. JingleSession.prototype.sendRinging = function () {
  11522. var info = $iq({to: this.peerjid,
  11523. type: 'set'})
  11524. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11525. action: 'session-info',
  11526. initiator: this.initiator,
  11527. sid: this.sid });
  11528. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11529. this.connection.send(info);
  11530. };
  11531. JingleSession.prototype.getStats = function (interval) {
  11532. var self = this;
  11533. var recv = {audio: 0, video: 0};
  11534. var lost = {audio: 0, video: 0};
  11535. var lastrecv = {audio: 0, video: 0};
  11536. var lastlost = {audio: 0, video: 0};
  11537. var loss = {audio: 0, video: 0};
  11538. var delta = {audio: 0, video: 0};
  11539. this.statsinterval = window.setInterval(function () {
  11540. if (self && self.peerconnection && self.peerconnection.getStats) {
  11541. self.peerconnection.getStats(function (stats) {
  11542. var results = stats.result();
  11543. // TODO: there are so much statistics you can get from this..
  11544. for (var i = 0; i < results.length; ++i) {
  11545. if (results[i].type == 'ssrc') {
  11546. var packetsrecv = results[i].stat('packetsReceived');
  11547. var packetslost = results[i].stat('packetsLost');
  11548. if (packetsrecv && packetslost) {
  11549. packetsrecv = parseInt(packetsrecv, 10);
  11550. packetslost = parseInt(packetslost, 10);
  11551. if (results[i].stat('googFrameRateReceived')) {
  11552. lastlost.video = lost.video;
  11553. lastrecv.video = recv.video;
  11554. recv.video = packetsrecv;
  11555. lost.video = packetslost;
  11556. } else {
  11557. lastlost.audio = lost.audio;
  11558. lastrecv.audio = recv.audio;
  11559. recv.audio = packetsrecv;
  11560. lost.audio = packetslost;
  11561. }
  11562. }
  11563. }
  11564. }
  11565. delta.audio = recv.audio - lastrecv.audio;
  11566. delta.video = recv.video - lastrecv.video;
  11567. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  11568. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  11569. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  11570. });
  11571. }
  11572. }, interval || 3000);
  11573. return this.statsinterval;
  11574. };
  11575. JingleSession.onJingleError = function (session, error)
  11576. {
  11577. console.error("Jingle error", error);
  11578. }
  11579. JingleSession.onJingleFatalError = function (session, error)
  11580. {
  11581. this.service.sessionTerminated = true;
  11582. this.connection.emuc.doLeave();
  11583. APP.UI.messageHandler.showError("dialog.sorry", "Sorry",
  11584. "dialog.internalError",
  11585. "Internal application error[setRemoteDescription]");
  11586. }
  11587. JingleSession.prototype.setLocalDescription = function () {
  11588. // put our ssrcs into presence so other clients can identify our stream
  11589. var newssrcs = [];
  11590. var media = APP.simulcast.parseMedia(this.peerconnection.localDescription);
  11591. media.forEach(function (media) {
  11592. if(Object.keys(media.sources).length > 0) {
  11593. // TODO(gp) maybe exclude FID streams?
  11594. Object.keys(media.sources).forEach(function (ssrc) {
  11595. newssrcs.push({
  11596. 'ssrc': ssrc,
  11597. 'type': media.type,
  11598. 'direction': media.direction
  11599. });
  11600. });
  11601. }
  11602. else if(this.localStreamsSSRC && this.localStreamsSSRC[media.type])
  11603. {
  11604. newssrcs.push({
  11605. 'ssrc': this.localStreamsSSRC[media.type],
  11606. 'type': media.type,
  11607. 'direction': media.direction
  11608. });
  11609. }
  11610. });
  11611. console.log('new ssrcs', newssrcs);
  11612. // Have to clear presence map to get rid of removed streams
  11613. this.connection.emuc.clearPresenceMedia();
  11614. if (newssrcs.length > 0) {
  11615. for (var i = 1; i <= newssrcs.length; i ++) {
  11616. // Change video type to screen
  11617. if (newssrcs[i-1].type === 'video' && APP.desktopsharing.isUsingScreenStream()) {
  11618. newssrcs[i-1].type = 'screen';
  11619. }
  11620. this.connection.emuc.addMediaToPresence(i,
  11621. newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
  11622. }
  11623. this.connection.emuc.sendPresence();
  11624. }
  11625. }
  11626. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11627. function sendKeyframe(pc) {
  11628. console.log('sendkeyframe', pc.iceConnectionState);
  11629. if (pc.iceConnectionState !== 'connected') return; // safe...
  11630. pc.setRemoteDescription(
  11631. pc.remoteDescription,
  11632. function () {
  11633. pc.createAnswer(
  11634. function (modifiedAnswer) {
  11635. pc.setLocalDescription(
  11636. modifiedAnswer,
  11637. function () {
  11638. // noop
  11639. },
  11640. function (error) {
  11641. console.log('triggerKeyframe setLocalDescription failed', error);
  11642. APP.UI.messageHandler.showError();
  11643. }
  11644. );
  11645. },
  11646. function (error) {
  11647. console.log('triggerKeyframe createAnswer failed', error);
  11648. APP.UI.messageHandler.showError();
  11649. }
  11650. );
  11651. },
  11652. function (error) {
  11653. console.log('triggerKeyframe setRemoteDescription failed', error);
  11654. APP.UI.messageHandler.showError();
  11655. }
  11656. );
  11657. }
  11658. JingleSession.prototype.remoteStreamAdded = function (data) {
  11659. var self = this;
  11660. var thessrc;
  11661. var ssrc2jid = this.connection.emuc.ssrc2jid;
  11662. // look up an associated JID for a stream id
  11663. if (data.stream.id && data.stream.id.indexOf('mixedmslabel') === -1) {
  11664. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  11665. var ssrclines
  11666. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  11667. ssrclines = ssrclines.filter(function (line) {
  11668. // NOTE(gp) previously we filtered on the mslabel, but that property
  11669. // is not always present.
  11670. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  11671. return ((line.indexOf('msid:' + data.stream.id) !== -1));
  11672. });
  11673. if (ssrclines.length) {
  11674. thessrc = ssrclines[0].substring(7).split(' ')[0];
  11675. // We signal our streams (through Jingle to the focus) before we set
  11676. // our presence (through which peers associate remote streams to
  11677. // jids). So, it might arrive that a remote stream is added but
  11678. // ssrc2jid is not yet updated and thus data.peerjid cannot be
  11679. // successfully set. Here we wait for up to a second for the
  11680. // presence to arrive.
  11681. if (!ssrc2jid[thessrc]) {
  11682. // TODO(gp) limit wait duration to 1 sec.
  11683. setTimeout(function(d) {
  11684. return function() {
  11685. self.remoteStreamAdded(d);
  11686. }
  11687. }(data), 250);
  11688. return;
  11689. }
  11690. // ok to overwrite the one from focus? might save work in colibri.js
  11691. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  11692. if (ssrc2jid[thessrc]) {
  11693. data.peerjid = ssrc2jid[thessrc];
  11694. }
  11695. }
  11696. }
  11697. //TODO: this code should be removed when firefox implement multistream support
  11698. if(APP.RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_FIREFOX)
  11699. {
  11700. if((JingleSession.notReceivedSSRCs.length == 0) ||
  11701. !ssrc2jid[JingleSession.notReceivedSSRCs[JingleSession.notReceivedSSRCs.length - 1]])
  11702. {
  11703. // TODO(gp) limit wait duration to 1 sec.
  11704. setTimeout(function(d) {
  11705. return function() {
  11706. self.remoteStreamAdded(d);
  11707. }
  11708. }(data), 250);
  11709. return;
  11710. }
  11711. thessrc = JingleSession.notReceivedSSRCs.pop();
  11712. if (ssrc2jid[thessrc]) {
  11713. data.peerjid = ssrc2jid[thessrc];
  11714. }
  11715. }
  11716. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  11717. var isVideo = data.stream.getVideoTracks().length > 0;
  11718. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11719. if (isVideo &&
  11720. data.peerjid && this.peerjid === data.peerjid &&
  11721. data.stream.getVideoTracks().length === 0 &&
  11722. APP.RTC.localVideo.getTracks().length > 0) {
  11723. window.setTimeout(function () {
  11724. sendKeyframe(self.peerconnection);
  11725. }, 3000);
  11726. }
  11727. }
  11728. module.exports = JingleSession;
  11729. },{"../../service/RTC/RTCBrowserType":80,"./SDP":49,"./SDPDiffer":50,"./SDPUtil":51,"./TraceablePeerConnection":52}],49:[function(require,module,exports){
  11730. /* jshint -W117 */
  11731. var SDPUtil = require("./SDPUtil");
  11732. // SDP STUFF
  11733. function SDP(sdp) {
  11734. this.media = sdp.split('\r\nm=');
  11735. for (var i = 1; i < this.media.length; i++) {
  11736. this.media[i] = 'm=' + this.media[i];
  11737. if (i != this.media.length - 1) {
  11738. this.media[i] += '\r\n';
  11739. }
  11740. }
  11741. this.session = this.media.shift() + '\r\n';
  11742. this.raw = this.session + this.media.join('');
  11743. }
  11744. /**
  11745. * Returns map of MediaChannel mapped per channel idx.
  11746. */
  11747. SDP.prototype.getMediaSsrcMap = function() {
  11748. var self = this;
  11749. var media_ssrcs = {};
  11750. var tmp;
  11751. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  11752. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  11753. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  11754. var media = {
  11755. mediaindex: mediaindex,
  11756. mid: mid,
  11757. ssrcs: {},
  11758. ssrcGroups: []
  11759. };
  11760. media_ssrcs[mediaindex] = media;
  11761. tmp.forEach(function (line) {
  11762. var linessrc = line.substring(7).split(' ')[0];
  11763. // allocate new ChannelSsrc
  11764. if(!media.ssrcs[linessrc]) {
  11765. media.ssrcs[linessrc] = {
  11766. ssrc: linessrc,
  11767. lines: []
  11768. };
  11769. }
  11770. media.ssrcs[linessrc].lines.push(line);
  11771. });
  11772. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  11773. tmp.forEach(function(line){
  11774. var semantics = line.substr(0, idx).substr(13);
  11775. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11776. if (ssrcs.length != 0) {
  11777. media.ssrcGroups.push({
  11778. semantics: semantics,
  11779. ssrcs: ssrcs
  11780. });
  11781. }
  11782. });
  11783. }
  11784. return media_ssrcs;
  11785. };
  11786. /**
  11787. * Returns <tt>true</tt> if this SDP contains given SSRC.
  11788. * @param ssrc the ssrc to check.
  11789. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  11790. */
  11791. SDP.prototype.containsSSRC = function(ssrc) {
  11792. var medias = this.getMediaSsrcMap();
  11793. var contains = false;
  11794. Object.keys(medias).forEach(function(mediaindex){
  11795. var media = medias[mediaindex];
  11796. //console.log("Check", channel, ssrc);
  11797. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  11798. contains = true;
  11799. }
  11800. });
  11801. return contains;
  11802. };
  11803. // remove iSAC and CN from SDP
  11804. SDP.prototype.mangle = function () {
  11805. var i, j, mline, lines, rtpmap, newdesc;
  11806. for (i = 0; i < this.media.length; i++) {
  11807. lines = this.media[i].split('\r\n');
  11808. lines.pop(); // remove empty last element
  11809. mline = SDPUtil.parse_mline(lines.shift());
  11810. if (mline.media != 'audio')
  11811. continue;
  11812. newdesc = '';
  11813. mline.fmt.length = 0;
  11814. for (j = 0; j < lines.length; j++) {
  11815. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  11816. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  11817. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  11818. continue;
  11819. mline.fmt.push(rtpmap.id);
  11820. newdesc += lines[j] + '\r\n';
  11821. } else {
  11822. newdesc += lines[j] + '\r\n';
  11823. }
  11824. }
  11825. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  11826. this.media[i] += newdesc;
  11827. }
  11828. this.raw = this.session + this.media.join('');
  11829. };
  11830. // remove lines matching prefix from session section
  11831. SDP.prototype.removeSessionLines = function(prefix) {
  11832. var self = this;
  11833. var lines = SDPUtil.find_lines(this.session, prefix);
  11834. lines.forEach(function(line) {
  11835. self.session = self.session.replace(line + '\r\n', '');
  11836. });
  11837. this.raw = this.session + this.media.join('');
  11838. return lines;
  11839. }
  11840. // remove lines matching prefix from a media section specified by mediaindex
  11841. // TODO: non-numeric mediaindex could match mid
  11842. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  11843. var self = this;
  11844. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  11845. lines.forEach(function(line) {
  11846. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  11847. });
  11848. this.raw = this.session + this.media.join('');
  11849. return lines;
  11850. }
  11851. // add content's to a jingle element
  11852. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  11853. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  11854. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  11855. var self = this;
  11856. // new bundle plan
  11857. if (SDPUtil.find_line(this.session, 'a=group:')) {
  11858. lines = SDPUtil.find_lines(this.session, 'a=group:');
  11859. for (i = 0; i < lines.length; i++) {
  11860. tmp = lines[i].split(' ');
  11861. var semantics = tmp.shift().substr(8);
  11862. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  11863. for (j = 0; j < tmp.length; j++) {
  11864. elem.c('content', {name: tmp[j]}).up();
  11865. }
  11866. elem.up();
  11867. }
  11868. }
  11869. for (i = 0; i < this.media.length; i++) {
  11870. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  11871. if (!(mline.media === 'audio' ||
  11872. mline.media === 'video' ||
  11873. mline.media === 'application'))
  11874. {
  11875. continue;
  11876. }
  11877. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  11878. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  11879. } else {
  11880. if(ssrcs && ssrcs[mline.media])
  11881. {
  11882. ssrc = ssrcs[mline.media];
  11883. }
  11884. else
  11885. ssrc = false;
  11886. }
  11887. elem.c('content', {creator: thecreator, name: mline.media});
  11888. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  11889. // prefer identifier from a=mid if present
  11890. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  11891. elem.attrs({ name: mid });
  11892. }
  11893. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  11894. {
  11895. elem.c('description',
  11896. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  11897. media: mline.media });
  11898. if (ssrc) {
  11899. elem.attrs({ssrc: ssrc});
  11900. }
  11901. for (j = 0; j < mline.fmt.length; j++) {
  11902. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  11903. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  11904. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  11905. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  11906. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  11907. for (k = 0; k < tmp.length; k++) {
  11908. elem.c('parameter', tmp[k]).up();
  11909. }
  11910. }
  11911. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  11912. elem.up();
  11913. }
  11914. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  11915. elem.c('encryption', {required: 1});
  11916. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  11917. crypto.forEach(function(line) {
  11918. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  11919. });
  11920. elem.up(); // end of encryption
  11921. }
  11922. if (ssrc) {
  11923. // new style mapping
  11924. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11925. // FIXME: group by ssrc and support multiple different ssrcs
  11926. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  11927. if(ssrclines.length > 0) {
  11928. ssrclines.forEach(function (line) {
  11929. idx = line.indexOf(' ');
  11930. var linessrc = line.substr(0, idx).substr(7);
  11931. if (linessrc != ssrc) {
  11932. elem.up();
  11933. ssrc = linessrc;
  11934. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11935. }
  11936. var kv = line.substr(idx + 1);
  11937. elem.c('parameter');
  11938. if (kv.indexOf(':') == -1) {
  11939. elem.attrs({ name: kv });
  11940. } else {
  11941. elem.attrs({ name: kv.split(':', 2)[0] });
  11942. elem.attrs({ value: kv.split(':', 2)[1] });
  11943. }
  11944. elem.up();
  11945. });
  11946. elem.up();
  11947. }
  11948. else
  11949. {
  11950. elem.up();
  11951. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11952. elem.c('parameter');
  11953. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  11954. elem.up();
  11955. var msid = null;
  11956. if(mline.media == "audio")
  11957. {
  11958. msid = APP.RTC.localAudio.getId();
  11959. }
  11960. else
  11961. {
  11962. msid = APP.RTC.localVideo.getId();
  11963. }
  11964. if(msid != null)
  11965. {
  11966. msid = msid.replace(/[\{,\}]/g,"");
  11967. elem.c('parameter');
  11968. elem.attrs({name: "msid", value:msid});
  11969. elem.up();
  11970. elem.c('parameter');
  11971. elem.attrs({name: "mslabel", value:msid});
  11972. elem.up();
  11973. elem.c('parameter');
  11974. elem.attrs({name: "label", value:msid});
  11975. elem.up();
  11976. elem.up();
  11977. }
  11978. }
  11979. // XEP-0339 handle ssrc-group attributes
  11980. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  11981. ssrc_group_lines.forEach(function(line) {
  11982. idx = line.indexOf(' ');
  11983. var semantics = line.substr(0, idx).substr(13);
  11984. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11985. if (ssrcs.length != 0) {
  11986. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11987. ssrcs.forEach(function(ssrc) {
  11988. elem.c('source', { ssrc: ssrc })
  11989. .up();
  11990. });
  11991. elem.up();
  11992. }
  11993. });
  11994. }
  11995. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  11996. elem.c('rtcp-mux').up();
  11997. }
  11998. // XEP-0293 -- map a=rtcp-fb:*
  11999. this.RtcpFbToJingle(i, elem, '*');
  12000. // XEP-0294
  12001. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  12002. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  12003. for (j = 0; j < lines.length; j++) {
  12004. tmp = SDPUtil.parse_extmap(lines[j]);
  12005. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  12006. uri: tmp.uri,
  12007. id: tmp.value });
  12008. if (tmp.hasOwnProperty('direction')) {
  12009. switch (tmp.direction) {
  12010. case 'sendonly':
  12011. elem.attrs({senders: 'responder'});
  12012. break;
  12013. case 'recvonly':
  12014. elem.attrs({senders: 'initiator'});
  12015. break;
  12016. case 'sendrecv':
  12017. elem.attrs({senders: 'both'});
  12018. break;
  12019. case 'inactive':
  12020. elem.attrs({senders: 'none'});
  12021. break;
  12022. }
  12023. }
  12024. // TODO: handle params
  12025. elem.up();
  12026. }
  12027. }
  12028. elem.up(); // end of description
  12029. }
  12030. // map ice-ufrag/pwd, dtls fingerprint, candidates
  12031. this.TransportToJingle(i, elem);
  12032. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  12033. elem.attrs({senders: 'both'});
  12034. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  12035. elem.attrs({senders: 'initiator'});
  12036. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  12037. elem.attrs({senders: 'responder'});
  12038. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  12039. elem.attrs({senders: 'none'});
  12040. }
  12041. if (mline.port == '0') {
  12042. // estos hack to reject an m-line
  12043. elem.attrs({senders: 'rejected'});
  12044. }
  12045. elem.up(); // end of content
  12046. }
  12047. elem.up();
  12048. return elem;
  12049. };
  12050. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  12051. var i = mediaindex;
  12052. var tmp;
  12053. var self = this;
  12054. elem.c('transport');
  12055. // XEP-0343 DTLS/SCTP
  12056. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  12057. {
  12058. var sctpmap = SDPUtil.find_line(
  12059. this.media[i], 'a=sctpmap:', self.session);
  12060. if (sctpmap)
  12061. {
  12062. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  12063. elem.c('sctpmap',
  12064. {
  12065. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  12066. number: sctpAttrs[0], /* SCTP port */
  12067. protocol: sctpAttrs[1], /* protocol */
  12068. });
  12069. // Optional stream count attribute
  12070. if (sctpAttrs.length > 2)
  12071. elem.attrs({ streams: sctpAttrs[2]});
  12072. elem.up();
  12073. }
  12074. }
  12075. // XEP-0320
  12076. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  12077. fingerprints.forEach(function(line) {
  12078. tmp = SDPUtil.parse_fingerprint(line);
  12079. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  12080. elem.c('fingerprint').t(tmp.fingerprint);
  12081. delete tmp.fingerprint;
  12082. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  12083. if (line) {
  12084. tmp.setup = line.substr(8);
  12085. }
  12086. elem.attrs(tmp);
  12087. elem.up(); // end of fingerprint
  12088. });
  12089. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  12090. if (tmp) {
  12091. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  12092. elem.attrs(tmp);
  12093. // XEP-0176
  12094. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  12095. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  12096. lines.forEach(function (line) {
  12097. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  12098. });
  12099. }
  12100. }
  12101. elem.up(); // end of transport
  12102. }
  12103. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  12104. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  12105. lines.forEach(function (line) {
  12106. var tmp = SDPUtil.parse_rtcpfb(line);
  12107. if (tmp.type == 'trr-int') {
  12108. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  12109. elem.up();
  12110. } else {
  12111. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  12112. if (tmp.params.length > 0) {
  12113. elem.attrs({'subtype': tmp.params[0]});
  12114. }
  12115. elem.up();
  12116. }
  12117. });
  12118. };
  12119. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  12120. var media = '';
  12121. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  12122. if (tmp.length) {
  12123. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  12124. if (tmp.attr('value')) {
  12125. media += tmp.attr('value');
  12126. } else {
  12127. media += '0';
  12128. }
  12129. media += '\r\n';
  12130. }
  12131. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  12132. tmp.each(function () {
  12133. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  12134. if ($(this).attr('subtype')) {
  12135. media += ' ' + $(this).attr('subtype');
  12136. }
  12137. media += '\r\n';
  12138. });
  12139. return media;
  12140. };
  12141. // construct an SDP from a jingle stanza
  12142. SDP.prototype.fromJingle = function (jingle) {
  12143. var self = this;
  12144. this.raw = 'v=0\r\n' +
  12145. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  12146. 's=-\r\n' +
  12147. 't=0 0\r\n';
  12148. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  12149. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  12150. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  12151. var contents = $(group).find('>content').map(function (idx, content) {
  12152. return content.getAttribute('name');
  12153. }).get();
  12154. if (contents.length > 0) {
  12155. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  12156. }
  12157. });
  12158. }
  12159. this.session = this.raw;
  12160. jingle.find('>content').each(function () {
  12161. var m = self.jingle2media($(this));
  12162. self.media.push(m);
  12163. });
  12164. // reconstruct msid-semantic -- apparently not necessary
  12165. /*
  12166. var msid = SDPUtil.parse_ssrc(this.raw);
  12167. if (msid.hasOwnProperty('mslabel')) {
  12168. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  12169. }
  12170. */
  12171. this.raw = this.session + this.media.join('');
  12172. };
  12173. // translate a jingle content element into an an SDP media part
  12174. SDP.prototype.jingle2media = function (content) {
  12175. var media = '',
  12176. desc = content.find('description'),
  12177. ssrc = desc.attr('ssrc'),
  12178. self = this,
  12179. tmp;
  12180. var sctp = content.find(
  12181. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  12182. tmp = { media: desc.attr('media') };
  12183. tmp.port = '1';
  12184. if (content.attr('senders') == 'rejected') {
  12185. // estos hack to reject an m-line.
  12186. tmp.port = '0';
  12187. }
  12188. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  12189. if (sctp.length)
  12190. tmp.proto = 'DTLS/SCTP';
  12191. else
  12192. tmp.proto = 'RTP/SAVPF';
  12193. } else {
  12194. tmp.proto = 'RTP/AVPF';
  12195. }
  12196. if (!sctp.length)
  12197. {
  12198. tmp.fmt = desc.find('payload-type').map(
  12199. function () { return this.getAttribute('id'); }).get();
  12200. media += SDPUtil.build_mline(tmp) + '\r\n';
  12201. }
  12202. else
  12203. {
  12204. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  12205. media += 'a=sctpmap:' + sctp.attr('number') +
  12206. ' ' + sctp.attr('protocol');
  12207. var streamCount = sctp.attr('streams');
  12208. if (streamCount)
  12209. media += ' ' + streamCount + '\r\n';
  12210. else
  12211. media += '\r\n';
  12212. }
  12213. media += 'c=IN IP4 0.0.0.0\r\n';
  12214. if (!sctp.length)
  12215. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  12216. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  12217. if (tmp.length) {
  12218. if (tmp.attr('ufrag')) {
  12219. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  12220. }
  12221. if (tmp.attr('pwd')) {
  12222. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  12223. }
  12224. tmp.find('>fingerprint').each(function () {
  12225. // FIXME: check namespace at some point
  12226. media += 'a=fingerprint:' + this.getAttribute('hash');
  12227. media += ' ' + $(this).text();
  12228. media += '\r\n';
  12229. if (this.getAttribute('setup')) {
  12230. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  12231. }
  12232. });
  12233. }
  12234. switch (content.attr('senders')) {
  12235. case 'initiator':
  12236. media += 'a=sendonly\r\n';
  12237. break;
  12238. case 'responder':
  12239. media += 'a=recvonly\r\n';
  12240. break;
  12241. case 'none':
  12242. media += 'a=inactive\r\n';
  12243. break;
  12244. case 'both':
  12245. media += 'a=sendrecv\r\n';
  12246. break;
  12247. }
  12248. media += 'a=mid:' + content.attr('name') + '\r\n';
  12249. // <description><rtcp-mux/></description>
  12250. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  12251. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  12252. if (desc.find('rtcp-mux').length) {
  12253. media += 'a=rtcp-mux\r\n';
  12254. }
  12255. if (desc.find('encryption').length) {
  12256. desc.find('encryption>crypto').each(function () {
  12257. media += 'a=crypto:' + this.getAttribute('tag');
  12258. media += ' ' + this.getAttribute('crypto-suite');
  12259. media += ' ' + this.getAttribute('key-params');
  12260. if (this.getAttribute('session-params')) {
  12261. media += ' ' + this.getAttribute('session-params');
  12262. }
  12263. media += '\r\n';
  12264. });
  12265. }
  12266. desc.find('payload-type').each(function () {
  12267. media += SDPUtil.build_rtpmap(this) + '\r\n';
  12268. if ($(this).find('>parameter').length) {
  12269. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  12270. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  12271. media += '\r\n';
  12272. }
  12273. // xep-0293
  12274. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  12275. });
  12276. // xep-0293
  12277. media += self.RtcpFbFromJingle(desc, '*');
  12278. // xep-0294
  12279. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  12280. tmp.each(function () {
  12281. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  12282. });
  12283. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  12284. media += SDPUtil.candidateFromJingle(this);
  12285. });
  12286. // XEP-0339 handle ssrc-group attributes
  12287. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12288. var semantics = this.getAttribute('semantics');
  12289. var ssrcs = $(this).find('>source').map(function() {
  12290. return this.getAttribute('ssrc');
  12291. }).get();
  12292. if (ssrcs.length != 0) {
  12293. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12294. }
  12295. });
  12296. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  12297. tmp.each(function () {
  12298. var ssrc = this.getAttribute('ssrc');
  12299. $(this).find('>parameter').each(function () {
  12300. media += 'a=ssrc:' + ssrc + ' ' + this.getAttribute('name');
  12301. if (this.getAttribute('value') && this.getAttribute('value').length)
  12302. media += ':' + this.getAttribute('value');
  12303. media += '\r\n';
  12304. });
  12305. });
  12306. return media;
  12307. };
  12308. module.exports = SDP;
  12309. },{"./SDPUtil":51}],50:[function(require,module,exports){
  12310. function SDPDiffer(mySDP, otherSDP) {
  12311. this.mySDP = mySDP;
  12312. this.otherSDP = otherSDP;
  12313. }
  12314. /**
  12315. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  12316. * @param otherSdp the other SDP to check ssrc with.
  12317. */
  12318. SDPDiffer.prototype.getNewMedia = function() {
  12319. // this could be useful in Array.prototype.
  12320. function arrayEquals(array) {
  12321. // if the other array is a falsy value, return
  12322. if (!array)
  12323. return false;
  12324. // compare lengths - can save a lot of time
  12325. if (this.length != array.length)
  12326. return false;
  12327. for (var i = 0, l=this.length; i < l; i++) {
  12328. // Check if we have nested arrays
  12329. if (this[i] instanceof Array && array[i] instanceof Array) {
  12330. // recurse into the nested arrays
  12331. if (!this[i].equals(array[i]))
  12332. return false;
  12333. }
  12334. else if (this[i] != array[i]) {
  12335. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  12336. return false;
  12337. }
  12338. }
  12339. return true;
  12340. }
  12341. var myMedias = this.mySDP.getMediaSsrcMap();
  12342. var othersMedias = this.otherSDP.getMediaSsrcMap();
  12343. var newMedia = {};
  12344. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  12345. var myMedia = myMedias[othersMediaIdx];
  12346. var othersMedia = othersMedias[othersMediaIdx];
  12347. if(!myMedia && othersMedia) {
  12348. // Add whole channel
  12349. newMedia[othersMediaIdx] = othersMedia;
  12350. return;
  12351. }
  12352. // Look for new ssrcs accross the channel
  12353. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  12354. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  12355. // Allocate channel if we've found ssrc that doesn't exist in our channel
  12356. if(!newMedia[othersMediaIdx]){
  12357. newMedia[othersMediaIdx] = {
  12358. mediaindex: othersMedia.mediaindex,
  12359. mid: othersMedia.mid,
  12360. ssrcs: {},
  12361. ssrcGroups: []
  12362. };
  12363. }
  12364. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  12365. }
  12366. });
  12367. // Look for new ssrc groups across the channels
  12368. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  12369. // try to match the other ssrc-group with an ssrc-group of ours
  12370. var matched = false;
  12371. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  12372. var mySsrcGroup = myMedia.ssrcGroups[i];
  12373. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  12374. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  12375. matched = true;
  12376. break;
  12377. }
  12378. }
  12379. if (!matched) {
  12380. // Allocate channel if we've found an ssrc-group that doesn't
  12381. // exist in our channel
  12382. if(!newMedia[othersMediaIdx]){
  12383. newMedia[othersMediaIdx] = {
  12384. mediaindex: othersMedia.mediaindex,
  12385. mid: othersMedia.mid,
  12386. ssrcs: {},
  12387. ssrcGroups: []
  12388. };
  12389. }
  12390. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  12391. }
  12392. });
  12393. });
  12394. return newMedia;
  12395. };
  12396. /**
  12397. * Sends SSRC update IQ.
  12398. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  12399. * @param sid session identifier that will be put into the IQ.
  12400. * @param initiator initiator identifier.
  12401. * @param toJid destination Jid
  12402. * @param isAdd indicates if this is remove or add operation.
  12403. */
  12404. SDPDiffer.prototype.toJingle = function(modify) {
  12405. var sdpMediaSsrcs = this.getNewMedia();
  12406. var self = this;
  12407. // FIXME: only announce video ssrcs since we mix audio and dont need
  12408. // the audio ssrcs therefore
  12409. var modified = false;
  12410. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  12411. modified = true;
  12412. var media = sdpMediaSsrcs[mediaindex];
  12413. modify.c('content', {name: media.mid});
  12414. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  12415. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  12416. // generate sources from lines
  12417. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  12418. var mediaSsrc = media.ssrcs[ssrcNum];
  12419. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12420. modify.attrs({ssrc: mediaSsrc.ssrc});
  12421. // iterate over ssrc lines
  12422. mediaSsrc.lines.forEach(function (line) {
  12423. var idx = line.indexOf(' ');
  12424. var kv = line.substr(idx + 1);
  12425. modify.c('parameter');
  12426. if (kv.indexOf(':') == -1) {
  12427. modify.attrs({ name: kv });
  12428. } else {
  12429. modify.attrs({ name: kv.split(':', 2)[0] });
  12430. modify.attrs({ value: kv.split(':', 2)[1] });
  12431. }
  12432. modify.up(); // end of parameter
  12433. });
  12434. modify.up(); // end of source
  12435. });
  12436. // generate source groups from lines
  12437. media.ssrcGroups.forEach(function(ssrcGroup) {
  12438. if (ssrcGroup.ssrcs.length != 0) {
  12439. modify.c('ssrc-group', {
  12440. semantics: ssrcGroup.semantics,
  12441. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  12442. });
  12443. ssrcGroup.ssrcs.forEach(function (ssrc) {
  12444. modify.c('source', { ssrc: ssrc })
  12445. .up(); // end of source
  12446. });
  12447. modify.up(); // end of ssrc-group
  12448. }
  12449. });
  12450. modify.up(); // end of description
  12451. modify.up(); // end of content
  12452. });
  12453. return modified;
  12454. };
  12455. module.exports = SDPDiffer;
  12456. },{}],51:[function(require,module,exports){
  12457. SDPUtil = {
  12458. iceparams: function (mediadesc, sessiondesc) {
  12459. var data = null;
  12460. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  12461. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  12462. data = {
  12463. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  12464. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  12465. };
  12466. }
  12467. return data;
  12468. },
  12469. parse_iceufrag: function (line) {
  12470. return line.substring(12);
  12471. },
  12472. build_iceufrag: function (frag) {
  12473. return 'a=ice-ufrag:' + frag;
  12474. },
  12475. parse_icepwd: function (line) {
  12476. return line.substring(10);
  12477. },
  12478. build_icepwd: function (pwd) {
  12479. return 'a=ice-pwd:' + pwd;
  12480. },
  12481. parse_mid: function (line) {
  12482. return line.substring(6);
  12483. },
  12484. parse_mline: function (line) {
  12485. var parts = line.substring(2).split(' '),
  12486. data = {};
  12487. data.media = parts.shift();
  12488. data.port = parts.shift();
  12489. data.proto = parts.shift();
  12490. if (parts[parts.length - 1] === '') { // trailing whitespace
  12491. parts.pop();
  12492. }
  12493. data.fmt = parts;
  12494. return data;
  12495. },
  12496. build_mline: function (mline) {
  12497. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  12498. },
  12499. parse_rtpmap: function (line) {
  12500. var parts = line.substring(9).split(' '),
  12501. data = {};
  12502. data.id = parts.shift();
  12503. parts = parts[0].split('/');
  12504. data.name = parts.shift();
  12505. data.clockrate = parts.shift();
  12506. data.channels = parts.length ? parts.shift() : '1';
  12507. return data;
  12508. },
  12509. /**
  12510. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  12511. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  12512. * @returns [SCTP port number, protocol, streams]
  12513. */
  12514. parse_sctpmap: function (line)
  12515. {
  12516. var parts = line.substring(10).split(' ');
  12517. var sctpPort = parts[0];
  12518. var protocol = parts[1];
  12519. // Stream count is optional
  12520. var streamCount = parts.length > 2 ? parts[2] : null;
  12521. return [sctpPort, protocol, streamCount];// SCTP port
  12522. },
  12523. build_rtpmap: function (el) {
  12524. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  12525. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  12526. line += '/' + el.getAttribute('channels');
  12527. }
  12528. return line;
  12529. },
  12530. parse_crypto: function (line) {
  12531. var parts = line.substring(9).split(' '),
  12532. data = {};
  12533. data.tag = parts.shift();
  12534. data['crypto-suite'] = parts.shift();
  12535. data['key-params'] = parts.shift();
  12536. if (parts.length) {
  12537. data['session-params'] = parts.join(' ');
  12538. }
  12539. return data;
  12540. },
  12541. parse_fingerprint: function (line) { // RFC 4572
  12542. var parts = line.substring(14).split(' '),
  12543. data = {};
  12544. data.hash = parts.shift();
  12545. data.fingerprint = parts.shift();
  12546. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  12547. return data;
  12548. },
  12549. parse_fmtp: function (line) {
  12550. var parts = line.split(' '),
  12551. i, key, value,
  12552. data = [];
  12553. parts.shift();
  12554. parts = parts.join(' ').split(';');
  12555. for (i = 0; i < parts.length; i++) {
  12556. key = parts[i].split('=')[0];
  12557. while (key.length && key[0] == ' ') {
  12558. key = key.substring(1);
  12559. }
  12560. value = parts[i].split('=')[1];
  12561. if (key && value) {
  12562. data.push({name: key, value: value});
  12563. } else if (key) {
  12564. // rfc 4733 (DTMF) style stuff
  12565. data.push({name: '', value: key});
  12566. }
  12567. }
  12568. return data;
  12569. },
  12570. parse_icecandidate: function (line) {
  12571. var candidate = {},
  12572. elems = line.split(' ');
  12573. candidate.foundation = elems[0].substring(12);
  12574. candidate.component = elems[1];
  12575. candidate.protocol = elems[2].toLowerCase();
  12576. candidate.priority = elems[3];
  12577. candidate.ip = elems[4];
  12578. candidate.port = elems[5];
  12579. // elems[6] => "typ"
  12580. candidate.type = elems[7];
  12581. candidate.generation = 0; // default value, may be overwritten below
  12582. for (var i = 8; i < elems.length; i += 2) {
  12583. switch (elems[i]) {
  12584. case 'raddr':
  12585. candidate['rel-addr'] = elems[i + 1];
  12586. break;
  12587. case 'rport':
  12588. candidate['rel-port'] = elems[i + 1];
  12589. break;
  12590. case 'generation':
  12591. candidate.generation = elems[i + 1];
  12592. break;
  12593. case 'tcptype':
  12594. candidate.tcptype = elems[i + 1];
  12595. break;
  12596. default: // TODO
  12597. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12598. }
  12599. }
  12600. candidate.network = '1';
  12601. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12602. return candidate;
  12603. },
  12604. build_icecandidate: function (cand) {
  12605. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  12606. line += ' ';
  12607. switch (cand.type) {
  12608. case 'srflx':
  12609. case 'prflx':
  12610. case 'relay':
  12611. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  12612. line += 'raddr';
  12613. line += ' ';
  12614. line += cand['rel-addr'];
  12615. line += ' ';
  12616. line += 'rport';
  12617. line += ' ';
  12618. line += cand['rel-port'];
  12619. line += ' ';
  12620. }
  12621. break;
  12622. }
  12623. if (cand.hasOwnAttribute('tcptype')) {
  12624. line += 'tcptype';
  12625. line += ' ';
  12626. line += cand.tcptype;
  12627. line += ' ';
  12628. }
  12629. line += 'generation';
  12630. line += ' ';
  12631. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  12632. return line;
  12633. },
  12634. parse_ssrc: function (desc) {
  12635. // proprietary mapping of a=ssrc lines
  12636. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  12637. // and parse according to that
  12638. var lines = desc.split('\r\n'),
  12639. data = {};
  12640. for (var i = 0; i < lines.length; i++) {
  12641. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  12642. var idx = lines[i].indexOf(' ');
  12643. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  12644. }
  12645. }
  12646. return data;
  12647. },
  12648. parse_rtcpfb: function (line) {
  12649. var parts = line.substr(10).split(' ');
  12650. var data = {};
  12651. data.pt = parts.shift();
  12652. data.type = parts.shift();
  12653. data.params = parts;
  12654. return data;
  12655. },
  12656. parse_extmap: function (line) {
  12657. var parts = line.substr(9).split(' ');
  12658. var data = {};
  12659. data.value = parts.shift();
  12660. if (data.value.indexOf('/') != -1) {
  12661. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  12662. data.value = data.value.substr(0, data.value.indexOf('/'));
  12663. } else {
  12664. data.direction = 'both';
  12665. }
  12666. data.uri = parts.shift();
  12667. data.params = parts;
  12668. return data;
  12669. },
  12670. find_line: function (haystack, needle, sessionpart) {
  12671. var lines = haystack.split('\r\n');
  12672. for (var i = 0; i < lines.length; i++) {
  12673. if (lines[i].substring(0, needle.length) == needle) {
  12674. return lines[i];
  12675. }
  12676. }
  12677. if (!sessionpart) {
  12678. return false;
  12679. }
  12680. // search session part
  12681. lines = sessionpart.split('\r\n');
  12682. for (var j = 0; j < lines.length; j++) {
  12683. if (lines[j].substring(0, needle.length) == needle) {
  12684. return lines[j];
  12685. }
  12686. }
  12687. return false;
  12688. },
  12689. find_lines: function (haystack, needle, sessionpart) {
  12690. var lines = haystack.split('\r\n'),
  12691. needles = [];
  12692. for (var i = 0; i < lines.length; i++) {
  12693. if (lines[i].substring(0, needle.length) == needle)
  12694. needles.push(lines[i]);
  12695. }
  12696. if (needles.length || !sessionpart) {
  12697. return needles;
  12698. }
  12699. // search session part
  12700. lines = sessionpart.split('\r\n');
  12701. for (var j = 0; j < lines.length; j++) {
  12702. if (lines[j].substring(0, needle.length) == needle) {
  12703. needles.push(lines[j]);
  12704. }
  12705. }
  12706. return needles;
  12707. },
  12708. candidateToJingle: function (line) {
  12709. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  12710. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  12711. if (line.indexOf('candidate:') === 0) {
  12712. line = 'a=' + line;
  12713. } else if (line.substring(0, 12) != 'a=candidate:') {
  12714. console.log('parseCandidate called with a line that is not a candidate line');
  12715. console.log(line);
  12716. return null;
  12717. }
  12718. if (line.substring(line.length - 2) == '\r\n') // chomp it
  12719. line = line.substring(0, line.length - 2);
  12720. var candidate = {},
  12721. elems = line.split(' '),
  12722. i;
  12723. if (elems[6] != 'typ') {
  12724. console.log('did not find typ in the right place');
  12725. console.log(line);
  12726. return null;
  12727. }
  12728. candidate.foundation = elems[0].substring(12);
  12729. candidate.component = elems[1];
  12730. candidate.protocol = elems[2].toLowerCase();
  12731. candidate.priority = elems[3];
  12732. candidate.ip = elems[4];
  12733. candidate.port = elems[5];
  12734. // elems[6] => "typ"
  12735. candidate.type = elems[7];
  12736. candidate.generation = '0'; // default, may be overwritten below
  12737. for (i = 8; i < elems.length; i += 2) {
  12738. switch (elems[i]) {
  12739. case 'raddr':
  12740. candidate['rel-addr'] = elems[i + 1];
  12741. break;
  12742. case 'rport':
  12743. candidate['rel-port'] = elems[i + 1];
  12744. break;
  12745. case 'generation':
  12746. candidate.generation = elems[i + 1];
  12747. break;
  12748. case 'tcptype':
  12749. candidate.tcptype = elems[i + 1];
  12750. break;
  12751. default: // TODO
  12752. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12753. }
  12754. }
  12755. candidate.network = '1';
  12756. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12757. return candidate;
  12758. },
  12759. candidateFromJingle: function (cand) {
  12760. var line = 'a=candidate:';
  12761. line += cand.getAttribute('foundation');
  12762. line += ' ';
  12763. line += cand.getAttribute('component');
  12764. line += ' ';
  12765. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  12766. line += ' ';
  12767. line += cand.getAttribute('priority');
  12768. line += ' ';
  12769. line += cand.getAttribute('ip');
  12770. line += ' ';
  12771. line += cand.getAttribute('port');
  12772. line += ' ';
  12773. line += 'typ';
  12774. line += ' ' + cand.getAttribute('type');
  12775. line += ' ';
  12776. switch (cand.getAttribute('type')) {
  12777. case 'srflx':
  12778. case 'prflx':
  12779. case 'relay':
  12780. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  12781. line += 'raddr';
  12782. line += ' ';
  12783. line += cand.getAttribute('rel-addr');
  12784. line += ' ';
  12785. line += 'rport';
  12786. line += ' ';
  12787. line += cand.getAttribute('rel-port');
  12788. line += ' ';
  12789. }
  12790. break;
  12791. }
  12792. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  12793. line += 'tcptype';
  12794. line += ' ';
  12795. line += cand.getAttribute('tcptype');
  12796. line += ' ';
  12797. }
  12798. line += 'generation';
  12799. line += ' ';
  12800. line += cand.getAttribute('generation') || '0';
  12801. return line + '\r\n';
  12802. }
  12803. };
  12804. module.exports = SDPUtil;
  12805. },{}],52:[function(require,module,exports){
  12806. function TraceablePeerConnection(ice_config, constraints) {
  12807. var self = this;
  12808. var RTCPeerconnection = navigator.mozGetUserMedia ? mozRTCPeerConnection : webkitRTCPeerConnection;
  12809. this.peerconnection = new RTCPeerconnection(ice_config, constraints);
  12810. this.updateLog = [];
  12811. this.stats = {};
  12812. this.statsinterval = null;
  12813. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  12814. // override as desired
  12815. this.trace = function (what, info) {
  12816. //console.warn('WTRACE', what, info);
  12817. self.updateLog.push({
  12818. time: new Date(),
  12819. type: what,
  12820. value: info || ""
  12821. });
  12822. };
  12823. this.onicecandidate = null;
  12824. this.peerconnection.onicecandidate = function (event) {
  12825. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  12826. if (self.onicecandidate !== null) {
  12827. self.onicecandidate(event);
  12828. }
  12829. };
  12830. this.onaddstream = null;
  12831. this.peerconnection.onaddstream = function (event) {
  12832. self.trace('onaddstream', event.stream.id);
  12833. if (self.onaddstream !== null) {
  12834. self.onaddstream(event);
  12835. }
  12836. };
  12837. this.onremovestream = null;
  12838. this.peerconnection.onremovestream = function (event) {
  12839. self.trace('onremovestream', event.stream.id);
  12840. if (self.onremovestream !== null) {
  12841. self.onremovestream(event);
  12842. }
  12843. };
  12844. this.onsignalingstatechange = null;
  12845. this.peerconnection.onsignalingstatechange = function (event) {
  12846. self.trace('onsignalingstatechange', self.signalingState);
  12847. if (self.onsignalingstatechange !== null) {
  12848. self.onsignalingstatechange(event);
  12849. }
  12850. };
  12851. this.oniceconnectionstatechange = null;
  12852. this.peerconnection.oniceconnectionstatechange = function (event) {
  12853. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  12854. if (self.oniceconnectionstatechange !== null) {
  12855. self.oniceconnectionstatechange(event);
  12856. }
  12857. };
  12858. this.onnegotiationneeded = null;
  12859. this.peerconnection.onnegotiationneeded = function (event) {
  12860. self.trace('onnegotiationneeded');
  12861. if (self.onnegotiationneeded !== null) {
  12862. self.onnegotiationneeded(event);
  12863. }
  12864. };
  12865. self.ondatachannel = null;
  12866. this.peerconnection.ondatachannel = function (event) {
  12867. self.trace('ondatachannel', event);
  12868. if (self.ondatachannel !== null) {
  12869. self.ondatachannel(event);
  12870. }
  12871. };
  12872. if (!navigator.mozGetUserMedia && this.maxstats) {
  12873. this.statsinterval = window.setInterval(function() {
  12874. self.peerconnection.getStats(function(stats) {
  12875. var results = stats.result();
  12876. for (var i = 0; i < results.length; ++i) {
  12877. //console.log(results[i].type, results[i].id, results[i].names())
  12878. var now = new Date();
  12879. results[i].names().forEach(function (name) {
  12880. var id = results[i].id + '-' + name;
  12881. if (!self.stats[id]) {
  12882. self.stats[id] = {
  12883. startTime: now,
  12884. endTime: now,
  12885. values: [],
  12886. times: []
  12887. };
  12888. }
  12889. self.stats[id].values.push(results[i].stat(name));
  12890. self.stats[id].times.push(now.getTime());
  12891. if (self.stats[id].values.length > self.maxstats) {
  12892. self.stats[id].values.shift();
  12893. self.stats[id].times.shift();
  12894. }
  12895. self.stats[id].endTime = now;
  12896. });
  12897. }
  12898. });
  12899. }, 1000);
  12900. }
  12901. };
  12902. dumpSDP = function(description) {
  12903. return 'type: ' + description.type + '\r\n' + description.sdp;
  12904. }
  12905. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  12906. TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
  12907. TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
  12908. TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() {
  12909. var publicLocalDescription = APP.simulcast.reverseTransformLocalDescription(this.peerconnection.localDescription);
  12910. return publicLocalDescription;
  12911. });
  12912. TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() {
  12913. var publicRemoteDescription = APP.simulcast.reverseTransformRemoteDescription(this.peerconnection.remoteDescription);
  12914. return publicRemoteDescription;
  12915. });
  12916. }
  12917. TraceablePeerConnection.prototype.addStream = function (stream) {
  12918. this.trace('addStream', stream.id);
  12919. APP.simulcast.resetSender();
  12920. try
  12921. {
  12922. this.peerconnection.addStream(stream);
  12923. }
  12924. catch (e)
  12925. {
  12926. console.error(e);
  12927. return;
  12928. }
  12929. };
  12930. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  12931. this.trace('removeStream', stream.id);
  12932. APP.simulcast.resetSender();
  12933. if(stopStreams) {
  12934. stream.getAudioTracks().forEach(function (track) {
  12935. track.stop();
  12936. });
  12937. stream.getVideoTracks().forEach(function (track) {
  12938. track.stop();
  12939. });
  12940. }
  12941. this.peerconnection.removeStream(stream);
  12942. };
  12943. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  12944. this.trace('createDataChannel', label, opts);
  12945. return this.peerconnection.createDataChannel(label, opts);
  12946. };
  12947. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  12948. var self = this;
  12949. description = APP.simulcast.transformLocalDescription(description);
  12950. this.trace('setLocalDescription', dumpSDP(description));
  12951. this.peerconnection.setLocalDescription(description,
  12952. function () {
  12953. self.trace('setLocalDescriptionOnSuccess');
  12954. successCallback();
  12955. },
  12956. function (err) {
  12957. self.trace('setLocalDescriptionOnFailure', err);
  12958. failureCallback(err);
  12959. }
  12960. );
  12961. /*
  12962. if (this.statsinterval === null && this.maxstats > 0) {
  12963. // start gathering stats
  12964. }
  12965. */
  12966. };
  12967. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  12968. var self = this;
  12969. description = APP.simulcast.transformRemoteDescription(description);
  12970. this.trace('setRemoteDescription', dumpSDP(description));
  12971. this.peerconnection.setRemoteDescription(description,
  12972. function () {
  12973. self.trace('setRemoteDescriptionOnSuccess');
  12974. successCallback();
  12975. },
  12976. function (err) {
  12977. self.trace('setRemoteDescriptionOnFailure', err);
  12978. failureCallback(err);
  12979. }
  12980. );
  12981. /*
  12982. if (this.statsinterval === null && this.maxstats > 0) {
  12983. // start gathering stats
  12984. }
  12985. */
  12986. };
  12987. TraceablePeerConnection.prototype.close = function () {
  12988. this.trace('stop');
  12989. if (this.statsinterval !== null) {
  12990. window.clearInterval(this.statsinterval);
  12991. this.statsinterval = null;
  12992. }
  12993. this.peerconnection.close();
  12994. };
  12995. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  12996. var self = this;
  12997. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  12998. this.peerconnection.createOffer(
  12999. function (offer) {
  13000. self.trace('createOfferOnSuccess', dumpSDP(offer));
  13001. successCallback(offer);
  13002. },
  13003. function(err) {
  13004. self.trace('createOfferOnFailure', err);
  13005. failureCallback(err);
  13006. },
  13007. constraints
  13008. );
  13009. };
  13010. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  13011. var self = this;
  13012. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  13013. this.peerconnection.createAnswer(
  13014. function (answer) {
  13015. answer = APP.simulcast.transformAnswer(answer);
  13016. self.trace('createAnswerOnSuccess', dumpSDP(answer));
  13017. successCallback(answer);
  13018. },
  13019. function(err) {
  13020. self.trace('createAnswerOnFailure', err);
  13021. failureCallback(err);
  13022. },
  13023. constraints
  13024. );
  13025. };
  13026. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  13027. var self = this;
  13028. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  13029. this.peerconnection.addIceCandidate(candidate);
  13030. /* maybe later
  13031. this.peerconnection.addIceCandidate(candidate,
  13032. function () {
  13033. self.trace('addIceCandidateOnSuccess');
  13034. successCallback();
  13035. },
  13036. function (err) {
  13037. self.trace('addIceCandidateOnFailure', err);
  13038. failureCallback(err);
  13039. }
  13040. );
  13041. */
  13042. };
  13043. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  13044. if (navigator.mozGetUserMedia) {
  13045. // ignore for now...
  13046. if(!errback)
  13047. errback = function () {
  13048. }
  13049. this.peerconnection.getStats(null,callback,errback);
  13050. } else {
  13051. this.peerconnection.getStats(callback);
  13052. }
  13053. };
  13054. module.exports = TraceablePeerConnection;
  13055. },{}],53:[function(require,module,exports){
  13056. /* global $, $iq, APP, config, connection, UI, messageHandler,
  13057. roomName, sessionTerminated, Strophe, Util */
  13058. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13059. var Settings = require("../settings/Settings");
  13060. var AuthenticationEvents
  13061. = require("../../service/authentication/AuthenticationEvents");
  13062. /**
  13063. * Contains logic responsible for enabling/disabling functionality available
  13064. * only to moderator users.
  13065. */
  13066. var connection = null;
  13067. var focusUserJid;
  13068. function createExpBackoffTimer(step) {
  13069. var count = 1;
  13070. return function (reset) {
  13071. // Reset call
  13072. if (reset) {
  13073. count = 1;
  13074. return;
  13075. }
  13076. // Calculate next timeout
  13077. var timeout = Math.pow(2, count - 1);
  13078. count += 1;
  13079. return timeout * step;
  13080. };
  13081. }
  13082. var getNextTimeout = createExpBackoffTimer(1000);
  13083. var getNextErrorTimeout = createExpBackoffTimer(1000);
  13084. // External authentication stuff
  13085. var externalAuthEnabled = false;
  13086. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  13087. // it will be enabled automatically if focus detects the component through
  13088. // service discovery.
  13089. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  13090. var eventEmitter = null;
  13091. var Moderator = {
  13092. isModerator: function () {
  13093. return connection && connection.emuc.isModerator();
  13094. },
  13095. isPeerModerator: function (peerJid) {
  13096. return connection &&
  13097. connection.emuc.getMemberRole(peerJid) === 'moderator';
  13098. },
  13099. isExternalAuthEnabled: function () {
  13100. return externalAuthEnabled;
  13101. },
  13102. isSipGatewayEnabled: function () {
  13103. return sipGatewayEnabled;
  13104. },
  13105. setConnection: function (con) {
  13106. connection = con;
  13107. },
  13108. init: function (xmpp, emitter) {
  13109. this.xmppService = xmpp;
  13110. eventEmitter = emitter;
  13111. // Message listener that talks to POPUP window
  13112. function listener(event) {
  13113. if (event.data && event.data.sessionId) {
  13114. if (event.origin !== window.location.origin) {
  13115. console.warn(
  13116. "Ignoring sessionId from different origin: " + event.origin);
  13117. return;
  13118. }
  13119. localStorage.setItem('sessionId', event.data.sessionId);
  13120. // After popup is closed we will authenticate
  13121. }
  13122. }
  13123. // Register
  13124. if (window.addEventListener) {
  13125. window.addEventListener("message", listener, false);
  13126. } else {
  13127. window.attachEvent("onmessage", listener);
  13128. }
  13129. },
  13130. onMucLeft: function (jid) {
  13131. console.info("Someone left is it focus ? " + jid);
  13132. var resource = Strophe.getResourceFromJid(jid);
  13133. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  13134. console.info(
  13135. "Focus has left the room - leaving conference");
  13136. //hangUp();
  13137. // We'd rather reload to have everything re-initialized
  13138. // FIXME: show some message before reload
  13139. location.reload();
  13140. }
  13141. },
  13142. setFocusUserJid: function (focusJid) {
  13143. if (!focusUserJid) {
  13144. focusUserJid = focusJid;
  13145. console.info("Focus jid set to: " + focusUserJid);
  13146. }
  13147. },
  13148. getFocusUserJid: function () {
  13149. return focusUserJid;
  13150. },
  13151. getFocusComponent: function () {
  13152. // Get focus component address
  13153. var focusComponent = config.hosts.focus;
  13154. // If not specified use default: 'focus.domain'
  13155. if (!focusComponent) {
  13156. focusComponent = 'focus.' + config.hosts.domain;
  13157. }
  13158. return focusComponent;
  13159. },
  13160. createConferenceIq: function (roomName) {
  13161. // Generate create conference IQ
  13162. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  13163. // Session Id used for authentication
  13164. var sessionId = localStorage.getItem('sessionId');
  13165. var machineUID = Settings.getSettings().uid;
  13166. console.info(
  13167. "Session ID: " + sessionId + " machine UID: " + machineUID);
  13168. elem.c('conference', {
  13169. xmlns: 'http://jitsi.org/protocol/focus',
  13170. room: roomName,
  13171. 'machine-uid': machineUID
  13172. });
  13173. if (sessionId) {
  13174. elem.attrs({ 'session-id': sessionId});
  13175. }
  13176. if (config.hosts.bridge !== undefined) {
  13177. elem.c(
  13178. 'property',
  13179. { name: 'bridge', value: config.hosts.bridge})
  13180. .up();
  13181. }
  13182. // Tell the focus we have Jigasi configured
  13183. if (config.hosts.call_control !== undefined) {
  13184. elem.c(
  13185. 'property',
  13186. { name: 'call_control', value: config.hosts.call_control})
  13187. .up();
  13188. }
  13189. if (config.channelLastN !== undefined) {
  13190. elem.c(
  13191. 'property',
  13192. { name: 'channelLastN', value: config.channelLastN})
  13193. .up();
  13194. }
  13195. if (config.adaptiveLastN !== undefined) {
  13196. elem.c(
  13197. 'property',
  13198. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  13199. .up();
  13200. }
  13201. if (config.adaptiveSimulcast !== undefined) {
  13202. elem.c(
  13203. 'property',
  13204. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  13205. .up();
  13206. }
  13207. if (config.openSctp !== undefined) {
  13208. elem.c(
  13209. 'property',
  13210. { name: 'openSctp', value: config.openSctp})
  13211. .up();
  13212. }
  13213. if (config.enableFirefoxSupport !== undefined) {
  13214. elem.c(
  13215. 'property',
  13216. { name: 'enableFirefoxHacks',
  13217. value: config.enableFirefoxSupport})
  13218. .up();
  13219. }
  13220. elem.up();
  13221. return elem;
  13222. },
  13223. parseConfigOptions: function (resultIq) {
  13224. Moderator.setFocusUserJid(
  13225. $(resultIq).find('conference').attr('focusjid'));
  13226. var authenticationEnabled
  13227. = $(resultIq).find(
  13228. '>conference>property' +
  13229. '[name=\'authentication\'][value=\'true\']').length > 0;
  13230. console.info("Authentication enabled: " + authenticationEnabled);
  13231. externalAuthEnabled
  13232. = $(resultIq).find(
  13233. '>conference>property' +
  13234. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  13235. console.info('External authentication enabled: ' + externalAuthEnabled);
  13236. if (!externalAuthEnabled) {
  13237. // We expect to receive sessionId in 'internal' authentication mode
  13238. var sessionId
  13239. = $(resultIq).find('conference').attr('session-id');
  13240. if (sessionId) {
  13241. console.info('Received sessionId: ' + sessionId);
  13242. localStorage.setItem('sessionId', sessionId);
  13243. }
  13244. }
  13245. var authIdentity = $(resultIq).find('>conference').attr('identity');
  13246. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  13247. authenticationEnabled, authIdentity);
  13248. // Check if focus has auto-detected Jigasi component(this will be also
  13249. // included if we have passed our host from the config)
  13250. if ($(resultIq).find(
  13251. '>conference>property' +
  13252. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  13253. sipGatewayEnabled = true;
  13254. }
  13255. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  13256. },
  13257. // FIXME: we need to show the fact that we're waiting for the focus
  13258. // to the user(or that focus is not available)
  13259. allocateConferenceFocus: function (roomName, callback) {
  13260. // Try to use focus user JID from the config
  13261. Moderator.setFocusUserJid(config.focusUserJid);
  13262. // Send create conference IQ
  13263. var iq = Moderator.createConferenceIq(roomName);
  13264. var self = this;
  13265. connection.sendIQ(
  13266. iq,
  13267. function (result) {
  13268. // Setup config options
  13269. Moderator.parseConfigOptions(result);
  13270. if ('true' === $(result).find('conference').attr('ready')) {
  13271. // Reset both timers
  13272. getNextTimeout(true);
  13273. getNextErrorTimeout(true);
  13274. // Exec callback
  13275. callback();
  13276. } else {
  13277. var waitMs = getNextTimeout();
  13278. console.info("Waiting for the focus... " + waitMs);
  13279. // Reset error timeout
  13280. getNextErrorTimeout(true);
  13281. window.setTimeout(
  13282. function () {
  13283. Moderator.allocateConferenceFocus(
  13284. roomName, callback);
  13285. }, waitMs);
  13286. }
  13287. },
  13288. function (error) {
  13289. // Invalid session ? remove and try again
  13290. // without session ID to get a new one
  13291. var invalidSession
  13292. = $(error).find('>error>session-invalid').length;
  13293. if (invalidSession) {
  13294. console.info("Session expired! - removing");
  13295. localStorage.removeItem("sessionId");
  13296. }
  13297. if ($(error).find('>error>graceful-shutdown').length) {
  13298. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  13299. return;
  13300. }
  13301. // Check for error returned by the reservation system
  13302. var reservationErr = $(error).find('>error>reservation-error');
  13303. if (reservationErr.length) {
  13304. // Trigger error event
  13305. var errorCode = reservationErr.attr('error-code');
  13306. var errorMsg;
  13307. if ($(error).find('>error>text')) {
  13308. errorMsg = $(error).find('>error>text').text();
  13309. }
  13310. eventEmitter.emit(
  13311. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  13312. return;
  13313. }
  13314. // Not authorized to create new room
  13315. if ($(error).find('>error>not-authorized').length) {
  13316. console.warn("Unauthorized to start the conference", error);
  13317. var toDomain
  13318. = Strophe.getDomainFromJid(error.getAttribute('to'));
  13319. if (toDomain === config.hosts.anonymousdomain) {
  13320. // we are connected with anonymous domain and
  13321. // only non anonymous users can create rooms
  13322. // we must authorize the user
  13323. self.xmppService.promptLogin();
  13324. } else {
  13325. // External authentication mode
  13326. eventEmitter.emit(
  13327. XMPPEvents.AUTHENTICATION_REQUIRED,
  13328. function () {
  13329. Moderator.allocateConferenceFocus(
  13330. roomName, callback);
  13331. });
  13332. }
  13333. return;
  13334. }
  13335. var waitMs = getNextErrorTimeout();
  13336. console.error("Focus error, retry after " + waitMs, error);
  13337. // Show message
  13338. var focusComponent = Moderator.getFocusComponent();
  13339. var retrySec = waitMs / 1000;
  13340. // FIXME: message is duplicated ?
  13341. // Do not show in case of session invalid
  13342. // which means just a retry
  13343. if (!invalidSession) {
  13344. APP.UI.messageHandler.notify(
  13345. null, "notify.focus",
  13346. 'Conference focus', 'disconnected', "notify.focusFail",
  13347. focusComponent + " not available - retry in " +
  13348. retrySec + " sec",
  13349. {component: focusComponent, ms: retrySec});
  13350. }
  13351. // Reset response timeout
  13352. getNextTimeout(true);
  13353. window.setTimeout(
  13354. function () {
  13355. Moderator.allocateConferenceFocus(roomName, callback);
  13356. }, waitMs);
  13357. }
  13358. );
  13359. },
  13360. getLoginUrl: function (roomName, urlCallback) {
  13361. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13362. iq.c('login-url', {
  13363. xmlns: 'http://jitsi.org/protocol/focus',
  13364. room: roomName,
  13365. 'machine-uid': Settings.getSettings().uid
  13366. });
  13367. connection.sendIQ(
  13368. iq,
  13369. function (result) {
  13370. var url = $(result).find('login-url').attr('url');
  13371. url = url = decodeURIComponent(url);
  13372. if (url) {
  13373. console.info("Got auth url: " + url);
  13374. urlCallback(url);
  13375. } else {
  13376. console.error(
  13377. "Failed to get auth url from the focus", result);
  13378. }
  13379. },
  13380. function (error) {
  13381. console.error("Get auth url error", error);
  13382. }
  13383. );
  13384. },
  13385. getPopupLoginUrl: function (roomName, urlCallback) {
  13386. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13387. iq.c('login-url', {
  13388. xmlns: 'http://jitsi.org/protocol/focus',
  13389. room: roomName,
  13390. 'machine-uid': Settings.getSettings().uid,
  13391. popup: true
  13392. });
  13393. connection.sendIQ(
  13394. iq,
  13395. function (result) {
  13396. var url = $(result).find('login-url').attr('url');
  13397. url = url = decodeURIComponent(url);
  13398. if (url) {
  13399. console.info("Got POPUP auth url: " + url);
  13400. urlCallback(url);
  13401. } else {
  13402. console.error(
  13403. "Failed to get POPUP auth url from the focus", result);
  13404. }
  13405. },
  13406. function (error) {
  13407. console.error('Get POPUP auth url error', error);
  13408. }
  13409. );
  13410. },
  13411. logout: function (callback) {
  13412. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  13413. var sessionId = localStorage.getItem('sessionId');
  13414. if (!sessionId) {
  13415. callback();
  13416. return;
  13417. }
  13418. iq.c('logout', {
  13419. xmlns: 'http://jitsi.org/protocol/focus',
  13420. 'session-id': sessionId
  13421. });
  13422. connection.sendIQ(
  13423. iq,
  13424. function (result) {
  13425. var logoutUrl = $(result).find('logout').attr('logout-url');
  13426. if (logoutUrl) {
  13427. logoutUrl = decodeURIComponent(logoutUrl);
  13428. }
  13429. console.info("Log out OK, url: " + logoutUrl, result);
  13430. localStorage.removeItem('sessionId');
  13431. callback(logoutUrl);
  13432. },
  13433. function (error) {
  13434. console.error("Logout error", error);
  13435. }
  13436. );
  13437. }
  13438. };
  13439. module.exports = Moderator;
  13440. },{"../../service/authentication/AuthenticationEvents":85,"../../service/xmpp/XMPPEvents":89,"../settings/Settings":38}],54:[function(require,module,exports){
  13441. /* global $, $iq, config, connection, focusMucJid, messageHandler, Moderator,
  13442. Toolbar, Util */
  13443. var Moderator = require("./moderator");
  13444. var recordingToken = null;
  13445. var recordingEnabled;
  13446. /**
  13447. * Whether to use a jirecon component for recording, or use the videobridge
  13448. * through COLIBRI.
  13449. */
  13450. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  13451. /**
  13452. * The ID of the jirecon recording session. Jirecon generates it when we
  13453. * initially start recording, and it needs to be used in subsequent requests
  13454. * to jirecon.
  13455. */
  13456. var jireconRid = null;
  13457. function setRecordingToken(token) {
  13458. recordingToken = token;
  13459. }
  13460. function setRecording(state, token, callback, connection) {
  13461. if (useJirecon){
  13462. setRecordingJirecon(state, token, callback, connection);
  13463. } else {
  13464. setRecordingColibri(state, token, callback, connection);
  13465. }
  13466. }
  13467. function setRecordingJirecon(state, token, callback, connection) {
  13468. if (state == recordingEnabled){
  13469. return;
  13470. }
  13471. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  13472. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  13473. action: state ? 'start' : 'stop',
  13474. mucjid: connection.emuc.roomjid});
  13475. if (!state){
  13476. iq.attrs({rid: jireconRid});
  13477. }
  13478. console.log('Start recording');
  13479. connection.sendIQ(
  13480. iq,
  13481. function (result) {
  13482. // TODO wait for an IQ with the real status, since this is
  13483. // provisional?
  13484. jireconRid = $(result).find('recording').attr('rid');
  13485. console.log('Recording ' + (state ? 'started' : 'stopped') +
  13486. '(jirecon)' + result);
  13487. recordingEnabled = state;
  13488. if (!state){
  13489. jireconRid = null;
  13490. }
  13491. callback(state);
  13492. },
  13493. function (error) {
  13494. console.log('Failed to start recording, error: ', error);
  13495. callback(recordingEnabled);
  13496. });
  13497. }
  13498. // Sends a COLIBRI message which enables or disables (according to 'state')
  13499. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  13500. // with the new recording state, according to the IQ.
  13501. function setRecordingColibri(state, token, callback, connection) {
  13502. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  13503. elem.c('conference', {
  13504. xmlns: 'http://jitsi.org/protocol/colibri'
  13505. });
  13506. elem.c('recording', {state: state, token: token});
  13507. connection.sendIQ(elem,
  13508. function (result) {
  13509. console.log('Set recording "', state, '". Result:', result);
  13510. var recordingElem = $(result).find('>conference>recording');
  13511. var newState = ('true' === recordingElem.attr('state'));
  13512. recordingEnabled = newState;
  13513. callback(newState);
  13514. },
  13515. function (error) {
  13516. console.warn(error);
  13517. callback(recordingEnabled);
  13518. }
  13519. );
  13520. }
  13521. var Recording = {
  13522. toggleRecording: function (tokenEmptyCallback,
  13523. startingCallback, startedCallback, connection) {
  13524. if (!Moderator.isModerator()) {
  13525. console.log(
  13526. 'non-focus, or conference not yet organized:' +
  13527. ' not enabling recording');
  13528. return;
  13529. }
  13530. var self = this;
  13531. // Jirecon does not (currently) support a token.
  13532. if (!recordingToken && !useJirecon) {
  13533. tokenEmptyCallback(function (value) {
  13534. setRecordingToken(value);
  13535. self.toggleRecording(tokenEmptyCallback,
  13536. startingCallback, startedCallback, connection);
  13537. });
  13538. return;
  13539. }
  13540. var oldState = recordingEnabled;
  13541. startingCallback(!oldState);
  13542. setRecording(!oldState,
  13543. recordingToken,
  13544. function (state) {
  13545. console.log("New recording state: ", state);
  13546. if (state === oldState) {
  13547. // FIXME: new focus:
  13548. // this will not work when moderator changes
  13549. // during active session. Then it will assume that
  13550. // recording status has changed to true, but it might have
  13551. // been already true(and we only received actual status from
  13552. // the focus).
  13553. //
  13554. // SO we start with status null, so that it is initialized
  13555. // here and will fail only after second click, so if invalid
  13556. // token was used we have to press the button twice before
  13557. // current status will be fetched and token will be reset.
  13558. //
  13559. // Reliable way would be to return authentication error.
  13560. // Or status update when moderator connects.
  13561. // Or we have to stop recording session when current
  13562. // moderator leaves the room.
  13563. // Failed to change, reset the token because it might
  13564. // have been wrong
  13565. setRecordingToken(null);
  13566. }
  13567. startedCallback(state);
  13568. },
  13569. connection
  13570. );
  13571. }
  13572. }
  13573. module.exports = Recording;
  13574. },{"./moderator":53}],55:[function(require,module,exports){
  13575. /* jshint -W117 */
  13576. /* a simple MUC connection plugin
  13577. * can only handle a single MUC room
  13578. */
  13579. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13580. var Moderator = require("./moderator");
  13581. var JingleSession = require("./JingleSession");
  13582. var bridgeIsDown = false;
  13583. module.exports = function(XMPP, eventEmitter) {
  13584. Strophe.addConnectionPlugin('emuc', {
  13585. connection: null,
  13586. roomjid: null,
  13587. myroomjid: null,
  13588. members: {},
  13589. list_members: [], // so we can elect a new focus
  13590. presMap: {},
  13591. preziMap: {},
  13592. joined: false,
  13593. isOwner: false,
  13594. role: null,
  13595. focusMucJid: null,
  13596. ssrc2jid: {},
  13597. init: function (conn) {
  13598. this.connection = conn;
  13599. },
  13600. initPresenceMap: function (myroomjid) {
  13601. this.presMap['to'] = myroomjid;
  13602. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  13603. },
  13604. doJoin: function (jid, password) {
  13605. this.myroomjid = jid;
  13606. console.info("Joined MUC as " + this.myroomjid);
  13607. this.initPresenceMap(this.myroomjid);
  13608. if (!this.roomjid) {
  13609. this.roomjid = Strophe.getBareJidFromJid(jid);
  13610. // add handlers (just once)
  13611. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  13612. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  13613. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  13614. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  13615. }
  13616. if (password !== undefined) {
  13617. this.presMap['password'] = password;
  13618. }
  13619. this.sendPresence();
  13620. },
  13621. doLeave: function () {
  13622. console.log("do leave", this.myroomjid);
  13623. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  13624. this.presMap.length = 0;
  13625. this.connection.send(pres);
  13626. },
  13627. createNonAnonymousRoom: function () {
  13628. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  13629. var getForm = $iq({type: 'get', to: this.roomjid})
  13630. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  13631. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13632. var self = this;
  13633. this.connection.sendIQ(getForm, function (form) {
  13634. if (!$(form).find(
  13635. '>query>x[xmlns="jabber:x:data"]' +
  13636. '>field[var="muc#roomconfig_whois"]').length) {
  13637. console.error('non-anonymous rooms not supported');
  13638. return;
  13639. }
  13640. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  13641. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  13642. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13643. formSubmit.c('field', {'var': 'FORM_TYPE'})
  13644. .c('value')
  13645. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  13646. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  13647. .c('value').t('anyone').up().up();
  13648. self.connection.sendIQ(formSubmit);
  13649. }, function (error) {
  13650. console.error("Error getting room configuration form");
  13651. });
  13652. },
  13653. onPresence: function (pres) {
  13654. var from = pres.getAttribute('from');
  13655. // What is this for? A workaround for something?
  13656. if (pres.getAttribute('type')) {
  13657. return true;
  13658. }
  13659. // Parse etherpad tag.
  13660. var etherpad = $(pres).find('>etherpad');
  13661. if (etherpad.length) {
  13662. if (config.etherpad_base && !Moderator.isModerator()) {
  13663. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  13664. }
  13665. }
  13666. // Parse prezi tag.
  13667. var presentation = $(pres).find('>prezi');
  13668. if (presentation.length) {
  13669. var url = presentation.attr('url');
  13670. var current = presentation.find('>current').text();
  13671. console.log('presentation info received from', from, url);
  13672. if (this.preziMap[from] == null) {
  13673. this.preziMap[from] = url;
  13674. $(document).trigger('presentationadded.muc', [from, url, current]);
  13675. }
  13676. else {
  13677. $(document).trigger('gotoslide.muc', [from, url, current]);
  13678. }
  13679. }
  13680. else if (this.preziMap[from] != null) {
  13681. var url = this.preziMap[from];
  13682. delete this.preziMap[from];
  13683. $(document).trigger('presentationremoved.muc', [from, url]);
  13684. }
  13685. // Parse audio info tag.
  13686. var audioMuted = $(pres).find('>audiomuted');
  13687. if (audioMuted.length) {
  13688. $(document).trigger('audiomuted.muc', [from, audioMuted.text()]);
  13689. }
  13690. // Parse video info tag.
  13691. var videoMuted = $(pres).find('>videomuted');
  13692. if (videoMuted.length) {
  13693. $(document).trigger('videomuted.muc', [from, videoMuted.text()]);
  13694. }
  13695. var stats = $(pres).find('>stats');
  13696. if (stats.length) {
  13697. var statsObj = {};
  13698. Strophe.forEachChild(stats[0], "stat", function (el) {
  13699. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  13700. });
  13701. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  13702. }
  13703. // Parse status.
  13704. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  13705. this.isOwner = true;
  13706. this.createNonAnonymousRoom();
  13707. }
  13708. // Parse roles.
  13709. var member = {};
  13710. member.show = $(pres).find('>show').text();
  13711. member.status = $(pres).find('>status').text();
  13712. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  13713. member.affiliation = tmp.attr('affiliation');
  13714. member.role = tmp.attr('role');
  13715. // Focus recognition
  13716. member.jid = tmp.attr('jid');
  13717. member.isFocus = false;
  13718. if (member.jid
  13719. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  13720. member.isFocus = true;
  13721. }
  13722. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  13723. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  13724. if (from == this.myroomjid) {
  13725. if (member.affiliation == 'owner') this.isOwner = true;
  13726. if (this.role !== member.role) {
  13727. this.role = member.role;
  13728. eventEmitter.emit(XMPPEvents.LOCALROLE_CHANGED,
  13729. from, member, pres, Moderator.isModerator());
  13730. }
  13731. if (!this.joined) {
  13732. this.joined = true;
  13733. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  13734. this.list_members.push(from);
  13735. }
  13736. } else if (this.members[from] === undefined) {
  13737. // new participant
  13738. this.members[from] = member;
  13739. this.list_members.push(from);
  13740. console.log('entered', from, member);
  13741. if (member.isFocus) {
  13742. this.focusMucJid = from;
  13743. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  13744. }
  13745. else {
  13746. var id = $(pres).find('>userID').text();
  13747. var email = $(pres).find('>email');
  13748. if (email.length > 0) {
  13749. id = email.text();
  13750. }
  13751. eventEmitter.emit(XMPPEvents.MUC_ENTER, from, id, member.displayName);
  13752. }
  13753. } else {
  13754. // Presence update for existing participant
  13755. // Watch role change:
  13756. if (this.members[from].role != member.role) {
  13757. this.members[from].role = member.role;
  13758. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  13759. member.role, member.displayName);
  13760. }
  13761. }
  13762. // Always trigger presence to update bindings
  13763. this.parsePresence(from, member, pres);
  13764. // Trigger status message update
  13765. if (member.status) {
  13766. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  13767. }
  13768. return true;
  13769. },
  13770. onPresenceUnavailable: function (pres) {
  13771. var from = pres.getAttribute('from');
  13772. // room destroyed ?
  13773. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  13774. '>destroy').length) {
  13775. var reason;
  13776. var reasonSelect = $(pres).find(
  13777. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  13778. '>destroy>reason');
  13779. if (reasonSelect.length) {
  13780. reason = reasonSelect.text();
  13781. }
  13782. XMPP.disposeConference(false);
  13783. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  13784. return true;
  13785. }
  13786. // Status code 110 indicates that this notification is "self-presence".
  13787. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  13788. delete this.members[from];
  13789. this.list_members.splice(this.list_members.indexOf(from), 1);
  13790. this.onParticipantLeft(from);
  13791. }
  13792. // If the status code is 110 this means we're leaving and we would like
  13793. // to remove everyone else from our view, so we trigger the event.
  13794. else if (this.list_members.length > 1) {
  13795. for (var i = 0; i < this.list_members.length; i++) {
  13796. var member = this.list_members[i];
  13797. delete this.members[i];
  13798. this.list_members.splice(i, 1);
  13799. this.onParticipantLeft(member);
  13800. }
  13801. }
  13802. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  13803. $(document).trigger('kicked.muc', [from]);
  13804. if (this.myroomjid === from) {
  13805. XMPP.disposeConference(false);
  13806. eventEmitter.emit(XMPPEvents.KICKED);
  13807. }
  13808. }
  13809. return true;
  13810. },
  13811. onPresenceError: function (pres) {
  13812. var from = pres.getAttribute('from');
  13813. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13814. console.log('on password required', from);
  13815. var self = this;
  13816. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  13817. self.doJoin(from, value);
  13818. });
  13819. } else if ($(pres).find(
  13820. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13821. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  13822. if (toDomain === config.hosts.anonymousdomain) {
  13823. // enter the room by replying with 'not-authorized'. This would
  13824. // result in reconnection from authorized domain.
  13825. // We're either missing Jicofo/Prosody config for anonymous
  13826. // domains or something is wrong.
  13827. // XMPP.promptLogin();
  13828. APP.UI.messageHandler.openReportDialog(null, null,
  13829. "dialog.joinError",
  13830. 'Oops ! We couldn`t join the conference.' +
  13831. ' There might be some problem with security' +
  13832. ' configuration. Please contact service' +
  13833. ' administrator.', pres);
  13834. } else {
  13835. console.warn('onPresError ', pres);
  13836. APP.UI.messageHandler.openReportDialog(null, null,
  13837. "dialog.connectError",
  13838. 'Oops! Something went wrong and we couldn`t ' +
  13839. 'connect to the conference.',
  13840. pres);
  13841. }
  13842. } else {
  13843. console.warn('onPresError ', pres);
  13844. APP.UI.messageHandler.openReportDialog(null, null,
  13845. "dialog.connectError",
  13846. 'Oops! Something went wrong and we couldn`t ' +
  13847. 'connect to the conference.',
  13848. pres);
  13849. }
  13850. return true;
  13851. },
  13852. sendMessage: function (body, nickname) {
  13853. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  13854. msg.c('body', body).up();
  13855. if (nickname) {
  13856. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  13857. }
  13858. this.connection.send(msg);
  13859. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  13860. },
  13861. setSubject: function (subject) {
  13862. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  13863. msg.c('subject', subject);
  13864. this.connection.send(msg);
  13865. console.log("topic changed to " + subject);
  13866. },
  13867. onMessage: function (msg) {
  13868. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  13869. var from = msg.getAttribute('from');
  13870. var nick =
  13871. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  13872. .text() ||
  13873. Strophe.getResourceFromJid(from);
  13874. var txt = $(msg).find('>body').text();
  13875. var type = msg.getAttribute("type");
  13876. if (type == "error") {
  13877. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  13878. $(msg).find('>text').text(), txt);
  13879. return true;
  13880. }
  13881. var subject = $(msg).find('>subject');
  13882. if (subject.length) {
  13883. var subjectText = subject.text();
  13884. if (subjectText || subjectText == "") {
  13885. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  13886. console.log("Subject is changed to " + subjectText);
  13887. }
  13888. }
  13889. if (txt) {
  13890. console.log('chat', nick, txt);
  13891. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  13892. from, nick, txt, this.myroomjid);
  13893. }
  13894. return true;
  13895. },
  13896. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  13897. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  13898. var ob = this;
  13899. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  13900. function (res) {
  13901. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  13902. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  13903. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13904. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  13905. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  13906. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  13907. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  13908. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  13909. ob.connection.sendIQ(formsubmit,
  13910. onSuccess,
  13911. onError);
  13912. } else {
  13913. onNotSupported();
  13914. }
  13915. }, onError);
  13916. },
  13917. kick: function (jid) {
  13918. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  13919. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  13920. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  13921. .c('reason').t('You have been kicked.').up().up().up();
  13922. this.connection.sendIQ(
  13923. kickIQ,
  13924. function (result) {
  13925. console.log('Kick participant with jid: ', jid, result);
  13926. },
  13927. function (error) {
  13928. console.log('Kick participant error: ', error);
  13929. });
  13930. },
  13931. sendPresence: function () {
  13932. var pres = $pres({to: this.presMap['to'] });
  13933. pres.c('x', {xmlns: this.presMap['xns']});
  13934. if (this.presMap['password']) {
  13935. pres.c('password').t(this.presMap['password']).up();
  13936. }
  13937. pres.up();
  13938. // Send XEP-0115 'c' stanza that contains our capabilities info
  13939. if (this.connection.caps) {
  13940. this.connection.caps.node = config.clientNode;
  13941. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  13942. }
  13943. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  13944. .t(navigator.userAgent).up();
  13945. if (this.presMap['bridgeIsDown']) {
  13946. pres.c('bridgeIsDown').up();
  13947. }
  13948. if (this.presMap['email']) {
  13949. pres.c('email').t(this.presMap['email']).up();
  13950. }
  13951. if (this.presMap['userId']) {
  13952. pres.c('userId').t(this.presMap['userId']).up();
  13953. }
  13954. if (this.presMap['displayName']) {
  13955. // XEP-0172
  13956. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  13957. .t(this.presMap['displayName']).up();
  13958. }
  13959. if (this.presMap['audions']) {
  13960. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  13961. .t(this.presMap['audiomuted']).up();
  13962. }
  13963. if (this.presMap['videons']) {
  13964. pres.c('videomuted', {xmlns: this.presMap['videons']})
  13965. .t(this.presMap['videomuted']).up();
  13966. }
  13967. if (this.presMap['statsns']) {
  13968. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  13969. for (var stat in this.presMap["stats"])
  13970. if (this.presMap["stats"][stat] != null)
  13971. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  13972. pres.up();
  13973. }
  13974. if (this.presMap['prezins']) {
  13975. pres.c('prezi',
  13976. {xmlns: this.presMap['prezins'],
  13977. 'url': this.presMap['preziurl']})
  13978. .c('current').t(this.presMap['prezicurrent']).up().up();
  13979. }
  13980. if (this.presMap['etherpadns']) {
  13981. pres.c('etherpad', {xmlns: this.presMap['etherpadns']})
  13982. .t(this.presMap['etherpadname']).up();
  13983. }
  13984. if (this.presMap['medians']) {
  13985. pres.c('media', {xmlns: this.presMap['medians']});
  13986. var sourceNumber = 0;
  13987. Object.keys(this.presMap).forEach(function (key) {
  13988. if (key.indexOf('source') >= 0) {
  13989. sourceNumber++;
  13990. }
  13991. });
  13992. if (sourceNumber > 0)
  13993. for (var i = 1; i <= sourceNumber / 3; i++) {
  13994. pres.c('source',
  13995. {type: this.presMap['source' + i + '_type'],
  13996. ssrc: this.presMap['source' + i + '_ssrc'],
  13997. direction: this.presMap['source' + i + '_direction']
  13998. || 'sendrecv' }
  13999. ).up();
  14000. }
  14001. }
  14002. pres.up();
  14003. this.connection.send(pres);
  14004. },
  14005. addDisplayNameToPresence: function (displayName) {
  14006. this.presMap['displayName'] = displayName;
  14007. },
  14008. addMediaToPresence: function (sourceNumber, mtype, ssrcs, direction) {
  14009. if (!this.presMap['medians'])
  14010. this.presMap['medians'] = 'http://estos.de/ns/mjs';
  14011. this.presMap['source' + sourceNumber + '_type'] = mtype;
  14012. this.presMap['source' + sourceNumber + '_ssrc'] = ssrcs;
  14013. this.presMap['source' + sourceNumber + '_direction'] = direction;
  14014. },
  14015. clearPresenceMedia: function () {
  14016. var self = this;
  14017. Object.keys(this.presMap).forEach(function (key) {
  14018. if (key.indexOf('source') != -1) {
  14019. delete self.presMap[key];
  14020. }
  14021. });
  14022. },
  14023. addPreziToPresence: function (url, currentSlide) {
  14024. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  14025. this.presMap['preziurl'] = url;
  14026. this.presMap['prezicurrent'] = currentSlide;
  14027. },
  14028. removePreziFromPresence: function () {
  14029. delete this.presMap['prezins'];
  14030. delete this.presMap['preziurl'];
  14031. delete this.presMap['prezicurrent'];
  14032. },
  14033. addCurrentSlideToPresence: function (currentSlide) {
  14034. this.presMap['prezicurrent'] = currentSlide;
  14035. },
  14036. getPrezi: function (roomjid) {
  14037. return this.preziMap[roomjid];
  14038. },
  14039. addEtherpadToPresence: function (etherpadName) {
  14040. this.presMap['etherpadns'] = 'http://jitsi.org/jitmeet/etherpad';
  14041. this.presMap['etherpadname'] = etherpadName;
  14042. },
  14043. addAudioInfoToPresence: function (isMuted) {
  14044. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  14045. this.presMap['audiomuted'] = isMuted.toString();
  14046. },
  14047. addVideoInfoToPresence: function (isMuted) {
  14048. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  14049. this.presMap['videomuted'] = isMuted.toString();
  14050. },
  14051. addConnectionInfoToPresence: function (stats) {
  14052. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  14053. this.presMap['stats'] = stats;
  14054. },
  14055. findJidFromResource: function (resourceJid) {
  14056. if (resourceJid &&
  14057. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  14058. return this.myroomjid;
  14059. }
  14060. var peerJid = null;
  14061. Object.keys(this.members).some(function (jid) {
  14062. peerJid = jid;
  14063. return Strophe.getResourceFromJid(jid) === resourceJid;
  14064. });
  14065. return peerJid;
  14066. },
  14067. addBridgeIsDownToPresence: function () {
  14068. this.presMap['bridgeIsDown'] = true;
  14069. },
  14070. addEmailToPresence: function (email) {
  14071. this.presMap['email'] = email;
  14072. },
  14073. addUserIdToPresence: function (userId) {
  14074. this.presMap['userId'] = userId;
  14075. },
  14076. isModerator: function () {
  14077. return this.role === 'moderator';
  14078. },
  14079. getMemberRole: function (peerJid) {
  14080. if (this.members[peerJid]) {
  14081. return this.members[peerJid].role;
  14082. }
  14083. return null;
  14084. },
  14085. onParticipantLeft: function (jid) {
  14086. eventEmitter.emit(XMPPEvents.MUC_LEFT, jid);
  14087. this.connection.jingle.terminateByJid(jid);
  14088. if (this.getPrezi(jid)) {
  14089. $(document).trigger('presentationremoved.muc',
  14090. [jid, this.getPrezi(jid)]);
  14091. }
  14092. Moderator.onMucLeft(jid);
  14093. },
  14094. parsePresence: function (from, memeber, pres) {
  14095. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  14096. bridgeIsDown = true;
  14097. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  14098. }
  14099. if(memeber.isFocus)
  14100. return;
  14101. var self = this;
  14102. // Remove old ssrcs coming from the jid
  14103. Object.keys(this.ssrc2jid).forEach(function (ssrc) {
  14104. if (self.ssrc2jid[ssrc] == from) {
  14105. delete self.ssrc2jid[ssrc];
  14106. }
  14107. });
  14108. var changedStreams = [];
  14109. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  14110. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  14111. var ssrcV = ssrc.getAttribute('ssrc');
  14112. self.ssrc2jid[ssrcV] = from;
  14113. JingleSession.notReceivedSSRCs.push(ssrcV);
  14114. var type = ssrc.getAttribute('type');
  14115. var direction = ssrc.getAttribute('direction');
  14116. changedStreams.push({type: type, direction: direction});
  14117. });
  14118. eventEmitter.emit(XMPPEvents.CHANGED_STREAMS, from, changedStreams);
  14119. var displayName = !config.displayJids
  14120. ? memeber.displayName : Strophe.getResourceFromJid(from);
  14121. if (displayName && displayName.length > 0)
  14122. {
  14123. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  14124. }
  14125. var id = $(pres).find('>userID').text();
  14126. var email = $(pres).find('>email');
  14127. if(email.length > 0) {
  14128. id = email.text();
  14129. }
  14130. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  14131. }
  14132. });
  14133. };
  14134. },{"../../service/xmpp/XMPPEvents":89,"./JingleSession":48,"./moderator":53}],56:[function(require,module,exports){
  14135. /* jshint -W117 */
  14136. var JingleSession = require("./JingleSession");
  14137. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14138. module.exports = function(XMPP, eventEmitter)
  14139. {
  14140. function CallIncomingJingle(sid, connection) {
  14141. var sess = connection.jingle.sessions[sid];
  14142. // TODO: do we check activecall == null?
  14143. connection.jingle.activecall = sess;
  14144. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  14145. // TODO: check affiliation and/or role
  14146. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  14147. sess.usedrip = true; // not-so-naive trickle ice
  14148. sess.sendAnswer();
  14149. sess.accept();
  14150. };
  14151. Strophe.addConnectionPlugin('jingle', {
  14152. connection: null,
  14153. sessions: {},
  14154. jid2session: {},
  14155. ice_config: {iceServers: []},
  14156. pc_constraints: {},
  14157. activecall: null,
  14158. media_constraints: {
  14159. mandatory: {
  14160. 'OfferToReceiveAudio': true,
  14161. 'OfferToReceiveVideo': true
  14162. }
  14163. // MozDontOfferDataChannel: true when this is firefox
  14164. },
  14165. init: function (conn) {
  14166. this.connection = conn;
  14167. if (this.connection.disco) {
  14168. // http://xmpp.org/extensions/xep-0167.html#support
  14169. // http://xmpp.org/extensions/xep-0176.html#support
  14170. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  14171. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  14172. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  14173. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  14174. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  14175. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  14176. // this is dealt with by SDP O/A so we don't need to annouce this
  14177. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  14178. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  14179. if (config.useRtcpMux) {
  14180. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  14181. }
  14182. if (config.useBundle) {
  14183. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  14184. }
  14185. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  14186. }
  14187. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  14188. },
  14189. onJingle: function (iq) {
  14190. var sid = $(iq).find('jingle').attr('sid');
  14191. var action = $(iq).find('jingle').attr('action');
  14192. var fromJid = iq.getAttribute('from');
  14193. // send ack first
  14194. var ack = $iq({type: 'result',
  14195. to: fromJid,
  14196. id: iq.getAttribute('id')
  14197. });
  14198. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  14199. var sess = this.sessions[sid];
  14200. if ('session-initiate' != action) {
  14201. if (sess === null) {
  14202. ack.type = 'error';
  14203. ack.c('error', {type: 'cancel'})
  14204. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  14205. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  14206. this.connection.send(ack);
  14207. return true;
  14208. }
  14209. // compare from to sess.peerjid (bare jid comparison for later compat with message-mode)
  14210. // local jid is not checked
  14211. if (Strophe.getBareJidFromJid(fromJid) != Strophe.getBareJidFromJid(sess.peerjid)) {
  14212. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  14213. ack.type = 'error';
  14214. ack.c('error', {type: 'cancel'})
  14215. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  14216. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  14217. this.connection.send(ack);
  14218. return true;
  14219. }
  14220. } else if (sess !== undefined) {
  14221. // existing session with same session id
  14222. // this might be out-of-order if the sess.peerjid is the same as from
  14223. ack.type = 'error';
  14224. ack.c('error', {type: 'cancel'})
  14225. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  14226. console.warn('duplicate session id', sid);
  14227. this.connection.send(ack);
  14228. return true;
  14229. }
  14230. // FIXME: check for a defined action
  14231. this.connection.send(ack);
  14232. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  14233. switch (action) {
  14234. case 'session-initiate':
  14235. sess = new JingleSession(
  14236. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  14237. this.connection, XMPP);
  14238. // configure session
  14239. sess.media_constraints = this.media_constraints;
  14240. sess.pc_constraints = this.pc_constraints;
  14241. sess.ice_config = this.ice_config;
  14242. sess.initiate(fromJid, false);
  14243. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  14244. sess.setRemoteDescription($(iq).find('>jingle'), 'offer');
  14245. this.sessions[sess.sid] = sess;
  14246. this.jid2session[sess.peerjid] = sess;
  14247. // the callback should either
  14248. // .sendAnswer and .accept
  14249. // or .sendTerminate -- not necessarily synchronus
  14250. CallIncomingJingle(sess.sid, this.connection);
  14251. break;
  14252. case 'session-accept':
  14253. sess.setRemoteDescription($(iq).find('>jingle'), 'answer');
  14254. sess.accept();
  14255. $(document).trigger('callaccepted.jingle', [sess.sid]);
  14256. break;
  14257. case 'session-terminate':
  14258. // If this is not the focus sending the terminate, we have
  14259. // nothing more to do here.
  14260. if (Object.keys(this.sessions).length < 1
  14261. || !(this.sessions[Object.keys(this.sessions)[0]]
  14262. instanceof JingleSession))
  14263. {
  14264. break;
  14265. }
  14266. console.log('terminating...', sess.sid);
  14267. sess.terminate();
  14268. this.terminate(sess.sid);
  14269. if ($(iq).find('>jingle>reason').length) {
  14270. $(document).trigger('callterminated.jingle', [
  14271. sess.sid,
  14272. sess.peerjid,
  14273. $(iq).find('>jingle>reason>:first')[0].tagName,
  14274. $(iq).find('>jingle>reason>text').text()
  14275. ]);
  14276. } else {
  14277. $(document).trigger('callterminated.jingle',
  14278. [sess.sid, sess.peerjid]);
  14279. }
  14280. break;
  14281. case 'transport-info':
  14282. sess.addIceCandidate($(iq).find('>jingle>content'));
  14283. break;
  14284. case 'session-info':
  14285. var affected;
  14286. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14287. $(document).trigger('ringing.jingle', [sess.sid]);
  14288. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14289. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14290. $(document).trigger('mute.jingle', [sess.sid, affected]);
  14291. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14292. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14293. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  14294. }
  14295. break;
  14296. case 'addsource': // FIXME: proprietary, un-jingleish
  14297. case 'source-add': // FIXME: proprietary
  14298. sess.addSource($(iq).find('>jingle>content'), fromJid);
  14299. break;
  14300. case 'removesource': // FIXME: proprietary, un-jingleish
  14301. case 'source-remove': // FIXME: proprietary
  14302. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  14303. break;
  14304. default:
  14305. console.warn('jingle action not implemented', action);
  14306. break;
  14307. }
  14308. return true;
  14309. },
  14310. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  14311. var sess = new JingleSession(myjid || this.connection.jid,
  14312. Math.random().toString(36).substr(2, 12), // random string
  14313. this.connection, XMPP);
  14314. // configure session
  14315. sess.media_constraints = this.media_constraints;
  14316. sess.pc_constraints = this.pc_constraints;
  14317. sess.ice_config = this.ice_config;
  14318. sess.initiate(peerjid, true);
  14319. this.sessions[sess.sid] = sess;
  14320. this.jid2session[sess.peerjid] = sess;
  14321. sess.sendOffer();
  14322. return sess;
  14323. },
  14324. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  14325. if (sid === null || sid === undefined) {
  14326. for (sid in this.sessions) {
  14327. if (this.sessions[sid].state != 'ended') {
  14328. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14329. this.sessions[sid].terminate();
  14330. }
  14331. delete this.jid2session[this.sessions[sid].peerjid];
  14332. delete this.sessions[sid];
  14333. }
  14334. } else if (this.sessions.hasOwnProperty(sid)) {
  14335. if (this.sessions[sid].state != 'ended') {
  14336. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14337. this.sessions[sid].terminate();
  14338. }
  14339. delete this.jid2session[this.sessions[sid].peerjid];
  14340. delete this.sessions[sid];
  14341. }
  14342. },
  14343. // Used to terminate a session when an unavailable presence is received.
  14344. terminateByJid: function (jid) {
  14345. if (this.jid2session.hasOwnProperty(jid)) {
  14346. var sess = this.jid2session[jid];
  14347. if (sess) {
  14348. sess.terminate();
  14349. console.log('peer went away silently', jid);
  14350. delete this.sessions[sess.sid];
  14351. delete this.jid2session[jid];
  14352. $(document).trigger('callterminated.jingle',
  14353. [sess.sid, jid], 'gone');
  14354. }
  14355. }
  14356. },
  14357. terminateRemoteByJid: function (jid, reason) {
  14358. if (this.jid2session.hasOwnProperty(jid)) {
  14359. var sess = this.jid2session[jid];
  14360. if (sess) {
  14361. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  14362. sess.terminate();
  14363. console.log('terminate peer with jid', sess.sid, jid);
  14364. delete this.sessions[sess.sid];
  14365. delete this.jid2session[jid];
  14366. $(document).trigger('callterminated.jingle',
  14367. [sess.sid, jid, 'kicked']);
  14368. }
  14369. }
  14370. },
  14371. getStunAndTurnCredentials: function () {
  14372. // get stun and turn configuration from server via xep-0215
  14373. // uses time-limited credentials as described in
  14374. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  14375. //
  14376. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  14377. // for a prosody module which implements this
  14378. //
  14379. // currently, this doesn't work with updateIce and therefore credentials with a long
  14380. // validity have to be fetched before creating the peerconnection
  14381. // TODO: implement refresh via updateIce as described in
  14382. // https://code.google.com/p/webrtc/issues/detail?id=1650
  14383. var self = this;
  14384. this.connection.sendIQ(
  14385. $iq({type: 'get', to: this.connection.domain})
  14386. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  14387. function (res) {
  14388. var iceservers = [];
  14389. $(res).find('>services>service').each(function (idx, el) {
  14390. el = $(el);
  14391. var dict = {};
  14392. var type = el.attr('type');
  14393. switch (type) {
  14394. case 'stun':
  14395. dict.url = 'stun:' + el.attr('host');
  14396. if (el.attr('port')) {
  14397. dict.url += ':' + el.attr('port');
  14398. }
  14399. iceservers.push(dict);
  14400. break;
  14401. case 'turn':
  14402. case 'turns':
  14403. dict.url = type + ':';
  14404. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  14405. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  14406. dict.url += el.attr('username') + '@';
  14407. } else {
  14408. dict.username = el.attr('username'); // only works in M28
  14409. }
  14410. }
  14411. dict.url += el.attr('host');
  14412. if (el.attr('port') && el.attr('port') != '3478') {
  14413. dict.url += ':' + el.attr('port');
  14414. }
  14415. if (el.attr('transport') && el.attr('transport') != 'udp') {
  14416. dict.url += '?transport=' + el.attr('transport');
  14417. }
  14418. if (el.attr('password')) {
  14419. dict.credential = el.attr('password');
  14420. }
  14421. iceservers.push(dict);
  14422. break;
  14423. }
  14424. });
  14425. self.ice_config.iceServers = iceservers;
  14426. },
  14427. function (err) {
  14428. console.warn('getting turn credentials failed', err);
  14429. console.warn('is mod_turncredentials or similar installed?');
  14430. }
  14431. );
  14432. // implement push?
  14433. },
  14434. /**
  14435. * Populates the log data
  14436. */
  14437. populateData: function () {
  14438. var data = {};
  14439. Object.keys(this.sessions).forEach(function (sid) {
  14440. var session = this.sessions[sid];
  14441. if (session.peerconnection && session.peerconnection.updateLog) {
  14442. // FIXME: should probably be a .dump call
  14443. data["jingle_" + session.sid] = {
  14444. updateLog: session.peerconnection.updateLog,
  14445. stats: session.peerconnection.stats,
  14446. url: window.location.href
  14447. };
  14448. }
  14449. });
  14450. return data;
  14451. }
  14452. });
  14453. };
  14454. },{"../../service/xmpp/XMPPEvents":89,"./JingleSession":48}],57:[function(require,module,exports){
  14455. /* global Strophe */
  14456. module.exports = function () {
  14457. Strophe.addConnectionPlugin('logger', {
  14458. // logs raw stanzas and makes them available for download as JSON
  14459. connection: null,
  14460. log: [],
  14461. init: function (conn) {
  14462. this.connection = conn;
  14463. this.connection.rawInput = this.log_incoming.bind(this);
  14464. this.connection.rawOutput = this.log_outgoing.bind(this);
  14465. },
  14466. log_incoming: function (stanza) {
  14467. this.log.push([new Date().getTime(), 'incoming', stanza]);
  14468. },
  14469. log_outgoing: function (stanza) {
  14470. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  14471. }
  14472. });
  14473. };
  14474. },{}],58:[function(require,module,exports){
  14475. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  14476. setAudioMuted, Strophe */
  14477. /**
  14478. * Moderate connection plugin.
  14479. */
  14480. module.exports = function (XMPP) {
  14481. Strophe.addConnectionPlugin('moderate', {
  14482. connection: null,
  14483. init: function (conn) {
  14484. this.connection = conn;
  14485. this.connection.addHandler(this.onMute.bind(this),
  14486. 'http://jitsi.org/jitmeet/audio',
  14487. 'iq',
  14488. 'set',
  14489. null,
  14490. null);
  14491. },
  14492. setMute: function (jid, mute) {
  14493. console.info("set mute", mute);
  14494. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  14495. .c('mute', {
  14496. xmlns: 'http://jitsi.org/jitmeet/audio',
  14497. jid: jid
  14498. })
  14499. .t(mute.toString())
  14500. .up();
  14501. this.connection.sendIQ(
  14502. iqToFocus,
  14503. function (result) {
  14504. console.log('set mute', result);
  14505. },
  14506. function (error) {
  14507. console.log('set mute error', error);
  14508. });
  14509. },
  14510. onMute: function (iq) {
  14511. var from = iq.getAttribute('from');
  14512. if (from !== this.connection.emuc.focusMucJid) {
  14513. console.warn("Ignored mute from non focus peer");
  14514. return false;
  14515. }
  14516. var mute = $(iq).find('mute');
  14517. if (mute.length) {
  14518. var doMuteAudio = mute.text() === "true";
  14519. APP.UI.setAudioMuted(doMuteAudio);
  14520. XMPP.forceMuted = doMuteAudio;
  14521. }
  14522. return true;
  14523. },
  14524. eject: function (jid) {
  14525. // We're not the focus, so can't terminate
  14526. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  14527. this.connection.emuc.kick(jid);
  14528. }
  14529. });
  14530. }
  14531. },{}],59:[function(require,module,exports){
  14532. /* jshint -W117 */
  14533. module.exports = function() {
  14534. Strophe.addConnectionPlugin('rayo',
  14535. {
  14536. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  14537. connection: null,
  14538. init: function (conn) {
  14539. this.connection = conn;
  14540. if (this.connection.disco) {
  14541. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  14542. }
  14543. this.connection.addHandler(
  14544. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  14545. },
  14546. onRayo: function (iq) {
  14547. console.info("Rayo IQ", iq);
  14548. },
  14549. dial: function (to, from, roomName, roomPass) {
  14550. var self = this;
  14551. var req = $iq(
  14552. {
  14553. type: 'set',
  14554. to: this.connection.emuc.focusMucJid
  14555. }
  14556. );
  14557. req.c('dial',
  14558. {
  14559. xmlns: this.RAYO_XMLNS,
  14560. to: to,
  14561. from: from
  14562. });
  14563. req.c('header',
  14564. {
  14565. name: 'JvbRoomName',
  14566. value: roomName
  14567. }).up();
  14568. if (roomPass !== null && roomPass.length) {
  14569. req.c('header',
  14570. {
  14571. name: 'JvbRoomPassword',
  14572. value: roomPass
  14573. }).up();
  14574. }
  14575. this.connection.sendIQ(
  14576. req,
  14577. function (result) {
  14578. console.info('Dial result ', result);
  14579. var resource = $(result).find('ref').attr('uri');
  14580. this.call_resource = resource.substr('xmpp:'.length);
  14581. console.info(
  14582. "Received call resource: " + this.call_resource);
  14583. },
  14584. function (error) {
  14585. console.info('Dial error ', error);
  14586. }
  14587. );
  14588. },
  14589. hang_up: function () {
  14590. if (!this.call_resource) {
  14591. console.warn("No call in progress");
  14592. return;
  14593. }
  14594. var self = this;
  14595. var req = $iq(
  14596. {
  14597. type: 'set',
  14598. to: this.call_resource
  14599. }
  14600. );
  14601. req.c('hangup',
  14602. {
  14603. xmlns: this.RAYO_XMLNS
  14604. });
  14605. this.connection.sendIQ(
  14606. req,
  14607. function (result) {
  14608. console.info('Hangup result ', result);
  14609. self.call_resource = null;
  14610. },
  14611. function (error) {
  14612. console.info('Hangup error ', error);
  14613. self.call_resource = null;
  14614. }
  14615. );
  14616. }
  14617. }
  14618. );
  14619. };
  14620. },{}],60:[function(require,module,exports){
  14621. /**
  14622. * Strophe logger implementation. Logs from level WARN and above.
  14623. */
  14624. module.exports = function () {
  14625. Strophe.log = function (level, msg) {
  14626. switch (level) {
  14627. case Strophe.LogLevel.WARN:
  14628. console.warn("Strophe: " + msg);
  14629. break;
  14630. case Strophe.LogLevel.ERROR:
  14631. case Strophe.LogLevel.FATAL:
  14632. console.error("Strophe: " + msg);
  14633. break;
  14634. }
  14635. };
  14636. Strophe.getStatusString = function (status) {
  14637. switch (status) {
  14638. case Strophe.Status.ERROR:
  14639. return "ERROR";
  14640. case Strophe.Status.CONNECTING:
  14641. return "CONNECTING";
  14642. case Strophe.Status.CONNFAIL:
  14643. return "CONNFAIL";
  14644. case Strophe.Status.AUTHENTICATING:
  14645. return "AUTHENTICATING";
  14646. case Strophe.Status.AUTHFAIL:
  14647. return "AUTHFAIL";
  14648. case Strophe.Status.CONNECTED:
  14649. return "CONNECTED";
  14650. case Strophe.Status.DISCONNECTED:
  14651. return "DISCONNECTED";
  14652. case Strophe.Status.DISCONNECTING:
  14653. return "DISCONNECTING";
  14654. case Strophe.Status.ATTACHED:
  14655. return "ATTACHED";
  14656. default:
  14657. return "unknown";
  14658. }
  14659. };
  14660. };
  14661. },{}],61:[function(require,module,exports){
  14662. var Moderator = require("./moderator");
  14663. var EventEmitter = require("events");
  14664. var Recording = require("./recording");
  14665. var SDP = require("./SDP");
  14666. var Pako = require("pako");
  14667. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  14668. var UIEvents = require("../../service/UI/UIEvents");
  14669. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14670. var eventEmitter = new EventEmitter();
  14671. var connection = null;
  14672. var authenticatedUser = false;
  14673. function connect(jid, password, uiCredentials) {
  14674. var bosh
  14675. = (uiCredentials && uiCredentials.bosh? uiCredentials.bosh : null)
  14676. || config.bosh || '/http-bind';
  14677. connection = new Strophe.Connection(bosh);
  14678. Moderator.setConnection(connection);
  14679. if(uiCredentials) {
  14680. var email = uiCredentials.email;
  14681. var displayName = uiCredentials.displayName;
  14682. if (email) {
  14683. connection.emuc.addEmailToPresence(email);
  14684. } else {
  14685. connection.emuc.addUserIdToPresence(uiCredentials.uid);
  14686. }
  14687. if (displayName) {
  14688. connection.emuc.addDisplayNameToPresence(displayName);
  14689. }
  14690. }
  14691. if (connection.disco) {
  14692. // for chrome, add multistream cap
  14693. }
  14694. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  14695. if (config.useIPv6) {
  14696. // https://code.google.com/p/webrtc/issues/detail?id=2828
  14697. if (!connection.jingle.pc_constraints.optional)
  14698. connection.jingle.pc_constraints.optional = [];
  14699. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  14700. }
  14701. if(!password)
  14702. password = uiCredentials.password;
  14703. var anonymousConnectionFailed = false;
  14704. connection.connect(jid, password, function (status, msg) {
  14705. console.log('Strophe status changed to',
  14706. Strophe.getStatusString(status));
  14707. if (status === Strophe.Status.CONNECTED) {
  14708. if (config.useStunTurn) {
  14709. connection.jingle.getStunAndTurnCredentials();
  14710. }
  14711. APP.UI.disableConnect();
  14712. console.info("My Jabber ID: " + connection.jid);
  14713. if(password)
  14714. authenticatedUser = true;
  14715. maybeDoJoin();
  14716. } else if (status === Strophe.Status.CONNFAIL) {
  14717. if(msg === 'x-strophe-bad-non-anon-jid') {
  14718. anonymousConnectionFailed = true;
  14719. }
  14720. } else if (status === Strophe.Status.DISCONNECTED) {
  14721. if(anonymousConnectionFailed) {
  14722. // prompt user for username and password
  14723. XMPP.promptLogin();
  14724. }
  14725. } else if (status === Strophe.Status.AUTHFAIL) {
  14726. // wrong password or username, prompt user
  14727. XMPP.promptLogin();
  14728. }
  14729. });
  14730. }
  14731. function maybeDoJoin() {
  14732. if (connection && connection.connected &&
  14733. Strophe.getResourceFromJid(connection.jid)
  14734. && (APP.RTC.localAudio || APP.RTC.localVideo)) {
  14735. // .connected is true while connecting?
  14736. doJoin();
  14737. }
  14738. }
  14739. function doJoin() {
  14740. var roomName = APP.UI.generateRoomName();
  14741. Moderator.allocateConferenceFocus(
  14742. roomName, APP.UI.checkForNicknameAndJoin);
  14743. }
  14744. function initStrophePlugins()
  14745. {
  14746. require("./strophe.emuc")(XMPP, eventEmitter);
  14747. require("./strophe.jingle")(XMPP, eventEmitter);
  14748. require("./strophe.moderate")(XMPP);
  14749. require("./strophe.util")();
  14750. require("./strophe.rayo")();
  14751. require("./strophe.logger")();
  14752. }
  14753. function registerListeners() {
  14754. APP.RTC.addStreamListener(maybeDoJoin,
  14755. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  14756. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  14757. XMPP.addToPresence("displayName", nickname);
  14758. });
  14759. }
  14760. function setupEvents() {
  14761. $(window).bind('beforeunload', function () {
  14762. if (connection && connection.connected) {
  14763. // ensure signout
  14764. $.ajax({
  14765. type: 'POST',
  14766. url: config.bosh,
  14767. async: false,
  14768. cache: false,
  14769. contentType: 'application/xml',
  14770. data: "<body rid='" + (connection.rid || connection._proto.rid)
  14771. + "' xmlns='http://jabber.org/protocol/httpbind' sid='"
  14772. + (connection.sid || connection._proto.sid)
  14773. + "' type='terminate'>" +
  14774. "<presence xmlns='jabber:client' type='unavailable'/>" +
  14775. "</body>",
  14776. success: function (data) {
  14777. console.log('signed out');
  14778. console.log(data);
  14779. },
  14780. error: function (XMLHttpRequest, textStatus, errorThrown) {
  14781. console.log('signout error',
  14782. textStatus + ' (' + errorThrown + ')');
  14783. }
  14784. });
  14785. }
  14786. XMPP.disposeConference(true);
  14787. });
  14788. }
  14789. var XMPP = {
  14790. sessionTerminated: false,
  14791. /**
  14792. * Remembers if we were muted by the focus.
  14793. * @type {boolean}
  14794. */
  14795. forceMuted: false,
  14796. start: function (uiCredentials) {
  14797. setupEvents();
  14798. initStrophePlugins();
  14799. registerListeners();
  14800. Moderator.init(this, eventEmitter);
  14801. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  14802. // Force authenticated domain if room is appended with '?login=true'
  14803. if (config.hosts.anonymousdomain &&
  14804. window.location.search.indexOf("login=true") !== -1) {
  14805. configDomain = config.hosts.domain;
  14806. }
  14807. var jid = uiCredentials.jid || configDomain || window.location.hostname;
  14808. connect(jid, null, uiCredentials);
  14809. },
  14810. promptLogin: function () {
  14811. APP.UI.showLoginPopup(connect);
  14812. },
  14813. joinRoom: function(roomName, useNicks, nick)
  14814. {
  14815. var roomjid;
  14816. roomjid = roomName;
  14817. if (useNicks) {
  14818. if (nick) {
  14819. roomjid += '/' + nick;
  14820. } else {
  14821. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  14822. }
  14823. } else {
  14824. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  14825. if(!authenticatedUser)
  14826. tmpJid = tmpJid.substr(0, 8);
  14827. roomjid += '/' + tmpJid;
  14828. }
  14829. connection.emuc.doJoin(roomjid);
  14830. },
  14831. myJid: function () {
  14832. if(!connection)
  14833. return null;
  14834. return connection.emuc.myroomjid;
  14835. },
  14836. myResource: function () {
  14837. if(!connection || ! connection.emuc.myroomjid)
  14838. return null;
  14839. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  14840. },
  14841. disposeConference: function (onUnload) {
  14842. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  14843. var handler = connection.jingle.activecall;
  14844. if (handler && handler.peerconnection) {
  14845. // FIXME: probably removing streams is not required and close() should
  14846. // be enough
  14847. if (APP.RTC.localAudio) {
  14848. handler.peerconnection.removeStream(APP.RTC.localAudio.getOriginalStream(), onUnload);
  14849. }
  14850. if (APP.RTC.localVideo) {
  14851. handler.peerconnection.removeStream(APP.RTC.localVideo.getOriginalStream(), onUnload);
  14852. }
  14853. handler.peerconnection.close();
  14854. }
  14855. connection.jingle.activecall = null;
  14856. if(!onUnload)
  14857. {
  14858. this.sessionTerminated = true;
  14859. connection.emuc.doLeave();
  14860. }
  14861. },
  14862. addListener: function(type, listener)
  14863. {
  14864. eventEmitter.on(type, listener);
  14865. },
  14866. removeListener: function (type, listener) {
  14867. eventEmitter.removeListener(type, listener);
  14868. },
  14869. allocateConferenceFocus: function(roomName, callback) {
  14870. Moderator.allocateConferenceFocus(roomName, callback);
  14871. },
  14872. getLoginUrl: function (roomName, callback) {
  14873. Moderator.getLoginUrl(roomName, callback);
  14874. },
  14875. getPopupLoginUrl: function (roomName, callback) {
  14876. Moderator.getPopupLoginUrl(roomName, callback);
  14877. },
  14878. isModerator: function () {
  14879. return Moderator.isModerator();
  14880. },
  14881. isSipGatewayEnabled: function () {
  14882. return Moderator.isSipGatewayEnabled();
  14883. },
  14884. isExternalAuthEnabled: function () {
  14885. return Moderator.isExternalAuthEnabled();
  14886. },
  14887. switchStreams: function (stream, oldStream, callback) {
  14888. if (connection && connection.jingle.activecall) {
  14889. // FIXME: will block switchInProgress on true value in case of exception
  14890. connection.jingle.activecall.switchStreams(stream, oldStream, callback);
  14891. } else {
  14892. // We are done immediately
  14893. console.error("No conference handler");
  14894. APP.UI.messageHandler.showError("dialog.error", 'Error',
  14895. "dialog.unableToSwitch", 'Unable to switch video stream.');
  14896. callback();
  14897. }
  14898. },
  14899. setVideoMute: function (mute, callback, options) {
  14900. if(connection && APP.RTC.localVideo && connection.jingle.activecall)
  14901. {
  14902. connection.jingle.activecall.setVideoMute(mute, callback, options);
  14903. }
  14904. },
  14905. setAudioMute: function (mute, callback) {
  14906. if (!(connection && APP.RTC.localAudio)) {
  14907. return false;
  14908. }
  14909. if (this.forceMuted && !mute) {
  14910. console.info("Asking focus for unmute");
  14911. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  14912. // FIXME: wait for result before resetting muted status
  14913. this.forceMuted = false;
  14914. }
  14915. if (mute == APP.RTC.localAudio.isMuted()) {
  14916. // Nothing to do
  14917. return true;
  14918. }
  14919. // It is not clear what is the right way to handle multiple tracks.
  14920. // So at least make sure that they are all muted or all unmuted and
  14921. // that we send presence just once.
  14922. APP.RTC.localAudio.mute();
  14923. // isMuted is the opposite of audioEnabled
  14924. connection.emuc.addAudioInfoToPresence(mute);
  14925. connection.emuc.sendPresence();
  14926. callback();
  14927. return true;
  14928. },
  14929. // Really mute video, i.e. dont even send black frames
  14930. muteVideo: function (pc, unmute) {
  14931. // FIXME: this probably needs another of those lovely state safeguards...
  14932. // which checks for iceconn == connected and sigstate == stable
  14933. pc.setRemoteDescription(pc.remoteDescription,
  14934. function () {
  14935. pc.createAnswer(
  14936. function (answer) {
  14937. var sdp = new SDP(answer.sdp);
  14938. if (sdp.media.length > 1) {
  14939. if (unmute)
  14940. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  14941. else
  14942. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  14943. sdp.raw = sdp.session + sdp.media.join('');
  14944. answer.sdp = sdp.raw;
  14945. }
  14946. pc.setLocalDescription(answer,
  14947. function () {
  14948. console.log('mute SLD ok');
  14949. },
  14950. function (error) {
  14951. console.log('mute SLD error');
  14952. APP.UI.messageHandler.showError("dialog.error",
  14953. 'Error', "dialog.SLDFailure",
  14954. 'Oops! Something went wrong and we failed to ' +
  14955. 'mute! (SLD Failure)');
  14956. }
  14957. );
  14958. },
  14959. function (error) {
  14960. console.log(error);
  14961. APP.UI.messageHandler.showError();
  14962. }
  14963. );
  14964. },
  14965. function (error) {
  14966. console.log('muteVideo SRD error');
  14967. APP.UI.messageHandler.showError("dialog.error", 'Error',
  14968. "dialog.SRDFailure",
  14969. 'Oops! Something went wrong and we failed to stop video!' +
  14970. '(SRD Failure)');
  14971. }
  14972. );
  14973. },
  14974. toggleRecording: function (tokenEmptyCallback,
  14975. startingCallback, startedCallback) {
  14976. Recording.toggleRecording(tokenEmptyCallback,
  14977. startingCallback, startedCallback, connection);
  14978. },
  14979. addToPresence: function (name, value, dontSend) {
  14980. switch (name)
  14981. {
  14982. case "displayName":
  14983. connection.emuc.addDisplayNameToPresence(value);
  14984. break;
  14985. case "etherpad":
  14986. connection.emuc.addEtherpadToPresence(value);
  14987. break;
  14988. case "prezi":
  14989. connection.emuc.addPreziToPresence(value, 0);
  14990. break;
  14991. case "preziSlide":
  14992. connection.emuc.addCurrentSlideToPresence(value);
  14993. break;
  14994. case "connectionQuality":
  14995. connection.emuc.addConnectionInfoToPresence(value);
  14996. break;
  14997. case "email":
  14998. connection.emuc.addEmailToPresence(value);
  14999. default :
  15000. console.log("Unknown tag for presence.");
  15001. return;
  15002. }
  15003. if(!dontSend)
  15004. connection.emuc.sendPresence();
  15005. },
  15006. /**
  15007. * Sends 'data' as a log message to the focus. Returns true iff a message
  15008. * was sent.
  15009. * @param data
  15010. * @returns {boolean} true iff a message was sent.
  15011. */
  15012. sendLogs: function (data) {
  15013. if(!connection.emuc.focusMucJid)
  15014. return false;
  15015. var deflate = true;
  15016. var content = JSON.stringify(data);
  15017. if (deflate) {
  15018. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  15019. }
  15020. content = Base64.encode(content);
  15021. // XEP-0337-ish
  15022. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  15023. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  15024. id: 'PeerConnectionStats'});
  15025. message.c('message').t(content).up();
  15026. if (deflate) {
  15027. message.c('tag', {name: "deflated", value: "true"}).up();
  15028. }
  15029. message.up();
  15030. connection.send(message);
  15031. return true;
  15032. },
  15033. populateData: function () {
  15034. var data = {};
  15035. if (connection.jingle) {
  15036. data = connection.jingle.populateData();
  15037. }
  15038. return data;
  15039. },
  15040. getLogger: function () {
  15041. if(connection.logger)
  15042. return connection.logger.log;
  15043. return null;
  15044. },
  15045. getPrezi: function () {
  15046. return connection.emuc.getPrezi(this.myJid());
  15047. },
  15048. removePreziFromPresence: function () {
  15049. connection.emuc.removePreziFromPresence();
  15050. connection.emuc.sendPresence();
  15051. },
  15052. sendChatMessage: function (message, nickname) {
  15053. connection.emuc.sendMessage(message, nickname);
  15054. },
  15055. setSubject: function (topic) {
  15056. connection.emuc.setSubject(topic);
  15057. },
  15058. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  15059. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  15060. },
  15061. dial: function (to, from, roomName,roomPass) {
  15062. connection.rayo.dial(to, from, roomName,roomPass);
  15063. },
  15064. setMute: function (jid, mute) {
  15065. connection.moderate.setMute(jid, mute);
  15066. },
  15067. eject: function (jid) {
  15068. connection.moderate.eject(jid);
  15069. },
  15070. logout: function (callback) {
  15071. Moderator.logout(callback);
  15072. },
  15073. findJidFromResource: function (resource) {
  15074. return connection.emuc.findJidFromResource(resource);
  15075. },
  15076. getMembers: function () {
  15077. return connection.emuc.members;
  15078. },
  15079. getJidFromSSRC: function (ssrc) {
  15080. if(!connection)
  15081. return null;
  15082. return connection.emuc.ssrc2jid[ssrc];
  15083. },
  15084. getMUCJoined: function () {
  15085. return connection.emuc.joined;
  15086. },
  15087. getSessions: function () {
  15088. return connection.jingle.sessions;
  15089. }
  15090. };
  15091. module.exports = XMPP;
  15092. },{"../../service/RTC/StreamEventTypes":83,"../../service/UI/UIEvents":84,"../../service/xmpp/XMPPEvents":89,"./SDP":49,"./moderator":53,"./recording":54,"./strophe.emuc":55,"./strophe.jingle":56,"./strophe.logger":57,"./strophe.moderate":58,"./strophe.rayo":59,"./strophe.util":60,"events":1,"pako":63}],62:[function(require,module,exports){
  15093. // i18next, v1.7.7
  15094. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  15095. // Distributed under MIT license
  15096. // http://i18next.com
  15097. (function() {
  15098. // add indexOf to non ECMA-262 standard compliant browsers
  15099. if (!Array.prototype.indexOf) {
  15100. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  15101. "use strict";
  15102. if (this == null) {
  15103. throw new TypeError();
  15104. }
  15105. var t = Object(this);
  15106. var len = t.length >>> 0;
  15107. if (len === 0) {
  15108. return -1;
  15109. }
  15110. var n = 0;
  15111. if (arguments.length > 0) {
  15112. n = Number(arguments[1]);
  15113. if (n != n) { // shortcut for verifying if it's NaN
  15114. n = 0;
  15115. } else if (n != 0 && n != Infinity && n != -Infinity) {
  15116. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  15117. }
  15118. }
  15119. if (n >= len) {
  15120. return -1;
  15121. }
  15122. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  15123. for (; k < len; k++) {
  15124. if (k in t && t[k] === searchElement) {
  15125. return k;
  15126. }
  15127. }
  15128. return -1;
  15129. }
  15130. }
  15131. // add lastIndexOf to non ECMA-262 standard compliant browsers
  15132. if (!Array.prototype.lastIndexOf) {
  15133. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  15134. "use strict";
  15135. if (this == null) {
  15136. throw new TypeError();
  15137. }
  15138. var t = Object(this);
  15139. var len = t.length >>> 0;
  15140. if (len === 0) {
  15141. return -1;
  15142. }
  15143. var n = len;
  15144. if (arguments.length > 1) {
  15145. n = Number(arguments[1]);
  15146. if (n != n) {
  15147. n = 0;
  15148. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  15149. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  15150. }
  15151. }
  15152. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  15153. for (; k >= 0; k--) {
  15154. if (k in t && t[k] === searchElement) {
  15155. return k;
  15156. }
  15157. }
  15158. return -1;
  15159. };
  15160. }
  15161. // Add string trim for IE8.
  15162. if (typeof String.prototype.trim !== 'function') {
  15163. String.prototype.trim = function() {
  15164. return this.replace(/^\s+|\s+$/g, '');
  15165. }
  15166. }
  15167. var root = this
  15168. , $ = root.jQuery || root.Zepto
  15169. , i18n = {}
  15170. , resStore = {}
  15171. , currentLng
  15172. , replacementCounter = 0
  15173. , languages = []
  15174. , initialized = false
  15175. , sync = {};
  15176. // Export the i18next object for **CommonJS**.
  15177. // If we're not in CommonJS, add `i18n` to the
  15178. // global object or to jquery.
  15179. if (typeof module !== 'undefined' && module.exports) {
  15180. if (!$) {
  15181. try {
  15182. $ = require('jquery');
  15183. } catch(e) {
  15184. // just ignore
  15185. }
  15186. }
  15187. if ($) {
  15188. $.i18n = $.i18n || i18n;
  15189. }
  15190. module.exports = i18n;
  15191. } else {
  15192. if ($) {
  15193. $.i18n = $.i18n || i18n;
  15194. }
  15195. root.i18n = root.i18n || i18n;
  15196. }
  15197. sync = {
  15198. load: function(lngs, options, cb) {
  15199. if (options.useLocalStorage) {
  15200. sync._loadLocal(lngs, options, function(err, store) {
  15201. var missingLngs = [];
  15202. for (var i = 0, len = lngs.length; i < len; i++) {
  15203. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  15204. }
  15205. if (missingLngs.length > 0) {
  15206. sync._fetch(missingLngs, options, function(err, fetched) {
  15207. f.extend(store, fetched);
  15208. sync._storeLocal(fetched);
  15209. cb(null, store);
  15210. });
  15211. } else {
  15212. cb(null, store);
  15213. }
  15214. });
  15215. } else {
  15216. sync._fetch(lngs, options, function(err, store){
  15217. cb(null, store);
  15218. });
  15219. }
  15220. },
  15221. _loadLocal: function(lngs, options, cb) {
  15222. var store = {}
  15223. , nowMS = new Date().getTime();
  15224. if(window.localStorage) {
  15225. var todo = lngs.length;
  15226. f.each(lngs, function(key, lng) {
  15227. var local = window.localStorage.getItem('res_' + lng);
  15228. if (local) {
  15229. local = JSON.parse(local);
  15230. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  15231. store[lng] = local;
  15232. }
  15233. }
  15234. todo--; // wait for all done befor callback
  15235. if (todo === 0) cb(null, store);
  15236. });
  15237. }
  15238. },
  15239. _storeLocal: function(store) {
  15240. if(window.localStorage) {
  15241. for (var m in store) {
  15242. store[m].i18nStamp = new Date().getTime();
  15243. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  15244. }
  15245. }
  15246. return;
  15247. },
  15248. _fetch: function(lngs, options, cb) {
  15249. var ns = options.ns
  15250. , store = {};
  15251. if (!options.dynamicLoad) {
  15252. var todo = ns.namespaces.length * lngs.length
  15253. , errors;
  15254. // load each file individual
  15255. f.each(ns.namespaces, function(nsIndex, nsValue) {
  15256. f.each(lngs, function(lngIndex, lngValue) {
  15257. // Call this once our translation has returned.
  15258. var loadComplete = function(err, data) {
  15259. if (err) {
  15260. errors = errors || [];
  15261. errors.push(err);
  15262. }
  15263. store[lngValue] = store[lngValue] || {};
  15264. store[lngValue][nsValue] = data;
  15265. todo--; // wait for all done befor callback
  15266. if (todo === 0) cb(errors, store);
  15267. };
  15268. if(typeof options.customLoad == 'function'){
  15269. // Use the specified custom callback.
  15270. options.customLoad(lngValue, nsValue, options, loadComplete);
  15271. } else {
  15272. //~ // Use our inbuilt sync.
  15273. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  15274. }
  15275. });
  15276. });
  15277. } else {
  15278. // Call this once our translation has returned.
  15279. var loadComplete = function(err, data) {
  15280. cb(null, data);
  15281. };
  15282. if(typeof options.customLoad == 'function'){
  15283. // Use the specified custom callback.
  15284. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  15285. } else {
  15286. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  15287. // load all needed stuff once
  15288. f.ajax({
  15289. url: url,
  15290. success: function(data, status, xhr) {
  15291. f.log('loaded: ' + url);
  15292. loadComplete(null, data);
  15293. },
  15294. error : function(xhr, status, error) {
  15295. f.log('failed loading: ' + url);
  15296. loadComplete('failed loading resource.json error: ' + error);
  15297. },
  15298. dataType: "json",
  15299. async : options.getAsync
  15300. });
  15301. }
  15302. }
  15303. },
  15304. _fetchOne: function(lng, ns, options, done) {
  15305. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  15306. f.ajax({
  15307. url: url,
  15308. success: function(data, status, xhr) {
  15309. f.log('loaded: ' + url);
  15310. done(null, data);
  15311. },
  15312. error : function(xhr, status, error) {
  15313. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  15314. // file loaded but invalid json, stop waste time !
  15315. f.error('There is a typo in: ' + url);
  15316. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  15317. f.log('Does not exist: ' + url);
  15318. } else {
  15319. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  15320. f.log(theStatus + ' when loading ' + url);
  15321. }
  15322. done(error, {});
  15323. },
  15324. dataType: "json",
  15325. async : options.getAsync
  15326. });
  15327. },
  15328. postMissing: function(lng, ns, key, defaultValue, lngs) {
  15329. var payload = {};
  15330. payload[key] = defaultValue;
  15331. var urls = [];
  15332. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  15333. for (var i = 0; i < o.fallbackLng.length; i++) {
  15334. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  15335. }
  15336. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  15337. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  15338. } else if (o.sendMissingTo === 'all') {
  15339. for (var i = 0, l = lngs.length; i < l; i++) {
  15340. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  15341. }
  15342. }
  15343. for (var y = 0, len = urls.length; y < len; y++) {
  15344. var item = urls[y];
  15345. f.ajax({
  15346. url: item.url,
  15347. type: o.sendType,
  15348. data: payload,
  15349. success: function(data, status, xhr) {
  15350. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  15351. // add key to resStore
  15352. var keys = key.split('.');
  15353. var x = 0;
  15354. var value = resStore[item.lng][ns];
  15355. while (keys[x]) {
  15356. if (x === keys.length - 1) {
  15357. value = value[keys[x]] = defaultValue;
  15358. } else {
  15359. value = value[keys[x]] = value[keys[x]] || {};
  15360. }
  15361. x++;
  15362. }
  15363. },
  15364. error : function(xhr, status, error) {
  15365. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  15366. },
  15367. dataType: "json",
  15368. async : o.postAsync
  15369. });
  15370. }
  15371. },
  15372. reload: reload
  15373. };
  15374. // defaults
  15375. var o = {
  15376. lng: undefined,
  15377. load: 'all',
  15378. preload: [],
  15379. lowerCaseLng: false,
  15380. returnObjectTrees: false,
  15381. fallbackLng: ['dev'],
  15382. fallbackNS: [],
  15383. detectLngQS: 'setLng',
  15384. detectLngFromLocalStorage: false,
  15385. ns: 'translation',
  15386. fallbackOnNull: true,
  15387. fallbackOnEmpty: false,
  15388. fallbackToDefaultNS: false,
  15389. nsseparator: ':',
  15390. keyseparator: '.',
  15391. selectorAttr: 'data-i18n',
  15392. debug: false,
  15393. resGetPath: 'locales/__lng__/__ns__.json',
  15394. resPostPath: 'locales/add/__lng__/__ns__',
  15395. getAsync: true,
  15396. postAsync: true,
  15397. resStore: undefined,
  15398. useLocalStorage: false,
  15399. localStorageExpirationTime: 7*24*60*60*1000,
  15400. dynamicLoad: false,
  15401. sendMissing: false,
  15402. sendMissingTo: 'fallback', // current | all
  15403. sendType: 'POST',
  15404. interpolationPrefix: '__',
  15405. interpolationSuffix: '__',
  15406. defaultVariables: false,
  15407. reusePrefix: '$t(',
  15408. reuseSuffix: ')',
  15409. pluralSuffix: '_plural',
  15410. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  15411. contextNotFound: ['context_not_found', Math.random()].join(''),
  15412. escapeInterpolation: false,
  15413. indefiniteSuffix: '_indefinite',
  15414. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  15415. setJqueryExt: true,
  15416. defaultValueFromContent: true,
  15417. useDataAttrOptions: false,
  15418. cookieExpirationTime: undefined,
  15419. useCookie: true,
  15420. cookieName: 'i18next',
  15421. cookieDomain: undefined,
  15422. objectTreeKeyHandler: undefined,
  15423. postProcess: undefined,
  15424. parseMissingKey: undefined,
  15425. missingKeyHandler: sync.postMissing,
  15426. shortcutFunction: 'sprintf' // or: defaultValue
  15427. };
  15428. function _extend(target, source) {
  15429. if (!source || typeof source === 'function') {
  15430. return target;
  15431. }
  15432. for (var attr in source) { target[attr] = source[attr]; }
  15433. return target;
  15434. }
  15435. function _deepExtend(target, source) {
  15436. for (var prop in source)
  15437. if (prop in target)
  15438. _deepExtend(target[prop], source[prop]);
  15439. else
  15440. target[prop] = source[prop];
  15441. return target;
  15442. }
  15443. function _each(object, callback, args) {
  15444. var name, i = 0,
  15445. length = object.length,
  15446. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  15447. if (args) {
  15448. if (isObj) {
  15449. for (name in object) {
  15450. if (callback.apply(object[name], args) === false) {
  15451. break;
  15452. }
  15453. }
  15454. } else {
  15455. for ( ; i < length; ) {
  15456. if (callback.apply(object[i++], args) === false) {
  15457. break;
  15458. }
  15459. }
  15460. }
  15461. // A special, fast, case for the most common use of each
  15462. } else {
  15463. if (isObj) {
  15464. for (name in object) {
  15465. if (callback.call(object[name], name, object[name]) === false) {
  15466. break;
  15467. }
  15468. }
  15469. } else {
  15470. for ( ; i < length; ) {
  15471. if (callback.call(object[i], i, object[i++]) === false) {
  15472. break;
  15473. }
  15474. }
  15475. }
  15476. }
  15477. return object;
  15478. }
  15479. var _entityMap = {
  15480. "&": "&amp;",
  15481. "<": "&lt;",
  15482. ">": "&gt;",
  15483. '"': '&quot;',
  15484. "'": '&#39;',
  15485. "/": '&#x2F;'
  15486. };
  15487. function _escape(data) {
  15488. if (typeof data === 'string') {
  15489. return data.replace(/[&<>"'\/]/g, function (s) {
  15490. return _entityMap[s];
  15491. });
  15492. }else{
  15493. return data;
  15494. }
  15495. }
  15496. function _ajax(options) {
  15497. // v0.5.0 of https://github.com/goloroden/http.js
  15498. var getXhr = function (callback) {
  15499. // Use the native XHR object if the browser supports it.
  15500. if (window.XMLHttpRequest) {
  15501. return callback(null, new XMLHttpRequest());
  15502. } else if (window.ActiveXObject) {
  15503. // In Internet Explorer check for ActiveX versions of the XHR object.
  15504. try {
  15505. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  15506. } catch (e) {
  15507. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  15508. }
  15509. }
  15510. // If no XHR support was found, throw an error.
  15511. return callback(new Error());
  15512. };
  15513. var encodeUsingUrlEncoding = function (data) {
  15514. if(typeof data === 'string') {
  15515. return data;
  15516. }
  15517. var result = [];
  15518. for(var dataItem in data) {
  15519. if(data.hasOwnProperty(dataItem)) {
  15520. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  15521. }
  15522. }
  15523. return result.join('&');
  15524. };
  15525. var utf8 = function (text) {
  15526. text = text.replace(/\r\n/g, '\n');
  15527. var result = '';
  15528. for(var i = 0; i < text.length; i++) {
  15529. var c = text.charCodeAt(i);
  15530. if(c < 128) {
  15531. result += String.fromCharCode(c);
  15532. } else if((c > 127) && (c < 2048)) {
  15533. result += String.fromCharCode((c >> 6) | 192);
  15534. result += String.fromCharCode((c & 63) | 128);
  15535. } else {
  15536. result += String.fromCharCode((c >> 12) | 224);
  15537. result += String.fromCharCode(((c >> 6) & 63) | 128);
  15538. result += String.fromCharCode((c & 63) | 128);
  15539. }
  15540. }
  15541. return result;
  15542. };
  15543. var base64 = function (text) {
  15544. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  15545. text = utf8(text);
  15546. var result = '',
  15547. chr1, chr2, chr3,
  15548. enc1, enc2, enc3, enc4,
  15549. i = 0;
  15550. do {
  15551. chr1 = text.charCodeAt(i++);
  15552. chr2 = text.charCodeAt(i++);
  15553. chr3 = text.charCodeAt(i++);
  15554. enc1 = chr1 >> 2;
  15555. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  15556. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  15557. enc4 = chr3 & 63;
  15558. if(isNaN(chr2)) {
  15559. enc3 = enc4 = 64;
  15560. } else if(isNaN(chr3)) {
  15561. enc4 = 64;
  15562. }
  15563. result +=
  15564. keyStr.charAt(enc1) +
  15565. keyStr.charAt(enc2) +
  15566. keyStr.charAt(enc3) +
  15567. keyStr.charAt(enc4);
  15568. chr1 = chr2 = chr3 = '';
  15569. enc1 = enc2 = enc3 = enc4 = '';
  15570. } while(i < text.length);
  15571. return result;
  15572. };
  15573. var mergeHeaders = function () {
  15574. // Use the first header object as base.
  15575. var result = arguments[0];
  15576. // Iterate through the remaining header objects and add them.
  15577. for(var i = 1; i < arguments.length; i++) {
  15578. var currentHeaders = arguments[i];
  15579. for(var header in currentHeaders) {
  15580. if(currentHeaders.hasOwnProperty(header)) {
  15581. result[header] = currentHeaders[header];
  15582. }
  15583. }
  15584. }
  15585. // Return the merged headers.
  15586. return result;
  15587. };
  15588. var ajax = function (method, url, options, callback) {
  15589. // Adjust parameters.
  15590. if(typeof options === 'function') {
  15591. callback = options;
  15592. options = {};
  15593. }
  15594. // Set default parameter values.
  15595. options.cache = options.cache || false;
  15596. options.data = options.data || {};
  15597. options.headers = options.headers || {};
  15598. options.jsonp = options.jsonp || false;
  15599. options.async = options.async === undefined ? true : options.async;
  15600. // Merge the various header objects.
  15601. var headers = mergeHeaders({
  15602. 'accept': '*/*',
  15603. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  15604. }, ajax.headers, options.headers);
  15605. // Encode the data according to the content-type.
  15606. var payload;
  15607. if (headers['content-type'] === 'application/json') {
  15608. payload = JSON.stringify(options.data);
  15609. } else {
  15610. payload = encodeUsingUrlEncoding(options.data);
  15611. }
  15612. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  15613. // if neccessary.
  15614. if(method === 'GET') {
  15615. // Setup the query string.
  15616. var queryString = [];
  15617. if(payload) {
  15618. queryString.push(payload);
  15619. payload = null;
  15620. }
  15621. // Handle caching.
  15622. if(!options.cache) {
  15623. queryString.push('_=' + (new Date()).getTime());
  15624. }
  15625. // If neccessary prepare the query string for a JSONP call.
  15626. if(options.jsonp) {
  15627. queryString.push('callback=' + options.jsonp);
  15628. queryString.push('jsonp=' + options.jsonp);
  15629. }
  15630. // Merge the query string and attach it to the url.
  15631. queryString = queryString.join('&');
  15632. if (queryString.length > 1) {
  15633. if (url.indexOf('?') > -1) {
  15634. url += '&' + queryString;
  15635. } else {
  15636. url += '?' + queryString;
  15637. }
  15638. }
  15639. // Make a JSONP call if neccessary.
  15640. if(options.jsonp) {
  15641. var head = document.getElementsByTagName('head')[0];
  15642. var script = document.createElement('script');
  15643. script.type = 'text/javascript';
  15644. script.src = url;
  15645. head.appendChild(script);
  15646. return;
  15647. }
  15648. }
  15649. // Since we got here, it is no JSONP request, so make a normal XHR request.
  15650. getXhr(function (err, xhr) {
  15651. if(err) return callback(err);
  15652. // Open the request.
  15653. xhr.open(method, url, options.async);
  15654. // Set the request headers.
  15655. for(var header in headers) {
  15656. if(headers.hasOwnProperty(header)) {
  15657. xhr.setRequestHeader(header, headers[header]);
  15658. }
  15659. }
  15660. // Handle the request events.
  15661. xhr.onreadystatechange = function () {
  15662. if(xhr.readyState === 4) {
  15663. var data = xhr.responseText || '';
  15664. // If no callback is given, return.
  15665. if(!callback) {
  15666. return;
  15667. }
  15668. // Return an object that provides access to the data as text and JSON.
  15669. callback(xhr.status, {
  15670. text: function () {
  15671. return data;
  15672. },
  15673. json: function () {
  15674. try {
  15675. return JSON.parse(data)
  15676. } catch (e) {
  15677. f.error('Can not parse JSON. URL: ' + url);
  15678. return {};
  15679. }
  15680. }
  15681. });
  15682. }
  15683. };
  15684. // Actually send the XHR request.
  15685. xhr.send(payload);
  15686. });
  15687. };
  15688. // Define the external interface.
  15689. var http = {
  15690. authBasic: function (username, password) {
  15691. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  15692. },
  15693. connect: function (url, options, callback) {
  15694. return ajax('CONNECT', url, options, callback);
  15695. },
  15696. del: function (url, options, callback) {
  15697. return ajax('DELETE', url, options, callback);
  15698. },
  15699. get: function (url, options, callback) {
  15700. return ajax('GET', url, options, callback);
  15701. },
  15702. head: function (url, options, callback) {
  15703. return ajax('HEAD', url, options, callback);
  15704. },
  15705. headers: function (headers) {
  15706. ajax.headers = headers || {};
  15707. },
  15708. isAllowed: function (url, verb, callback) {
  15709. this.options(url, function (status, data) {
  15710. callback(data.text().indexOf(verb) !== -1);
  15711. });
  15712. },
  15713. options: function (url, options, callback) {
  15714. return ajax('OPTIONS', url, options, callback);
  15715. },
  15716. patch: function (url, options, callback) {
  15717. return ajax('PATCH', url, options, callback);
  15718. },
  15719. post: function (url, options, callback) {
  15720. return ajax('POST', url, options, callback);
  15721. },
  15722. put: function (url, options, callback) {
  15723. return ajax('PUT', url, options, callback);
  15724. },
  15725. trace: function (url, options, callback) {
  15726. return ajax('TRACE', url, options, callback);
  15727. }
  15728. };
  15729. var methode = options.type ? options.type.toLowerCase() : 'get';
  15730. http[methode](options.url, options, function (status, data) {
  15731. // file: protocol always gives status code 0, so check for data
  15732. if (status === 200 || (status === 0 && data.text())) {
  15733. options.success(data.json(), status, null);
  15734. } else {
  15735. options.error(data.text(), status, null);
  15736. }
  15737. });
  15738. }
  15739. var _cookie = {
  15740. create: function(name,value,minutes,domain) {
  15741. var expires;
  15742. if (minutes) {
  15743. var date = new Date();
  15744. date.setTime(date.getTime()+(minutes*60*1000));
  15745. expires = "; expires="+date.toGMTString();
  15746. }
  15747. else expires = "";
  15748. domain = (domain)? "domain="+domain+";" : "";
  15749. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  15750. },
  15751. read: function(name) {
  15752. var nameEQ = name + "=";
  15753. var ca = document.cookie.split(';');
  15754. for(var i=0;i < ca.length;i++) {
  15755. var c = ca[i];
  15756. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  15757. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  15758. }
  15759. return null;
  15760. },
  15761. remove: function(name) {
  15762. this.create(name,"",-1);
  15763. }
  15764. };
  15765. var cookie_noop = {
  15766. create: function(name,value,minutes,domain) {},
  15767. read: function(name) { return null; },
  15768. remove: function(name) {}
  15769. };
  15770. // move dependent functions to a container so that
  15771. // they can be overriden easier in no jquery environment (node.js)
  15772. var f = {
  15773. extend: $ ? $.extend : _extend,
  15774. deepExtend: _deepExtend,
  15775. each: $ ? $.each : _each,
  15776. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  15777. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  15778. detectLanguage: detectLanguage,
  15779. escape: _escape,
  15780. log: function(str) {
  15781. if (o.debug && typeof console !== "undefined") console.log(str);
  15782. },
  15783. error: function(str) {
  15784. if (typeof console !== "undefined") console.error(str);
  15785. },
  15786. getCountyIndexOfLng: function(lng) {
  15787. var lng_index = 0;
  15788. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  15789. return lng_index;
  15790. },
  15791. toLanguages: function(lng) {
  15792. var log = this.log;
  15793. function applyCase(l) {
  15794. var ret = l;
  15795. if (typeof l === 'string' && l.indexOf('-') > -1) {
  15796. var parts = l.split('-');
  15797. ret = o.lowerCaseLng ?
  15798. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  15799. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  15800. } else {
  15801. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  15802. }
  15803. return ret;
  15804. }
  15805. var languages = [];
  15806. var whitelist = o.lngWhitelist || false;
  15807. var addLanguage = function(language){
  15808. //reject langs not whitelisted
  15809. if(!whitelist || whitelist.indexOf(language) > -1){
  15810. languages.push(language);
  15811. }else{
  15812. log('rejecting non-whitelisted language: ' + language);
  15813. }
  15814. };
  15815. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  15816. var parts = lng.split('-');
  15817. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  15818. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  15819. } else {
  15820. addLanguage(applyCase(lng));
  15821. }
  15822. for (var i = 0; i < o.fallbackLng.length; i++) {
  15823. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  15824. }
  15825. return languages;
  15826. },
  15827. regexEscape: function(str) {
  15828. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  15829. },
  15830. regexReplacementEscape: function(strOrFn) {
  15831. if (typeof strOrFn === 'string') {
  15832. return strOrFn.replace(/\$/g, "$$$$");
  15833. } else {
  15834. return strOrFn;
  15835. }
  15836. },
  15837. localStorage: {
  15838. setItem: function(key, value) {
  15839. if (window.localStorage) {
  15840. try {
  15841. window.localStorage.setItem(key, value);
  15842. } catch (e) {
  15843. f.log('failed to set value for key "' + key + '" to localStorage.');
  15844. }
  15845. }
  15846. }
  15847. }
  15848. };
  15849. function init(options, cb) {
  15850. if (typeof options === 'function') {
  15851. cb = options;
  15852. options = {};
  15853. }
  15854. options = options || {};
  15855. // override defaults with passed in options
  15856. f.extend(o, options);
  15857. delete o.fixLng; /* passed in each time */
  15858. // override functions: .log(), .detectLanguage(), etc
  15859. if (o.functions) {
  15860. delete o.functions;
  15861. f.extend(f, options.functions);
  15862. }
  15863. // create namespace object if namespace is passed in as string
  15864. if (typeof o.ns == 'string') {
  15865. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  15866. }
  15867. // fallback namespaces
  15868. if (typeof o.fallbackNS == 'string') {
  15869. o.fallbackNS = [o.fallbackNS];
  15870. }
  15871. // fallback languages
  15872. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  15873. o.fallbackLng = [o.fallbackLng];
  15874. }
  15875. // escape prefix/suffix
  15876. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  15877. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  15878. if (!o.lng) o.lng = f.detectLanguage();
  15879. languages = f.toLanguages(o.lng);
  15880. currentLng = languages[0];
  15881. f.log('currentLng set to: ' + currentLng);
  15882. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  15883. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  15884. }
  15885. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  15886. f.localStorage.setItem('i18next_lng', currentLng);
  15887. }
  15888. var lngTranslate = translate;
  15889. if (options.fixLng) {
  15890. lngTranslate = function(key, options) {
  15891. options = options || {};
  15892. options.lng = options.lng || lngTranslate.lng;
  15893. return translate(key, options);
  15894. };
  15895. lngTranslate.lng = currentLng;
  15896. }
  15897. pluralExtensions.setCurrentLng(currentLng);
  15898. // add JQuery extensions
  15899. if ($ && o.setJqueryExt) addJqueryFunct();
  15900. // jQuery deferred
  15901. var deferred;
  15902. if ($ && $.Deferred) {
  15903. deferred = $.Deferred();
  15904. }
  15905. // return immidiatly if res are passed in
  15906. if (o.resStore) {
  15907. resStore = o.resStore;
  15908. initialized = true;
  15909. if (cb) cb(lngTranslate);
  15910. if (deferred) deferred.resolve(lngTranslate);
  15911. if (deferred) return deferred.promise();
  15912. return;
  15913. }
  15914. // languages to load
  15915. var lngsToLoad = f.toLanguages(o.lng);
  15916. if (typeof o.preload === 'string') o.preload = [o.preload];
  15917. for (var i = 0, l = o.preload.length; i < l; i++) {
  15918. var pres = f.toLanguages(o.preload[i]);
  15919. for (var y = 0, len = pres.length; y < len; y++) {
  15920. if (lngsToLoad.indexOf(pres[y]) < 0) {
  15921. lngsToLoad.push(pres[y]);
  15922. }
  15923. }
  15924. }
  15925. // else load them
  15926. i18n.sync.load(lngsToLoad, o, function(err, store) {
  15927. resStore = store;
  15928. initialized = true;
  15929. if (cb) cb(lngTranslate);
  15930. if (deferred) deferred.resolve(lngTranslate);
  15931. });
  15932. if (deferred) return deferred.promise();
  15933. }
  15934. function preload(lngs, cb) {
  15935. if (typeof lngs === 'string') lngs = [lngs];
  15936. for (var i = 0, l = lngs.length; i < l; i++) {
  15937. if (o.preload.indexOf(lngs[i]) < 0) {
  15938. o.preload.push(lngs[i]);
  15939. }
  15940. }
  15941. return init(cb);
  15942. }
  15943. function addResourceBundle(lng, ns, resources, deep) {
  15944. if (typeof ns !== 'string') {
  15945. resources = ns;
  15946. ns = o.ns.defaultNs;
  15947. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  15948. o.ns.namespaces.push(ns);
  15949. }
  15950. resStore[lng] = resStore[lng] || {};
  15951. resStore[lng][ns] = resStore[lng][ns] || {};
  15952. if (deep) {
  15953. f.deepExtend(resStore[lng][ns], resources);
  15954. } else {
  15955. f.extend(resStore[lng][ns], resources);
  15956. }
  15957. }
  15958. function hasResourceBundle(lng, ns) {
  15959. if (typeof ns !== 'string') {
  15960. ns = o.ns.defaultNs;
  15961. }
  15962. resStore[lng] = resStore[lng] || {};
  15963. var res = resStore[lng][ns] || {};
  15964. var hasValues = false;
  15965. for(var prop in res) {
  15966. if (res.hasOwnProperty(prop)) {
  15967. hasValues = true;
  15968. }
  15969. }
  15970. return hasValues;
  15971. }
  15972. function removeResourceBundle(lng, ns) {
  15973. if (typeof ns !== 'string') {
  15974. ns = o.ns.defaultNs;
  15975. }
  15976. resStore[lng] = resStore[lng] || {};
  15977. resStore[lng][ns] = {};
  15978. }
  15979. function addResource(lng, ns, key, value) {
  15980. if (typeof ns !== 'string') {
  15981. resource = ns;
  15982. ns = o.ns.defaultNs;
  15983. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  15984. o.ns.namespaces.push(ns);
  15985. }
  15986. resStore[lng] = resStore[lng] || {};
  15987. resStore[lng][ns] = resStore[lng][ns] || {};
  15988. var keys = key.split(o.keyseparator);
  15989. var x = 0;
  15990. var node = resStore[lng][ns];
  15991. var origRef = node;
  15992. while (keys[x]) {
  15993. if (x == keys.length - 1)
  15994. node[keys[x]] = value;
  15995. else {
  15996. if (node[keys[x]] == null)
  15997. node[keys[x]] = {};
  15998. node = node[keys[x]];
  15999. }
  16000. x++;
  16001. }
  16002. }
  16003. function addResources(lng, ns, resources) {
  16004. if (typeof ns !== 'string') {
  16005. resource = ns;
  16006. ns = o.ns.defaultNs;
  16007. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  16008. o.ns.namespaces.push(ns);
  16009. }
  16010. for (var m in resources) {
  16011. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  16012. }
  16013. }
  16014. function setDefaultNamespace(ns) {
  16015. o.ns.defaultNs = ns;
  16016. }
  16017. function loadNamespace(namespace, cb) {
  16018. loadNamespaces([namespace], cb);
  16019. }
  16020. function loadNamespaces(namespaces, cb) {
  16021. var opts = {
  16022. dynamicLoad: o.dynamicLoad,
  16023. resGetPath: o.resGetPath,
  16024. getAsync: o.getAsync,
  16025. customLoad: o.customLoad,
  16026. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  16027. };
  16028. // languages to load
  16029. var lngsToLoad = f.toLanguages(o.lng);
  16030. if (typeof o.preload === 'string') o.preload = [o.preload];
  16031. for (var i = 0, l = o.preload.length; i < l; i++) {
  16032. var pres = f.toLanguages(o.preload[i]);
  16033. for (var y = 0, len = pres.length; y < len; y++) {
  16034. if (lngsToLoad.indexOf(pres[y]) < 0) {
  16035. lngsToLoad.push(pres[y]);
  16036. }
  16037. }
  16038. }
  16039. // check if we have to load
  16040. var lngNeedLoad = [];
  16041. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  16042. var needLoad = false;
  16043. var resSet = resStore[lngsToLoad[a]];
  16044. if (resSet) {
  16045. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  16046. if (!resSet[namespaces[b]]) needLoad = true;
  16047. }
  16048. } else {
  16049. needLoad = true;
  16050. }
  16051. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  16052. }
  16053. if (lngNeedLoad.length) {
  16054. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  16055. var todo = namespaces.length * lngNeedLoad.length;
  16056. // load each file individual
  16057. f.each(namespaces, function(nsIndex, nsValue) {
  16058. // append namespace to namespace array
  16059. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  16060. o.ns.namespaces.push(nsValue);
  16061. }
  16062. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  16063. resStore[lngValue] = resStore[lngValue] || {};
  16064. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  16065. todo--; // wait for all done befor callback
  16066. if (todo === 0 && cb) {
  16067. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  16068. cb();
  16069. }
  16070. });
  16071. });
  16072. });
  16073. } else {
  16074. if (cb) cb();
  16075. }
  16076. }
  16077. function setLng(lng, options, cb) {
  16078. if (typeof options === 'function') {
  16079. cb = options;
  16080. options = {};
  16081. } else if (!options) {
  16082. options = {};
  16083. }
  16084. options.lng = lng;
  16085. return init(options, cb);
  16086. }
  16087. function lng() {
  16088. return currentLng;
  16089. }
  16090. function reload(cb) {
  16091. resStore = {};
  16092. setLng(currentLng, cb);
  16093. }
  16094. function addJqueryFunct() {
  16095. // $.t shortcut
  16096. $.t = $.t || translate;
  16097. function parse(ele, key, options) {
  16098. if (key.length === 0) return;
  16099. var attr = 'text';
  16100. if (key.indexOf('[') === 0) {
  16101. var parts = key.split(']');
  16102. key = parts[1];
  16103. attr = parts[0].substr(1, parts[0].length-1);
  16104. }
  16105. if (key.indexOf(';') === key.length-1) {
  16106. key = key.substr(0, key.length-2);
  16107. }
  16108. var optionsToUse;
  16109. if (attr === 'html') {
  16110. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  16111. ele.html($.t(key, optionsToUse));
  16112. } else if (attr === 'text') {
  16113. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  16114. ele.text($.t(key, optionsToUse));
  16115. } else if (attr === 'prepend') {
  16116. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  16117. ele.prepend($.t(key, optionsToUse));
  16118. } else if (attr === 'append') {
  16119. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  16120. ele.append($.t(key, optionsToUse));
  16121. } else if (attr.indexOf("data-") === 0) {
  16122. var dataAttr = attr.substr(("data-").length);
  16123. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  16124. var translated = $.t(key, optionsToUse);
  16125. //we change into the data cache
  16126. ele.data(dataAttr, translated);
  16127. //we change into the dom
  16128. ele.attr(attr, translated);
  16129. } else {
  16130. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  16131. ele.attr(attr, $.t(key, optionsToUse));
  16132. }
  16133. }
  16134. function localize(ele, options) {
  16135. var key = ele.attr(o.selectorAttr);
  16136. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  16137. if (!key) return;
  16138. var target = ele
  16139. , targetSelector = ele.data("i18n-target");
  16140. if (targetSelector) {
  16141. target = ele.find(targetSelector) || ele;
  16142. }
  16143. if (!options && o.useDataAttrOptions === true) {
  16144. options = ele.data("i18n-options");
  16145. }
  16146. options = options || {};
  16147. if (key.indexOf(';') >= 0) {
  16148. var keys = key.split(';');
  16149. $.each(keys, function(m, k) {
  16150. if (k !== '') parse(target, k, options);
  16151. });
  16152. } else {
  16153. parse(target, key, options);
  16154. }
  16155. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  16156. }
  16157. // fn
  16158. $.fn.i18n = function (options) {
  16159. return this.each(function() {
  16160. // localize element itself
  16161. localize($(this), options);
  16162. // localize childs
  16163. var elements = $(this).find('[' + o.selectorAttr + ']');
  16164. elements.each(function() {
  16165. localize($(this), options);
  16166. });
  16167. });
  16168. };
  16169. }
  16170. function applyReplacement(str, replacementHash, nestedKey, options) {
  16171. if (!str) return str;
  16172. options = options || replacementHash; // first call uses replacement hash combined with options
  16173. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  16174. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  16175. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  16176. , unEscapingSuffix = 'HTML'+suffix;
  16177. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  16178. f.each(hash, function(key, value) {
  16179. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  16180. if (typeof value === 'object' && value !== null) {
  16181. str = applyReplacement(str, value, nextKey, options);
  16182. } else {
  16183. if (options.escapeInterpolation || o.escapeInterpolation) {
  16184. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  16185. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  16186. } else {
  16187. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  16188. }
  16189. // str = options.escapeInterpolation;
  16190. }
  16191. });
  16192. return str;
  16193. }
  16194. // append it to functions
  16195. f.applyReplacement = applyReplacement;
  16196. function applyReuse(translated, options) {
  16197. var comma = ',';
  16198. var options_open = '{';
  16199. var options_close = '}';
  16200. var opts = f.extend({}, options);
  16201. delete opts.postProcess;
  16202. while (translated.indexOf(o.reusePrefix) != -1) {
  16203. replacementCounter++;
  16204. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  16205. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  16206. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  16207. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  16208. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  16209. if (index_of_end_of_closing <= index_of_opening) {
  16210. f.error('there is an missing closing in following translation value', translated);
  16211. return '';
  16212. }
  16213. if (token_without_symbols.indexOf(comma) != -1) {
  16214. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  16215. 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) {
  16216. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  16217. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  16218. try {
  16219. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  16220. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  16221. } catch (e) {
  16222. }
  16223. }
  16224. }
  16225. var translated_token = _translate(token_without_symbols, opts);
  16226. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  16227. }
  16228. return translated;
  16229. }
  16230. function hasContext(options) {
  16231. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  16232. }
  16233. function needsPlural(options, lng) {
  16234. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  16235. }
  16236. function needsIndefiniteArticle(options) {
  16237. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  16238. }
  16239. function exists(key, options) {
  16240. options = options || {};
  16241. var notFound = _getDefaultValue(key, options)
  16242. , found = _find(key, options);
  16243. return found !== undefined || found === notFound;
  16244. }
  16245. function translate(key, options) {
  16246. options = options || {};
  16247. if (!initialized) {
  16248. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  16249. return options.defaultValue || '';
  16250. };
  16251. replacementCounter = 0;
  16252. return _translate.apply(null, arguments);
  16253. }
  16254. function _getDefaultValue(key, options) {
  16255. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  16256. }
  16257. function _injectSprintfProcessor() {
  16258. var values = [];
  16259. // mh: build array from second argument onwards
  16260. for (var i = 1; i < arguments.length; i++) {
  16261. values.push(arguments[i]);
  16262. }
  16263. return {
  16264. postProcess: 'sprintf',
  16265. sprintf: values
  16266. };
  16267. }
  16268. function _translate(potentialKeys, options) {
  16269. if (options && typeof options !== 'object') {
  16270. if (o.shortcutFunction === 'sprintf') {
  16271. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  16272. options = _injectSprintfProcessor.apply(null, arguments);
  16273. } else if (o.shortcutFunction === 'defaultValue') {
  16274. options = {
  16275. defaultValue: options
  16276. }
  16277. }
  16278. } else {
  16279. options = options || {};
  16280. }
  16281. if (typeof o.defaultVariables === 'object') {
  16282. options = f.extend({}, o.defaultVariables, options);
  16283. }
  16284. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  16285. if (typeof potentialKeys === 'string') {
  16286. potentialKeys = [potentialKeys];
  16287. }
  16288. var key = potentialKeys[0];
  16289. if (potentialKeys.length > 1) {
  16290. for (var i = 0; i < potentialKeys.length; i++) {
  16291. key = potentialKeys[i];
  16292. if (exists(key, options)) {
  16293. break;
  16294. }
  16295. }
  16296. }
  16297. var notFound = _getDefaultValue(key, options)
  16298. , found = _find(key, options)
  16299. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  16300. , ns = options.ns || o.ns.defaultNs
  16301. , parts;
  16302. // split ns and key
  16303. if (key.indexOf(o.nsseparator) > -1) {
  16304. parts = key.split(o.nsseparator);
  16305. ns = parts[0];
  16306. key = parts[1];
  16307. }
  16308. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  16309. if (options.lng) {
  16310. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  16311. } else {
  16312. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  16313. }
  16314. }
  16315. var postProcessor = options.postProcess || o.postProcess;
  16316. if (found !== undefined && postProcessor) {
  16317. if (postProcessors[postProcessor]) {
  16318. found = postProcessors[postProcessor](found, key, options);
  16319. }
  16320. }
  16321. // process notFound if function exists
  16322. var splitNotFound = notFound;
  16323. if (notFound.indexOf(o.nsseparator) > -1) {
  16324. parts = notFound.split(o.nsseparator);
  16325. splitNotFound = parts[1];
  16326. }
  16327. if (splitNotFound === key && o.parseMissingKey) {
  16328. notFound = o.parseMissingKey(notFound);
  16329. }
  16330. if (found === undefined) {
  16331. notFound = applyReplacement(notFound, options);
  16332. notFound = applyReuse(notFound, options);
  16333. if (postProcessor && postProcessors[postProcessor]) {
  16334. var val = _getDefaultValue(key, options);
  16335. found = postProcessors[postProcessor](val, key, options);
  16336. }
  16337. }
  16338. return (found !== undefined) ? found : notFound;
  16339. }
  16340. function _find(key, options) {
  16341. options = options || {};
  16342. var optionWithoutCount, translated
  16343. , notFound = _getDefaultValue(key, options)
  16344. , lngs = languages;
  16345. if (!resStore) { return notFound; } // no resStore to translate from
  16346. // CI mode
  16347. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  16348. // passed in lng
  16349. if (options.lngs) lngs = options.lngs;
  16350. if (options.lng) {
  16351. lngs = f.toLanguages(options.lng, options.fallbackLng);
  16352. if (!resStore[lngs[0]]) {
  16353. var oldAsync = o.getAsync;
  16354. o.getAsync = false;
  16355. i18n.sync.load(lngs, o, function(err, store) {
  16356. f.extend(resStore, store);
  16357. o.getAsync = oldAsync;
  16358. });
  16359. }
  16360. }
  16361. var ns = options.ns || o.ns.defaultNs;
  16362. if (key.indexOf(o.nsseparator) > -1) {
  16363. var parts = key.split(o.nsseparator);
  16364. ns = parts[0];
  16365. key = parts[1];
  16366. }
  16367. if (hasContext(options)) {
  16368. optionWithoutCount = f.extend({}, options);
  16369. delete optionWithoutCount.context;
  16370. optionWithoutCount.defaultValue = o.contextNotFound;
  16371. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  16372. translated = translate(contextKey, optionWithoutCount);
  16373. if (translated != o.contextNotFound) {
  16374. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  16375. } // else continue translation with original/nonContext key
  16376. }
  16377. if (needsPlural(options, lngs[0])) {
  16378. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  16379. delete optionWithoutCount.count;
  16380. delete optionWithoutCount.lng;
  16381. optionWithoutCount.defaultValue = o.pluralNotFound;
  16382. var pluralKey;
  16383. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  16384. pluralKey = ns + o.nsseparator + key;
  16385. } else {
  16386. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  16387. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  16388. if (pluralExtension >= 0) {
  16389. pluralKey = pluralKey + '_' + pluralExtension;
  16390. } else if (pluralExtension === 1) {
  16391. pluralKey = ns + o.nsseparator + key; // singular
  16392. }
  16393. }
  16394. translated = translate(pluralKey, optionWithoutCount);
  16395. if (translated != o.pluralNotFound) {
  16396. return applyReplacement(translated, {
  16397. count: options.count,
  16398. interpolationPrefix: options.interpolationPrefix,
  16399. interpolationSuffix: options.interpolationSuffix
  16400. }); // apply replacement for count only
  16401. } else if (lngs.length > 1) {
  16402. // remove failed lng
  16403. var clone = lngs.slice();
  16404. clone.shift();
  16405. options = f.extend(options, { lngs: clone });
  16406. delete options.lng;
  16407. // retry with fallbacks
  16408. translated = translate(ns + o.nsseparator + key, options);
  16409. if (translated != o.pluralNotFound) return translated;
  16410. } else {
  16411. return translated;
  16412. }
  16413. }
  16414. if (needsIndefiniteArticle(options)) {
  16415. var optionsWithoutIndef = f.extend({}, options);
  16416. delete optionsWithoutIndef.indefinite_article;
  16417. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  16418. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  16419. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  16420. translated = translate(indefiniteKey, optionsWithoutIndef);
  16421. if (translated != o.indefiniteNotFound) {
  16422. return translated;
  16423. }
  16424. }
  16425. var found;
  16426. var keys = key.split(o.keyseparator);
  16427. for (var i = 0, len = lngs.length; i < len; i++ ) {
  16428. if (found !== undefined) break;
  16429. var l = lngs[i];
  16430. var x = 0;
  16431. var value = resStore[l] && resStore[l][ns];
  16432. while (keys[x]) {
  16433. value = value && value[keys[x]];
  16434. x++;
  16435. }
  16436. if (value !== undefined) {
  16437. var valueType = Object.prototype.toString.apply(value);
  16438. if (typeof value === 'string') {
  16439. value = applyReplacement(value, options);
  16440. value = applyReuse(value, options);
  16441. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  16442. value = value.join('\n');
  16443. value = applyReplacement(value, options);
  16444. value = applyReuse(value, options);
  16445. } else if (value === null && o.fallbackOnNull === true) {
  16446. value = undefined;
  16447. } else if (value !== null) {
  16448. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  16449. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  16450. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  16451. } else {
  16452. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  16453. 'returned an object instead of string.';
  16454. f.log(value);
  16455. }
  16456. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  16457. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  16458. f.each(value, function(m) {
  16459. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  16460. });
  16461. value = copy;
  16462. }
  16463. }
  16464. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  16465. value = undefined;
  16466. found = value;
  16467. }
  16468. }
  16469. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  16470. // set flag for fallback lookup - avoid recursion
  16471. options.isFallbackLookup = true;
  16472. if (o.fallbackNS.length) {
  16473. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  16474. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  16475. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  16476. /* compare value without namespace */
  16477. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  16478. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  16479. if (foundValue !== notFoundValue) break;
  16480. }
  16481. }
  16482. } else {
  16483. found = _find(key, options); // fallback to default NS
  16484. }
  16485. options.isFallbackLookup = false;
  16486. }
  16487. return found;
  16488. }
  16489. function detectLanguage() {
  16490. var detectedLng;
  16491. var whitelist = o.lngWhitelist || [];
  16492. var userLngChoices = [];
  16493. // get from qs
  16494. var qsParm = [];
  16495. if (typeof window !== 'undefined') {
  16496. (function() {
  16497. var query = window.location.search.substring(1);
  16498. var params = query.split('&');
  16499. for (var i=0; i<params.length; i++) {
  16500. var pos = params[i].indexOf('=');
  16501. if (pos > 0) {
  16502. var key = params[i].substring(0,pos);
  16503. if (key == o.detectLngQS) {
  16504. userLngChoices.push(params[i].substring(pos+1));
  16505. }
  16506. }
  16507. }
  16508. })();
  16509. }
  16510. // get from cookie
  16511. if (o.useCookie && typeof document !== 'undefined') {
  16512. var c = f.cookie.read(o.cookieName);
  16513. if (c) userLngChoices.push(c);
  16514. }
  16515. // get from localStorage
  16516. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  16517. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  16518. }
  16519. // get from navigator
  16520. if (typeof navigator !== 'undefined') {
  16521. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  16522. for (var i=0;i<navigator.languages.length;i++) {
  16523. userLngChoices.push(navigator.languages[i]);
  16524. }
  16525. }
  16526. if (navigator.userLanguage) {
  16527. userLngChoices.push(navigator.userLanguage);
  16528. }
  16529. if (navigator.language) {
  16530. userLngChoices.push(navigator.language);
  16531. }
  16532. }
  16533. (function() {
  16534. for (var i=0;i<userLngChoices.length;i++) {
  16535. var lng = userLngChoices[i];
  16536. if (lng.indexOf('-') > -1) {
  16537. var parts = lng.split('-');
  16538. lng = o.lowerCaseLng ?
  16539. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  16540. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  16541. }
  16542. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  16543. detectedLng = lng;
  16544. break;
  16545. }
  16546. }
  16547. })();
  16548. //fallback
  16549. if (!detectedLng){
  16550. detectedLng = o.fallbackLng[0];
  16551. }
  16552. return detectedLng;
  16553. }
  16554. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  16555. /* [code, name, numbers, pluralsType] */
  16556. var _rules = [
  16557. ["ach", "Acholi", [1,2], 1],
  16558. ["af", "Afrikaans",[1,2], 2],
  16559. ["ak", "Akan", [1,2], 1],
  16560. ["am", "Amharic", [1,2], 1],
  16561. ["an", "Aragonese",[1,2], 2],
  16562. ["ar", "Arabic", [0,1,2,3,11,100],5],
  16563. ["arn", "Mapudungun",[1,2], 1],
  16564. ["ast", "Asturian", [1,2], 2],
  16565. ["ay", "Aymará", [1], 3],
  16566. ["az", "Azerbaijani",[1,2],2],
  16567. ["be", "Belarusian",[1,2,5],4],
  16568. ["bg", "Bulgarian",[1,2], 2],
  16569. ["bn", "Bengali", [1,2], 2],
  16570. ["bo", "Tibetan", [1], 3],
  16571. ["br", "Breton", [1,2], 1],
  16572. ["bs", "Bosnian", [1,2,5],4],
  16573. ["ca", "Catalan", [1,2], 2],
  16574. ["cgg", "Chiga", [1], 3],
  16575. ["cs", "Czech", [1,2,5],6],
  16576. ["csb", "Kashubian",[1,2,5],7],
  16577. ["cy", "Welsh", [1,2,3,8],8],
  16578. ["da", "Danish", [1,2], 2],
  16579. ["de", "German", [1,2], 2],
  16580. ["dev", "Development Fallback", [1,2], 2],
  16581. ["dz", "Dzongkha", [1], 3],
  16582. ["el", "Greek", [1,2], 2],
  16583. ["en", "English", [1,2], 2],
  16584. ["eo", "Esperanto",[1,2], 2],
  16585. ["es", "Spanish", [1,2], 2],
  16586. ["es_ar","Argentinean Spanish", [1,2], 2],
  16587. ["et", "Estonian", [1,2], 2],
  16588. ["eu", "Basque", [1,2], 2],
  16589. ["fa", "Persian", [1], 3],
  16590. ["fi", "Finnish", [1,2], 2],
  16591. ["fil", "Filipino", [1,2], 1],
  16592. ["fo", "Faroese", [1,2], 2],
  16593. ["fr", "French", [1,2], 9],
  16594. ["fur", "Friulian", [1,2], 2],
  16595. ["fy", "Frisian", [1,2], 2],
  16596. ["ga", "Irish", [1,2,3,7,11],10],
  16597. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  16598. ["gl", "Galician", [1,2], 2],
  16599. ["gu", "Gujarati", [1,2], 2],
  16600. ["gun", "Gun", [1,2], 1],
  16601. ["ha", "Hausa", [1,2], 2],
  16602. ["he", "Hebrew", [1,2], 2],
  16603. ["hi", "Hindi", [1,2], 2],
  16604. ["hr", "Croatian", [1,2,5],4],
  16605. ["hu", "Hungarian",[1,2], 2],
  16606. ["hy", "Armenian", [1,2], 2],
  16607. ["ia", "Interlingua",[1,2],2],
  16608. ["id", "Indonesian",[1], 3],
  16609. ["is", "Icelandic",[1,2], 12],
  16610. ["it", "Italian", [1,2], 2],
  16611. ["ja", "Japanese", [1], 3],
  16612. ["jbo", "Lojban", [1], 3],
  16613. ["jv", "Javanese", [0,1], 13],
  16614. ["ka", "Georgian", [1], 3],
  16615. ["kk", "Kazakh", [1], 3],
  16616. ["km", "Khmer", [1], 3],
  16617. ["kn", "Kannada", [1,2], 2],
  16618. ["ko", "Korean", [1], 3],
  16619. ["ku", "Kurdish", [1,2], 2],
  16620. ["kw", "Cornish", [1,2,3,4],14],
  16621. ["ky", "Kyrgyz", [1], 3],
  16622. ["lb", "Letzeburgesch",[1,2],2],
  16623. ["ln", "Lingala", [1,2], 1],
  16624. ["lo", "Lao", [1], 3],
  16625. ["lt", "Lithuanian",[1,2,10],15],
  16626. ["lv", "Latvian", [1,2,0],16],
  16627. ["mai", "Maithili", [1,2], 2],
  16628. ["mfe", "Mauritian Creole",[1,2],1],
  16629. ["mg", "Malagasy", [1,2], 1],
  16630. ["mi", "Maori", [1,2], 1],
  16631. ["mk", "Macedonian",[1,2],17],
  16632. ["ml", "Malayalam",[1,2], 2],
  16633. ["mn", "Mongolian",[1,2], 2],
  16634. ["mnk", "Mandinka", [0,1,2],18],
  16635. ["mr", "Marathi", [1,2], 2],
  16636. ["ms", "Malay", [1], 3],
  16637. ["mt", "Maltese", [1,2,11,20],19],
  16638. ["nah", "Nahuatl", [1,2], 2],
  16639. ["nap", "Neapolitan",[1,2], 2],
  16640. ["nb", "Norwegian Bokmal",[1,2],2],
  16641. ["ne", "Nepali", [1,2], 2],
  16642. ["nl", "Dutch", [1,2], 2],
  16643. ["nn", "Norwegian Nynorsk",[1,2],2],
  16644. ["no", "Norwegian",[1,2], 2],
  16645. ["nso", "Northern Sotho",[1,2],2],
  16646. ["oc", "Occitan", [1,2], 1],
  16647. ["or", "Oriya", [2,1], 2],
  16648. ["pa", "Punjabi", [1,2], 2],
  16649. ["pap", "Papiamento",[1,2], 2],
  16650. ["pl", "Polish", [1,2,5],7],
  16651. ["pms", "Piemontese",[1,2], 2],
  16652. ["ps", "Pashto", [1,2], 2],
  16653. ["pt", "Portuguese",[1,2], 2],
  16654. ["pt_br","Brazilian Portuguese",[1,2], 2],
  16655. ["rm", "Romansh", [1,2], 2],
  16656. ["ro", "Romanian", [1,2,20],20],
  16657. ["ru", "Russian", [1,2,5],4],
  16658. ["sah", "Yakut", [1], 3],
  16659. ["sco", "Scots", [1,2], 2],
  16660. ["se", "Northern Sami",[1,2], 2],
  16661. ["si", "Sinhala", [1,2], 2],
  16662. ["sk", "Slovak", [1,2,5],6],
  16663. ["sl", "Slovenian",[5,1,2,3],21],
  16664. ["so", "Somali", [1,2], 2],
  16665. ["son", "Songhay", [1,2], 2],
  16666. ["sq", "Albanian", [1,2], 2],
  16667. ["sr", "Serbian", [1,2,5],4],
  16668. ["su", "Sundanese",[1], 3],
  16669. ["sv", "Swedish", [1,2], 2],
  16670. ["sw", "Swahili", [1,2], 2],
  16671. ["ta", "Tamil", [1,2], 2],
  16672. ["te", "Telugu", [1,2], 2],
  16673. ["tg", "Tajik", [1,2], 1],
  16674. ["th", "Thai", [1], 3],
  16675. ["ti", "Tigrinya", [1,2], 1],
  16676. ["tk", "Turkmen", [1,2], 2],
  16677. ["tr", "Turkish", [1,2], 1],
  16678. ["tt", "Tatar", [1], 3],
  16679. ["ug", "Uyghur", [1], 3],
  16680. ["uk", "Ukrainian",[1,2,5],4],
  16681. ["ur", "Urdu", [1,2], 2],
  16682. ["uz", "Uzbek", [1,2], 1],
  16683. ["vi", "Vietnamese",[1], 3],
  16684. ["wa", "Walloon", [1,2], 1],
  16685. ["wo", "Wolof", [1], 3],
  16686. ["yo", "Yoruba", [1,2], 2],
  16687. ["zh", "Chinese", [1], 3]
  16688. ];
  16689. var _rulesPluralsTypes = {
  16690. 1: function(n) {return Number(n > 1);},
  16691. 2: function(n) {return Number(n != 1);},
  16692. 3: function(n) {return 0;},
  16693. 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);},
  16694. 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);},
  16695. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  16696. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  16697. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  16698. 9: function(n) {return Number(n >= 2);},
  16699. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  16700. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  16701. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  16702. 13: function(n) {return Number(n !== 0);},
  16703. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  16704. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  16705. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  16706. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  16707. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  16708. 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);},
  16709. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  16710. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  16711. };
  16712. var pluralExtensions = {
  16713. rules: (function () {
  16714. var l, rules = {};
  16715. for (l=_rules.length; l-- ;) {
  16716. rules[_rules[l][0]] = {
  16717. name: _rules[l][1],
  16718. numbers: _rules[l][2],
  16719. plurals: _rulesPluralsTypes[_rules[l][3]]
  16720. }
  16721. }
  16722. return rules;
  16723. }()),
  16724. // you can add your own pluralExtensions
  16725. addRule: function(lng, obj) {
  16726. pluralExtensions.rules[lng] = obj;
  16727. },
  16728. setCurrentLng: function(lng) {
  16729. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  16730. var parts = lng.split('-');
  16731. pluralExtensions.currentRule = {
  16732. lng: lng,
  16733. rule: pluralExtensions.rules[parts[0]]
  16734. };
  16735. }
  16736. },
  16737. needsPlural: function(lng, count) {
  16738. var parts = lng.split('-');
  16739. var ext;
  16740. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  16741. ext = pluralExtensions.currentRule.rule;
  16742. } else {
  16743. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  16744. }
  16745. if (ext && ext.numbers.length <= 1) {
  16746. return false;
  16747. } else {
  16748. return this.get(lng, count) !== 1;
  16749. }
  16750. },
  16751. get: function(lng, count) {
  16752. var parts = lng.split('-');
  16753. function getResult(l, c) {
  16754. var ext;
  16755. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  16756. ext = pluralExtensions.currentRule.rule;
  16757. } else {
  16758. ext = pluralExtensions.rules[l];
  16759. }
  16760. if (ext) {
  16761. var i;
  16762. if (ext.noAbs) {
  16763. i = ext.plurals(c);
  16764. } else {
  16765. i = ext.plurals(Math.abs(c));
  16766. }
  16767. var number = ext.numbers[i];
  16768. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  16769. if (number === 2) {
  16770. number = -1; // regular plural
  16771. } else if (number === 1) {
  16772. number = 1; // singular
  16773. }
  16774. }//console.log(count + '-' + number);
  16775. return number;
  16776. } else {
  16777. return c === 1 ? '1' : '-1';
  16778. }
  16779. }
  16780. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  16781. }
  16782. };
  16783. var postProcessors = {};
  16784. var addPostProcessor = function(name, fc) {
  16785. postProcessors[name] = fc;
  16786. };
  16787. // sprintf support
  16788. var sprintf = (function() {
  16789. function get_type(variable) {
  16790. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  16791. }
  16792. function str_repeat(input, multiplier) {
  16793. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  16794. return output.join('');
  16795. }
  16796. var str_format = function() {
  16797. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  16798. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  16799. }
  16800. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  16801. };
  16802. str_format.format = function(parse_tree, argv) {
  16803. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  16804. for (i = 0; i < tree_length; i++) {
  16805. node_type = get_type(parse_tree[i]);
  16806. if (node_type === 'string') {
  16807. output.push(parse_tree[i]);
  16808. }
  16809. else if (node_type === 'array') {
  16810. match = parse_tree[i]; // convenience purposes only
  16811. if (match[2]) { // keyword argument
  16812. arg = argv[cursor];
  16813. for (k = 0; k < match[2].length; k++) {
  16814. if (!arg.hasOwnProperty(match[2][k])) {
  16815. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  16816. }
  16817. arg = arg[match[2][k]];
  16818. }
  16819. }
  16820. else if (match[1]) { // positional argument (explicit)
  16821. arg = argv[match[1]];
  16822. }
  16823. else { // positional argument (implicit)
  16824. arg = argv[cursor++];
  16825. }
  16826. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  16827. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  16828. }
  16829. switch (match[8]) {
  16830. case 'b': arg = arg.toString(2); break;
  16831. case 'c': arg = String.fromCharCode(arg); break;
  16832. case 'd': arg = parseInt(arg, 10); break;
  16833. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  16834. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  16835. case 'o': arg = arg.toString(8); break;
  16836. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  16837. case 'u': arg = Math.abs(arg); break;
  16838. case 'x': arg = arg.toString(16); break;
  16839. case 'X': arg = arg.toString(16).toUpperCase(); break;
  16840. }
  16841. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  16842. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  16843. pad_length = match[6] - String(arg).length;
  16844. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  16845. output.push(match[5] ? arg + pad : pad + arg);
  16846. }
  16847. }
  16848. return output.join('');
  16849. };
  16850. str_format.cache = {};
  16851. str_format.parse = function(fmt) {
  16852. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  16853. while (_fmt) {
  16854. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  16855. parse_tree.push(match[0]);
  16856. }
  16857. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  16858. parse_tree.push('%');
  16859. }
  16860. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  16861. if (match[2]) {
  16862. arg_names |= 1;
  16863. var field_list = [], replacement_field = match[2], field_match = [];
  16864. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  16865. field_list.push(field_match[1]);
  16866. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  16867. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  16868. field_list.push(field_match[1]);
  16869. }
  16870. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  16871. field_list.push(field_match[1]);
  16872. }
  16873. else {
  16874. throw('[sprintf] huh?');
  16875. }
  16876. }
  16877. }
  16878. else {
  16879. throw('[sprintf] huh?');
  16880. }
  16881. match[2] = field_list;
  16882. }
  16883. else {
  16884. arg_names |= 2;
  16885. }
  16886. if (arg_names === 3) {
  16887. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  16888. }
  16889. parse_tree.push(match);
  16890. }
  16891. else {
  16892. throw('[sprintf] huh?');
  16893. }
  16894. _fmt = _fmt.substring(match[0].length);
  16895. }
  16896. return parse_tree;
  16897. };
  16898. return str_format;
  16899. })();
  16900. var vsprintf = function(fmt, argv) {
  16901. argv.unshift(fmt);
  16902. return sprintf.apply(null, argv);
  16903. };
  16904. addPostProcessor("sprintf", function(val, key, opts) {
  16905. if (!opts.sprintf) return val;
  16906. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  16907. return vsprintf(val, opts.sprintf);
  16908. } else if (typeof opts.sprintf === 'object') {
  16909. return sprintf(val, opts.sprintf);
  16910. }
  16911. return val;
  16912. });
  16913. // public api interface
  16914. i18n.init = init;
  16915. i18n.setLng = setLng;
  16916. i18n.preload = preload;
  16917. i18n.addResourceBundle = addResourceBundle;
  16918. i18n.hasResourceBundle = hasResourceBundle;
  16919. i18n.addResource = addResource;
  16920. i18n.addResources = addResources;
  16921. i18n.removeResourceBundle = removeResourceBundle;
  16922. i18n.loadNamespace = loadNamespace;
  16923. i18n.loadNamespaces = loadNamespaces;
  16924. i18n.setDefaultNamespace = setDefaultNamespace;
  16925. i18n.t = translate;
  16926. i18n.translate = translate;
  16927. i18n.exists = exists;
  16928. i18n.detectLanguage = f.detectLanguage;
  16929. i18n.pluralExtensions = pluralExtensions;
  16930. i18n.sync = sync;
  16931. i18n.functions = f;
  16932. i18n.lng = lng;
  16933. i18n.addPostProcessor = addPostProcessor;
  16934. i18n.options = o;
  16935. })();
  16936. },{"jquery":"jquery"}],63:[function(require,module,exports){
  16937. // Top level file is just a mixin of submodules & constants
  16938. 'use strict';
  16939. var assign = require('./lib/utils/common').assign;
  16940. var deflate = require('./lib/deflate');
  16941. var inflate = require('./lib/inflate');
  16942. var constants = require('./lib/zlib/constants');
  16943. var pako = {};
  16944. assign(pako, deflate, inflate, constants);
  16945. module.exports = pako;
  16946. },{"./lib/deflate":64,"./lib/inflate":65,"./lib/utils/common":66,"./lib/zlib/constants":69}],64:[function(require,module,exports){
  16947. 'use strict';
  16948. var zlib_deflate = require('./zlib/deflate.js');
  16949. var utils = require('./utils/common');
  16950. var strings = require('./utils/strings');
  16951. var msg = require('./zlib/messages');
  16952. var zstream = require('./zlib/zstream');
  16953. /* Public constants ==========================================================*/
  16954. /* ===========================================================================*/
  16955. var Z_NO_FLUSH = 0;
  16956. var Z_FINISH = 4;
  16957. var Z_OK = 0;
  16958. var Z_STREAM_END = 1;
  16959. var Z_DEFAULT_COMPRESSION = -1;
  16960. var Z_DEFAULT_STRATEGY = 0;
  16961. var Z_DEFLATED = 8;
  16962. /* ===========================================================================*/
  16963. /**
  16964. * class Deflate
  16965. *
  16966. * Generic JS-style wrapper for zlib calls. If you don't need
  16967. * streaming behaviour - use more simple functions: [[deflate]],
  16968. * [[deflateRaw]] and [[gzip]].
  16969. **/
  16970. /* internal
  16971. * Deflate.chunks -> Array
  16972. *
  16973. * Chunks of output data, if [[Deflate#onData]] not overriden.
  16974. **/
  16975. /**
  16976. * Deflate.result -> Uint8Array|Array
  16977. *
  16978. * Compressed result, generated by default [[Deflate#onData]]
  16979. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  16980. * (call [[Deflate#push]] with `Z_FINISH` / `true` param).
  16981. **/
  16982. /**
  16983. * Deflate.err -> Number
  16984. *
  16985. * Error code after deflate finished. 0 (Z_OK) on success.
  16986. * You will not need it in real life, because deflate errors
  16987. * are possible only on wrong options or bad `onData` / `onEnd`
  16988. * custom handlers.
  16989. **/
  16990. /**
  16991. * Deflate.msg -> String
  16992. *
  16993. * Error message, if [[Deflate.err]] != 0
  16994. **/
  16995. /**
  16996. * new Deflate(options)
  16997. * - options (Object): zlib deflate options.
  16998. *
  16999. * Creates new deflator instance with specified params. Throws exception
  17000. * on bad params. Supported options:
  17001. *
  17002. * - `level`
  17003. * - `windowBits`
  17004. * - `memLevel`
  17005. * - `strategy`
  17006. *
  17007. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17008. * for more information on these.
  17009. *
  17010. * Additional options, for internal needs:
  17011. *
  17012. * - `chunkSize` - size of generated data chunks (16K by default)
  17013. * - `raw` (Boolean) - do raw deflate
  17014. * - `gzip` (Boolean) - create gzip wrapper
  17015. * - `to` (String) - if equal to 'string', then result will be "binary string"
  17016. * (each char code [0..255])
  17017. * - `header` (Object) - custom header for gzip
  17018. * - `text` (Boolean) - true if compressed data believed to be text
  17019. * - `time` (Number) - modification time, unix timestamp
  17020. * - `os` (Number) - operation system code
  17021. * - `extra` (Array) - array of bytes with extra data (max 65536)
  17022. * - `name` (String) - file name (binary string)
  17023. * - `comment` (String) - comment (binary string)
  17024. * - `hcrc` (Boolean) - true if header crc should be added
  17025. *
  17026. * ##### Example:
  17027. *
  17028. * ```javascript
  17029. * var pako = require('pako')
  17030. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  17031. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  17032. *
  17033. * var deflate = new pako.Deflate({ level: 3});
  17034. *
  17035. * deflate.push(chunk1, false);
  17036. * deflate.push(chunk2, true); // true -> last chunk
  17037. *
  17038. * if (deflate.err) { throw new Error(deflate.err); }
  17039. *
  17040. * console.log(deflate.result);
  17041. * ```
  17042. **/
  17043. var Deflate = function(options) {
  17044. this.options = utils.assign({
  17045. level: Z_DEFAULT_COMPRESSION,
  17046. method: Z_DEFLATED,
  17047. chunkSize: 16384,
  17048. windowBits: 15,
  17049. memLevel: 8,
  17050. strategy: Z_DEFAULT_STRATEGY,
  17051. to: ''
  17052. }, options || {});
  17053. var opt = this.options;
  17054. if (opt.raw && (opt.windowBits > 0)) {
  17055. opt.windowBits = -opt.windowBits;
  17056. }
  17057. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  17058. opt.windowBits += 16;
  17059. }
  17060. this.err = 0; // error code, if happens (0 = Z_OK)
  17061. this.msg = ''; // error message
  17062. this.ended = false; // used to avoid multiple onEnd() calls
  17063. this.chunks = []; // chunks of compressed data
  17064. this.strm = new zstream();
  17065. this.strm.avail_out = 0;
  17066. var status = zlib_deflate.deflateInit2(
  17067. this.strm,
  17068. opt.level,
  17069. opt.method,
  17070. opt.windowBits,
  17071. opt.memLevel,
  17072. opt.strategy
  17073. );
  17074. if (status !== Z_OK) {
  17075. throw new Error(msg[status]);
  17076. }
  17077. if (opt.header) {
  17078. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  17079. }
  17080. };
  17081. /**
  17082. * Deflate#push(data[, mode]) -> Boolean
  17083. * - data (Uint8Array|Array|String): input data. Strings will be converted to
  17084. * utf8 byte sequence.
  17085. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  17086. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  17087. *
  17088. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  17089. * new compressed chunks. Returns `true` on success. The last data block must have
  17090. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  17091. * [[Deflate#onEnd]].
  17092. *
  17093. * On fail call [[Deflate#onEnd]] with error code and return false.
  17094. *
  17095. * We strongly recommend to use `Uint8Array` on input for best speed (output
  17096. * array format is detected automatically). Also, don't skip last param and always
  17097. * use the same type in your code (boolean or number). That will improve JS speed.
  17098. *
  17099. * For regular `Array`-s make sure all elements are [0..255].
  17100. *
  17101. * ##### Example
  17102. *
  17103. * ```javascript
  17104. * push(chunk, false); // push one of data chunks
  17105. * ...
  17106. * push(chunk, true); // push last chunk
  17107. * ```
  17108. **/
  17109. Deflate.prototype.push = function(data, mode) {
  17110. var strm = this.strm;
  17111. var chunkSize = this.options.chunkSize;
  17112. var status, _mode;
  17113. if (this.ended) { return false; }
  17114. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  17115. // Convert data if needed
  17116. if (typeof data === 'string') {
  17117. // If we need to compress text, change encoding to utf8.
  17118. strm.input = strings.string2buf(data);
  17119. } else {
  17120. strm.input = data;
  17121. }
  17122. strm.next_in = 0;
  17123. strm.avail_in = strm.input.length;
  17124. do {
  17125. if (strm.avail_out === 0) {
  17126. strm.output = new utils.Buf8(chunkSize);
  17127. strm.next_out = 0;
  17128. strm.avail_out = chunkSize;
  17129. }
  17130. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  17131. if (status !== Z_STREAM_END && status !== Z_OK) {
  17132. this.onEnd(status);
  17133. this.ended = true;
  17134. return false;
  17135. }
  17136. if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) {
  17137. if (this.options.to === 'string') {
  17138. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  17139. } else {
  17140. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  17141. }
  17142. }
  17143. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  17144. // Finalize on the last chunk.
  17145. if (_mode === Z_FINISH) {
  17146. status = zlib_deflate.deflateEnd(this.strm);
  17147. this.onEnd(status);
  17148. this.ended = true;
  17149. return status === Z_OK;
  17150. }
  17151. return true;
  17152. };
  17153. /**
  17154. * Deflate#onData(chunk) -> Void
  17155. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  17156. * on js engine support. When string output requested, each chunk
  17157. * will be string.
  17158. *
  17159. * By default, stores data blocks in `chunks[]` property and glue
  17160. * those in `onEnd`. Override this handler, if you need another behaviour.
  17161. **/
  17162. Deflate.prototype.onData = function(chunk) {
  17163. this.chunks.push(chunk);
  17164. };
  17165. /**
  17166. * Deflate#onEnd(status) -> Void
  17167. * - status (Number): deflate status. 0 (Z_OK) on success,
  17168. * other if not.
  17169. *
  17170. * Called once after you tell deflate that input stream complete
  17171. * or error happenned. By default - join collected chunks,
  17172. * free memory and fill `results` / `err` properties.
  17173. **/
  17174. Deflate.prototype.onEnd = function(status) {
  17175. // On success - join
  17176. if (status === Z_OK) {
  17177. if (this.options.to === 'string') {
  17178. this.result = this.chunks.join('');
  17179. } else {
  17180. this.result = utils.flattenChunks(this.chunks);
  17181. }
  17182. }
  17183. this.chunks = [];
  17184. this.err = status;
  17185. this.msg = this.strm.msg;
  17186. };
  17187. /**
  17188. * deflate(data[, options]) -> Uint8Array|Array|String
  17189. * - data (Uint8Array|Array|String): input data to compress.
  17190. * - options (Object): zlib deflate options.
  17191. *
  17192. * Compress `data` with deflate alrorythm and `options`.
  17193. *
  17194. * Supported options are:
  17195. *
  17196. * - level
  17197. * - windowBits
  17198. * - memLevel
  17199. * - strategy
  17200. *
  17201. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17202. * for more information on these.
  17203. *
  17204. * Sugar (options):
  17205. *
  17206. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  17207. * negative windowBits implicitly.
  17208. * - `to` (String) - if equal to 'string', then result will be "binary string"
  17209. * (each char code [0..255])
  17210. *
  17211. * ##### Example:
  17212. *
  17213. * ```javascript
  17214. * var pako = require('pako')
  17215. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  17216. *
  17217. * console.log(pako.deflate(data));
  17218. * ```
  17219. **/
  17220. function deflate(input, options) {
  17221. var deflator = new Deflate(options);
  17222. deflator.push(input, true);
  17223. // That will never happens, if you don't cheat with options :)
  17224. if (deflator.err) { throw deflator.msg; }
  17225. return deflator.result;
  17226. }
  17227. /**
  17228. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  17229. * - data (Uint8Array|Array|String): input data to compress.
  17230. * - options (Object): zlib deflate options.
  17231. *
  17232. * The same as [[deflate]], but creates raw data, without wrapper
  17233. * (header and adler32 crc).
  17234. **/
  17235. function deflateRaw(input, options) {
  17236. options = options || {};
  17237. options.raw = true;
  17238. return deflate(input, options);
  17239. }
  17240. /**
  17241. * gzip(data[, options]) -> Uint8Array|Array|String
  17242. * - data (Uint8Array|Array|String): input data to compress.
  17243. * - options (Object): zlib deflate options.
  17244. *
  17245. * The same as [[deflate]], but create gzip wrapper instead of
  17246. * deflate one.
  17247. **/
  17248. function gzip(input, options) {
  17249. options = options || {};
  17250. options.gzip = true;
  17251. return deflate(input, options);
  17252. }
  17253. exports.Deflate = Deflate;
  17254. exports.deflate = deflate;
  17255. exports.deflateRaw = deflateRaw;
  17256. exports.gzip = gzip;
  17257. },{"./utils/common":66,"./utils/strings":67,"./zlib/deflate.js":71,"./zlib/messages":76,"./zlib/zstream":78}],65:[function(require,module,exports){
  17258. 'use strict';
  17259. var zlib_inflate = require('./zlib/inflate.js');
  17260. var utils = require('./utils/common');
  17261. var strings = require('./utils/strings');
  17262. var c = require('./zlib/constants');
  17263. var msg = require('./zlib/messages');
  17264. var zstream = require('./zlib/zstream');
  17265. var gzheader = require('./zlib/gzheader');
  17266. /**
  17267. * class Inflate
  17268. *
  17269. * Generic JS-style wrapper for zlib calls. If you don't need
  17270. * streaming behaviour - use more simple functions: [[inflate]]
  17271. * and [[inflateRaw]].
  17272. **/
  17273. /* internal
  17274. * inflate.chunks -> Array
  17275. *
  17276. * Chunks of output data, if [[Inflate#onData]] not overriden.
  17277. **/
  17278. /**
  17279. * Inflate.result -> Uint8Array|Array|String
  17280. *
  17281. * Uncompressed result, generated by default [[Inflate#onData]]
  17282. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  17283. * (call [[Inflate#push]] with `Z_FINISH` / `true` param).
  17284. **/
  17285. /**
  17286. * Inflate.err -> Number
  17287. *
  17288. * Error code after inflate finished. 0 (Z_OK) on success.
  17289. * Should be checked if broken data possible.
  17290. **/
  17291. /**
  17292. * Inflate.msg -> String
  17293. *
  17294. * Error message, if [[Inflate.err]] != 0
  17295. **/
  17296. /**
  17297. * new Inflate(options)
  17298. * - options (Object): zlib inflate options.
  17299. *
  17300. * Creates new inflator instance with specified params. Throws exception
  17301. * on bad params. Supported options:
  17302. *
  17303. * - `windowBits`
  17304. *
  17305. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17306. * for more information on these.
  17307. *
  17308. * Additional options, for internal needs:
  17309. *
  17310. * - `chunkSize` - size of generated data chunks (16K by default)
  17311. * - `raw` (Boolean) - do raw inflate
  17312. * - `to` (String) - if equal to 'string', then result will be converted
  17313. * from utf8 to utf16 (javascript) string. When string output requested,
  17314. * chunk length can differ from `chunkSize`, depending on content.
  17315. *
  17316. * By default, when no options set, autodetect deflate/gzip data format via
  17317. * wrapper header.
  17318. *
  17319. * ##### Example:
  17320. *
  17321. * ```javascript
  17322. * var pako = require('pako')
  17323. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  17324. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  17325. *
  17326. * var inflate = new pako.Inflate({ level: 3});
  17327. *
  17328. * inflate.push(chunk1, false);
  17329. * inflate.push(chunk2, true); // true -> last chunk
  17330. *
  17331. * if (inflate.err) { throw new Error(inflate.err); }
  17332. *
  17333. * console.log(inflate.result);
  17334. * ```
  17335. **/
  17336. var Inflate = function(options) {
  17337. this.options = utils.assign({
  17338. chunkSize: 16384,
  17339. windowBits: 0,
  17340. to: ''
  17341. }, options || {});
  17342. var opt = this.options;
  17343. // Force window size for `raw` data, if not set directly,
  17344. // because we have no header for autodetect.
  17345. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  17346. opt.windowBits = -opt.windowBits;
  17347. if (opt.windowBits === 0) { opt.windowBits = -15; }
  17348. }
  17349. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  17350. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  17351. !(options && options.windowBits)) {
  17352. opt.windowBits += 32;
  17353. }
  17354. // Gzip header has no info about windows size, we can do autodetect only
  17355. // for deflate. So, if window size not set, force it to max when gzip possible
  17356. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  17357. // bit 3 (16) -> gzipped data
  17358. // bit 4 (32) -> autodetect gzip/deflate
  17359. if ((opt.windowBits & 15) === 0) {
  17360. opt.windowBits |= 15;
  17361. }
  17362. }
  17363. this.err = 0; // error code, if happens (0 = Z_OK)
  17364. this.msg = ''; // error message
  17365. this.ended = false; // used to avoid multiple onEnd() calls
  17366. this.chunks = []; // chunks of compressed data
  17367. this.strm = new zstream();
  17368. this.strm.avail_out = 0;
  17369. var status = zlib_inflate.inflateInit2(
  17370. this.strm,
  17371. opt.windowBits
  17372. );
  17373. if (status !== c.Z_OK) {
  17374. throw new Error(msg[status]);
  17375. }
  17376. this.header = new gzheader();
  17377. zlib_inflate.inflateGetHeader(this.strm, this.header);
  17378. };
  17379. /**
  17380. * Inflate#push(data[, mode]) -> Boolean
  17381. * - data (Uint8Array|Array|String): input data
  17382. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  17383. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  17384. *
  17385. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  17386. * new output chunks. Returns `true` on success. The last data block must have
  17387. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  17388. * [[Inflate#onEnd]].
  17389. *
  17390. * On fail call [[Inflate#onEnd]] with error code and return false.
  17391. *
  17392. * We strongly recommend to use `Uint8Array` on input for best speed (output
  17393. * format is detected automatically). Also, don't skip last param and always
  17394. * use the same type in your code (boolean or number). That will improve JS speed.
  17395. *
  17396. * For regular `Array`-s make sure all elements are [0..255].
  17397. *
  17398. * ##### Example
  17399. *
  17400. * ```javascript
  17401. * push(chunk, false); // push one of data chunks
  17402. * ...
  17403. * push(chunk, true); // push last chunk
  17404. * ```
  17405. **/
  17406. Inflate.prototype.push = function(data, mode) {
  17407. var strm = this.strm;
  17408. var chunkSize = this.options.chunkSize;
  17409. var status, _mode;
  17410. var next_out_utf8, tail, utf8str;
  17411. if (this.ended) { return false; }
  17412. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  17413. // Convert data if needed
  17414. if (typeof data === 'string') {
  17415. // Only binary strings can be decompressed on practice
  17416. strm.input = strings.binstring2buf(data);
  17417. } else {
  17418. strm.input = data;
  17419. }
  17420. strm.next_in = 0;
  17421. strm.avail_in = strm.input.length;
  17422. do {
  17423. if (strm.avail_out === 0) {
  17424. strm.output = new utils.Buf8(chunkSize);
  17425. strm.next_out = 0;
  17426. strm.avail_out = chunkSize;
  17427. }
  17428. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  17429. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  17430. this.onEnd(status);
  17431. this.ended = true;
  17432. return false;
  17433. }
  17434. if (strm.next_out) {
  17435. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) {
  17436. if (this.options.to === 'string') {
  17437. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  17438. tail = strm.next_out - next_out_utf8;
  17439. utf8str = strings.buf2string(strm.output, next_out_utf8);
  17440. // move tail
  17441. strm.next_out = tail;
  17442. strm.avail_out = chunkSize - tail;
  17443. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  17444. this.onData(utf8str);
  17445. } else {
  17446. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  17447. }
  17448. }
  17449. }
  17450. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  17451. if (status === c.Z_STREAM_END) {
  17452. _mode = c.Z_FINISH;
  17453. }
  17454. // Finalize on the last chunk.
  17455. if (_mode === c.Z_FINISH) {
  17456. status = zlib_inflate.inflateEnd(this.strm);
  17457. this.onEnd(status);
  17458. this.ended = true;
  17459. return status === c.Z_OK;
  17460. }
  17461. return true;
  17462. };
  17463. /**
  17464. * Inflate#onData(chunk) -> Void
  17465. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  17466. * on js engine support. When string output requested, each chunk
  17467. * will be string.
  17468. *
  17469. * By default, stores data blocks in `chunks[]` property and glue
  17470. * those in `onEnd`. Override this handler, if you need another behaviour.
  17471. **/
  17472. Inflate.prototype.onData = function(chunk) {
  17473. this.chunks.push(chunk);
  17474. };
  17475. /**
  17476. * Inflate#onEnd(status) -> Void
  17477. * - status (Number): inflate status. 0 (Z_OK) on success,
  17478. * other if not.
  17479. *
  17480. * Called once after you tell inflate that input stream complete
  17481. * or error happenned. By default - join collected chunks,
  17482. * free memory and fill `results` / `err` properties.
  17483. **/
  17484. Inflate.prototype.onEnd = function(status) {
  17485. // On success - join
  17486. if (status === c.Z_OK) {
  17487. if (this.options.to === 'string') {
  17488. // Glue & convert here, until we teach pako to send
  17489. // utf8 alligned strings to onData
  17490. this.result = this.chunks.join('');
  17491. } else {
  17492. this.result = utils.flattenChunks(this.chunks);
  17493. }
  17494. }
  17495. this.chunks = [];
  17496. this.err = status;
  17497. this.msg = this.strm.msg;
  17498. };
  17499. /**
  17500. * inflate(data[, options]) -> Uint8Array|Array|String
  17501. * - data (Uint8Array|Array|String): input data to decompress.
  17502. * - options (Object): zlib inflate options.
  17503. *
  17504. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  17505. * format via wrapper header by default. That's why we don't provide
  17506. * separate `ungzip` method.
  17507. *
  17508. * Supported options are:
  17509. *
  17510. * - windowBits
  17511. *
  17512. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17513. * for more information.
  17514. *
  17515. * Sugar (options):
  17516. *
  17517. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  17518. * negative windowBits implicitly.
  17519. * - `to` (String) - if equal to 'string', then result will be converted
  17520. * from utf8 to utf16 (javascript) string. When string output requested,
  17521. * chunk length can differ from `chunkSize`, depending on content.
  17522. *
  17523. *
  17524. * ##### Example:
  17525. *
  17526. * ```javascript
  17527. * var pako = require('pako')
  17528. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  17529. * , output;
  17530. *
  17531. * try {
  17532. * output = pako.inflate(input);
  17533. * } catch (err)
  17534. * console.log(err);
  17535. * }
  17536. * ```
  17537. **/
  17538. function inflate(input, options) {
  17539. var inflator = new Inflate(options);
  17540. inflator.push(input, true);
  17541. // That will never happens, if you don't cheat with options :)
  17542. if (inflator.err) { throw inflator.msg; }
  17543. return inflator.result;
  17544. }
  17545. /**
  17546. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  17547. * - data (Uint8Array|Array|String): input data to decompress.
  17548. * - options (Object): zlib inflate options.
  17549. *
  17550. * The same as [[inflate]], but creates raw data, without wrapper
  17551. * (header and adler32 crc).
  17552. **/
  17553. function inflateRaw(input, options) {
  17554. options = options || {};
  17555. options.raw = true;
  17556. return inflate(input, options);
  17557. }
  17558. /**
  17559. * ungzip(data[, options]) -> Uint8Array|Array|String
  17560. * - data (Uint8Array|Array|String): input data to decompress.
  17561. * - options (Object): zlib inflate options.
  17562. *
  17563. * Just shortcut to [[inflate]], because it autodetects format
  17564. * by header.content. Done for convenience.
  17565. **/
  17566. exports.Inflate = Inflate;
  17567. exports.inflate = inflate;
  17568. exports.inflateRaw = inflateRaw;
  17569. exports.ungzip = inflate;
  17570. },{"./utils/common":66,"./utils/strings":67,"./zlib/constants":69,"./zlib/gzheader":72,"./zlib/inflate.js":74,"./zlib/messages":76,"./zlib/zstream":78}],66:[function(require,module,exports){
  17571. 'use strict';
  17572. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  17573. (typeof Uint16Array !== 'undefined') &&
  17574. (typeof Int32Array !== 'undefined');
  17575. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  17576. var sources = Array.prototype.slice.call(arguments, 1);
  17577. while (sources.length) {
  17578. var source = sources.shift();
  17579. if (!source) { continue; }
  17580. if (typeof(source) !== 'object') {
  17581. throw new TypeError(source + 'must be non-object');
  17582. }
  17583. for (var p in source) {
  17584. if (source.hasOwnProperty(p)) {
  17585. obj[p] = source[p];
  17586. }
  17587. }
  17588. }
  17589. return obj;
  17590. };
  17591. // reduce buffer size, avoiding mem copy
  17592. exports.shrinkBuf = function (buf, size) {
  17593. if (buf.length === size) { return buf; }
  17594. if (buf.subarray) { return buf.subarray(0, size); }
  17595. buf.length = size;
  17596. return buf;
  17597. };
  17598. var fnTyped = {
  17599. arraySet: function (dest, src, src_offs, len, dest_offs) {
  17600. if (src.subarray && dest.subarray) {
  17601. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  17602. return;
  17603. }
  17604. // Fallback to ordinary array
  17605. for(var i=0; i<len; i++) {
  17606. dest[dest_offs + i] = src[src_offs + i];
  17607. }
  17608. },
  17609. // Join array of chunks to single array.
  17610. flattenChunks: function(chunks) {
  17611. var i, l, len, pos, chunk, result;
  17612. // calculate data length
  17613. len = 0;
  17614. for (i=0, l=chunks.length; i<l; i++) {
  17615. len += chunks[i].length;
  17616. }
  17617. // join chunks
  17618. result = new Uint8Array(len);
  17619. pos = 0;
  17620. for (i=0, l=chunks.length; i<l; i++) {
  17621. chunk = chunks[i];
  17622. result.set(chunk, pos);
  17623. pos += chunk.length;
  17624. }
  17625. return result;
  17626. }
  17627. };
  17628. var fnUntyped = {
  17629. arraySet: function (dest, src, src_offs, len, dest_offs) {
  17630. for(var i=0; i<len; i++) {
  17631. dest[dest_offs + i] = src[src_offs + i];
  17632. }
  17633. },
  17634. // Join array of chunks to single array.
  17635. flattenChunks: function(chunks) {
  17636. return [].concat.apply([], chunks);
  17637. }
  17638. };
  17639. // Enable/Disable typed arrays use, for testing
  17640. //
  17641. exports.setTyped = function (on) {
  17642. if (on) {
  17643. exports.Buf8 = Uint8Array;
  17644. exports.Buf16 = Uint16Array;
  17645. exports.Buf32 = Int32Array;
  17646. exports.assign(exports, fnTyped);
  17647. } else {
  17648. exports.Buf8 = Array;
  17649. exports.Buf16 = Array;
  17650. exports.Buf32 = Array;
  17651. exports.assign(exports, fnUntyped);
  17652. }
  17653. };
  17654. exports.setTyped(TYPED_OK);
  17655. },{}],67:[function(require,module,exports){
  17656. // String encode/decode helpers
  17657. 'use strict';
  17658. var utils = require('./common');
  17659. // Quick check if we can use fast array to bin string conversion
  17660. //
  17661. // - apply(Array) can fail on Android 2.2
  17662. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  17663. //
  17664. var STR_APPLY_OK = true;
  17665. var STR_APPLY_UIA_OK = true;
  17666. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  17667. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  17668. // Table with utf8 lengths (calculated by first byte of sequence)
  17669. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  17670. // because max possible codepoint is 0x10ffff
  17671. var _utf8len = new utils.Buf8(256);
  17672. for (var i=0; i<256; i++) {
  17673. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  17674. }
  17675. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  17676. // convert string to array (typed, when possible)
  17677. exports.string2buf = function (str) {
  17678. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  17679. // count binary size
  17680. for (m_pos = 0; m_pos < str_len; m_pos++) {
  17681. c = str.charCodeAt(m_pos);
  17682. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  17683. c2 = str.charCodeAt(m_pos+1);
  17684. if ((c2 & 0xfc00) === 0xdc00) {
  17685. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  17686. m_pos++;
  17687. }
  17688. }
  17689. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  17690. }
  17691. // allocate buffer
  17692. buf = new utils.Buf8(buf_len);
  17693. // convert
  17694. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  17695. c = str.charCodeAt(m_pos);
  17696. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  17697. c2 = str.charCodeAt(m_pos+1);
  17698. if ((c2 & 0xfc00) === 0xdc00) {
  17699. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  17700. m_pos++;
  17701. }
  17702. }
  17703. if (c < 0x80) {
  17704. /* one byte */
  17705. buf[i++] = c;
  17706. } else if (c < 0x800) {
  17707. /* two bytes */
  17708. buf[i++] = 0xC0 | (c >>> 6);
  17709. buf[i++] = 0x80 | (c & 0x3f);
  17710. } else if (c < 0x10000) {
  17711. /* three bytes */
  17712. buf[i++] = 0xE0 | (c >>> 12);
  17713. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  17714. buf[i++] = 0x80 | (c & 0x3f);
  17715. } else {
  17716. /* four bytes */
  17717. buf[i++] = 0xf0 | (c >>> 18);
  17718. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  17719. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  17720. buf[i++] = 0x80 | (c & 0x3f);
  17721. }
  17722. }
  17723. return buf;
  17724. };
  17725. // Helper (used in 2 places)
  17726. function buf2binstring(buf, len) {
  17727. // use fallback for big arrays to avoid stack overflow
  17728. if (len < 65537) {
  17729. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  17730. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  17731. }
  17732. }
  17733. var result = '';
  17734. for(var i=0; i < len; i++) {
  17735. result += String.fromCharCode(buf[i]);
  17736. }
  17737. return result;
  17738. }
  17739. // Convert byte array to binary string
  17740. exports.buf2binstring = function(buf) {
  17741. return buf2binstring(buf, buf.length);
  17742. };
  17743. // Convert binary string (typed, when possible)
  17744. exports.binstring2buf = function(str) {
  17745. var buf = new utils.Buf8(str.length);
  17746. for(var i=0, len=buf.length; i < len; i++) {
  17747. buf[i] = str.charCodeAt(i);
  17748. }
  17749. return buf;
  17750. };
  17751. // convert array to string
  17752. exports.buf2string = function (buf, max) {
  17753. var i, out, c, c_len;
  17754. var len = max || buf.length;
  17755. // Reserve max possible length (2 words per char)
  17756. // NB: by unknown reasons, Array is significantly faster for
  17757. // String.fromCharCode.apply than Uint16Array.
  17758. var utf16buf = new Array(len*2);
  17759. for (out=0, i=0; i<len;) {
  17760. c = buf[i++];
  17761. // quick process ascii
  17762. if (c < 0x80) { utf16buf[out++] = c; continue; }
  17763. c_len = _utf8len[c];
  17764. // skip 5 & 6 byte codes
  17765. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  17766. // apply mask on first byte
  17767. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  17768. // join the rest
  17769. while (c_len > 1 && i < len) {
  17770. c = (c << 6) | (buf[i++] & 0x3f);
  17771. c_len--;
  17772. }
  17773. // terminated by end of string?
  17774. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  17775. if (c < 0x10000) {
  17776. utf16buf[out++] = c;
  17777. } else {
  17778. c -= 0x10000;
  17779. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  17780. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  17781. }
  17782. }
  17783. return buf2binstring(utf16buf, out);
  17784. };
  17785. // Calculate max possible position in utf8 buffer,
  17786. // that will not break sequence. If that's not possible
  17787. // - (very small limits) return max size as is.
  17788. //
  17789. // buf[] - utf8 bytes array
  17790. // max - length limit (mandatory);
  17791. exports.utf8border = function(buf, max) {
  17792. var pos;
  17793. max = max || buf.length;
  17794. if (max > buf.length) { max = buf.length; }
  17795. // go back from last position, until start of sequence found
  17796. pos = max-1;
  17797. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  17798. // Fuckup - very small and broken sequence,
  17799. // return max, because we should return something anyway.
  17800. if (pos < 0) { return max; }
  17801. // If we came to start of buffer - that means vuffer is too small,
  17802. // return max too.
  17803. if (pos === 0) { return max; }
  17804. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  17805. };
  17806. },{"./common":66}],68:[function(require,module,exports){
  17807. 'use strict';
  17808. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  17809. // It doesn't worth to make additional optimizationa as in original.
  17810. // Small size is preferable.
  17811. function adler32(adler, buf, len, pos) {
  17812. var s1 = (adler & 0xffff) |0
  17813. , s2 = ((adler >>> 16) & 0xffff) |0
  17814. , n = 0;
  17815. while (len !== 0) {
  17816. // Set limit ~ twice less than 5552, to keep
  17817. // s2 in 31-bits, because we force signed ints.
  17818. // in other case %= will fail.
  17819. n = len > 2000 ? 2000 : len;
  17820. len -= n;
  17821. do {
  17822. s1 = (s1 + buf[pos++]) |0;
  17823. s2 = (s2 + s1) |0;
  17824. } while (--n);
  17825. s1 %= 65521;
  17826. s2 %= 65521;
  17827. }
  17828. return (s1 | (s2 << 16)) |0;
  17829. }
  17830. module.exports = adler32;
  17831. },{}],69:[function(require,module,exports){
  17832. module.exports = {
  17833. /* Allowed flush values; see deflate() and inflate() below for details */
  17834. Z_NO_FLUSH: 0,
  17835. Z_PARTIAL_FLUSH: 1,
  17836. Z_SYNC_FLUSH: 2,
  17837. Z_FULL_FLUSH: 3,
  17838. Z_FINISH: 4,
  17839. Z_BLOCK: 5,
  17840. Z_TREES: 6,
  17841. /* Return codes for the compression/decompression functions. Negative values
  17842. * are errors, positive values are used for special but normal events.
  17843. */
  17844. Z_OK: 0,
  17845. Z_STREAM_END: 1,
  17846. Z_NEED_DICT: 2,
  17847. Z_ERRNO: -1,
  17848. Z_STREAM_ERROR: -2,
  17849. Z_DATA_ERROR: -3,
  17850. //Z_MEM_ERROR: -4,
  17851. Z_BUF_ERROR: -5,
  17852. //Z_VERSION_ERROR: -6,
  17853. /* compression levels */
  17854. Z_NO_COMPRESSION: 0,
  17855. Z_BEST_SPEED: 1,
  17856. Z_BEST_COMPRESSION: 9,
  17857. Z_DEFAULT_COMPRESSION: -1,
  17858. Z_FILTERED: 1,
  17859. Z_HUFFMAN_ONLY: 2,
  17860. Z_RLE: 3,
  17861. Z_FIXED: 4,
  17862. Z_DEFAULT_STRATEGY: 0,
  17863. /* Possible values of the data_type field (though see inflate()) */
  17864. Z_BINARY: 0,
  17865. Z_TEXT: 1,
  17866. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  17867. Z_UNKNOWN: 2,
  17868. /* The deflate compression method */
  17869. Z_DEFLATED: 8
  17870. //Z_NULL: null // Use -1 or null inline, depending on var type
  17871. };
  17872. },{}],70:[function(require,module,exports){
  17873. 'use strict';
  17874. // Note: we can't get significant speed boost here.
  17875. // So write code to minimize size - no pregenerated tables
  17876. // and array tools dependencies.
  17877. // Use ordinary array, since untyped makes no boost here
  17878. function makeTable() {
  17879. var c, table = [];
  17880. for(var n =0; n < 256; n++){
  17881. c = n;
  17882. for(var k =0; k < 8; k++){
  17883. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  17884. }
  17885. table[n] = c;
  17886. }
  17887. return table;
  17888. }
  17889. // Create table on load. Just 255 signed longs. Not a problem.
  17890. var crcTable = makeTable();
  17891. function crc32(crc, buf, len, pos) {
  17892. var t = crcTable
  17893. , end = pos + len;
  17894. crc = crc ^ (-1);
  17895. for (var i = pos; i < end; i++ ) {
  17896. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  17897. }
  17898. return (crc ^ (-1)); // >>> 0;
  17899. }
  17900. module.exports = crc32;
  17901. },{}],71:[function(require,module,exports){
  17902. 'use strict';
  17903. var utils = require('../utils/common');
  17904. var trees = require('./trees');
  17905. var adler32 = require('./adler32');
  17906. var crc32 = require('./crc32');
  17907. var msg = require('./messages');
  17908. /* Public constants ==========================================================*/
  17909. /* ===========================================================================*/
  17910. /* Allowed flush values; see deflate() and inflate() below for details */
  17911. var Z_NO_FLUSH = 0;
  17912. var Z_PARTIAL_FLUSH = 1;
  17913. //var Z_SYNC_FLUSH = 2;
  17914. var Z_FULL_FLUSH = 3;
  17915. var Z_FINISH = 4;
  17916. var Z_BLOCK = 5;
  17917. //var Z_TREES = 6;
  17918. /* Return codes for the compression/decompression functions. Negative values
  17919. * are errors, positive values are used for special but normal events.
  17920. */
  17921. var Z_OK = 0;
  17922. var Z_STREAM_END = 1;
  17923. //var Z_NEED_DICT = 2;
  17924. //var Z_ERRNO = -1;
  17925. var Z_STREAM_ERROR = -2;
  17926. var Z_DATA_ERROR = -3;
  17927. //var Z_MEM_ERROR = -4;
  17928. var Z_BUF_ERROR = -5;
  17929. //var Z_VERSION_ERROR = -6;
  17930. /* compression levels */
  17931. //var Z_NO_COMPRESSION = 0;
  17932. //var Z_BEST_SPEED = 1;
  17933. //var Z_BEST_COMPRESSION = 9;
  17934. var Z_DEFAULT_COMPRESSION = -1;
  17935. var Z_FILTERED = 1;
  17936. var Z_HUFFMAN_ONLY = 2;
  17937. var Z_RLE = 3;
  17938. var Z_FIXED = 4;
  17939. var Z_DEFAULT_STRATEGY = 0;
  17940. /* Possible values of the data_type field (though see inflate()) */
  17941. //var Z_BINARY = 0;
  17942. //var Z_TEXT = 1;
  17943. //var Z_ASCII = 1; // = Z_TEXT
  17944. var Z_UNKNOWN = 2;
  17945. /* The deflate compression method */
  17946. var Z_DEFLATED = 8;
  17947. /*============================================================================*/
  17948. var MAX_MEM_LEVEL = 9;
  17949. /* Maximum value for memLevel in deflateInit2 */
  17950. var MAX_WBITS = 15;
  17951. /* 32K LZ77 window */
  17952. var DEF_MEM_LEVEL = 8;
  17953. var LENGTH_CODES = 29;
  17954. /* number of length codes, not counting the special END_BLOCK code */
  17955. var LITERALS = 256;
  17956. /* number of literal bytes 0..255 */
  17957. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  17958. /* number of Literal or Length codes, including the END_BLOCK code */
  17959. var D_CODES = 30;
  17960. /* number of distance codes */
  17961. var BL_CODES = 19;
  17962. /* number of codes used to transfer the bit lengths */
  17963. var HEAP_SIZE = 2*L_CODES + 1;
  17964. /* maximum heap size */
  17965. var MAX_BITS = 15;
  17966. /* All codes must not exceed MAX_BITS bits */
  17967. var MIN_MATCH = 3;
  17968. var MAX_MATCH = 258;
  17969. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  17970. var PRESET_DICT = 0x20;
  17971. var INIT_STATE = 42;
  17972. var EXTRA_STATE = 69;
  17973. var NAME_STATE = 73;
  17974. var COMMENT_STATE = 91;
  17975. var HCRC_STATE = 103;
  17976. var BUSY_STATE = 113;
  17977. var FINISH_STATE = 666;
  17978. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  17979. var BS_BLOCK_DONE = 2; /* block flush performed */
  17980. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  17981. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  17982. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  17983. function err(strm, errorCode) {
  17984. strm.msg = msg[errorCode];
  17985. return errorCode;
  17986. }
  17987. function rank(f) {
  17988. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  17989. }
  17990. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  17991. /* =========================================================================
  17992. * Flush as much pending output as possible. All deflate() output goes
  17993. * through this function so some applications may wish to modify it
  17994. * to avoid allocating a large strm->output buffer and copying into it.
  17995. * (See also read_buf()).
  17996. */
  17997. function flush_pending(strm) {
  17998. var s = strm.state;
  17999. //_tr_flush_bits(s);
  18000. var len = s.pending;
  18001. if (len > strm.avail_out) {
  18002. len = strm.avail_out;
  18003. }
  18004. if (len === 0) { return; }
  18005. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  18006. strm.next_out += len;
  18007. s.pending_out += len;
  18008. strm.total_out += len;
  18009. strm.avail_out -= len;
  18010. s.pending -= len;
  18011. if (s.pending === 0) {
  18012. s.pending_out = 0;
  18013. }
  18014. }
  18015. function flush_block_only (s, last) {
  18016. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  18017. s.block_start = s.strstart;
  18018. flush_pending(s.strm);
  18019. }
  18020. function put_byte(s, b) {
  18021. s.pending_buf[s.pending++] = b;
  18022. }
  18023. /* =========================================================================
  18024. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  18025. * IN assertion: the stream state is correct and there is enough room in
  18026. * pending_buf.
  18027. */
  18028. function putShortMSB(s, b) {
  18029. // put_byte(s, (Byte)(b >> 8));
  18030. // put_byte(s, (Byte)(b & 0xff));
  18031. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  18032. s.pending_buf[s.pending++] = b & 0xff;
  18033. }
  18034. /* ===========================================================================
  18035. * Read a new buffer from the current input stream, update the adler32
  18036. * and total number of bytes read. All deflate() input goes through
  18037. * this function so some applications may wish to modify it to avoid
  18038. * allocating a large strm->input buffer and copying from it.
  18039. * (See also flush_pending()).
  18040. */
  18041. function read_buf(strm, buf, start, size) {
  18042. var len = strm.avail_in;
  18043. if (len > size) { len = size; }
  18044. if (len === 0) { return 0; }
  18045. strm.avail_in -= len;
  18046. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  18047. if (strm.state.wrap === 1) {
  18048. strm.adler = adler32(strm.adler, buf, len, start);
  18049. }
  18050. else if (strm.state.wrap === 2) {
  18051. strm.adler = crc32(strm.adler, buf, len, start);
  18052. }
  18053. strm.next_in += len;
  18054. strm.total_in += len;
  18055. return len;
  18056. }
  18057. /* ===========================================================================
  18058. * Set match_start to the longest match starting at the given string and
  18059. * return its length. Matches shorter or equal to prev_length are discarded,
  18060. * in which case the result is equal to prev_length and match_start is
  18061. * garbage.
  18062. * IN assertions: cur_match is the head of the hash chain for the current
  18063. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  18064. * OUT assertion: the match length is not greater than s->lookahead.
  18065. */
  18066. function longest_match(s, cur_match) {
  18067. var chain_length = s.max_chain_length; /* max hash chain length */
  18068. var scan = s.strstart; /* current string */
  18069. var match; /* matched string */
  18070. var len; /* length of current match */
  18071. var best_len = s.prev_length; /* best match length so far */
  18072. var nice_match = s.nice_match; /* stop if match long enough */
  18073. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  18074. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  18075. var _win = s.window; // shortcut
  18076. var wmask = s.w_mask;
  18077. var prev = s.prev;
  18078. /* Stop when cur_match becomes <= limit. To simplify the code,
  18079. * we prevent matches with the string of window index 0.
  18080. */
  18081. var strend = s.strstart + MAX_MATCH;
  18082. var scan_end1 = _win[scan + best_len - 1];
  18083. var scan_end = _win[scan + best_len];
  18084. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  18085. * It is easy to get rid of this optimization if necessary.
  18086. */
  18087. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  18088. /* Do not waste too much time if we already have a good match: */
  18089. if (s.prev_length >= s.good_match) {
  18090. chain_length >>= 2;
  18091. }
  18092. /* Do not look for matches beyond the end of the input. This is necessary
  18093. * to make deflate deterministic.
  18094. */
  18095. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  18096. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  18097. do {
  18098. // Assert(cur_match < s->strstart, "no future");
  18099. match = cur_match;
  18100. /* Skip to next match if the match length cannot increase
  18101. * or if the match length is less than 2. Note that the checks below
  18102. * for insufficient lookahead only occur occasionally for performance
  18103. * reasons. Therefore uninitialized memory will be accessed, and
  18104. * conditional jumps will be made that depend on those values.
  18105. * However the length of the match is limited to the lookahead, so
  18106. * the output of deflate is not affected by the uninitialized values.
  18107. */
  18108. if (_win[match + best_len] !== scan_end ||
  18109. _win[match + best_len - 1] !== scan_end1 ||
  18110. _win[match] !== _win[scan] ||
  18111. _win[++match] !== _win[scan + 1]) {
  18112. continue;
  18113. }
  18114. /* The check at best_len-1 can be removed because it will be made
  18115. * again later. (This heuristic is not always a win.)
  18116. * It is not necessary to compare scan[2] and match[2] since they
  18117. * are always equal when the other bytes match, given that
  18118. * the hash keys are equal and that HASH_BITS >= 8.
  18119. */
  18120. scan += 2;
  18121. match++;
  18122. // Assert(*scan == *match, "match[2]?");
  18123. /* We check for insufficient lookahead only every 8th comparison;
  18124. * the 256th check will be made at strstart+258.
  18125. */
  18126. do {
  18127. /*jshint noempty:false*/
  18128. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18129. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18130. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18131. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18132. scan < strend);
  18133. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  18134. len = MAX_MATCH - (strend - scan);
  18135. scan = strend - MAX_MATCH;
  18136. if (len > best_len) {
  18137. s.match_start = cur_match;
  18138. best_len = len;
  18139. if (len >= nice_match) {
  18140. break;
  18141. }
  18142. scan_end1 = _win[scan + best_len - 1];
  18143. scan_end = _win[scan + best_len];
  18144. }
  18145. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  18146. if (best_len <= s.lookahead) {
  18147. return best_len;
  18148. }
  18149. return s.lookahead;
  18150. }
  18151. /* ===========================================================================
  18152. * Fill the window when the lookahead becomes insufficient.
  18153. * Updates strstart and lookahead.
  18154. *
  18155. * IN assertion: lookahead < MIN_LOOKAHEAD
  18156. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  18157. * At least one byte has been read, or avail_in == 0; reads are
  18158. * performed for at least two bytes (required for the zip translate_eol
  18159. * option -- not supported here).
  18160. */
  18161. function fill_window(s) {
  18162. var _w_size = s.w_size;
  18163. var p, n, m, more, str;
  18164. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  18165. do {
  18166. more = s.window_size - s.lookahead - s.strstart;
  18167. // JS ints have 32 bit, block below not needed
  18168. /* Deal with !@#$% 64K limit: */
  18169. //if (sizeof(int) <= 2) {
  18170. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  18171. // more = wsize;
  18172. //
  18173. // } else if (more == (unsigned)(-1)) {
  18174. // /* Very unlikely, but possible on 16 bit machine if
  18175. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  18176. // */
  18177. // more--;
  18178. // }
  18179. //}
  18180. /* If the window is almost full and there is insufficient lookahead,
  18181. * move the upper half to the lower one to make room in the upper half.
  18182. */
  18183. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  18184. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  18185. s.match_start -= _w_size;
  18186. s.strstart -= _w_size;
  18187. /* we now have strstart >= MAX_DIST */
  18188. s.block_start -= _w_size;
  18189. /* Slide the hash table (could be avoided with 32 bit values
  18190. at the expense of memory usage). We slide even when level == 0
  18191. to keep the hash table consistent if we switch back to level > 0
  18192. later. (Using level 0 permanently is not an optimal usage of
  18193. zlib, so we don't care about this pathological case.)
  18194. */
  18195. n = s.hash_size;
  18196. p = n;
  18197. do {
  18198. m = s.head[--p];
  18199. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  18200. } while (--n);
  18201. n = _w_size;
  18202. p = n;
  18203. do {
  18204. m = s.prev[--p];
  18205. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  18206. /* If n is not on any hash chain, prev[n] is garbage but
  18207. * its value will never be used.
  18208. */
  18209. } while (--n);
  18210. more += _w_size;
  18211. }
  18212. if (s.strm.avail_in === 0) {
  18213. break;
  18214. }
  18215. /* If there was no sliding:
  18216. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  18217. * more == window_size - lookahead - strstart
  18218. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  18219. * => more >= window_size - 2*WSIZE + 2
  18220. * In the BIG_MEM or MMAP case (not yet supported),
  18221. * window_size == input_size + MIN_LOOKAHEAD &&
  18222. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  18223. * Otherwise, window_size == 2*WSIZE so more >= 2.
  18224. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  18225. */
  18226. //Assert(more >= 2, "more < 2");
  18227. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  18228. s.lookahead += n;
  18229. /* Initialize the hash value now that we have some input: */
  18230. if (s.lookahead + s.insert >= MIN_MATCH) {
  18231. str = s.strstart - s.insert;
  18232. s.ins_h = s.window[str];
  18233. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  18234. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  18235. //#if MIN_MATCH != 3
  18236. // Call update_hash() MIN_MATCH-3 more times
  18237. //#endif
  18238. while (s.insert) {
  18239. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  18240. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  18241. s.prev[str & s.w_mask] = s.head[s.ins_h];
  18242. s.head[s.ins_h] = str;
  18243. str++;
  18244. s.insert--;
  18245. if (s.lookahead + s.insert < MIN_MATCH) {
  18246. break;
  18247. }
  18248. }
  18249. }
  18250. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  18251. * but this is not important since only literal bytes will be emitted.
  18252. */
  18253. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  18254. /* If the WIN_INIT bytes after the end of the current data have never been
  18255. * written, then zero those bytes in order to avoid memory check reports of
  18256. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  18257. * the longest match routines. Update the high water mark for the next
  18258. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  18259. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  18260. */
  18261. // if (s.high_water < s.window_size) {
  18262. // var curr = s.strstart + s.lookahead;
  18263. // var init = 0;
  18264. //
  18265. // if (s.high_water < curr) {
  18266. // /* Previous high water mark below current data -- zero WIN_INIT
  18267. // * bytes or up to end of window, whichever is less.
  18268. // */
  18269. // init = s.window_size - curr;
  18270. // if (init > WIN_INIT)
  18271. // init = WIN_INIT;
  18272. // zmemzero(s->window + curr, (unsigned)init);
  18273. // s->high_water = curr + init;
  18274. // }
  18275. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  18276. // /* High water mark at or above current data, but below current data
  18277. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  18278. // * to end of window, whichever is less.
  18279. // */
  18280. // init = (ulg)curr + WIN_INIT - s->high_water;
  18281. // if (init > s->window_size - s->high_water)
  18282. // init = s->window_size - s->high_water;
  18283. // zmemzero(s->window + s->high_water, (unsigned)init);
  18284. // s->high_water += init;
  18285. // }
  18286. // }
  18287. //
  18288. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  18289. // "not enough room for search");
  18290. }
  18291. /* ===========================================================================
  18292. * Copy without compression as much as possible from the input stream, return
  18293. * the current block state.
  18294. * This function does not insert new strings in the dictionary since
  18295. * uncompressible data is probably not useful. This function is used
  18296. * only for the level=0 compression option.
  18297. * NOTE: this function should be optimized to avoid extra copying from
  18298. * window to pending_buf.
  18299. */
  18300. function deflate_stored(s, flush) {
  18301. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  18302. * to pending_buf_size, and each stored block has a 5 byte header:
  18303. */
  18304. var max_block_size = 0xffff;
  18305. if (max_block_size > s.pending_buf_size - 5) {
  18306. max_block_size = s.pending_buf_size - 5;
  18307. }
  18308. /* Copy as much as possible from input to output: */
  18309. for (;;) {
  18310. /* Fill the window as much as possible: */
  18311. if (s.lookahead <= 1) {
  18312. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  18313. // s->block_start >= (long)s->w_size, "slide too late");
  18314. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  18315. // s.block_start >= s.w_size)) {
  18316. // throw new Error("slide too late");
  18317. // }
  18318. fill_window(s);
  18319. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  18320. return BS_NEED_MORE;
  18321. }
  18322. if (s.lookahead === 0) {
  18323. break;
  18324. }
  18325. /* flush the current block */
  18326. }
  18327. //Assert(s->block_start >= 0L, "block gone");
  18328. // if (s.block_start < 0) throw new Error("block gone");
  18329. s.strstart += s.lookahead;
  18330. s.lookahead = 0;
  18331. /* Emit a stored block if pending_buf will be full: */
  18332. var max_start = s.block_start + max_block_size;
  18333. if (s.strstart === 0 || s.strstart >= max_start) {
  18334. /* strstart == 0 is possible when wraparound on 16-bit machine */
  18335. s.lookahead = s.strstart - max_start;
  18336. s.strstart = max_start;
  18337. /*** FLUSH_BLOCK(s, 0); ***/
  18338. flush_block_only(s, false);
  18339. if (s.strm.avail_out === 0) {
  18340. return BS_NEED_MORE;
  18341. }
  18342. /***/
  18343. }
  18344. /* Flush if we may have to slide, otherwise block_start may become
  18345. * negative and the data will be gone:
  18346. */
  18347. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  18348. /*** FLUSH_BLOCK(s, 0); ***/
  18349. flush_block_only(s, false);
  18350. if (s.strm.avail_out === 0) {
  18351. return BS_NEED_MORE;
  18352. }
  18353. /***/
  18354. }
  18355. }
  18356. s.insert = 0;
  18357. if (flush === Z_FINISH) {
  18358. /*** FLUSH_BLOCK(s, 1); ***/
  18359. flush_block_only(s, true);
  18360. if (s.strm.avail_out === 0) {
  18361. return BS_FINISH_STARTED;
  18362. }
  18363. /***/
  18364. return BS_FINISH_DONE;
  18365. }
  18366. if (s.strstart > s.block_start) {
  18367. /*** FLUSH_BLOCK(s, 0); ***/
  18368. flush_block_only(s, false);
  18369. if (s.strm.avail_out === 0) {
  18370. return BS_NEED_MORE;
  18371. }
  18372. /***/
  18373. }
  18374. return BS_NEED_MORE;
  18375. }
  18376. /* ===========================================================================
  18377. * Compress as much as possible from the input stream, return the current
  18378. * block state.
  18379. * This function does not perform lazy evaluation of matches and inserts
  18380. * new strings in the dictionary only for unmatched strings or for short
  18381. * matches. It is used only for the fast compression options.
  18382. */
  18383. function deflate_fast(s, flush) {
  18384. var hash_head; /* head of the hash chain */
  18385. var bflush; /* set if current block must be flushed */
  18386. for (;;) {
  18387. /* Make sure that we always have enough lookahead, except
  18388. * at the end of the input file. We need MAX_MATCH bytes
  18389. * for the next match, plus MIN_MATCH bytes to insert the
  18390. * string following the next match.
  18391. */
  18392. if (s.lookahead < MIN_LOOKAHEAD) {
  18393. fill_window(s);
  18394. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  18395. return BS_NEED_MORE;
  18396. }
  18397. if (s.lookahead === 0) {
  18398. break; /* flush the current block */
  18399. }
  18400. }
  18401. /* Insert the string window[strstart .. strstart+2] in the
  18402. * dictionary, and set hash_head to the head of the hash chain:
  18403. */
  18404. hash_head = 0/*NIL*/;
  18405. if (s.lookahead >= MIN_MATCH) {
  18406. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18407. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18408. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18409. s.head[s.ins_h] = s.strstart;
  18410. /***/
  18411. }
  18412. /* Find the longest match, discarding those <= prev_length.
  18413. * At this point we have always match_length < MIN_MATCH
  18414. */
  18415. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  18416. /* To simplify the code, we prevent matches with the string
  18417. * of window index 0 (in particular we have to avoid a match
  18418. * of the string with itself at the start of the input file).
  18419. */
  18420. s.match_length = longest_match(s, hash_head);
  18421. /* longest_match() sets match_start */
  18422. }
  18423. if (s.match_length >= MIN_MATCH) {
  18424. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  18425. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  18426. s.match_length - MIN_MATCH, bflush); ***/
  18427. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  18428. s.lookahead -= s.match_length;
  18429. /* Insert new strings in the hash table only if the match length
  18430. * is not too large. This saves time but degrades compression.
  18431. */
  18432. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  18433. s.match_length--; /* string at strstart already in table */
  18434. do {
  18435. s.strstart++;
  18436. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18437. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18438. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18439. s.head[s.ins_h] = s.strstart;
  18440. /***/
  18441. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  18442. * always MIN_MATCH bytes ahead.
  18443. */
  18444. } while (--s.match_length !== 0);
  18445. s.strstart++;
  18446. } else
  18447. {
  18448. s.strstart += s.match_length;
  18449. s.match_length = 0;
  18450. s.ins_h = s.window[s.strstart];
  18451. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  18452. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  18453. //#if MIN_MATCH != 3
  18454. // Call UPDATE_HASH() MIN_MATCH-3 more times
  18455. //#endif
  18456. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  18457. * matter since it will be recomputed at next deflate call.
  18458. */
  18459. }
  18460. } else {
  18461. /* No match, output a literal byte */
  18462. //Tracevv((stderr,"%c", s.window[s.strstart]));
  18463. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18464. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18465. s.lookahead--;
  18466. s.strstart++;
  18467. }
  18468. if (bflush) {
  18469. /*** FLUSH_BLOCK(s, 0); ***/
  18470. flush_block_only(s, false);
  18471. if (s.strm.avail_out === 0) {
  18472. return BS_NEED_MORE;
  18473. }
  18474. /***/
  18475. }
  18476. }
  18477. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  18478. if (flush === Z_FINISH) {
  18479. /*** FLUSH_BLOCK(s, 1); ***/
  18480. flush_block_only(s, true);
  18481. if (s.strm.avail_out === 0) {
  18482. return BS_FINISH_STARTED;
  18483. }
  18484. /***/
  18485. return BS_FINISH_DONE;
  18486. }
  18487. if (s.last_lit) {
  18488. /*** FLUSH_BLOCK(s, 0); ***/
  18489. flush_block_only(s, false);
  18490. if (s.strm.avail_out === 0) {
  18491. return BS_NEED_MORE;
  18492. }
  18493. /***/
  18494. }
  18495. return BS_BLOCK_DONE;
  18496. }
  18497. /* ===========================================================================
  18498. * Same as above, but achieves better compression. We use a lazy
  18499. * evaluation for matches: a match is finally adopted only if there is
  18500. * no better match at the next window position.
  18501. */
  18502. function deflate_slow(s, flush) {
  18503. var hash_head; /* head of hash chain */
  18504. var bflush; /* set if current block must be flushed */
  18505. var max_insert;
  18506. /* Process the input block. */
  18507. for (;;) {
  18508. /* Make sure that we always have enough lookahead, except
  18509. * at the end of the input file. We need MAX_MATCH bytes
  18510. * for the next match, plus MIN_MATCH bytes to insert the
  18511. * string following the next match.
  18512. */
  18513. if (s.lookahead < MIN_LOOKAHEAD) {
  18514. fill_window(s);
  18515. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  18516. return BS_NEED_MORE;
  18517. }
  18518. if (s.lookahead === 0) { break; } /* flush the current block */
  18519. }
  18520. /* Insert the string window[strstart .. strstart+2] in the
  18521. * dictionary, and set hash_head to the head of the hash chain:
  18522. */
  18523. hash_head = 0/*NIL*/;
  18524. if (s.lookahead >= MIN_MATCH) {
  18525. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18526. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18527. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18528. s.head[s.ins_h] = s.strstart;
  18529. /***/
  18530. }
  18531. /* Find the longest match, discarding those <= prev_length.
  18532. */
  18533. s.prev_length = s.match_length;
  18534. s.prev_match = s.match_start;
  18535. s.match_length = MIN_MATCH-1;
  18536. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  18537. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  18538. /* To simplify the code, we prevent matches with the string
  18539. * of window index 0 (in particular we have to avoid a match
  18540. * of the string with itself at the start of the input file).
  18541. */
  18542. s.match_length = longest_match(s, hash_head);
  18543. /* longest_match() sets match_start */
  18544. if (s.match_length <= 5 &&
  18545. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  18546. /* If prev_match is also MIN_MATCH, match_start is garbage
  18547. * but we will ignore the current match anyway.
  18548. */
  18549. s.match_length = MIN_MATCH-1;
  18550. }
  18551. }
  18552. /* If there was a match at the previous step and the current
  18553. * match is not better, output the previous match:
  18554. */
  18555. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  18556. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  18557. /* Do not insert strings in hash table beyond this. */
  18558. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  18559. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  18560. s.prev_length - MIN_MATCH, bflush);***/
  18561. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  18562. /* Insert in hash table all strings up to the end of the match.
  18563. * strstart-1 and strstart are already inserted. If there is not
  18564. * enough lookahead, the last two strings are not inserted in
  18565. * the hash table.
  18566. */
  18567. s.lookahead -= s.prev_length-1;
  18568. s.prev_length -= 2;
  18569. do {
  18570. if (++s.strstart <= max_insert) {
  18571. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18572. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18573. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18574. s.head[s.ins_h] = s.strstart;
  18575. /***/
  18576. }
  18577. } while (--s.prev_length !== 0);
  18578. s.match_available = 0;
  18579. s.match_length = MIN_MATCH-1;
  18580. s.strstart++;
  18581. if (bflush) {
  18582. /*** FLUSH_BLOCK(s, 0); ***/
  18583. flush_block_only(s, false);
  18584. if (s.strm.avail_out === 0) {
  18585. return BS_NEED_MORE;
  18586. }
  18587. /***/
  18588. }
  18589. } else if (s.match_available) {
  18590. /* If there was no match at the previous position, output a
  18591. * single literal. If there was a match but the current match
  18592. * is longer, truncate the previous match to a single literal.
  18593. */
  18594. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  18595. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  18596. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  18597. if (bflush) {
  18598. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  18599. flush_block_only(s, false);
  18600. /***/
  18601. }
  18602. s.strstart++;
  18603. s.lookahead--;
  18604. if (s.strm.avail_out === 0) {
  18605. return BS_NEED_MORE;
  18606. }
  18607. } else {
  18608. /* There is no previous match to compare with, wait for
  18609. * the next step to decide.
  18610. */
  18611. s.match_available = 1;
  18612. s.strstart++;
  18613. s.lookahead--;
  18614. }
  18615. }
  18616. //Assert (flush != Z_NO_FLUSH, "no flush?");
  18617. if (s.match_available) {
  18618. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  18619. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  18620. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  18621. s.match_available = 0;
  18622. }
  18623. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  18624. if (flush === Z_FINISH) {
  18625. /*** FLUSH_BLOCK(s, 1); ***/
  18626. flush_block_only(s, true);
  18627. if (s.strm.avail_out === 0) {
  18628. return BS_FINISH_STARTED;
  18629. }
  18630. /***/
  18631. return BS_FINISH_DONE;
  18632. }
  18633. if (s.last_lit) {
  18634. /*** FLUSH_BLOCK(s, 0); ***/
  18635. flush_block_only(s, false);
  18636. if (s.strm.avail_out === 0) {
  18637. return BS_NEED_MORE;
  18638. }
  18639. /***/
  18640. }
  18641. return BS_BLOCK_DONE;
  18642. }
  18643. /* ===========================================================================
  18644. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  18645. * one. Do not maintain a hash table. (It will be regenerated if this run of
  18646. * deflate switches away from Z_RLE.)
  18647. */
  18648. function deflate_rle(s, flush) {
  18649. var bflush; /* set if current block must be flushed */
  18650. var prev; /* byte at distance one to match */
  18651. var scan, strend; /* scan goes up to strend for length of run */
  18652. var _win = s.window;
  18653. for (;;) {
  18654. /* Make sure that we always have enough lookahead, except
  18655. * at the end of the input file. We need MAX_MATCH bytes
  18656. * for the longest run, plus one for the unrolled loop.
  18657. */
  18658. if (s.lookahead <= MAX_MATCH) {
  18659. fill_window(s);
  18660. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  18661. return BS_NEED_MORE;
  18662. }
  18663. if (s.lookahead === 0) { break; } /* flush the current block */
  18664. }
  18665. /* See how many times the previous byte repeats */
  18666. s.match_length = 0;
  18667. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  18668. scan = s.strstart - 1;
  18669. prev = _win[scan];
  18670. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  18671. strend = s.strstart + MAX_MATCH;
  18672. do {
  18673. /*jshint noempty:false*/
  18674. } while (prev === _win[++scan] && prev === _win[++scan] &&
  18675. prev === _win[++scan] && prev === _win[++scan] &&
  18676. prev === _win[++scan] && prev === _win[++scan] &&
  18677. prev === _win[++scan] && prev === _win[++scan] &&
  18678. scan < strend);
  18679. s.match_length = MAX_MATCH - (strend - scan);
  18680. if (s.match_length > s.lookahead) {
  18681. s.match_length = s.lookahead;
  18682. }
  18683. }
  18684. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  18685. }
  18686. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  18687. if (s.match_length >= MIN_MATCH) {
  18688. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  18689. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  18690. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  18691. s.lookahead -= s.match_length;
  18692. s.strstart += s.match_length;
  18693. s.match_length = 0;
  18694. } else {
  18695. /* No match, output a literal byte */
  18696. //Tracevv((stderr,"%c", s->window[s->strstart]));
  18697. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18698. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18699. s.lookahead--;
  18700. s.strstart++;
  18701. }
  18702. if (bflush) {
  18703. /*** FLUSH_BLOCK(s, 0); ***/
  18704. flush_block_only(s, false);
  18705. if (s.strm.avail_out === 0) {
  18706. return BS_NEED_MORE;
  18707. }
  18708. /***/
  18709. }
  18710. }
  18711. s.insert = 0;
  18712. if (flush === Z_FINISH) {
  18713. /*** FLUSH_BLOCK(s, 1); ***/
  18714. flush_block_only(s, true);
  18715. if (s.strm.avail_out === 0) {
  18716. return BS_FINISH_STARTED;
  18717. }
  18718. /***/
  18719. return BS_FINISH_DONE;
  18720. }
  18721. if (s.last_lit) {
  18722. /*** FLUSH_BLOCK(s, 0); ***/
  18723. flush_block_only(s, false);
  18724. if (s.strm.avail_out === 0) {
  18725. return BS_NEED_MORE;
  18726. }
  18727. /***/
  18728. }
  18729. return BS_BLOCK_DONE;
  18730. }
  18731. /* ===========================================================================
  18732. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  18733. * (It will be regenerated if this run of deflate switches away from Huffman.)
  18734. */
  18735. function deflate_huff(s, flush) {
  18736. var bflush; /* set if current block must be flushed */
  18737. for (;;) {
  18738. /* Make sure that we have a literal to write. */
  18739. if (s.lookahead === 0) {
  18740. fill_window(s);
  18741. if (s.lookahead === 0) {
  18742. if (flush === Z_NO_FLUSH) {
  18743. return BS_NEED_MORE;
  18744. }
  18745. break; /* flush the current block */
  18746. }
  18747. }
  18748. /* Output a literal byte */
  18749. s.match_length = 0;
  18750. //Tracevv((stderr,"%c", s->window[s->strstart]));
  18751. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18752. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18753. s.lookahead--;
  18754. s.strstart++;
  18755. if (bflush) {
  18756. /*** FLUSH_BLOCK(s, 0); ***/
  18757. flush_block_only(s, false);
  18758. if (s.strm.avail_out === 0) {
  18759. return BS_NEED_MORE;
  18760. }
  18761. /***/
  18762. }
  18763. }
  18764. s.insert = 0;
  18765. if (flush === Z_FINISH) {
  18766. /*** FLUSH_BLOCK(s, 1); ***/
  18767. flush_block_only(s, true);
  18768. if (s.strm.avail_out === 0) {
  18769. return BS_FINISH_STARTED;
  18770. }
  18771. /***/
  18772. return BS_FINISH_DONE;
  18773. }
  18774. if (s.last_lit) {
  18775. /*** FLUSH_BLOCK(s, 0); ***/
  18776. flush_block_only(s, false);
  18777. if (s.strm.avail_out === 0) {
  18778. return BS_NEED_MORE;
  18779. }
  18780. /***/
  18781. }
  18782. return BS_BLOCK_DONE;
  18783. }
  18784. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  18785. * the desired pack level (0..9). The values given below have been tuned to
  18786. * exclude worst case performance for pathological files. Better values may be
  18787. * found for specific files.
  18788. */
  18789. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  18790. this.good_length = good_length;
  18791. this.max_lazy = max_lazy;
  18792. this.nice_length = nice_length;
  18793. this.max_chain = max_chain;
  18794. this.func = func;
  18795. };
  18796. var configuration_table;
  18797. configuration_table = [
  18798. /* good lazy nice chain */
  18799. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  18800. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  18801. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  18802. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  18803. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  18804. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  18805. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  18806. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  18807. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  18808. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  18809. ];
  18810. /* ===========================================================================
  18811. * Initialize the "longest match" routines for a new zlib stream
  18812. */
  18813. function lm_init(s) {
  18814. s.window_size = 2 * s.w_size;
  18815. /*** CLEAR_HASH(s); ***/
  18816. zero(s.head); // Fill with NIL (= 0);
  18817. /* Set the default configuration parameters:
  18818. */
  18819. s.max_lazy_match = configuration_table[s.level].max_lazy;
  18820. s.good_match = configuration_table[s.level].good_length;
  18821. s.nice_match = configuration_table[s.level].nice_length;
  18822. s.max_chain_length = configuration_table[s.level].max_chain;
  18823. s.strstart = 0;
  18824. s.block_start = 0;
  18825. s.lookahead = 0;
  18826. s.insert = 0;
  18827. s.match_length = s.prev_length = MIN_MATCH - 1;
  18828. s.match_available = 0;
  18829. s.ins_h = 0;
  18830. }
  18831. function DeflateState() {
  18832. this.strm = null; /* pointer back to this zlib stream */
  18833. this.status = 0; /* as the name implies */
  18834. this.pending_buf = null; /* output still pending */
  18835. this.pending_buf_size = 0; /* size of pending_buf */
  18836. this.pending_out = 0; /* next pending byte to output to the stream */
  18837. this.pending = 0; /* nb of bytes in the pending buffer */
  18838. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  18839. this.gzhead = null; /* gzip header information to write */
  18840. this.gzindex = 0; /* where in extra, name, or comment */
  18841. this.method = Z_DEFLATED; /* can only be DEFLATED */
  18842. this.last_flush = -1; /* value of flush param for previous deflate call */
  18843. this.w_size = 0; /* LZ77 window size (32K by default) */
  18844. this.w_bits = 0; /* log2(w_size) (8..16) */
  18845. this.w_mask = 0; /* w_size - 1 */
  18846. this.window = null;
  18847. /* Sliding window. Input bytes are read into the second half of the window,
  18848. * and move to the first half later to keep a dictionary of at least wSize
  18849. * bytes. With this organization, matches are limited to a distance of
  18850. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  18851. * performed with a length multiple of the block size.
  18852. */
  18853. this.window_size = 0;
  18854. /* Actual size of window: 2*wSize, except when the user input buffer
  18855. * is directly used as sliding window.
  18856. */
  18857. this.prev = null;
  18858. /* Link to older string with same hash index. To limit the size of this
  18859. * array to 64K, this link is maintained only for the last 32K strings.
  18860. * An index in this array is thus a window index modulo 32K.
  18861. */
  18862. this.head = null; /* Heads of the hash chains or NIL. */
  18863. this.ins_h = 0; /* hash index of string to be inserted */
  18864. this.hash_size = 0; /* number of elements in hash table */
  18865. this.hash_bits = 0; /* log2(hash_size) */
  18866. this.hash_mask = 0; /* hash_size-1 */
  18867. this.hash_shift = 0;
  18868. /* Number of bits by which ins_h must be shifted at each input
  18869. * step. It must be such that after MIN_MATCH steps, the oldest
  18870. * byte no longer takes part in the hash key, that is:
  18871. * hash_shift * MIN_MATCH >= hash_bits
  18872. */
  18873. this.block_start = 0;
  18874. /* Window position at the beginning of the current output block. Gets
  18875. * negative when the window is moved backwards.
  18876. */
  18877. this.match_length = 0; /* length of best match */
  18878. this.prev_match = 0; /* previous match */
  18879. this.match_available = 0; /* set if previous match exists */
  18880. this.strstart = 0; /* start of string to insert */
  18881. this.match_start = 0; /* start of matching string */
  18882. this.lookahead = 0; /* number of valid bytes ahead in window */
  18883. this.prev_length = 0;
  18884. /* Length of the best match at previous step. Matches not greater than this
  18885. * are discarded. This is used in the lazy match evaluation.
  18886. */
  18887. this.max_chain_length = 0;
  18888. /* To speed up deflation, hash chains are never searched beyond this
  18889. * length. A higher limit improves compression ratio but degrades the
  18890. * speed.
  18891. */
  18892. this.max_lazy_match = 0;
  18893. /* Attempt to find a better match only when the current match is strictly
  18894. * smaller than this value. This mechanism is used only for compression
  18895. * levels >= 4.
  18896. */
  18897. // That's alias to max_lazy_match, don't use directly
  18898. //this.max_insert_length = 0;
  18899. /* Insert new strings in the hash table only if the match length is not
  18900. * greater than this length. This saves time but degrades compression.
  18901. * max_insert_length is used only for compression levels <= 3.
  18902. */
  18903. this.level = 0; /* compression level (1..9) */
  18904. this.strategy = 0; /* favor or force Huffman coding*/
  18905. this.good_match = 0;
  18906. /* Use a faster search when the previous match is longer than this */
  18907. this.nice_match = 0; /* Stop searching when current match exceeds this */
  18908. /* used by trees.c: */
  18909. /* Didn't use ct_data typedef below to suppress compiler warning */
  18910. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  18911. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  18912. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  18913. // Use flat array of DOUBLE size, with interleaved fata,
  18914. // because JS does not support effective
  18915. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  18916. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  18917. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  18918. zero(this.dyn_ltree);
  18919. zero(this.dyn_dtree);
  18920. zero(this.bl_tree);
  18921. this.l_desc = null; /* desc. for literal tree */
  18922. this.d_desc = null; /* desc. for distance tree */
  18923. this.bl_desc = null; /* desc. for bit length tree */
  18924. //ush bl_count[MAX_BITS+1];
  18925. this.bl_count = new utils.Buf16(MAX_BITS+1);
  18926. /* number of codes at each bit length for an optimal tree */
  18927. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  18928. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  18929. zero(this.heap);
  18930. this.heap_len = 0; /* number of elements in the heap */
  18931. this.heap_max = 0; /* element of largest frequency */
  18932. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  18933. * The same heap array is used to build all trees.
  18934. */
  18935. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  18936. zero(this.depth);
  18937. /* Depth of each subtree used as tie breaker for trees of equal frequency
  18938. */
  18939. this.l_buf = 0; /* buffer index for literals or lengths */
  18940. this.lit_bufsize = 0;
  18941. /* Size of match buffer for literals/lengths. There are 4 reasons for
  18942. * limiting lit_bufsize to 64K:
  18943. * - frequencies can be kept in 16 bit counters
  18944. * - if compression is not successful for the first block, all input
  18945. * data is still in the window so we can still emit a stored block even
  18946. * when input comes from standard input. (This can also be done for
  18947. * all blocks if lit_bufsize is not greater than 32K.)
  18948. * - if compression is not successful for a file smaller than 64K, we can
  18949. * even emit a stored file instead of a stored block (saving 5 bytes).
  18950. * This is applicable only for zip (not gzip or zlib).
  18951. * - creating new Huffman trees less frequently may not provide fast
  18952. * adaptation to changes in the input data statistics. (Take for
  18953. * example a binary file with poorly compressible code followed by
  18954. * a highly compressible string table.) Smaller buffer sizes give
  18955. * fast adaptation but have of course the overhead of transmitting
  18956. * trees more frequently.
  18957. * - I can't count above 4
  18958. */
  18959. this.last_lit = 0; /* running index in l_buf */
  18960. this.d_buf = 0;
  18961. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  18962. * the same number of elements. To use different lengths, an extra flag
  18963. * array would be necessary.
  18964. */
  18965. this.opt_len = 0; /* bit length of current block with optimal trees */
  18966. this.static_len = 0; /* bit length of current block with static trees */
  18967. this.matches = 0; /* number of string matches in current block */
  18968. this.insert = 0; /* bytes at end of window left to insert */
  18969. this.bi_buf = 0;
  18970. /* Output buffer. bits are inserted starting at the bottom (least
  18971. * significant bits).
  18972. */
  18973. this.bi_valid = 0;
  18974. /* Number of valid bits in bi_buf. All bits above the last valid bit
  18975. * are always zero.
  18976. */
  18977. // Used for window memory init. We safely ignore it for JS. That makes
  18978. // sense only for pointers and memory check tools.
  18979. //this.high_water = 0;
  18980. /* High water mark offset in window for initialized bytes -- bytes above
  18981. * this are set to zero in order to avoid memory check warnings when
  18982. * longest match routines access bytes past the input. This is then
  18983. * updated to the new high water mark.
  18984. */
  18985. }
  18986. function deflateResetKeep(strm) {
  18987. var s;
  18988. if (!strm || !strm.state) {
  18989. return err(strm, Z_STREAM_ERROR);
  18990. }
  18991. strm.total_in = strm.total_out = 0;
  18992. strm.data_type = Z_UNKNOWN;
  18993. s = strm.state;
  18994. s.pending = 0;
  18995. s.pending_out = 0;
  18996. if (s.wrap < 0) {
  18997. s.wrap = -s.wrap;
  18998. /* was made negative by deflate(..., Z_FINISH); */
  18999. }
  19000. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  19001. strm.adler = (s.wrap === 2) ?
  19002. 0 // crc32(0, Z_NULL, 0)
  19003. :
  19004. 1; // adler32(0, Z_NULL, 0)
  19005. s.last_flush = Z_NO_FLUSH;
  19006. trees._tr_init(s);
  19007. return Z_OK;
  19008. }
  19009. function deflateReset(strm) {
  19010. var ret = deflateResetKeep(strm);
  19011. if (ret === Z_OK) {
  19012. lm_init(strm.state);
  19013. }
  19014. return ret;
  19015. }
  19016. function deflateSetHeader(strm, head) {
  19017. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19018. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  19019. strm.state.gzhead = head;
  19020. return Z_OK;
  19021. }
  19022. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  19023. if (!strm) { // === Z_NULL
  19024. return Z_STREAM_ERROR;
  19025. }
  19026. var wrap = 1;
  19027. if (level === Z_DEFAULT_COMPRESSION) {
  19028. level = 6;
  19029. }
  19030. if (windowBits < 0) { /* suppress zlib wrapper */
  19031. wrap = 0;
  19032. windowBits = -windowBits;
  19033. }
  19034. else if (windowBits > 15) {
  19035. wrap = 2; /* write gzip wrapper instead */
  19036. windowBits -= 16;
  19037. }
  19038. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  19039. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  19040. strategy < 0 || strategy > Z_FIXED) {
  19041. return err(strm, Z_STREAM_ERROR);
  19042. }
  19043. if (windowBits === 8) {
  19044. windowBits = 9;
  19045. }
  19046. /* until 256-byte window bug fixed */
  19047. var s = new DeflateState();
  19048. strm.state = s;
  19049. s.strm = strm;
  19050. s.wrap = wrap;
  19051. s.gzhead = null;
  19052. s.w_bits = windowBits;
  19053. s.w_size = 1 << s.w_bits;
  19054. s.w_mask = s.w_size - 1;
  19055. s.hash_bits = memLevel + 7;
  19056. s.hash_size = 1 << s.hash_bits;
  19057. s.hash_mask = s.hash_size - 1;
  19058. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  19059. s.window = new utils.Buf8(s.w_size * 2);
  19060. s.head = new utils.Buf16(s.hash_size);
  19061. s.prev = new utils.Buf16(s.w_size);
  19062. // Don't need mem init magic for JS.
  19063. //s.high_water = 0; /* nothing written to s->window yet */
  19064. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  19065. s.pending_buf_size = s.lit_bufsize * 4;
  19066. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  19067. s.d_buf = s.lit_bufsize >> 1;
  19068. s.l_buf = (1 + 2) * s.lit_bufsize;
  19069. s.level = level;
  19070. s.strategy = strategy;
  19071. s.method = method;
  19072. return deflateReset(strm);
  19073. }
  19074. function deflateInit(strm, level) {
  19075. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  19076. }
  19077. function deflate(strm, flush) {
  19078. var old_flush, s;
  19079. var beg, val; // for gzip header write only
  19080. if (!strm || !strm.state ||
  19081. flush > Z_BLOCK || flush < 0) {
  19082. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  19083. }
  19084. s = strm.state;
  19085. if (!strm.output ||
  19086. (!strm.input && strm.avail_in !== 0) ||
  19087. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  19088. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  19089. }
  19090. s.strm = strm; /* just in case */
  19091. old_flush = s.last_flush;
  19092. s.last_flush = flush;
  19093. /* Write the header */
  19094. if (s.status === INIT_STATE) {
  19095. if (s.wrap === 2) { // GZIP header
  19096. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  19097. put_byte(s, 31);
  19098. put_byte(s, 139);
  19099. put_byte(s, 8);
  19100. if (!s.gzhead) { // s->gzhead == Z_NULL
  19101. put_byte(s, 0);
  19102. put_byte(s, 0);
  19103. put_byte(s, 0);
  19104. put_byte(s, 0);
  19105. put_byte(s, 0);
  19106. put_byte(s, s.level === 9 ? 2 :
  19107. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  19108. 4 : 0));
  19109. put_byte(s, OS_CODE);
  19110. s.status = BUSY_STATE;
  19111. }
  19112. else {
  19113. put_byte(s, (s.gzhead.text ? 1 : 0) +
  19114. (s.gzhead.hcrc ? 2 : 0) +
  19115. (!s.gzhead.extra ? 0 : 4) +
  19116. (!s.gzhead.name ? 0 : 8) +
  19117. (!s.gzhead.comment ? 0 : 16)
  19118. );
  19119. put_byte(s, s.gzhead.time & 0xff);
  19120. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  19121. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  19122. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  19123. put_byte(s, s.level === 9 ? 2 :
  19124. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  19125. 4 : 0));
  19126. put_byte(s, s.gzhead.os & 0xff);
  19127. if (s.gzhead.extra && s.gzhead.extra.length) {
  19128. put_byte(s, s.gzhead.extra.length & 0xff);
  19129. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  19130. }
  19131. if (s.gzhead.hcrc) {
  19132. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  19133. }
  19134. s.gzindex = 0;
  19135. s.status = EXTRA_STATE;
  19136. }
  19137. }
  19138. else // DEFLATE header
  19139. {
  19140. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  19141. var level_flags = -1;
  19142. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  19143. level_flags = 0;
  19144. } else if (s.level < 6) {
  19145. level_flags = 1;
  19146. } else if (s.level === 6) {
  19147. level_flags = 2;
  19148. } else {
  19149. level_flags = 3;
  19150. }
  19151. header |= (level_flags << 6);
  19152. if (s.strstart !== 0) { header |= PRESET_DICT; }
  19153. header += 31 - (header % 31);
  19154. s.status = BUSY_STATE;
  19155. putShortMSB(s, header);
  19156. /* Save the adler32 of the preset dictionary: */
  19157. if (s.strstart !== 0) {
  19158. putShortMSB(s, strm.adler >>> 16);
  19159. putShortMSB(s, strm.adler & 0xffff);
  19160. }
  19161. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  19162. }
  19163. }
  19164. //#ifdef GZIP
  19165. if (s.status === EXTRA_STATE) {
  19166. if (s.gzhead.extra/* != Z_NULL*/) {
  19167. beg = s.pending; /* start of bytes to update crc */
  19168. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  19169. if (s.pending === s.pending_buf_size) {
  19170. if (s.gzhead.hcrc && s.pending > beg) {
  19171. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19172. }
  19173. flush_pending(strm);
  19174. beg = s.pending;
  19175. if (s.pending === s.pending_buf_size) {
  19176. break;
  19177. }
  19178. }
  19179. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  19180. s.gzindex++;
  19181. }
  19182. if (s.gzhead.hcrc && s.pending > beg) {
  19183. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19184. }
  19185. if (s.gzindex === s.gzhead.extra.length) {
  19186. s.gzindex = 0;
  19187. s.status = NAME_STATE;
  19188. }
  19189. }
  19190. else {
  19191. s.status = NAME_STATE;
  19192. }
  19193. }
  19194. if (s.status === NAME_STATE) {
  19195. if (s.gzhead.name/* != Z_NULL*/) {
  19196. beg = s.pending; /* start of bytes to update crc */
  19197. //int val;
  19198. do {
  19199. if (s.pending === s.pending_buf_size) {
  19200. if (s.gzhead.hcrc && s.pending > beg) {
  19201. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19202. }
  19203. flush_pending(strm);
  19204. beg = s.pending;
  19205. if (s.pending === s.pending_buf_size) {
  19206. val = 1;
  19207. break;
  19208. }
  19209. }
  19210. // JS specific: little magic to add zero terminator to end of string
  19211. if (s.gzindex < s.gzhead.name.length) {
  19212. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  19213. } else {
  19214. val = 0;
  19215. }
  19216. put_byte(s, val);
  19217. } while (val !== 0);
  19218. if (s.gzhead.hcrc && s.pending > beg){
  19219. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19220. }
  19221. if (val === 0) {
  19222. s.gzindex = 0;
  19223. s.status = COMMENT_STATE;
  19224. }
  19225. }
  19226. else {
  19227. s.status = COMMENT_STATE;
  19228. }
  19229. }
  19230. if (s.status === COMMENT_STATE) {
  19231. if (s.gzhead.comment/* != Z_NULL*/) {
  19232. beg = s.pending; /* start of bytes to update crc */
  19233. //int val;
  19234. do {
  19235. if (s.pending === s.pending_buf_size) {
  19236. if (s.gzhead.hcrc && s.pending > beg) {
  19237. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19238. }
  19239. flush_pending(strm);
  19240. beg = s.pending;
  19241. if (s.pending === s.pending_buf_size) {
  19242. val = 1;
  19243. break;
  19244. }
  19245. }
  19246. // JS specific: little magic to add zero terminator to end of string
  19247. if (s.gzindex < s.gzhead.comment.length) {
  19248. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  19249. } else {
  19250. val = 0;
  19251. }
  19252. put_byte(s, val);
  19253. } while (val !== 0);
  19254. if (s.gzhead.hcrc && s.pending > beg) {
  19255. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19256. }
  19257. if (val === 0) {
  19258. s.status = HCRC_STATE;
  19259. }
  19260. }
  19261. else {
  19262. s.status = HCRC_STATE;
  19263. }
  19264. }
  19265. if (s.status === HCRC_STATE) {
  19266. if (s.gzhead.hcrc) {
  19267. if (s.pending + 2 > s.pending_buf_size) {
  19268. flush_pending(strm);
  19269. }
  19270. if (s.pending + 2 <= s.pending_buf_size) {
  19271. put_byte(s, strm.adler & 0xff);
  19272. put_byte(s, (strm.adler >> 8) & 0xff);
  19273. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  19274. s.status = BUSY_STATE;
  19275. }
  19276. }
  19277. else {
  19278. s.status = BUSY_STATE;
  19279. }
  19280. }
  19281. //#endif
  19282. /* Flush as much pending output as possible */
  19283. if (s.pending !== 0) {
  19284. flush_pending(strm);
  19285. if (strm.avail_out === 0) {
  19286. /* Since avail_out is 0, deflate will be called again with
  19287. * more output space, but possibly with both pending and
  19288. * avail_in equal to zero. There won't be anything to do,
  19289. * but this is not an error situation so make sure we
  19290. * return OK instead of BUF_ERROR at next call of deflate:
  19291. */
  19292. s.last_flush = -1;
  19293. return Z_OK;
  19294. }
  19295. /* Make sure there is something to do and avoid duplicate consecutive
  19296. * flushes. For repeated and useless calls with Z_FINISH, we keep
  19297. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  19298. */
  19299. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  19300. flush !== Z_FINISH) {
  19301. return err(strm, Z_BUF_ERROR);
  19302. }
  19303. /* User must not provide more input after the first FINISH: */
  19304. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  19305. return err(strm, Z_BUF_ERROR);
  19306. }
  19307. /* Start a new block or continue the current one.
  19308. */
  19309. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  19310. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  19311. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  19312. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  19313. configuration_table[s.level].func(s, flush));
  19314. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  19315. s.status = FINISH_STATE;
  19316. }
  19317. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  19318. if (strm.avail_out === 0) {
  19319. s.last_flush = -1;
  19320. /* avoid BUF_ERROR next call, see above */
  19321. }
  19322. return Z_OK;
  19323. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  19324. * of deflate should use the same flush parameter to make sure
  19325. * that the flush is complete. So we don't have to output an
  19326. * empty block here, this will be done at next call. This also
  19327. * ensures that for a very small output buffer, we emit at most
  19328. * one empty block.
  19329. */
  19330. }
  19331. if (bstate === BS_BLOCK_DONE) {
  19332. if (flush === Z_PARTIAL_FLUSH) {
  19333. trees._tr_align(s);
  19334. }
  19335. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  19336. trees._tr_stored_block(s, 0, 0, false);
  19337. /* For a full flush, this empty block will be recognized
  19338. * as a special marker by inflate_sync().
  19339. */
  19340. if (flush === Z_FULL_FLUSH) {
  19341. /*** CLEAR_HASH(s); ***/ /* forget history */
  19342. zero(s.head); // Fill with NIL (= 0);
  19343. if (s.lookahead === 0) {
  19344. s.strstart = 0;
  19345. s.block_start = 0;
  19346. s.insert = 0;
  19347. }
  19348. }
  19349. }
  19350. flush_pending(strm);
  19351. if (strm.avail_out === 0) {
  19352. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  19353. return Z_OK;
  19354. }
  19355. }
  19356. }
  19357. //Assert(strm->avail_out > 0, "bug2");
  19358. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  19359. if (flush !== Z_FINISH) { return Z_OK; }
  19360. if (s.wrap <= 0) { return Z_STREAM_END; }
  19361. /* Write the trailer */
  19362. if (s.wrap === 2) {
  19363. put_byte(s, strm.adler & 0xff);
  19364. put_byte(s, (strm.adler >> 8) & 0xff);
  19365. put_byte(s, (strm.adler >> 16) & 0xff);
  19366. put_byte(s, (strm.adler >> 24) & 0xff);
  19367. put_byte(s, strm.total_in & 0xff);
  19368. put_byte(s, (strm.total_in >> 8) & 0xff);
  19369. put_byte(s, (strm.total_in >> 16) & 0xff);
  19370. put_byte(s, (strm.total_in >> 24) & 0xff);
  19371. }
  19372. else
  19373. {
  19374. putShortMSB(s, strm.adler >>> 16);
  19375. putShortMSB(s, strm.adler & 0xffff);
  19376. }
  19377. flush_pending(strm);
  19378. /* If avail_out is zero, the application will call deflate again
  19379. * to flush the rest.
  19380. */
  19381. if (s.wrap > 0) { s.wrap = -s.wrap; }
  19382. /* write the trailer only once! */
  19383. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  19384. }
  19385. function deflateEnd(strm) {
  19386. var status;
  19387. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  19388. return Z_STREAM_ERROR;
  19389. }
  19390. status = strm.state.status;
  19391. if (status !== INIT_STATE &&
  19392. status !== EXTRA_STATE &&
  19393. status !== NAME_STATE &&
  19394. status !== COMMENT_STATE &&
  19395. status !== HCRC_STATE &&
  19396. status !== BUSY_STATE &&
  19397. status !== FINISH_STATE
  19398. ) {
  19399. return err(strm, Z_STREAM_ERROR);
  19400. }
  19401. strm.state = null;
  19402. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  19403. }
  19404. /* =========================================================================
  19405. * Copy the source state to the destination state
  19406. */
  19407. //function deflateCopy(dest, source) {
  19408. //
  19409. //}
  19410. exports.deflateInit = deflateInit;
  19411. exports.deflateInit2 = deflateInit2;
  19412. exports.deflateReset = deflateReset;
  19413. exports.deflateResetKeep = deflateResetKeep;
  19414. exports.deflateSetHeader = deflateSetHeader;
  19415. exports.deflate = deflate;
  19416. exports.deflateEnd = deflateEnd;
  19417. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  19418. /* Not implemented
  19419. exports.deflateBound = deflateBound;
  19420. exports.deflateCopy = deflateCopy;
  19421. exports.deflateSetDictionary = deflateSetDictionary;
  19422. exports.deflateParams = deflateParams;
  19423. exports.deflatePending = deflatePending;
  19424. exports.deflatePrime = deflatePrime;
  19425. exports.deflateTune = deflateTune;
  19426. */
  19427. },{"../utils/common":66,"./adler32":68,"./crc32":70,"./messages":76,"./trees":77}],72:[function(require,module,exports){
  19428. 'use strict';
  19429. function GZheader() {
  19430. /* true if compressed data believed to be text */
  19431. this.text = 0;
  19432. /* modification time */
  19433. this.time = 0;
  19434. /* extra flags (not used when writing a gzip file) */
  19435. this.xflags = 0;
  19436. /* operating system */
  19437. this.os = 0;
  19438. /* pointer to extra field or Z_NULL if none */
  19439. this.extra = null;
  19440. /* extra field length (valid if extra != Z_NULL) */
  19441. this.extra_len = 0; // Actually, we don't need it in JS,
  19442. // but leave for few code modifications
  19443. //
  19444. // Setup limits is not necessary because in js we should not preallocate memory
  19445. // for inflate use constant limit in 65536 bytes
  19446. //
  19447. /* space at extra (only when reading header) */
  19448. // this.extra_max = 0;
  19449. /* pointer to zero-terminated file name or Z_NULL */
  19450. this.name = '';
  19451. /* space at name (only when reading header) */
  19452. // this.name_max = 0;
  19453. /* pointer to zero-terminated comment or Z_NULL */
  19454. this.comment = '';
  19455. /* space at comment (only when reading header) */
  19456. // this.comm_max = 0;
  19457. /* true if there was or will be a header crc */
  19458. this.hcrc = 0;
  19459. /* true when done reading gzip header (not used when writing a gzip file) */
  19460. this.done = false;
  19461. }
  19462. module.exports = GZheader;
  19463. },{}],73:[function(require,module,exports){
  19464. 'use strict';
  19465. // See state defs from inflate.js
  19466. var BAD = 30; /* got a data error -- remain here until reset */
  19467. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  19468. /*
  19469. Decode literal, length, and distance codes and write out the resulting
  19470. literal and match bytes until either not enough input or output is
  19471. available, an end-of-block is encountered, or a data error is encountered.
  19472. When large enough input and output buffers are supplied to inflate(), for
  19473. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  19474. inflate execution time is spent in this routine.
  19475. Entry assumptions:
  19476. state.mode === LEN
  19477. strm.avail_in >= 6
  19478. strm.avail_out >= 258
  19479. start >= strm.avail_out
  19480. state.bits < 8
  19481. On return, state.mode is one of:
  19482. LEN -- ran out of enough output space or enough available input
  19483. TYPE -- reached end of block code, inflate() to interpret next block
  19484. BAD -- error in block data
  19485. Notes:
  19486. - The maximum input bits used by a length/distance pair is 15 bits for the
  19487. length code, 5 bits for the length extra, 15 bits for the distance code,
  19488. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  19489. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  19490. checking for available input while decoding.
  19491. - The maximum bytes that a single length/distance pair can output is 258
  19492. bytes, which is the maximum length that can be coded. inflate_fast()
  19493. requires strm.avail_out >= 258 for each loop to avoid checking for
  19494. output space.
  19495. */
  19496. module.exports = function inflate_fast(strm, start) {
  19497. var state;
  19498. var _in; /* local strm.input */
  19499. var last; /* have enough input while in < last */
  19500. var _out; /* local strm.output */
  19501. var beg; /* inflate()'s initial strm.output */
  19502. var end; /* while out < end, enough space available */
  19503. //#ifdef INFLATE_STRICT
  19504. var dmax; /* maximum distance from zlib header */
  19505. //#endif
  19506. var wsize; /* window size or zero if not using window */
  19507. var whave; /* valid bytes in the window */
  19508. var wnext; /* window write index */
  19509. var window; /* allocated sliding window, if wsize != 0 */
  19510. var hold; /* local strm.hold */
  19511. var bits; /* local strm.bits */
  19512. var lcode; /* local strm.lencode */
  19513. var dcode; /* local strm.distcode */
  19514. var lmask; /* mask for first level of length codes */
  19515. var dmask; /* mask for first level of distance codes */
  19516. var here; /* retrieved table entry */
  19517. var op; /* code bits, operation, extra bits, or */
  19518. /* window position, window bytes to copy */
  19519. var len; /* match length, unused bytes */
  19520. var dist; /* match distance */
  19521. var from; /* where to copy match from */
  19522. var from_source;
  19523. var input, output; // JS specific, because we have no pointers
  19524. /* copy state to local variables */
  19525. state = strm.state;
  19526. //here = state.here;
  19527. _in = strm.next_in;
  19528. input = strm.input;
  19529. last = _in + (strm.avail_in - 5);
  19530. _out = strm.next_out;
  19531. output = strm.output;
  19532. beg = _out - (start - strm.avail_out);
  19533. end = _out + (strm.avail_out - 257);
  19534. //#ifdef INFLATE_STRICT
  19535. dmax = state.dmax;
  19536. //#endif
  19537. wsize = state.wsize;
  19538. whave = state.whave;
  19539. wnext = state.wnext;
  19540. window = state.window;
  19541. hold = state.hold;
  19542. bits = state.bits;
  19543. lcode = state.lencode;
  19544. dcode = state.distcode;
  19545. lmask = (1 << state.lenbits) - 1;
  19546. dmask = (1 << state.distbits) - 1;
  19547. /* decode literals and length/distances until end-of-block or not enough
  19548. input data or output space */
  19549. top:
  19550. do {
  19551. if (bits < 15) {
  19552. hold += input[_in++] << bits;
  19553. bits += 8;
  19554. hold += input[_in++] << bits;
  19555. bits += 8;
  19556. }
  19557. here = lcode[hold & lmask];
  19558. dolen:
  19559. for (;;) { // Goto emulation
  19560. op = here >>> 24/*here.bits*/;
  19561. hold >>>= op;
  19562. bits -= op;
  19563. op = (here >>> 16) & 0xff/*here.op*/;
  19564. if (op === 0) { /* literal */
  19565. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  19566. // "inflate: literal '%c'\n" :
  19567. // "inflate: literal 0x%02x\n", here.val));
  19568. output[_out++] = here & 0xffff/*here.val*/;
  19569. }
  19570. else if (op & 16) { /* length base */
  19571. len = here & 0xffff/*here.val*/;
  19572. op &= 15; /* number of extra bits */
  19573. if (op) {
  19574. if (bits < op) {
  19575. hold += input[_in++] << bits;
  19576. bits += 8;
  19577. }
  19578. len += hold & ((1 << op) - 1);
  19579. hold >>>= op;
  19580. bits -= op;
  19581. }
  19582. //Tracevv((stderr, "inflate: length %u\n", len));
  19583. if (bits < 15) {
  19584. hold += input[_in++] << bits;
  19585. bits += 8;
  19586. hold += input[_in++] << bits;
  19587. bits += 8;
  19588. }
  19589. here = dcode[hold & dmask];
  19590. dodist:
  19591. for (;;) { // goto emulation
  19592. op = here >>> 24/*here.bits*/;
  19593. hold >>>= op;
  19594. bits -= op;
  19595. op = (here >>> 16) & 0xff/*here.op*/;
  19596. if (op & 16) { /* distance base */
  19597. dist = here & 0xffff/*here.val*/;
  19598. op &= 15; /* number of extra bits */
  19599. if (bits < op) {
  19600. hold += input[_in++] << bits;
  19601. bits += 8;
  19602. if (bits < op) {
  19603. hold += input[_in++] << bits;
  19604. bits += 8;
  19605. }
  19606. }
  19607. dist += hold & ((1 << op) - 1);
  19608. //#ifdef INFLATE_STRICT
  19609. if (dist > dmax) {
  19610. strm.msg = 'invalid distance too far back';
  19611. state.mode = BAD;
  19612. break top;
  19613. }
  19614. //#endif
  19615. hold >>>= op;
  19616. bits -= op;
  19617. //Tracevv((stderr, "inflate: distance %u\n", dist));
  19618. op = _out - beg; /* max distance in output */
  19619. if (dist > op) { /* see if copy from window */
  19620. op = dist - op; /* distance back in window */
  19621. if (op > whave) {
  19622. if (state.sane) {
  19623. strm.msg = 'invalid distance too far back';
  19624. state.mode = BAD;
  19625. break top;
  19626. }
  19627. // (!) This block is disabled in zlib defailts,
  19628. // don't enable it for binary compatibility
  19629. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  19630. // if (len <= op - whave) {
  19631. // do {
  19632. // output[_out++] = 0;
  19633. // } while (--len);
  19634. // continue top;
  19635. // }
  19636. // len -= op - whave;
  19637. // do {
  19638. // output[_out++] = 0;
  19639. // } while (--op > whave);
  19640. // if (op === 0) {
  19641. // from = _out - dist;
  19642. // do {
  19643. // output[_out++] = output[from++];
  19644. // } while (--len);
  19645. // continue top;
  19646. // }
  19647. //#endif
  19648. }
  19649. from = 0; // window index
  19650. from_source = window;
  19651. if (wnext === 0) { /* very common case */
  19652. from += wsize - op;
  19653. if (op < len) { /* some from window */
  19654. len -= op;
  19655. do {
  19656. output[_out++] = window[from++];
  19657. } while (--op);
  19658. from = _out - dist; /* rest from output */
  19659. from_source = output;
  19660. }
  19661. }
  19662. else if (wnext < op) { /* wrap around window */
  19663. from += wsize + wnext - op;
  19664. op -= wnext;
  19665. if (op < len) { /* some from end of window */
  19666. len -= op;
  19667. do {
  19668. output[_out++] = window[from++];
  19669. } while (--op);
  19670. from = 0;
  19671. if (wnext < len) { /* some from start of window */
  19672. op = wnext;
  19673. len -= op;
  19674. do {
  19675. output[_out++] = window[from++];
  19676. } while (--op);
  19677. from = _out - dist; /* rest from output */
  19678. from_source = output;
  19679. }
  19680. }
  19681. }
  19682. else { /* contiguous in window */
  19683. from += wnext - op;
  19684. if (op < len) { /* some from window */
  19685. len -= op;
  19686. do {
  19687. output[_out++] = window[from++];
  19688. } while (--op);
  19689. from = _out - dist; /* rest from output */
  19690. from_source = output;
  19691. }
  19692. }
  19693. while (len > 2) {
  19694. output[_out++] = from_source[from++];
  19695. output[_out++] = from_source[from++];
  19696. output[_out++] = from_source[from++];
  19697. len -= 3;
  19698. }
  19699. if (len) {
  19700. output[_out++] = from_source[from++];
  19701. if (len > 1) {
  19702. output[_out++] = from_source[from++];
  19703. }
  19704. }
  19705. }
  19706. else {
  19707. from = _out - dist; /* copy direct from output */
  19708. do { /* minimum length is three */
  19709. output[_out++] = output[from++];
  19710. output[_out++] = output[from++];
  19711. output[_out++] = output[from++];
  19712. len -= 3;
  19713. } while (len > 2);
  19714. if (len) {
  19715. output[_out++] = output[from++];
  19716. if (len > 1) {
  19717. output[_out++] = output[from++];
  19718. }
  19719. }
  19720. }
  19721. }
  19722. else if ((op & 64) === 0) { /* 2nd level distance code */
  19723. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  19724. continue dodist;
  19725. }
  19726. else {
  19727. strm.msg = 'invalid distance code';
  19728. state.mode = BAD;
  19729. break top;
  19730. }
  19731. break; // need to emulate goto via "continue"
  19732. }
  19733. }
  19734. else if ((op & 64) === 0) { /* 2nd level length code */
  19735. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  19736. continue dolen;
  19737. }
  19738. else if (op & 32) { /* end-of-block */
  19739. //Tracevv((stderr, "inflate: end of block\n"));
  19740. state.mode = TYPE;
  19741. break top;
  19742. }
  19743. else {
  19744. strm.msg = 'invalid literal/length code';
  19745. state.mode = BAD;
  19746. break top;
  19747. }
  19748. break; // need to emulate goto via "continue"
  19749. }
  19750. } while (_in < last && _out < end);
  19751. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  19752. len = bits >> 3;
  19753. _in -= len;
  19754. bits -= len << 3;
  19755. hold &= (1 << bits) - 1;
  19756. /* update state and return */
  19757. strm.next_in = _in;
  19758. strm.next_out = _out;
  19759. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  19760. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  19761. state.hold = hold;
  19762. state.bits = bits;
  19763. return;
  19764. };
  19765. },{}],74:[function(require,module,exports){
  19766. 'use strict';
  19767. var utils = require('../utils/common');
  19768. var adler32 = require('./adler32');
  19769. var crc32 = require('./crc32');
  19770. var inflate_fast = require('./inffast');
  19771. var inflate_table = require('./inftrees');
  19772. var CODES = 0;
  19773. var LENS = 1;
  19774. var DISTS = 2;
  19775. /* Public constants ==========================================================*/
  19776. /* ===========================================================================*/
  19777. /* Allowed flush values; see deflate() and inflate() below for details */
  19778. //var Z_NO_FLUSH = 0;
  19779. //var Z_PARTIAL_FLUSH = 1;
  19780. //var Z_SYNC_FLUSH = 2;
  19781. //var Z_FULL_FLUSH = 3;
  19782. var Z_FINISH = 4;
  19783. var Z_BLOCK = 5;
  19784. var Z_TREES = 6;
  19785. /* Return codes for the compression/decompression functions. Negative values
  19786. * are errors, positive values are used for special but normal events.
  19787. */
  19788. var Z_OK = 0;
  19789. var Z_STREAM_END = 1;
  19790. var Z_NEED_DICT = 2;
  19791. //var Z_ERRNO = -1;
  19792. var Z_STREAM_ERROR = -2;
  19793. var Z_DATA_ERROR = -3;
  19794. var Z_MEM_ERROR = -4;
  19795. var Z_BUF_ERROR = -5;
  19796. //var Z_VERSION_ERROR = -6;
  19797. /* The deflate compression method */
  19798. var Z_DEFLATED = 8;
  19799. /* STATES ====================================================================*/
  19800. /* ===========================================================================*/
  19801. var HEAD = 1; /* i: waiting for magic header */
  19802. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  19803. var TIME = 3; /* i: waiting for modification time (gzip) */
  19804. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  19805. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  19806. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  19807. var NAME = 7; /* i: waiting for end of file name (gzip) */
  19808. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  19809. var HCRC = 9; /* i: waiting for header crc (gzip) */
  19810. var DICTID = 10; /* i: waiting for dictionary check value */
  19811. var DICT = 11; /* waiting for inflateSetDictionary() call */
  19812. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  19813. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  19814. var STORED = 14; /* i: waiting for stored size (length and complement) */
  19815. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  19816. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  19817. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  19818. var LENLENS = 18; /* i: waiting for code length code lengths */
  19819. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  19820. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  19821. var LEN = 21; /* i: waiting for length/lit/eob code */
  19822. var LENEXT = 22; /* i: waiting for length extra bits */
  19823. var DIST = 23; /* i: waiting for distance code */
  19824. var DISTEXT = 24; /* i: waiting for distance extra bits */
  19825. var MATCH = 25; /* o: waiting for output space to copy string */
  19826. var LIT = 26; /* o: waiting for output space to write literal */
  19827. var CHECK = 27; /* i: waiting for 32-bit check value */
  19828. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  19829. var DONE = 29; /* finished check, done -- remain here until reset */
  19830. var BAD = 30; /* got a data error -- remain here until reset */
  19831. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  19832. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  19833. /* ===========================================================================*/
  19834. var ENOUGH_LENS = 852;
  19835. var ENOUGH_DISTS = 592;
  19836. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  19837. var MAX_WBITS = 15;
  19838. /* 32K LZ77 window */
  19839. var DEF_WBITS = MAX_WBITS;
  19840. function ZSWAP32(q) {
  19841. return (((q >>> 24) & 0xff) +
  19842. ((q >>> 8) & 0xff00) +
  19843. ((q & 0xff00) << 8) +
  19844. ((q & 0xff) << 24));
  19845. }
  19846. function InflateState() {
  19847. this.mode = 0; /* current inflate mode */
  19848. this.last = false; /* true if processing last block */
  19849. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  19850. this.havedict = false; /* true if dictionary provided */
  19851. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  19852. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  19853. this.check = 0; /* protected copy of check value */
  19854. this.total = 0; /* protected copy of output count */
  19855. // TODO: may be {}
  19856. this.head = null; /* where to save gzip header information */
  19857. /* sliding window */
  19858. this.wbits = 0; /* log base 2 of requested window size */
  19859. this.wsize = 0; /* window size or zero if not using window */
  19860. this.whave = 0; /* valid bytes in the window */
  19861. this.wnext = 0; /* window write index */
  19862. this.window = null; /* allocated sliding window, if needed */
  19863. /* bit accumulator */
  19864. this.hold = 0; /* input bit accumulator */
  19865. this.bits = 0; /* number of bits in "in" */
  19866. /* for string and stored block copying */
  19867. this.length = 0; /* literal or length of data to copy */
  19868. this.offset = 0; /* distance back to copy string from */
  19869. /* for table and code decoding */
  19870. this.extra = 0; /* extra bits needed */
  19871. /* fixed and dynamic code tables */
  19872. this.lencode = null; /* starting table for length/literal codes */
  19873. this.distcode = null; /* starting table for distance codes */
  19874. this.lenbits = 0; /* index bits for lencode */
  19875. this.distbits = 0; /* index bits for distcode */
  19876. /* dynamic table building */
  19877. this.ncode = 0; /* number of code length code lengths */
  19878. this.nlen = 0; /* number of length code lengths */
  19879. this.ndist = 0; /* number of distance code lengths */
  19880. this.have = 0; /* number of code lengths in lens[] */
  19881. this.next = null; /* next available space in codes[] */
  19882. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  19883. this.work = new utils.Buf16(288); /* work area for code table building */
  19884. /*
  19885. because we don't have pointers in js, we use lencode and distcode directly
  19886. as buffers so we don't need codes
  19887. */
  19888. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  19889. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  19890. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  19891. this.sane = 0; /* if false, allow invalid distance too far */
  19892. this.back = 0; /* bits back of last unprocessed length/lit */
  19893. this.was = 0; /* initial length of match */
  19894. }
  19895. function inflateResetKeep(strm) {
  19896. var state;
  19897. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19898. state = strm.state;
  19899. strm.total_in = strm.total_out = state.total = 0;
  19900. strm.msg = ''; /*Z_NULL*/
  19901. if (state.wrap) { /* to support ill-conceived Java test suite */
  19902. strm.adler = state.wrap & 1;
  19903. }
  19904. state.mode = HEAD;
  19905. state.last = 0;
  19906. state.havedict = 0;
  19907. state.dmax = 32768;
  19908. state.head = null/*Z_NULL*/;
  19909. state.hold = 0;
  19910. state.bits = 0;
  19911. //state.lencode = state.distcode = state.next = state.codes;
  19912. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  19913. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  19914. state.sane = 1;
  19915. state.back = -1;
  19916. //Tracev((stderr, "inflate: reset\n"));
  19917. return Z_OK;
  19918. }
  19919. function inflateReset(strm) {
  19920. var state;
  19921. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19922. state = strm.state;
  19923. state.wsize = 0;
  19924. state.whave = 0;
  19925. state.wnext = 0;
  19926. return inflateResetKeep(strm);
  19927. }
  19928. function inflateReset2(strm, windowBits) {
  19929. var wrap;
  19930. var state;
  19931. /* get the state */
  19932. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19933. state = strm.state;
  19934. /* extract wrap request from windowBits parameter */
  19935. if (windowBits < 0) {
  19936. wrap = 0;
  19937. windowBits = -windowBits;
  19938. }
  19939. else {
  19940. wrap = (windowBits >> 4) + 1;
  19941. if (windowBits < 48) {
  19942. windowBits &= 15;
  19943. }
  19944. }
  19945. /* set number of window bits, free window if different */
  19946. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  19947. return Z_STREAM_ERROR;
  19948. }
  19949. if (state.window !== null && state.wbits !== windowBits) {
  19950. state.window = null;
  19951. }
  19952. /* update state and reset the rest of it */
  19953. state.wrap = wrap;
  19954. state.wbits = windowBits;
  19955. return inflateReset(strm);
  19956. }
  19957. function inflateInit2(strm, windowBits) {
  19958. var ret;
  19959. var state;
  19960. if (!strm) { return Z_STREAM_ERROR; }
  19961. //strm.msg = Z_NULL; /* in case we return an error */
  19962. state = new InflateState();
  19963. //if (state === Z_NULL) return Z_MEM_ERROR;
  19964. //Tracev((stderr, "inflate: allocated\n"));
  19965. strm.state = state;
  19966. state.window = null/*Z_NULL*/;
  19967. ret = inflateReset2(strm, windowBits);
  19968. if (ret !== Z_OK) {
  19969. strm.state = null/*Z_NULL*/;
  19970. }
  19971. return ret;
  19972. }
  19973. function inflateInit(strm) {
  19974. return inflateInit2(strm, DEF_WBITS);
  19975. }
  19976. /*
  19977. Return state with length and distance decoding tables and index sizes set to
  19978. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  19979. If BUILDFIXED is defined, then instead this routine builds the tables the
  19980. first time it's called, and returns those tables the first time and
  19981. thereafter. This reduces the size of the code by about 2K bytes, in
  19982. exchange for a little execution time. However, BUILDFIXED should not be
  19983. used for threaded applications, since the rewriting of the tables and virgin
  19984. may not be thread-safe.
  19985. */
  19986. var virgin = true;
  19987. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  19988. function fixedtables(state) {
  19989. /* build fixed huffman tables if first call (may not be thread safe) */
  19990. if (virgin) {
  19991. var sym;
  19992. lenfix = new utils.Buf32(512);
  19993. distfix = new utils.Buf32(32);
  19994. /* literal/length table */
  19995. sym = 0;
  19996. while (sym < 144) { state.lens[sym++] = 8; }
  19997. while (sym < 256) { state.lens[sym++] = 9; }
  19998. while (sym < 280) { state.lens[sym++] = 7; }
  19999. while (sym < 288) { state.lens[sym++] = 8; }
  20000. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  20001. /* distance table */
  20002. sym = 0;
  20003. while (sym < 32) { state.lens[sym++] = 5; }
  20004. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  20005. /* do this just once */
  20006. virgin = false;
  20007. }
  20008. state.lencode = lenfix;
  20009. state.lenbits = 9;
  20010. state.distcode = distfix;
  20011. state.distbits = 5;
  20012. }
  20013. /*
  20014. Update the window with the last wsize (normally 32K) bytes written before
  20015. returning. If window does not exist yet, create it. This is only called
  20016. when a window is already in use, or when output has been written during this
  20017. inflate call, but the end of the deflate stream has not been reached yet.
  20018. It is also called to create a window for dictionary data when a dictionary
  20019. is loaded.
  20020. Providing output buffers larger than 32K to inflate() should provide a speed
  20021. advantage, since only the last 32K of output is copied to the sliding window
  20022. upon return from inflate(), and since all distances after the first 32K of
  20023. output will fall in the output data, making match copies simpler and faster.
  20024. The advantage may be dependent on the size of the processor's data caches.
  20025. */
  20026. function updatewindow(strm, src, end, copy) {
  20027. var dist;
  20028. var state = strm.state;
  20029. /* if it hasn't been done already, allocate space for the window */
  20030. if (state.window === null) {
  20031. state.wsize = 1 << state.wbits;
  20032. state.wnext = 0;
  20033. state.whave = 0;
  20034. state.window = new utils.Buf8(state.wsize);
  20035. }
  20036. /* copy state->wsize or less output bytes into the circular window */
  20037. if (copy >= state.wsize) {
  20038. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  20039. state.wnext = 0;
  20040. state.whave = state.wsize;
  20041. }
  20042. else {
  20043. dist = state.wsize - state.wnext;
  20044. if (dist > copy) {
  20045. dist = copy;
  20046. }
  20047. //zmemcpy(state->window + state->wnext, end - copy, dist);
  20048. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  20049. copy -= dist;
  20050. if (copy) {
  20051. //zmemcpy(state->window, end - copy, copy);
  20052. utils.arraySet(state.window,src, end - copy, copy, 0);
  20053. state.wnext = copy;
  20054. state.whave = state.wsize;
  20055. }
  20056. else {
  20057. state.wnext += dist;
  20058. if (state.wnext === state.wsize) { state.wnext = 0; }
  20059. if (state.whave < state.wsize) { state.whave += dist; }
  20060. }
  20061. }
  20062. return 0;
  20063. }
  20064. function inflate(strm, flush) {
  20065. var state;
  20066. var input, output; // input/output buffers
  20067. var next; /* next input INDEX */
  20068. var put; /* next output INDEX */
  20069. var have, left; /* available input and output */
  20070. var hold; /* bit buffer */
  20071. var bits; /* bits in bit buffer */
  20072. var _in, _out; /* save starting available input and output */
  20073. var copy; /* number of stored or match bytes to copy */
  20074. var from; /* where to copy match bytes from */
  20075. var from_source;
  20076. var here = 0; /* current decoding table entry */
  20077. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  20078. //var last; /* parent table entry */
  20079. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  20080. var len; /* length to copy for repeats, bits to drop */
  20081. var ret; /* return code */
  20082. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  20083. var opts;
  20084. var n; // temporary var for NEED_BITS
  20085. var order = /* permutation of code lengths */
  20086. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  20087. if (!strm || !strm.state || !strm.output ||
  20088. (!strm.input && strm.avail_in !== 0)) {
  20089. return Z_STREAM_ERROR;
  20090. }
  20091. state = strm.state;
  20092. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  20093. //--- LOAD() ---
  20094. put = strm.next_out;
  20095. output = strm.output;
  20096. left = strm.avail_out;
  20097. next = strm.next_in;
  20098. input = strm.input;
  20099. have = strm.avail_in;
  20100. hold = state.hold;
  20101. bits = state.bits;
  20102. //---
  20103. _in = have;
  20104. _out = left;
  20105. ret = Z_OK;
  20106. inf_leave: // goto emulation
  20107. for (;;) {
  20108. switch (state.mode) {
  20109. case HEAD:
  20110. if (state.wrap === 0) {
  20111. state.mode = TYPEDO;
  20112. break;
  20113. }
  20114. //=== NEEDBITS(16);
  20115. while (bits < 16) {
  20116. if (have === 0) { break inf_leave; }
  20117. have--;
  20118. hold += input[next++] << bits;
  20119. bits += 8;
  20120. }
  20121. //===//
  20122. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  20123. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  20124. //=== CRC2(state.check, hold);
  20125. hbuf[0] = hold & 0xff;
  20126. hbuf[1] = (hold >>> 8) & 0xff;
  20127. state.check = crc32(state.check, hbuf, 2, 0);
  20128. //===//
  20129. //=== INITBITS();
  20130. hold = 0;
  20131. bits = 0;
  20132. //===//
  20133. state.mode = FLAGS;
  20134. break;
  20135. }
  20136. state.flags = 0; /* expect zlib header */
  20137. if (state.head) {
  20138. state.head.done = false;
  20139. }
  20140. if (!(state.wrap & 1) || /* check if zlib header allowed */
  20141. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  20142. strm.msg = 'incorrect header check';
  20143. state.mode = BAD;
  20144. break;
  20145. }
  20146. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  20147. strm.msg = 'unknown compression method';
  20148. state.mode = BAD;
  20149. break;
  20150. }
  20151. //--- DROPBITS(4) ---//
  20152. hold >>>= 4;
  20153. bits -= 4;
  20154. //---//
  20155. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  20156. if (state.wbits === 0) {
  20157. state.wbits = len;
  20158. }
  20159. else if (len > state.wbits) {
  20160. strm.msg = 'invalid window size';
  20161. state.mode = BAD;
  20162. break;
  20163. }
  20164. state.dmax = 1 << len;
  20165. //Tracev((stderr, "inflate: zlib header ok\n"));
  20166. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  20167. state.mode = hold & 0x200 ? DICTID : TYPE;
  20168. //=== INITBITS();
  20169. hold = 0;
  20170. bits = 0;
  20171. //===//
  20172. break;
  20173. case FLAGS:
  20174. //=== NEEDBITS(16); */
  20175. while (bits < 16) {
  20176. if (have === 0) { break inf_leave; }
  20177. have--;
  20178. hold += input[next++] << bits;
  20179. bits += 8;
  20180. }
  20181. //===//
  20182. state.flags = hold;
  20183. if ((state.flags & 0xff) !== Z_DEFLATED) {
  20184. strm.msg = 'unknown compression method';
  20185. state.mode = BAD;
  20186. break;
  20187. }
  20188. if (state.flags & 0xe000) {
  20189. strm.msg = 'unknown header flags set';
  20190. state.mode = BAD;
  20191. break;
  20192. }
  20193. if (state.head) {
  20194. state.head.text = ((hold >> 8) & 1);
  20195. }
  20196. if (state.flags & 0x0200) {
  20197. //=== CRC2(state.check, hold);
  20198. hbuf[0] = hold & 0xff;
  20199. hbuf[1] = (hold >>> 8) & 0xff;
  20200. state.check = crc32(state.check, hbuf, 2, 0);
  20201. //===//
  20202. }
  20203. //=== INITBITS();
  20204. hold = 0;
  20205. bits = 0;
  20206. //===//
  20207. state.mode = TIME;
  20208. /* falls through */
  20209. case TIME:
  20210. //=== NEEDBITS(32); */
  20211. while (bits < 32) {
  20212. if (have === 0) { break inf_leave; }
  20213. have--;
  20214. hold += input[next++] << bits;
  20215. bits += 8;
  20216. }
  20217. //===//
  20218. if (state.head) {
  20219. state.head.time = hold;
  20220. }
  20221. if (state.flags & 0x0200) {
  20222. //=== CRC4(state.check, hold)
  20223. hbuf[0] = hold & 0xff;
  20224. hbuf[1] = (hold >>> 8) & 0xff;
  20225. hbuf[2] = (hold >>> 16) & 0xff;
  20226. hbuf[3] = (hold >>> 24) & 0xff;
  20227. state.check = crc32(state.check, hbuf, 4, 0);
  20228. //===
  20229. }
  20230. //=== INITBITS();
  20231. hold = 0;
  20232. bits = 0;
  20233. //===//
  20234. state.mode = OS;
  20235. /* falls through */
  20236. case OS:
  20237. //=== NEEDBITS(16); */
  20238. while (bits < 16) {
  20239. if (have === 0) { break inf_leave; }
  20240. have--;
  20241. hold += input[next++] << bits;
  20242. bits += 8;
  20243. }
  20244. //===//
  20245. if (state.head) {
  20246. state.head.xflags = (hold & 0xff);
  20247. state.head.os = (hold >> 8);
  20248. }
  20249. if (state.flags & 0x0200) {
  20250. //=== CRC2(state.check, hold);
  20251. hbuf[0] = hold & 0xff;
  20252. hbuf[1] = (hold >>> 8) & 0xff;
  20253. state.check = crc32(state.check, hbuf, 2, 0);
  20254. //===//
  20255. }
  20256. //=== INITBITS();
  20257. hold = 0;
  20258. bits = 0;
  20259. //===//
  20260. state.mode = EXLEN;
  20261. /* falls through */
  20262. case EXLEN:
  20263. if (state.flags & 0x0400) {
  20264. //=== NEEDBITS(16); */
  20265. while (bits < 16) {
  20266. if (have === 0) { break inf_leave; }
  20267. have--;
  20268. hold += input[next++] << bits;
  20269. bits += 8;
  20270. }
  20271. //===//
  20272. state.length = hold;
  20273. if (state.head) {
  20274. state.head.extra_len = hold;
  20275. }
  20276. if (state.flags & 0x0200) {
  20277. //=== CRC2(state.check, hold);
  20278. hbuf[0] = hold & 0xff;
  20279. hbuf[1] = (hold >>> 8) & 0xff;
  20280. state.check = crc32(state.check, hbuf, 2, 0);
  20281. //===//
  20282. }
  20283. //=== INITBITS();
  20284. hold = 0;
  20285. bits = 0;
  20286. //===//
  20287. }
  20288. else if (state.head) {
  20289. state.head.extra = null/*Z_NULL*/;
  20290. }
  20291. state.mode = EXTRA;
  20292. /* falls through */
  20293. case EXTRA:
  20294. if (state.flags & 0x0400) {
  20295. copy = state.length;
  20296. if (copy > have) { copy = have; }
  20297. if (copy) {
  20298. if (state.head) {
  20299. len = state.head.extra_len - state.length;
  20300. if (!state.head.extra) {
  20301. // Use untyped array for more conveniend processing later
  20302. state.head.extra = new Array(state.head.extra_len);
  20303. }
  20304. utils.arraySet(
  20305. state.head.extra,
  20306. input,
  20307. next,
  20308. // extra field is limited to 65536 bytes
  20309. // - no need for additional size check
  20310. copy,
  20311. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  20312. len
  20313. );
  20314. //zmemcpy(state.head.extra + len, next,
  20315. // len + copy > state.head.extra_max ?
  20316. // state.head.extra_max - len : copy);
  20317. }
  20318. if (state.flags & 0x0200) {
  20319. state.check = crc32(state.check, input, copy, next);
  20320. }
  20321. have -= copy;
  20322. next += copy;
  20323. state.length -= copy;
  20324. }
  20325. if (state.length) { break inf_leave; }
  20326. }
  20327. state.length = 0;
  20328. state.mode = NAME;
  20329. /* falls through */
  20330. case NAME:
  20331. if (state.flags & 0x0800) {
  20332. if (have === 0) { break inf_leave; }
  20333. copy = 0;
  20334. do {
  20335. // TODO: 2 or 1 bytes?
  20336. len = input[next + copy++];
  20337. /* use constant limit because in js we should not preallocate memory */
  20338. if (state.head && len &&
  20339. (state.length < 65536 /*state.head.name_max*/)) {
  20340. state.head.name += String.fromCharCode(len);
  20341. }
  20342. } while (len && copy < have);
  20343. if (state.flags & 0x0200) {
  20344. state.check = crc32(state.check, input, copy, next);
  20345. }
  20346. have -= copy;
  20347. next += copy;
  20348. if (len) { break inf_leave; }
  20349. }
  20350. else if (state.head) {
  20351. state.head.name = null;
  20352. }
  20353. state.length = 0;
  20354. state.mode = COMMENT;
  20355. /* falls through */
  20356. case COMMENT:
  20357. if (state.flags & 0x1000) {
  20358. if (have === 0) { break inf_leave; }
  20359. copy = 0;
  20360. do {
  20361. len = input[next + copy++];
  20362. /* use constant limit because in js we should not preallocate memory */
  20363. if (state.head && len &&
  20364. (state.length < 65536 /*state.head.comm_max*/)) {
  20365. state.head.comment += String.fromCharCode(len);
  20366. }
  20367. } while (len && copy < have);
  20368. if (state.flags & 0x0200) {
  20369. state.check = crc32(state.check, input, copy, next);
  20370. }
  20371. have -= copy;
  20372. next += copy;
  20373. if (len) { break inf_leave; }
  20374. }
  20375. else if (state.head) {
  20376. state.head.comment = null;
  20377. }
  20378. state.mode = HCRC;
  20379. /* falls through */
  20380. case HCRC:
  20381. if (state.flags & 0x0200) {
  20382. //=== NEEDBITS(16); */
  20383. while (bits < 16) {
  20384. if (have === 0) { break inf_leave; }
  20385. have--;
  20386. hold += input[next++] << bits;
  20387. bits += 8;
  20388. }
  20389. //===//
  20390. if (hold !== (state.check & 0xffff)) {
  20391. strm.msg = 'header crc mismatch';
  20392. state.mode = BAD;
  20393. break;
  20394. }
  20395. //=== INITBITS();
  20396. hold = 0;
  20397. bits = 0;
  20398. //===//
  20399. }
  20400. if (state.head) {
  20401. state.head.hcrc = ((state.flags >> 9) & 1);
  20402. state.head.done = true;
  20403. }
  20404. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  20405. state.mode = TYPE;
  20406. break;
  20407. case DICTID:
  20408. //=== NEEDBITS(32); */
  20409. while (bits < 32) {
  20410. if (have === 0) { break inf_leave; }
  20411. have--;
  20412. hold += input[next++] << bits;
  20413. bits += 8;
  20414. }
  20415. //===//
  20416. strm.adler = state.check = ZSWAP32(hold);
  20417. //=== INITBITS();
  20418. hold = 0;
  20419. bits = 0;
  20420. //===//
  20421. state.mode = DICT;
  20422. /* falls through */
  20423. case DICT:
  20424. if (state.havedict === 0) {
  20425. //--- RESTORE() ---
  20426. strm.next_out = put;
  20427. strm.avail_out = left;
  20428. strm.next_in = next;
  20429. strm.avail_in = have;
  20430. state.hold = hold;
  20431. state.bits = bits;
  20432. //---
  20433. return Z_NEED_DICT;
  20434. }
  20435. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  20436. state.mode = TYPE;
  20437. /* falls through */
  20438. case TYPE:
  20439. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  20440. /* falls through */
  20441. case TYPEDO:
  20442. if (state.last) {
  20443. //--- BYTEBITS() ---//
  20444. hold >>>= bits & 7;
  20445. bits -= bits & 7;
  20446. //---//
  20447. state.mode = CHECK;
  20448. break;
  20449. }
  20450. //=== NEEDBITS(3); */
  20451. while (bits < 3) {
  20452. if (have === 0) { break inf_leave; }
  20453. have--;
  20454. hold += input[next++] << bits;
  20455. bits += 8;
  20456. }
  20457. //===//
  20458. state.last = (hold & 0x01)/*BITS(1)*/;
  20459. //--- DROPBITS(1) ---//
  20460. hold >>>= 1;
  20461. bits -= 1;
  20462. //---//
  20463. switch ((hold & 0x03)/*BITS(2)*/) {
  20464. case 0: /* stored block */
  20465. //Tracev((stderr, "inflate: stored block%s\n",
  20466. // state.last ? " (last)" : ""));
  20467. state.mode = STORED;
  20468. break;
  20469. case 1: /* fixed block */
  20470. fixedtables(state);
  20471. //Tracev((stderr, "inflate: fixed codes block%s\n",
  20472. // state.last ? " (last)" : ""));
  20473. state.mode = LEN_; /* decode codes */
  20474. if (flush === Z_TREES) {
  20475. //--- DROPBITS(2) ---//
  20476. hold >>>= 2;
  20477. bits -= 2;
  20478. //---//
  20479. break inf_leave;
  20480. }
  20481. break;
  20482. case 2: /* dynamic block */
  20483. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  20484. // state.last ? " (last)" : ""));
  20485. state.mode = TABLE;
  20486. break;
  20487. case 3:
  20488. strm.msg = 'invalid block type';
  20489. state.mode = BAD;
  20490. }
  20491. //--- DROPBITS(2) ---//
  20492. hold >>>= 2;
  20493. bits -= 2;
  20494. //---//
  20495. break;
  20496. case STORED:
  20497. //--- BYTEBITS() ---// /* go to byte boundary */
  20498. hold >>>= bits & 7;
  20499. bits -= bits & 7;
  20500. //---//
  20501. //=== NEEDBITS(32); */
  20502. while (bits < 32) {
  20503. if (have === 0) { break inf_leave; }
  20504. have--;
  20505. hold += input[next++] << bits;
  20506. bits += 8;
  20507. }
  20508. //===//
  20509. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  20510. strm.msg = 'invalid stored block lengths';
  20511. state.mode = BAD;
  20512. break;
  20513. }
  20514. state.length = hold & 0xffff;
  20515. //Tracev((stderr, "inflate: stored length %u\n",
  20516. // state.length));
  20517. //=== INITBITS();
  20518. hold = 0;
  20519. bits = 0;
  20520. //===//
  20521. state.mode = COPY_;
  20522. if (flush === Z_TREES) { break inf_leave; }
  20523. /* falls through */
  20524. case COPY_:
  20525. state.mode = COPY;
  20526. /* falls through */
  20527. case COPY:
  20528. copy = state.length;
  20529. if (copy) {
  20530. if (copy > have) { copy = have; }
  20531. if (copy > left) { copy = left; }
  20532. if (copy === 0) { break inf_leave; }
  20533. //--- zmemcpy(put, next, copy); ---
  20534. utils.arraySet(output, input, next, copy, put);
  20535. //---//
  20536. have -= copy;
  20537. next += copy;
  20538. left -= copy;
  20539. put += copy;
  20540. state.length -= copy;
  20541. break;
  20542. }
  20543. //Tracev((stderr, "inflate: stored end\n"));
  20544. state.mode = TYPE;
  20545. break;
  20546. case TABLE:
  20547. //=== NEEDBITS(14); */
  20548. while (bits < 14) {
  20549. if (have === 0) { break inf_leave; }
  20550. have--;
  20551. hold += input[next++] << bits;
  20552. bits += 8;
  20553. }
  20554. //===//
  20555. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  20556. //--- DROPBITS(5) ---//
  20557. hold >>>= 5;
  20558. bits -= 5;
  20559. //---//
  20560. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  20561. //--- DROPBITS(5) ---//
  20562. hold >>>= 5;
  20563. bits -= 5;
  20564. //---//
  20565. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  20566. //--- DROPBITS(4) ---//
  20567. hold >>>= 4;
  20568. bits -= 4;
  20569. //---//
  20570. //#ifndef PKZIP_BUG_WORKAROUND
  20571. if (state.nlen > 286 || state.ndist > 30) {
  20572. strm.msg = 'too many length or distance symbols';
  20573. state.mode = BAD;
  20574. break;
  20575. }
  20576. //#endif
  20577. //Tracev((stderr, "inflate: table sizes ok\n"));
  20578. state.have = 0;
  20579. state.mode = LENLENS;
  20580. /* falls through */
  20581. case LENLENS:
  20582. while (state.have < state.ncode) {
  20583. //=== NEEDBITS(3);
  20584. while (bits < 3) {
  20585. if (have === 0) { break inf_leave; }
  20586. have--;
  20587. hold += input[next++] << bits;
  20588. bits += 8;
  20589. }
  20590. //===//
  20591. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  20592. //--- DROPBITS(3) ---//
  20593. hold >>>= 3;
  20594. bits -= 3;
  20595. //---//
  20596. }
  20597. while (state.have < 19) {
  20598. state.lens[order[state.have++]] = 0;
  20599. }
  20600. // We have separate tables & no pointers. 2 commented lines below not needed.
  20601. //state.next = state.codes;
  20602. //state.lencode = state.next;
  20603. // Switch to use dynamic table
  20604. state.lencode = state.lendyn;
  20605. state.lenbits = 7;
  20606. opts = {bits: state.lenbits};
  20607. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  20608. state.lenbits = opts.bits;
  20609. if (ret) {
  20610. strm.msg = 'invalid code lengths set';
  20611. state.mode = BAD;
  20612. break;
  20613. }
  20614. //Tracev((stderr, "inflate: code lengths ok\n"));
  20615. state.have = 0;
  20616. state.mode = CODELENS;
  20617. /* falls through */
  20618. case CODELENS:
  20619. while (state.have < state.nlen + state.ndist) {
  20620. for (;;) {
  20621. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  20622. here_bits = here >>> 24;
  20623. here_op = (here >>> 16) & 0xff;
  20624. here_val = here & 0xffff;
  20625. if ((here_bits) <= bits) { break; }
  20626. //--- PULLBYTE() ---//
  20627. if (have === 0) { break inf_leave; }
  20628. have--;
  20629. hold += input[next++] << bits;
  20630. bits += 8;
  20631. //---//
  20632. }
  20633. if (here_val < 16) {
  20634. //--- DROPBITS(here.bits) ---//
  20635. hold >>>= here_bits;
  20636. bits -= here_bits;
  20637. //---//
  20638. state.lens[state.have++] = here_val;
  20639. }
  20640. else {
  20641. if (here_val === 16) {
  20642. //=== NEEDBITS(here.bits + 2);
  20643. n = here_bits + 2;
  20644. while (bits < n) {
  20645. if (have === 0) { break inf_leave; }
  20646. have--;
  20647. hold += input[next++] << bits;
  20648. bits += 8;
  20649. }
  20650. //===//
  20651. //--- DROPBITS(here.bits) ---//
  20652. hold >>>= here_bits;
  20653. bits -= here_bits;
  20654. //---//
  20655. if (state.have === 0) {
  20656. strm.msg = 'invalid bit length repeat';
  20657. state.mode = BAD;
  20658. break;
  20659. }
  20660. len = state.lens[state.have - 1];
  20661. copy = 3 + (hold & 0x03);//BITS(2);
  20662. //--- DROPBITS(2) ---//
  20663. hold >>>= 2;
  20664. bits -= 2;
  20665. //---//
  20666. }
  20667. else if (here_val === 17) {
  20668. //=== NEEDBITS(here.bits + 3);
  20669. n = here_bits + 3;
  20670. while (bits < n) {
  20671. if (have === 0) { break inf_leave; }
  20672. have--;
  20673. hold += input[next++] << bits;
  20674. bits += 8;
  20675. }
  20676. //===//
  20677. //--- DROPBITS(here.bits) ---//
  20678. hold >>>= here_bits;
  20679. bits -= here_bits;
  20680. //---//
  20681. len = 0;
  20682. copy = 3 + (hold & 0x07);//BITS(3);
  20683. //--- DROPBITS(3) ---//
  20684. hold >>>= 3;
  20685. bits -= 3;
  20686. //---//
  20687. }
  20688. else {
  20689. //=== NEEDBITS(here.bits + 7);
  20690. n = here_bits + 7;
  20691. while (bits < n) {
  20692. if (have === 0) { break inf_leave; }
  20693. have--;
  20694. hold += input[next++] << bits;
  20695. bits += 8;
  20696. }
  20697. //===//
  20698. //--- DROPBITS(here.bits) ---//
  20699. hold >>>= here_bits;
  20700. bits -= here_bits;
  20701. //---//
  20702. len = 0;
  20703. copy = 11 + (hold & 0x7f);//BITS(7);
  20704. //--- DROPBITS(7) ---//
  20705. hold >>>= 7;
  20706. bits -= 7;
  20707. //---//
  20708. }
  20709. if (state.have + copy > state.nlen + state.ndist) {
  20710. strm.msg = 'invalid bit length repeat';
  20711. state.mode = BAD;
  20712. break;
  20713. }
  20714. while (copy--) {
  20715. state.lens[state.have++] = len;
  20716. }
  20717. }
  20718. }
  20719. /* handle error breaks in while */
  20720. if (state.mode === BAD) { break; }
  20721. /* check for end-of-block code (better have one) */
  20722. if (state.lens[256] === 0) {
  20723. strm.msg = 'invalid code -- missing end-of-block';
  20724. state.mode = BAD;
  20725. break;
  20726. }
  20727. /* build code tables -- note: do not change the lenbits or distbits
  20728. values here (9 and 6) without reading the comments in inftrees.h
  20729. concerning the ENOUGH constants, which depend on those values */
  20730. state.lenbits = 9;
  20731. opts = {bits: state.lenbits};
  20732. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  20733. // We have separate tables & no pointers. 2 commented lines below not needed.
  20734. // state.next_index = opts.table_index;
  20735. state.lenbits = opts.bits;
  20736. // state.lencode = state.next;
  20737. if (ret) {
  20738. strm.msg = 'invalid literal/lengths set';
  20739. state.mode = BAD;
  20740. break;
  20741. }
  20742. state.distbits = 6;
  20743. //state.distcode.copy(state.codes);
  20744. // Switch to use dynamic table
  20745. state.distcode = state.distdyn;
  20746. opts = {bits: state.distbits};
  20747. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  20748. // We have separate tables & no pointers. 2 commented lines below not needed.
  20749. // state.next_index = opts.table_index;
  20750. state.distbits = opts.bits;
  20751. // state.distcode = state.next;
  20752. if (ret) {
  20753. strm.msg = 'invalid distances set';
  20754. state.mode = BAD;
  20755. break;
  20756. }
  20757. //Tracev((stderr, 'inflate: codes ok\n'));
  20758. state.mode = LEN_;
  20759. if (flush === Z_TREES) { break inf_leave; }
  20760. /* falls through */
  20761. case LEN_:
  20762. state.mode = LEN;
  20763. /* falls through */
  20764. case LEN:
  20765. if (have >= 6 && left >= 258) {
  20766. //--- RESTORE() ---
  20767. strm.next_out = put;
  20768. strm.avail_out = left;
  20769. strm.next_in = next;
  20770. strm.avail_in = have;
  20771. state.hold = hold;
  20772. state.bits = bits;
  20773. //---
  20774. inflate_fast(strm, _out);
  20775. //--- LOAD() ---
  20776. put = strm.next_out;
  20777. output = strm.output;
  20778. left = strm.avail_out;
  20779. next = strm.next_in;
  20780. input = strm.input;
  20781. have = strm.avail_in;
  20782. hold = state.hold;
  20783. bits = state.bits;
  20784. //---
  20785. if (state.mode === TYPE) {
  20786. state.back = -1;
  20787. }
  20788. break;
  20789. }
  20790. state.back = 0;
  20791. for (;;) {
  20792. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  20793. here_bits = here >>> 24;
  20794. here_op = (here >>> 16) & 0xff;
  20795. here_val = here & 0xffff;
  20796. if (here_bits <= bits) { break; }
  20797. //--- PULLBYTE() ---//
  20798. if (have === 0) { break inf_leave; }
  20799. have--;
  20800. hold += input[next++] << bits;
  20801. bits += 8;
  20802. //---//
  20803. }
  20804. if (here_op && (here_op & 0xf0) === 0) {
  20805. last_bits = here_bits;
  20806. last_op = here_op;
  20807. last_val = here_val;
  20808. for (;;) {
  20809. here = state.lencode[last_val +
  20810. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  20811. here_bits = here >>> 24;
  20812. here_op = (here >>> 16) & 0xff;
  20813. here_val = here & 0xffff;
  20814. if ((last_bits + here_bits) <= bits) { break; }
  20815. //--- PULLBYTE() ---//
  20816. if (have === 0) { break inf_leave; }
  20817. have--;
  20818. hold += input[next++] << bits;
  20819. bits += 8;
  20820. //---//
  20821. }
  20822. //--- DROPBITS(last.bits) ---//
  20823. hold >>>= last_bits;
  20824. bits -= last_bits;
  20825. //---//
  20826. state.back += last_bits;
  20827. }
  20828. //--- DROPBITS(here.bits) ---//
  20829. hold >>>= here_bits;
  20830. bits -= here_bits;
  20831. //---//
  20832. state.back += here_bits;
  20833. state.length = here_val;
  20834. if (here_op === 0) {
  20835. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  20836. // "inflate: literal '%c'\n" :
  20837. // "inflate: literal 0x%02x\n", here.val));
  20838. state.mode = LIT;
  20839. break;
  20840. }
  20841. if (here_op & 32) {
  20842. //Tracevv((stderr, "inflate: end of block\n"));
  20843. state.back = -1;
  20844. state.mode = TYPE;
  20845. break;
  20846. }
  20847. if (here_op & 64) {
  20848. strm.msg = 'invalid literal/length code';
  20849. state.mode = BAD;
  20850. break;
  20851. }
  20852. state.extra = here_op & 15;
  20853. state.mode = LENEXT;
  20854. /* falls through */
  20855. case LENEXT:
  20856. if (state.extra) {
  20857. //=== NEEDBITS(state.extra);
  20858. n = state.extra;
  20859. while (bits < n) {
  20860. if (have === 0) { break inf_leave; }
  20861. have--;
  20862. hold += input[next++] << bits;
  20863. bits += 8;
  20864. }
  20865. //===//
  20866. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  20867. //--- DROPBITS(state.extra) ---//
  20868. hold >>>= state.extra;
  20869. bits -= state.extra;
  20870. //---//
  20871. state.back += state.extra;
  20872. }
  20873. //Tracevv((stderr, "inflate: length %u\n", state.length));
  20874. state.was = state.length;
  20875. state.mode = DIST;
  20876. /* falls through */
  20877. case DIST:
  20878. for (;;) {
  20879. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  20880. here_bits = here >>> 24;
  20881. here_op = (here >>> 16) & 0xff;
  20882. here_val = here & 0xffff;
  20883. if ((here_bits) <= bits) { break; }
  20884. //--- PULLBYTE() ---//
  20885. if (have === 0) { break inf_leave; }
  20886. have--;
  20887. hold += input[next++] << bits;
  20888. bits += 8;
  20889. //---//
  20890. }
  20891. if ((here_op & 0xf0) === 0) {
  20892. last_bits = here_bits;
  20893. last_op = here_op;
  20894. last_val = here_val;
  20895. for (;;) {
  20896. here = state.distcode[last_val +
  20897. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  20898. here_bits = here >>> 24;
  20899. here_op = (here >>> 16) & 0xff;
  20900. here_val = here & 0xffff;
  20901. if ((last_bits + here_bits) <= bits) { break; }
  20902. //--- PULLBYTE() ---//
  20903. if (have === 0) { break inf_leave; }
  20904. have--;
  20905. hold += input[next++] << bits;
  20906. bits += 8;
  20907. //---//
  20908. }
  20909. //--- DROPBITS(last.bits) ---//
  20910. hold >>>= last_bits;
  20911. bits -= last_bits;
  20912. //---//
  20913. state.back += last_bits;
  20914. }
  20915. //--- DROPBITS(here.bits) ---//
  20916. hold >>>= here_bits;
  20917. bits -= here_bits;
  20918. //---//
  20919. state.back += here_bits;
  20920. if (here_op & 64) {
  20921. strm.msg = 'invalid distance code';
  20922. state.mode = BAD;
  20923. break;
  20924. }
  20925. state.offset = here_val;
  20926. state.extra = (here_op) & 15;
  20927. state.mode = DISTEXT;
  20928. /* falls through */
  20929. case DISTEXT:
  20930. if (state.extra) {
  20931. //=== NEEDBITS(state.extra);
  20932. n = state.extra;
  20933. while (bits < n) {
  20934. if (have === 0) { break inf_leave; }
  20935. have--;
  20936. hold += input[next++] << bits;
  20937. bits += 8;
  20938. }
  20939. //===//
  20940. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  20941. //--- DROPBITS(state.extra) ---//
  20942. hold >>>= state.extra;
  20943. bits -= state.extra;
  20944. //---//
  20945. state.back += state.extra;
  20946. }
  20947. //#ifdef INFLATE_STRICT
  20948. if (state.offset > state.dmax) {
  20949. strm.msg = 'invalid distance too far back';
  20950. state.mode = BAD;
  20951. break;
  20952. }
  20953. //#endif
  20954. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  20955. state.mode = MATCH;
  20956. /* falls through */
  20957. case MATCH:
  20958. if (left === 0) { break inf_leave; }
  20959. copy = _out - left;
  20960. if (state.offset > copy) { /* copy from window */
  20961. copy = state.offset - copy;
  20962. if (copy > state.whave) {
  20963. if (state.sane) {
  20964. strm.msg = 'invalid distance too far back';
  20965. state.mode = BAD;
  20966. break;
  20967. }
  20968. // (!) This block is disabled in zlib defailts,
  20969. // don't enable it for binary compatibility
  20970. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  20971. // Trace((stderr, "inflate.c too far\n"));
  20972. // copy -= state.whave;
  20973. // if (copy > state.length) { copy = state.length; }
  20974. // if (copy > left) { copy = left; }
  20975. // left -= copy;
  20976. // state.length -= copy;
  20977. // do {
  20978. // output[put++] = 0;
  20979. // } while (--copy);
  20980. // if (state.length === 0) { state.mode = LEN; }
  20981. // break;
  20982. //#endif
  20983. }
  20984. if (copy > state.wnext) {
  20985. copy -= state.wnext;
  20986. from = state.wsize - copy;
  20987. }
  20988. else {
  20989. from = state.wnext - copy;
  20990. }
  20991. if (copy > state.length) { copy = state.length; }
  20992. from_source = state.window;
  20993. }
  20994. else { /* copy from output */
  20995. from_source = output;
  20996. from = put - state.offset;
  20997. copy = state.length;
  20998. }
  20999. if (copy > left) { copy = left; }
  21000. left -= copy;
  21001. state.length -= copy;
  21002. do {
  21003. output[put++] = from_source[from++];
  21004. } while (--copy);
  21005. if (state.length === 0) { state.mode = LEN; }
  21006. break;
  21007. case LIT:
  21008. if (left === 0) { break inf_leave; }
  21009. output[put++] = state.length;
  21010. left--;
  21011. state.mode = LEN;
  21012. break;
  21013. case CHECK:
  21014. if (state.wrap) {
  21015. //=== NEEDBITS(32);
  21016. while (bits < 32) {
  21017. if (have === 0) { break inf_leave; }
  21018. have--;
  21019. // Use '|' insdead of '+' to make sure that result is signed
  21020. hold |= input[next++] << bits;
  21021. bits += 8;
  21022. }
  21023. //===//
  21024. _out -= left;
  21025. strm.total_out += _out;
  21026. state.total += _out;
  21027. if (_out) {
  21028. strm.adler = state.check =
  21029. /*UPDATE(state.check, put - _out, _out);*/
  21030. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  21031. }
  21032. _out = left;
  21033. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  21034. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  21035. strm.msg = 'incorrect data check';
  21036. state.mode = BAD;
  21037. break;
  21038. }
  21039. //=== INITBITS();
  21040. hold = 0;
  21041. bits = 0;
  21042. //===//
  21043. //Tracev((stderr, "inflate: check matches trailer\n"));
  21044. }
  21045. state.mode = LENGTH;
  21046. /* falls through */
  21047. case LENGTH:
  21048. if (state.wrap && state.flags) {
  21049. //=== NEEDBITS(32);
  21050. while (bits < 32) {
  21051. if (have === 0) { break inf_leave; }
  21052. have--;
  21053. hold += input[next++] << bits;
  21054. bits += 8;
  21055. }
  21056. //===//
  21057. if (hold !== (state.total & 0xffffffff)) {
  21058. strm.msg = 'incorrect length check';
  21059. state.mode = BAD;
  21060. break;
  21061. }
  21062. //=== INITBITS();
  21063. hold = 0;
  21064. bits = 0;
  21065. //===//
  21066. //Tracev((stderr, "inflate: length matches trailer\n"));
  21067. }
  21068. state.mode = DONE;
  21069. /* falls through */
  21070. case DONE:
  21071. ret = Z_STREAM_END;
  21072. break inf_leave;
  21073. case BAD:
  21074. ret = Z_DATA_ERROR;
  21075. break inf_leave;
  21076. case MEM:
  21077. return Z_MEM_ERROR;
  21078. case SYNC:
  21079. /* falls through */
  21080. default:
  21081. return Z_STREAM_ERROR;
  21082. }
  21083. }
  21084. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  21085. /*
  21086. Return from inflate(), updating the total counts and the check value.
  21087. If there was no progress during the inflate() call, return a buffer
  21088. error. Call updatewindow() to create and/or update the window state.
  21089. Note: a memory error from inflate() is non-recoverable.
  21090. */
  21091. //--- RESTORE() ---
  21092. strm.next_out = put;
  21093. strm.avail_out = left;
  21094. strm.next_in = next;
  21095. strm.avail_in = have;
  21096. state.hold = hold;
  21097. state.bits = bits;
  21098. //---
  21099. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  21100. (state.mode < CHECK || flush !== Z_FINISH))) {
  21101. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  21102. state.mode = MEM;
  21103. return Z_MEM_ERROR;
  21104. }
  21105. }
  21106. _in -= strm.avail_in;
  21107. _out -= strm.avail_out;
  21108. strm.total_in += _in;
  21109. strm.total_out += _out;
  21110. state.total += _out;
  21111. if (state.wrap && _out) {
  21112. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  21113. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  21114. }
  21115. strm.data_type = state.bits + (state.last ? 64 : 0) +
  21116. (state.mode === TYPE ? 128 : 0) +
  21117. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  21118. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  21119. ret = Z_BUF_ERROR;
  21120. }
  21121. return ret;
  21122. }
  21123. function inflateEnd(strm) {
  21124. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  21125. return Z_STREAM_ERROR;
  21126. }
  21127. var state = strm.state;
  21128. if (state.window) {
  21129. state.window = null;
  21130. }
  21131. strm.state = null;
  21132. return Z_OK;
  21133. }
  21134. function inflateGetHeader(strm, head) {
  21135. var state;
  21136. /* check state */
  21137. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21138. state = strm.state;
  21139. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  21140. /* save header structure */
  21141. state.head = head;
  21142. head.done = false;
  21143. return Z_OK;
  21144. }
  21145. exports.inflateReset = inflateReset;
  21146. exports.inflateReset2 = inflateReset2;
  21147. exports.inflateResetKeep = inflateResetKeep;
  21148. exports.inflateInit = inflateInit;
  21149. exports.inflateInit2 = inflateInit2;
  21150. exports.inflate = inflate;
  21151. exports.inflateEnd = inflateEnd;
  21152. exports.inflateGetHeader = inflateGetHeader;
  21153. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  21154. /* Not implemented
  21155. exports.inflateCopy = inflateCopy;
  21156. exports.inflateGetDictionary = inflateGetDictionary;
  21157. exports.inflateMark = inflateMark;
  21158. exports.inflatePrime = inflatePrime;
  21159. exports.inflateSetDictionary = inflateSetDictionary;
  21160. exports.inflateSync = inflateSync;
  21161. exports.inflateSyncPoint = inflateSyncPoint;
  21162. exports.inflateUndermine = inflateUndermine;
  21163. */
  21164. },{"../utils/common":66,"./adler32":68,"./crc32":70,"./inffast":73,"./inftrees":75}],75:[function(require,module,exports){
  21165. 'use strict';
  21166. var utils = require('../utils/common');
  21167. var MAXBITS = 15;
  21168. var ENOUGH_LENS = 852;
  21169. var ENOUGH_DISTS = 592;
  21170. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  21171. var CODES = 0;
  21172. var LENS = 1;
  21173. var DISTS = 2;
  21174. var lbase = [ /* Length codes 257..285 base */
  21175. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  21176. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  21177. ];
  21178. var lext = [ /* Length codes 257..285 extra */
  21179. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  21180. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  21181. ];
  21182. var dbase = [ /* Distance codes 0..29 base */
  21183. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  21184. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  21185. 8193, 12289, 16385, 24577, 0, 0
  21186. ];
  21187. var dext = [ /* Distance codes 0..29 extra */
  21188. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  21189. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  21190. 28, 28, 29, 29, 64, 64
  21191. ];
  21192. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  21193. {
  21194. var bits = opts.bits;
  21195. //here = opts.here; /* table entry for duplication */
  21196. var len = 0; /* a code's length in bits */
  21197. var sym = 0; /* index of code symbols */
  21198. var min = 0, max = 0; /* minimum and maximum code lengths */
  21199. var root = 0; /* number of index bits for root table */
  21200. var curr = 0; /* number of index bits for current table */
  21201. var drop = 0; /* code bits to drop for sub-table */
  21202. var left = 0; /* number of prefix codes available */
  21203. var used = 0; /* code entries in table used */
  21204. var huff = 0; /* Huffman code */
  21205. var incr; /* for incrementing code, index */
  21206. var fill; /* index for replicating entries */
  21207. var low; /* low bits for current root entry */
  21208. var mask; /* mask for low root bits */
  21209. var next; /* next available space in table */
  21210. var base = null; /* base value table to use */
  21211. var base_index = 0;
  21212. // var shoextra; /* extra bits table to use */
  21213. var end; /* use base and extra for symbol > end */
  21214. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  21215. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  21216. var extra = null;
  21217. var extra_index = 0;
  21218. var here_bits, here_op, here_val;
  21219. /*
  21220. Process a set of code lengths to create a canonical Huffman code. The
  21221. code lengths are lens[0..codes-1]. Each length corresponds to the
  21222. symbols 0..codes-1. The Huffman code is generated by first sorting the
  21223. symbols by length from short to long, and retaining the symbol order
  21224. for codes with equal lengths. Then the code starts with all zero bits
  21225. for the first code of the shortest length, and the codes are integer
  21226. increments for the same length, and zeros are appended as the length
  21227. increases. For the deflate format, these bits are stored backwards
  21228. from their more natural integer increment ordering, and so when the
  21229. decoding tables are built in the large loop below, the integer codes
  21230. are incremented backwards.
  21231. This routine assumes, but does not check, that all of the entries in
  21232. lens[] are in the range 0..MAXBITS. The caller must assure this.
  21233. 1..MAXBITS is interpreted as that code length. zero means that that
  21234. symbol does not occur in this code.
  21235. The codes are sorted by computing a count of codes for each length,
  21236. creating from that a table of starting indices for each length in the
  21237. sorted table, and then entering the symbols in order in the sorted
  21238. table. The sorted table is work[], with that space being provided by
  21239. the caller.
  21240. The length counts are used for other purposes as well, i.e. finding
  21241. the minimum and maximum length codes, determining if there are any
  21242. codes at all, checking for a valid set of lengths, and looking ahead
  21243. at length counts to determine sub-table sizes when building the
  21244. decoding tables.
  21245. */
  21246. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  21247. for (len = 0; len <= MAXBITS; len++) {
  21248. count[len] = 0;
  21249. }
  21250. for (sym = 0; sym < codes; sym++) {
  21251. count[lens[lens_index + sym]]++;
  21252. }
  21253. /* bound code lengths, force root to be within code lengths */
  21254. root = bits;
  21255. for (max = MAXBITS; max >= 1; max--) {
  21256. if (count[max] !== 0) { break; }
  21257. }
  21258. if (root > max) {
  21259. root = max;
  21260. }
  21261. if (max === 0) { /* no symbols to code at all */
  21262. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  21263. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  21264. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  21265. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  21266. //table.op[opts.table_index] = 64;
  21267. //table.bits[opts.table_index] = 1;
  21268. //table.val[opts.table_index++] = 0;
  21269. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  21270. opts.bits = 1;
  21271. return 0; /* no symbols, but wait for decoding to report error */
  21272. }
  21273. for (min = 1; min < max; min++) {
  21274. if (count[min] !== 0) { break; }
  21275. }
  21276. if (root < min) {
  21277. root = min;
  21278. }
  21279. /* check for an over-subscribed or incomplete set of lengths */
  21280. left = 1;
  21281. for (len = 1; len <= MAXBITS; len++) {
  21282. left <<= 1;
  21283. left -= count[len];
  21284. if (left < 0) {
  21285. return -1;
  21286. } /* over-subscribed */
  21287. }
  21288. if (left > 0 && (type === CODES || max !== 1)) {
  21289. return -1; /* incomplete set */
  21290. }
  21291. /* generate offsets into symbol table for each length for sorting */
  21292. offs[1] = 0;
  21293. for (len = 1; len < MAXBITS; len++) {
  21294. offs[len + 1] = offs[len] + count[len];
  21295. }
  21296. /* sort symbols by length, by symbol order within each length */
  21297. for (sym = 0; sym < codes; sym++) {
  21298. if (lens[lens_index + sym] !== 0) {
  21299. work[offs[lens[lens_index + sym]]++] = sym;
  21300. }
  21301. }
  21302. /*
  21303. Create and fill in decoding tables. In this loop, the table being
  21304. filled is at next and has curr index bits. The code being used is huff
  21305. with length len. That code is converted to an index by dropping drop
  21306. bits off of the bottom. For codes where len is less than drop + curr,
  21307. those top drop + curr - len bits are incremented through all values to
  21308. fill the table with replicated entries.
  21309. root is the number of index bits for the root table. When len exceeds
  21310. root, sub-tables are created pointed to by the root entry with an index
  21311. of the low root bits of huff. This is saved in low to check for when a
  21312. new sub-table should be started. drop is zero when the root table is
  21313. being filled, and drop is root when sub-tables are being filled.
  21314. When a new sub-table is needed, it is necessary to look ahead in the
  21315. code lengths to determine what size sub-table is needed. The length
  21316. counts are used for this, and so count[] is decremented as codes are
  21317. entered in the tables.
  21318. used keeps track of how many table entries have been allocated from the
  21319. provided *table space. It is checked for LENS and DIST tables against
  21320. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  21321. the initial root table size constants. See the comments in inftrees.h
  21322. for more information.
  21323. sym increments through all symbols, and the loop terminates when
  21324. all codes of length max, i.e. all codes, have been processed. This
  21325. routine permits incomplete codes, so another loop after this one fills
  21326. in the rest of the decoding tables with invalid code markers.
  21327. */
  21328. /* set up for code type */
  21329. // poor man optimization - use if-else instead of switch,
  21330. // to avoid deopts in old v8
  21331. if (type === CODES) {
  21332. base = extra = work; /* dummy value--not used */
  21333. end = 19;
  21334. } else if (type === LENS) {
  21335. base = lbase;
  21336. base_index -= 257;
  21337. extra = lext;
  21338. extra_index -= 257;
  21339. end = 256;
  21340. } else { /* DISTS */
  21341. base = dbase;
  21342. extra = dext;
  21343. end = -1;
  21344. }
  21345. /* initialize opts for loop */
  21346. huff = 0; /* starting code */
  21347. sym = 0; /* starting code symbol */
  21348. len = min; /* starting code length */
  21349. next = table_index; /* current table to fill in */
  21350. curr = root; /* current table index bits */
  21351. drop = 0; /* current bits to drop from code for index */
  21352. low = -1; /* trigger new sub-table when len > root */
  21353. used = 1 << root; /* use root table entries */
  21354. mask = used - 1; /* mask for comparing low */
  21355. /* check available table space */
  21356. if ((type === LENS && used > ENOUGH_LENS) ||
  21357. (type === DISTS && used > ENOUGH_DISTS)) {
  21358. return 1;
  21359. }
  21360. var i=0;
  21361. /* process all codes and make table entries */
  21362. for (;;) {
  21363. i++;
  21364. /* create table entry */
  21365. here_bits = len - drop;
  21366. if (work[sym] < end) {
  21367. here_op = 0;
  21368. here_val = work[sym];
  21369. }
  21370. else if (work[sym] > end) {
  21371. here_op = extra[extra_index + work[sym]];
  21372. here_val = base[base_index + work[sym]];
  21373. }
  21374. else {
  21375. here_op = 32 + 64; /* end of block */
  21376. here_val = 0;
  21377. }
  21378. /* replicate for those indices with low len bits equal to huff */
  21379. incr = 1 << (len - drop);
  21380. fill = 1 << curr;
  21381. min = fill; /* save offset to next table */
  21382. do {
  21383. fill -= incr;
  21384. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  21385. } while (fill !== 0);
  21386. /* backwards increment the len-bit code huff */
  21387. incr = 1 << (len - 1);
  21388. while (huff & incr) {
  21389. incr >>= 1;
  21390. }
  21391. if (incr !== 0) {
  21392. huff &= incr - 1;
  21393. huff += incr;
  21394. } else {
  21395. huff = 0;
  21396. }
  21397. /* go to next symbol, update count, len */
  21398. sym++;
  21399. if (--count[len] === 0) {
  21400. if (len === max) { break; }
  21401. len = lens[lens_index + work[sym]];
  21402. }
  21403. /* create new sub-table if needed */
  21404. if (len > root && (huff & mask) !== low) {
  21405. /* if first time, transition to sub-tables */
  21406. if (drop === 0) {
  21407. drop = root;
  21408. }
  21409. /* increment past last table */
  21410. next += min; /* here min is 1 << curr */
  21411. /* determine length of next table */
  21412. curr = len - drop;
  21413. left = 1 << curr;
  21414. while (curr + drop < max) {
  21415. left -= count[curr + drop];
  21416. if (left <= 0) { break; }
  21417. curr++;
  21418. left <<= 1;
  21419. }
  21420. /* check for enough space */
  21421. used += 1 << curr;
  21422. if ((type === LENS && used > ENOUGH_LENS) ||
  21423. (type === DISTS && used > ENOUGH_DISTS)) {
  21424. return 1;
  21425. }
  21426. /* point entry in root table to sub-table */
  21427. low = huff & mask;
  21428. /*table.op[low] = curr;
  21429. table.bits[low] = root;
  21430. table.val[low] = next - opts.table_index;*/
  21431. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  21432. }
  21433. }
  21434. /* fill in remaining table entry if code is incomplete (guaranteed to have
  21435. at most one remaining entry, since if the code is incomplete, the
  21436. maximum code length that was allowed to get this far is one bit) */
  21437. if (huff !== 0) {
  21438. //table.op[next + huff] = 64; /* invalid code marker */
  21439. //table.bits[next + huff] = len - drop;
  21440. //table.val[next + huff] = 0;
  21441. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  21442. }
  21443. /* set return parameters */
  21444. //opts.table_index += used;
  21445. opts.bits = root;
  21446. return 0;
  21447. };
  21448. },{"../utils/common":66}],76:[function(require,module,exports){
  21449. 'use strict';
  21450. module.exports = {
  21451. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  21452. '1': 'stream end', /* Z_STREAM_END 1 */
  21453. '0': '', /* Z_OK 0 */
  21454. '-1': 'file error', /* Z_ERRNO (-1) */
  21455. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  21456. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  21457. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  21458. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  21459. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  21460. };
  21461. },{}],77:[function(require,module,exports){
  21462. 'use strict';
  21463. var utils = require('../utils/common');
  21464. /* Public constants ==========================================================*/
  21465. /* ===========================================================================*/
  21466. //var Z_FILTERED = 1;
  21467. //var Z_HUFFMAN_ONLY = 2;
  21468. //var Z_RLE = 3;
  21469. var Z_FIXED = 4;
  21470. //var Z_DEFAULT_STRATEGY = 0;
  21471. /* Possible values of the data_type field (though see inflate()) */
  21472. var Z_BINARY = 0;
  21473. var Z_TEXT = 1;
  21474. //var Z_ASCII = 1; // = Z_TEXT
  21475. var Z_UNKNOWN = 2;
  21476. /*============================================================================*/
  21477. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  21478. // From zutil.h
  21479. var STORED_BLOCK = 0;
  21480. var STATIC_TREES = 1;
  21481. var DYN_TREES = 2;
  21482. /* The three kinds of block type */
  21483. var MIN_MATCH = 3;
  21484. var MAX_MATCH = 258;
  21485. /* The minimum and maximum match lengths */
  21486. // From deflate.h
  21487. /* ===========================================================================
  21488. * Internal compression state.
  21489. */
  21490. var LENGTH_CODES = 29;
  21491. /* number of length codes, not counting the special END_BLOCK code */
  21492. var LITERALS = 256;
  21493. /* number of literal bytes 0..255 */
  21494. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  21495. /* number of Literal or Length codes, including the END_BLOCK code */
  21496. var D_CODES = 30;
  21497. /* number of distance codes */
  21498. var BL_CODES = 19;
  21499. /* number of codes used to transfer the bit lengths */
  21500. var HEAP_SIZE = 2*L_CODES + 1;
  21501. /* maximum heap size */
  21502. var MAX_BITS = 15;
  21503. /* All codes must not exceed MAX_BITS bits */
  21504. var Buf_size = 16;
  21505. /* size of bit buffer in bi_buf */
  21506. /* ===========================================================================
  21507. * Constants
  21508. */
  21509. var MAX_BL_BITS = 7;
  21510. /* Bit length codes must not exceed MAX_BL_BITS bits */
  21511. var END_BLOCK = 256;
  21512. /* end of block literal code */
  21513. var REP_3_6 = 16;
  21514. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  21515. var REPZ_3_10 = 17;
  21516. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  21517. var REPZ_11_138 = 18;
  21518. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  21519. var extra_lbits = /* extra bits for each length code */
  21520. [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];
  21521. var extra_dbits = /* extra bits for each distance code */
  21522. [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];
  21523. var extra_blbits = /* extra bits for each bit length code */
  21524. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  21525. var bl_order =
  21526. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  21527. /* The lengths of the bit length codes are sent in order of decreasing
  21528. * probability, to avoid transmitting the lengths for unused bit length codes.
  21529. */
  21530. /* ===========================================================================
  21531. * Local data. These are initialized only once.
  21532. */
  21533. // We pre-fill arrays with 0 to avoid uninitialized gaps
  21534. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  21535. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  21536. var static_ltree = new Array((L_CODES+2) * 2);
  21537. zero(static_ltree);
  21538. /* The static literal tree. Since the bit lengths are imposed, there is no
  21539. * need for the L_CODES extra codes used during heap construction. However
  21540. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  21541. * below).
  21542. */
  21543. var static_dtree = new Array(D_CODES * 2);
  21544. zero(static_dtree);
  21545. /* The static distance tree. (Actually a trivial tree since all codes use
  21546. * 5 bits.)
  21547. */
  21548. var _dist_code = new Array(DIST_CODE_LEN);
  21549. zero(_dist_code);
  21550. /* Distance codes. The first 256 values correspond to the distances
  21551. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  21552. * the 15 bit distances.
  21553. */
  21554. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  21555. zero(_length_code);
  21556. /* length code for each normalized match length (0 == MIN_MATCH) */
  21557. var base_length = new Array(LENGTH_CODES);
  21558. zero(base_length);
  21559. /* First normalized length for each code (0 = MIN_MATCH) */
  21560. var base_dist = new Array(D_CODES);
  21561. zero(base_dist);
  21562. /* First normalized distance for each code (0 = distance of 1) */
  21563. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  21564. this.static_tree = static_tree; /* static tree or NULL */
  21565. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  21566. this.extra_base = extra_base; /* base index for extra_bits */
  21567. this.elems = elems; /* max number of elements in the tree */
  21568. this.max_length = max_length; /* max bit length for the codes */
  21569. // show if `static_tree` has data or dummy - needed for monomorphic objects
  21570. this.has_stree = static_tree && static_tree.length;
  21571. };
  21572. var static_l_desc;
  21573. var static_d_desc;
  21574. var static_bl_desc;
  21575. var TreeDesc = function(dyn_tree, stat_desc) {
  21576. this.dyn_tree = dyn_tree; /* the dynamic tree */
  21577. this.max_code = 0; /* largest code with non zero frequency */
  21578. this.stat_desc = stat_desc; /* the corresponding static tree */
  21579. };
  21580. function d_code(dist) {
  21581. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  21582. }
  21583. /* ===========================================================================
  21584. * Output a short LSB first on the stream.
  21585. * IN assertion: there is enough room in pendingBuf.
  21586. */
  21587. function put_short (s, w) {
  21588. // put_byte(s, (uch)((w) & 0xff));
  21589. // put_byte(s, (uch)((ush)(w) >> 8));
  21590. s.pending_buf[s.pending++] = (w) & 0xff;
  21591. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  21592. }
  21593. /* ===========================================================================
  21594. * Send a value on a given number of bits.
  21595. * IN assertion: length <= 16 and value fits in length bits.
  21596. */
  21597. function send_bits(s, value, length) {
  21598. if (s.bi_valid > (Buf_size - length)) {
  21599. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  21600. put_short(s, s.bi_buf);
  21601. s.bi_buf = value >> (Buf_size - s.bi_valid);
  21602. s.bi_valid += length - Buf_size;
  21603. } else {
  21604. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  21605. s.bi_valid += length;
  21606. }
  21607. }
  21608. function send_code(s, c, tree) {
  21609. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  21610. }
  21611. /* ===========================================================================
  21612. * Reverse the first len bits of a code, using straightforward code (a faster
  21613. * method would use a table)
  21614. * IN assertion: 1 <= len <= 15
  21615. */
  21616. function bi_reverse(code, len) {
  21617. var res = 0;
  21618. do {
  21619. res |= code & 1;
  21620. code >>>= 1;
  21621. res <<= 1;
  21622. } while (--len > 0);
  21623. return res >>> 1;
  21624. }
  21625. /* ===========================================================================
  21626. * Flush the bit buffer, keeping at most 7 bits in it.
  21627. */
  21628. function bi_flush(s) {
  21629. if (s.bi_valid === 16) {
  21630. put_short(s, s.bi_buf);
  21631. s.bi_buf = 0;
  21632. s.bi_valid = 0;
  21633. } else if (s.bi_valid >= 8) {
  21634. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  21635. s.bi_buf >>= 8;
  21636. s.bi_valid -= 8;
  21637. }
  21638. }
  21639. /* ===========================================================================
  21640. * Compute the optimal bit lengths for a tree and update the total bit length
  21641. * for the current block.
  21642. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  21643. * above are the tree nodes sorted by increasing frequency.
  21644. * OUT assertions: the field len is set to the optimal bit length, the
  21645. * array bl_count contains the frequencies for each bit length.
  21646. * The length opt_len is updated; static_len is also updated if stree is
  21647. * not null.
  21648. */
  21649. function gen_bitlen(s, desc)
  21650. // deflate_state *s;
  21651. // tree_desc *desc; /* the tree descriptor */
  21652. {
  21653. var tree = desc.dyn_tree;
  21654. var max_code = desc.max_code;
  21655. var stree = desc.stat_desc.static_tree;
  21656. var has_stree = desc.stat_desc.has_stree;
  21657. var extra = desc.stat_desc.extra_bits;
  21658. var base = desc.stat_desc.extra_base;
  21659. var max_length = desc.stat_desc.max_length;
  21660. var h; /* heap index */
  21661. var n, m; /* iterate over the tree elements */
  21662. var bits; /* bit length */
  21663. var xbits; /* extra bits */
  21664. var f; /* frequency */
  21665. var overflow = 0; /* number of elements with bit length too large */
  21666. for (bits = 0; bits <= MAX_BITS; bits++) {
  21667. s.bl_count[bits] = 0;
  21668. }
  21669. /* In a first pass, compute the optimal bit lengths (which may
  21670. * overflow in the case of the bit length tree).
  21671. */
  21672. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  21673. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  21674. n = s.heap[h];
  21675. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  21676. if (bits > max_length) {
  21677. bits = max_length;
  21678. overflow++;
  21679. }
  21680. tree[n*2 + 1]/*.Len*/ = bits;
  21681. /* We overwrite tree[n].Dad which is no longer needed */
  21682. if (n > max_code) { continue; } /* not a leaf node */
  21683. s.bl_count[bits]++;
  21684. xbits = 0;
  21685. if (n >= base) {
  21686. xbits = extra[n-base];
  21687. }
  21688. f = tree[n * 2]/*.Freq*/;
  21689. s.opt_len += f * (bits + xbits);
  21690. if (has_stree) {
  21691. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  21692. }
  21693. }
  21694. if (overflow === 0) { return; }
  21695. // Trace((stderr,"\nbit length overflow\n"));
  21696. /* This happens for example on obj2 and pic of the Calgary corpus */
  21697. /* Find the first bit length which could increase: */
  21698. do {
  21699. bits = max_length-1;
  21700. while (s.bl_count[bits] === 0) { bits--; }
  21701. s.bl_count[bits]--; /* move one leaf down the tree */
  21702. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  21703. s.bl_count[max_length]--;
  21704. /* The brother of the overflow item also moves one step up,
  21705. * but this does not affect bl_count[max_length]
  21706. */
  21707. overflow -= 2;
  21708. } while (overflow > 0);
  21709. /* Now recompute all bit lengths, scanning in increasing frequency.
  21710. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  21711. * lengths instead of fixing only the wrong ones. This idea is taken
  21712. * from 'ar' written by Haruhiko Okumura.)
  21713. */
  21714. for (bits = max_length; bits !== 0; bits--) {
  21715. n = s.bl_count[bits];
  21716. while (n !== 0) {
  21717. m = s.heap[--h];
  21718. if (m > max_code) { continue; }
  21719. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  21720. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  21721. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  21722. tree[m*2 + 1]/*.Len*/ = bits;
  21723. }
  21724. n--;
  21725. }
  21726. }
  21727. }
  21728. /* ===========================================================================
  21729. * Generate the codes for a given tree and bit counts (which need not be
  21730. * optimal).
  21731. * IN assertion: the array bl_count contains the bit length statistics for
  21732. * the given tree and the field len is set for all tree elements.
  21733. * OUT assertion: the field code is set for all tree elements of non
  21734. * zero code length.
  21735. */
  21736. function gen_codes(tree, max_code, bl_count)
  21737. // ct_data *tree; /* the tree to decorate */
  21738. // int max_code; /* largest code with non zero frequency */
  21739. // ushf *bl_count; /* number of codes at each bit length */
  21740. {
  21741. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  21742. var code = 0; /* running code value */
  21743. var bits; /* bit index */
  21744. var n; /* code index */
  21745. /* The distribution counts are first used to generate the code values
  21746. * without bit reversal.
  21747. */
  21748. for (bits = 1; bits <= MAX_BITS; bits++) {
  21749. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  21750. }
  21751. /* Check that the bit counts in bl_count are consistent. The last code
  21752. * must be all ones.
  21753. */
  21754. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  21755. // "inconsistent bit counts");
  21756. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  21757. for (n = 0; n <= max_code; n++) {
  21758. var len = tree[n*2 + 1]/*.Len*/;
  21759. if (len === 0) { continue; }
  21760. /* Now reverse the bits */
  21761. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  21762. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  21763. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  21764. }
  21765. }
  21766. /* ===========================================================================
  21767. * Initialize the various 'constant' tables.
  21768. */
  21769. function tr_static_init() {
  21770. var n; /* iterates over tree elements */
  21771. var bits; /* bit counter */
  21772. var length; /* length value */
  21773. var code; /* code value */
  21774. var dist; /* distance index */
  21775. var bl_count = new Array(MAX_BITS+1);
  21776. /* number of codes at each bit length for an optimal tree */
  21777. // do check in _tr_init()
  21778. //if (static_init_done) return;
  21779. /* For some embedded targets, global variables are not initialized: */
  21780. /*#ifdef NO_INIT_GLOBAL_POINTERS
  21781. static_l_desc.static_tree = static_ltree;
  21782. static_l_desc.extra_bits = extra_lbits;
  21783. static_d_desc.static_tree = static_dtree;
  21784. static_d_desc.extra_bits = extra_dbits;
  21785. static_bl_desc.extra_bits = extra_blbits;
  21786. #endif*/
  21787. /* Initialize the mapping length (0..255) -> length code (0..28) */
  21788. length = 0;
  21789. for (code = 0; code < LENGTH_CODES-1; code++) {
  21790. base_length[code] = length;
  21791. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  21792. _length_code[length++] = code;
  21793. }
  21794. }
  21795. //Assert (length == 256, "tr_static_init: length != 256");
  21796. /* Note that the length 255 (match length 258) can be represented
  21797. * in two different ways: code 284 + 5 bits or code 285, so we
  21798. * overwrite length_code[255] to use the best encoding:
  21799. */
  21800. _length_code[length-1] = code;
  21801. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  21802. dist = 0;
  21803. for (code = 0 ; code < 16; code++) {
  21804. base_dist[code] = dist;
  21805. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  21806. _dist_code[dist++] = code;
  21807. }
  21808. }
  21809. //Assert (dist == 256, "tr_static_init: dist != 256");
  21810. dist >>= 7; /* from now on, all distances are divided by 128 */
  21811. for ( ; code < D_CODES; code++) {
  21812. base_dist[code] = dist << 7;
  21813. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  21814. _dist_code[256 + dist++] = code;
  21815. }
  21816. }
  21817. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  21818. /* Construct the codes of the static literal tree */
  21819. for (bits = 0; bits <= MAX_BITS; bits++) {
  21820. bl_count[bits] = 0;
  21821. }
  21822. n = 0;
  21823. while (n <= 143) {
  21824. static_ltree[n*2 + 1]/*.Len*/ = 8;
  21825. n++;
  21826. bl_count[8]++;
  21827. }
  21828. while (n <= 255) {
  21829. static_ltree[n*2 + 1]/*.Len*/ = 9;
  21830. n++;
  21831. bl_count[9]++;
  21832. }
  21833. while (n <= 279) {
  21834. static_ltree[n*2 + 1]/*.Len*/ = 7;
  21835. n++;
  21836. bl_count[7]++;
  21837. }
  21838. while (n <= 287) {
  21839. static_ltree[n*2 + 1]/*.Len*/ = 8;
  21840. n++;
  21841. bl_count[8]++;
  21842. }
  21843. /* Codes 286 and 287 do not exist, but we must include them in the
  21844. * tree construction to get a canonical Huffman tree (longest code
  21845. * all ones)
  21846. */
  21847. gen_codes(static_ltree, L_CODES+1, bl_count);
  21848. /* The static distance tree is trivial: */
  21849. for (n = 0; n < D_CODES; n++) {
  21850. static_dtree[n*2 + 1]/*.Len*/ = 5;
  21851. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  21852. }
  21853. // Now data ready and we can init static trees
  21854. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  21855. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  21856. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  21857. //static_init_done = true;
  21858. }
  21859. /* ===========================================================================
  21860. * Initialize a new block.
  21861. */
  21862. function init_block(s) {
  21863. var n; /* iterates over tree elements */
  21864. /* Initialize the trees. */
  21865. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  21866. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  21867. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  21868. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  21869. s.opt_len = s.static_len = 0;
  21870. s.last_lit = s.matches = 0;
  21871. }
  21872. /* ===========================================================================
  21873. * Flush the bit buffer and align the output on a byte boundary
  21874. */
  21875. function bi_windup(s)
  21876. {
  21877. if (s.bi_valid > 8) {
  21878. put_short(s, s.bi_buf);
  21879. } else if (s.bi_valid > 0) {
  21880. //put_byte(s, (Byte)s->bi_buf);
  21881. s.pending_buf[s.pending++] = s.bi_buf;
  21882. }
  21883. s.bi_buf = 0;
  21884. s.bi_valid = 0;
  21885. }
  21886. /* ===========================================================================
  21887. * Copy a stored block, storing first the length and its
  21888. * one's complement if requested.
  21889. */
  21890. function copy_block(s, buf, len, header)
  21891. //DeflateState *s;
  21892. //charf *buf; /* the input data */
  21893. //unsigned len; /* its length */
  21894. //int header; /* true if block header must be written */
  21895. {
  21896. bi_windup(s); /* align on byte boundary */
  21897. if (header) {
  21898. put_short(s, len);
  21899. put_short(s, ~len);
  21900. }
  21901. // while (len--) {
  21902. // put_byte(s, *buf++);
  21903. // }
  21904. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  21905. s.pending += len;
  21906. }
  21907. /* ===========================================================================
  21908. * Compares to subtrees, using the tree depth as tie breaker when
  21909. * the subtrees have equal frequency. This minimizes the worst case length.
  21910. */
  21911. function smaller(tree, n, m, depth) {
  21912. var _n2 = n*2;
  21913. var _m2 = m*2;
  21914. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  21915. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  21916. }
  21917. /* ===========================================================================
  21918. * Restore the heap property by moving down the tree starting at node k,
  21919. * exchanging a node with the smallest of its two sons if necessary, stopping
  21920. * when the heap property is re-established (each father smaller than its
  21921. * two sons).
  21922. */
  21923. function pqdownheap(s, tree, k)
  21924. // deflate_state *s;
  21925. // ct_data *tree; /* the tree to restore */
  21926. // int k; /* node to move down */
  21927. {
  21928. var v = s.heap[k];
  21929. var j = k << 1; /* left son of k */
  21930. while (j <= s.heap_len) {
  21931. /* Set j to the smallest of the two sons: */
  21932. if (j < s.heap_len &&
  21933. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  21934. j++;
  21935. }
  21936. /* Exit if v is smaller than both sons */
  21937. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  21938. /* Exchange v with the smallest son */
  21939. s.heap[k] = s.heap[j];
  21940. k = j;
  21941. /* And continue down the tree, setting j to the left son of k */
  21942. j <<= 1;
  21943. }
  21944. s.heap[k] = v;
  21945. }
  21946. // inlined manually
  21947. // var SMALLEST = 1;
  21948. /* ===========================================================================
  21949. * Send the block data compressed using the given Huffman trees
  21950. */
  21951. function compress_block(s, ltree, dtree)
  21952. // deflate_state *s;
  21953. // const ct_data *ltree; /* literal tree */
  21954. // const ct_data *dtree; /* distance tree */
  21955. {
  21956. var dist; /* distance of matched string */
  21957. var lc; /* match length or unmatched char (if dist == 0) */
  21958. var lx = 0; /* running index in l_buf */
  21959. var code; /* the code to send */
  21960. var extra; /* number of extra bits to send */
  21961. if (s.last_lit !== 0) {
  21962. do {
  21963. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  21964. lc = s.pending_buf[s.l_buf + lx];
  21965. lx++;
  21966. if (dist === 0) {
  21967. send_code(s, lc, ltree); /* send a literal byte */
  21968. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  21969. } else {
  21970. /* Here, lc is the match length - MIN_MATCH */
  21971. code = _length_code[lc];
  21972. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  21973. extra = extra_lbits[code];
  21974. if (extra !== 0) {
  21975. lc -= base_length[code];
  21976. send_bits(s, lc, extra); /* send the extra length bits */
  21977. }
  21978. dist--; /* dist is now the match distance - 1 */
  21979. code = d_code(dist);
  21980. //Assert (code < D_CODES, "bad d_code");
  21981. send_code(s, code, dtree); /* send the distance code */
  21982. extra = extra_dbits[code];
  21983. if (extra !== 0) {
  21984. dist -= base_dist[code];
  21985. send_bits(s, dist, extra); /* send the extra distance bits */
  21986. }
  21987. } /* literal or match pair ? */
  21988. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  21989. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  21990. // "pendingBuf overflow");
  21991. } while (lx < s.last_lit);
  21992. }
  21993. send_code(s, END_BLOCK, ltree);
  21994. }
  21995. /* ===========================================================================
  21996. * Construct one Huffman tree and assigns the code bit strings and lengths.
  21997. * Update the total bit length for the current block.
  21998. * IN assertion: the field freq is set for all tree elements.
  21999. * OUT assertions: the fields len and code are set to the optimal bit length
  22000. * and corresponding code. The length opt_len is updated; static_len is
  22001. * also updated if stree is not null. The field max_code is set.
  22002. */
  22003. function build_tree(s, desc)
  22004. // deflate_state *s;
  22005. // tree_desc *desc; /* the tree descriptor */
  22006. {
  22007. var tree = desc.dyn_tree;
  22008. var stree = desc.stat_desc.static_tree;
  22009. var has_stree = desc.stat_desc.has_stree;
  22010. var elems = desc.stat_desc.elems;
  22011. var n, m; /* iterate over heap elements */
  22012. var max_code = -1; /* largest code with non zero frequency */
  22013. var node; /* new node being created */
  22014. /* Construct the initial heap, with least frequent element in
  22015. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  22016. * heap[0] is not used.
  22017. */
  22018. s.heap_len = 0;
  22019. s.heap_max = HEAP_SIZE;
  22020. for (n = 0; n < elems; n++) {
  22021. if (tree[n * 2]/*.Freq*/ !== 0) {
  22022. s.heap[++s.heap_len] = max_code = n;
  22023. s.depth[n] = 0;
  22024. } else {
  22025. tree[n*2 + 1]/*.Len*/ = 0;
  22026. }
  22027. }
  22028. /* The pkzip format requires that at least one distance code exists,
  22029. * and that at least one bit should be sent even if there is only one
  22030. * possible code. So to avoid special checks later on we force at least
  22031. * two codes of non zero frequency.
  22032. */
  22033. while (s.heap_len < 2) {
  22034. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  22035. tree[node * 2]/*.Freq*/ = 1;
  22036. s.depth[node] = 0;
  22037. s.opt_len--;
  22038. if (has_stree) {
  22039. s.static_len -= stree[node*2 + 1]/*.Len*/;
  22040. }
  22041. /* node is 0 or 1 so it does not have extra bits */
  22042. }
  22043. desc.max_code = max_code;
  22044. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  22045. * establish sub-heaps of increasing lengths:
  22046. */
  22047. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  22048. /* Construct the Huffman tree by repeatedly combining the least two
  22049. * frequent nodes.
  22050. */
  22051. node = elems; /* next internal node of the tree */
  22052. do {
  22053. //pqremove(s, tree, n); /* n = node of least frequency */
  22054. /*** pqremove ***/
  22055. n = s.heap[1/*SMALLEST*/];
  22056. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  22057. pqdownheap(s, tree, 1/*SMALLEST*/);
  22058. /***/
  22059. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  22060. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  22061. s.heap[--s.heap_max] = m;
  22062. /* Create a new node father of n and m */
  22063. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  22064. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  22065. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  22066. /* and insert the new node in the heap */
  22067. s.heap[1/*SMALLEST*/] = node++;
  22068. pqdownheap(s, tree, 1/*SMALLEST*/);
  22069. } while (s.heap_len >= 2);
  22070. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  22071. /* At this point, the fields freq and dad are set. We can now
  22072. * generate the bit lengths.
  22073. */
  22074. gen_bitlen(s, desc);
  22075. /* The field len is now set, we can generate the bit codes */
  22076. gen_codes(tree, max_code, s.bl_count);
  22077. }
  22078. /* ===========================================================================
  22079. * Scan a literal or distance tree to determine the frequencies of the codes
  22080. * in the bit length tree.
  22081. */
  22082. function scan_tree(s, tree, max_code)
  22083. // deflate_state *s;
  22084. // ct_data *tree; /* the tree to be scanned */
  22085. // int max_code; /* and its largest code of non zero frequency */
  22086. {
  22087. var n; /* iterates over all tree elements */
  22088. var prevlen = -1; /* last emitted length */
  22089. var curlen; /* length of current code */
  22090. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  22091. var count = 0; /* repeat count of the current code */
  22092. var max_count = 7; /* max repeat count */
  22093. var min_count = 4; /* min repeat count */
  22094. if (nextlen === 0) {
  22095. max_count = 138;
  22096. min_count = 3;
  22097. }
  22098. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  22099. for (n = 0; n <= max_code; n++) {
  22100. curlen = nextlen;
  22101. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  22102. if (++count < max_count && curlen === nextlen) {
  22103. continue;
  22104. } else if (count < min_count) {
  22105. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  22106. } else if (curlen !== 0) {
  22107. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  22108. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  22109. } else if (count <= 10) {
  22110. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  22111. } else {
  22112. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  22113. }
  22114. count = 0;
  22115. prevlen = curlen;
  22116. if (nextlen === 0) {
  22117. max_count = 138;
  22118. min_count = 3;
  22119. } else if (curlen === nextlen) {
  22120. max_count = 6;
  22121. min_count = 3;
  22122. } else {
  22123. max_count = 7;
  22124. min_count = 4;
  22125. }
  22126. }
  22127. }
  22128. /* ===========================================================================
  22129. * Send a literal or distance tree in compressed form, using the codes in
  22130. * bl_tree.
  22131. */
  22132. function send_tree(s, tree, max_code)
  22133. // deflate_state *s;
  22134. // ct_data *tree; /* the tree to be scanned */
  22135. // int max_code; /* and its largest code of non zero frequency */
  22136. {
  22137. var n; /* iterates over all tree elements */
  22138. var prevlen = -1; /* last emitted length */
  22139. var curlen; /* length of current code */
  22140. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  22141. var count = 0; /* repeat count of the current code */
  22142. var max_count = 7; /* max repeat count */
  22143. var min_count = 4; /* min repeat count */
  22144. /* tree[max_code+1].Len = -1; */ /* guard already set */
  22145. if (nextlen === 0) {
  22146. max_count = 138;
  22147. min_count = 3;
  22148. }
  22149. for (n = 0; n <= max_code; n++) {
  22150. curlen = nextlen;
  22151. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  22152. if (++count < max_count && curlen === nextlen) {
  22153. continue;
  22154. } else if (count < min_count) {
  22155. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  22156. } else if (curlen !== 0) {
  22157. if (curlen !== prevlen) {
  22158. send_code(s, curlen, s.bl_tree);
  22159. count--;
  22160. }
  22161. //Assert(count >= 3 && count <= 6, " 3_6?");
  22162. send_code(s, REP_3_6, s.bl_tree);
  22163. send_bits(s, count-3, 2);
  22164. } else if (count <= 10) {
  22165. send_code(s, REPZ_3_10, s.bl_tree);
  22166. send_bits(s, count-3, 3);
  22167. } else {
  22168. send_code(s, REPZ_11_138, s.bl_tree);
  22169. send_bits(s, count-11, 7);
  22170. }
  22171. count = 0;
  22172. prevlen = curlen;
  22173. if (nextlen === 0) {
  22174. max_count = 138;
  22175. min_count = 3;
  22176. } else if (curlen === nextlen) {
  22177. max_count = 6;
  22178. min_count = 3;
  22179. } else {
  22180. max_count = 7;
  22181. min_count = 4;
  22182. }
  22183. }
  22184. }
  22185. /* ===========================================================================
  22186. * Construct the Huffman tree for the bit lengths and return the index in
  22187. * bl_order of the last bit length code to send.
  22188. */
  22189. function build_bl_tree(s) {
  22190. var max_blindex; /* index of last bit length code of non zero freq */
  22191. /* Determine the bit length frequencies for literal and distance trees */
  22192. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  22193. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  22194. /* Build the bit length tree: */
  22195. build_tree(s, s.bl_desc);
  22196. /* opt_len now includes the length of the tree representations, except
  22197. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  22198. */
  22199. /* Determine the number of bit length codes to send. The pkzip format
  22200. * requires that at least 4 bit length codes be sent. (appnote.txt says
  22201. * 3 but the actual value used is 4.)
  22202. */
  22203. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  22204. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  22205. break;
  22206. }
  22207. }
  22208. /* Update opt_len to include the bit length tree and counts */
  22209. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  22210. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  22211. // s->opt_len, s->static_len));
  22212. return max_blindex;
  22213. }
  22214. /* ===========================================================================
  22215. * Send the header for a block using dynamic Huffman trees: the counts, the
  22216. * lengths of the bit length codes, the literal tree and the distance tree.
  22217. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  22218. */
  22219. function send_all_trees(s, lcodes, dcodes, blcodes)
  22220. // deflate_state *s;
  22221. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  22222. {
  22223. var rank; /* index in bl_order */
  22224. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  22225. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  22226. // "too many codes");
  22227. //Tracev((stderr, "\nbl counts: "));
  22228. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  22229. send_bits(s, dcodes-1, 5);
  22230. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  22231. for (rank = 0; rank < blcodes; rank++) {
  22232. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  22233. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  22234. }
  22235. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  22236. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  22237. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  22238. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  22239. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  22240. }
  22241. /* ===========================================================================
  22242. * Check if the data type is TEXT or BINARY, using the following algorithm:
  22243. * - TEXT if the two conditions below are satisfied:
  22244. * a) There are no non-portable control characters belonging to the
  22245. * "black list" (0..6, 14..25, 28..31).
  22246. * b) There is at least one printable character belonging to the
  22247. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  22248. * - BINARY otherwise.
  22249. * - The following partially-portable control characters form a
  22250. * "gray list" that is ignored in this detection algorithm:
  22251. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  22252. * IN assertion: the fields Freq of dyn_ltree are set.
  22253. */
  22254. function detect_data_type(s) {
  22255. /* black_mask is the bit mask of black-listed bytes
  22256. * set bits 0..6, 14..25, and 28..31
  22257. * 0xf3ffc07f = binary 11110011111111111100000001111111
  22258. */
  22259. var black_mask = 0xf3ffc07f;
  22260. var n;
  22261. /* Check for non-textual ("black-listed") bytes. */
  22262. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  22263. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  22264. return Z_BINARY;
  22265. }
  22266. }
  22267. /* Check for textual ("white-listed") bytes. */
  22268. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  22269. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  22270. return Z_TEXT;
  22271. }
  22272. for (n = 32; n < LITERALS; n++) {
  22273. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  22274. return Z_TEXT;
  22275. }
  22276. }
  22277. /* There are no "black-listed" or "white-listed" bytes:
  22278. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  22279. */
  22280. return Z_BINARY;
  22281. }
  22282. var static_init_done = false;
  22283. /* ===========================================================================
  22284. * Initialize the tree data structures for a new zlib stream.
  22285. */
  22286. function _tr_init(s)
  22287. {
  22288. if (!static_init_done) {
  22289. tr_static_init();
  22290. static_init_done = true;
  22291. }
  22292. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  22293. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  22294. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  22295. s.bi_buf = 0;
  22296. s.bi_valid = 0;
  22297. /* Initialize the first block of the first file: */
  22298. init_block(s);
  22299. }
  22300. /* ===========================================================================
  22301. * Send a stored block
  22302. */
  22303. function _tr_stored_block(s, buf, stored_len, last)
  22304. //DeflateState *s;
  22305. //charf *buf; /* input block */
  22306. //ulg stored_len; /* length of input block */
  22307. //int last; /* one if this is the last block for a file */
  22308. {
  22309. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  22310. copy_block(s, buf, stored_len, true); /* with header */
  22311. }
  22312. /* ===========================================================================
  22313. * Send one empty static block to give enough lookahead for inflate.
  22314. * This takes 10 bits, of which 7 may remain in the bit buffer.
  22315. */
  22316. function _tr_align(s) {
  22317. send_bits(s, STATIC_TREES<<1, 3);
  22318. send_code(s, END_BLOCK, static_ltree);
  22319. bi_flush(s);
  22320. }
  22321. /* ===========================================================================
  22322. * Determine the best encoding for the current block: dynamic trees, static
  22323. * trees or store, and output the encoded block to the zip file.
  22324. */
  22325. function _tr_flush_block(s, buf, stored_len, last)
  22326. //DeflateState *s;
  22327. //charf *buf; /* input block, or NULL if too old */
  22328. //ulg stored_len; /* length of input block */
  22329. //int last; /* one if this is the last block for a file */
  22330. {
  22331. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  22332. var max_blindex = 0; /* index of last bit length code of non zero freq */
  22333. /* Build the Huffman trees unless a stored block is forced */
  22334. if (s.level > 0) {
  22335. /* Check if the file is binary or text */
  22336. if (s.strm.data_type === Z_UNKNOWN) {
  22337. s.strm.data_type = detect_data_type(s);
  22338. }
  22339. /* Construct the literal and distance trees */
  22340. build_tree(s, s.l_desc);
  22341. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  22342. // s->static_len));
  22343. build_tree(s, s.d_desc);
  22344. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  22345. // s->static_len));
  22346. /* At this point, opt_len and static_len are the total bit lengths of
  22347. * the compressed block data, excluding the tree representations.
  22348. */
  22349. /* Build the bit length tree for the above two trees, and get the index
  22350. * in bl_order of the last bit length code to send.
  22351. */
  22352. max_blindex = build_bl_tree(s);
  22353. /* Determine the best encoding. Compute the block lengths in bytes. */
  22354. opt_lenb = (s.opt_len+3+7) >>> 3;
  22355. static_lenb = (s.static_len+3+7) >>> 3;
  22356. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  22357. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  22358. // s->last_lit));
  22359. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  22360. } else {
  22361. // Assert(buf != (char*)0, "lost buf");
  22362. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  22363. }
  22364. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  22365. /* 4: two words for the lengths */
  22366. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  22367. * Otherwise we can't have processed more than WSIZE input bytes since
  22368. * the last block flush, because compression would have been
  22369. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  22370. * transform a block into a stored block.
  22371. */
  22372. _tr_stored_block(s, buf, stored_len, last);
  22373. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  22374. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  22375. compress_block(s, static_ltree, static_dtree);
  22376. } else {
  22377. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  22378. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  22379. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  22380. }
  22381. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  22382. /* The above check is made mod 2^32, for files larger than 512 MB
  22383. * and uLong implemented on 32 bits.
  22384. */
  22385. init_block(s);
  22386. if (last) {
  22387. bi_windup(s);
  22388. }
  22389. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  22390. // s->compressed_len-7*last));
  22391. }
  22392. /* ===========================================================================
  22393. * Save the match info and tally the frequency counts. Return true if
  22394. * the current block must be flushed.
  22395. */
  22396. function _tr_tally(s, dist, lc)
  22397. // deflate_state *s;
  22398. // unsigned dist; /* distance of matched string */
  22399. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  22400. {
  22401. //var out_length, in_length, dcode;
  22402. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  22403. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  22404. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  22405. s.last_lit++;
  22406. if (dist === 0) {
  22407. /* lc is the unmatched char */
  22408. s.dyn_ltree[lc*2]/*.Freq*/++;
  22409. } else {
  22410. s.matches++;
  22411. /* Here, lc is the match length - MIN_MATCH */
  22412. dist--; /* dist = match distance - 1 */
  22413. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  22414. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  22415. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  22416. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  22417. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  22418. }
  22419. // (!) This block is disabled in zlib defailts,
  22420. // don't enable it for binary compatibility
  22421. //#ifdef TRUNCATE_BLOCK
  22422. // /* Try to guess if it is profitable to stop the current block here */
  22423. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  22424. // /* Compute an upper bound for the compressed length */
  22425. // out_length = s.last_lit*8;
  22426. // in_length = s.strstart - s.block_start;
  22427. //
  22428. // for (dcode = 0; dcode < D_CODES; dcode++) {
  22429. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  22430. // }
  22431. // out_length >>>= 3;
  22432. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  22433. // // s->last_lit, in_length, out_length,
  22434. // // 100L - out_length*100L/in_length));
  22435. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  22436. // return true;
  22437. // }
  22438. // }
  22439. //#endif
  22440. return (s.last_lit === s.lit_bufsize-1);
  22441. /* We avoid equality with lit_bufsize because of wraparound at 64K
  22442. * on 16 bit machines and because stored blocks are restricted to
  22443. * 64K-1 bytes.
  22444. */
  22445. }
  22446. exports._tr_init = _tr_init;
  22447. exports._tr_stored_block = _tr_stored_block;
  22448. exports._tr_flush_block = _tr_flush_block;
  22449. exports._tr_tally = _tr_tally;
  22450. exports._tr_align = _tr_align;
  22451. },{"../utils/common":66}],78:[function(require,module,exports){
  22452. 'use strict';
  22453. function ZStream() {
  22454. /* next input byte */
  22455. this.input = null; // JS specific, because we have no pointers
  22456. this.next_in = 0;
  22457. /* number of bytes available at input */
  22458. this.avail_in = 0;
  22459. /* total number of input bytes read so far */
  22460. this.total_in = 0;
  22461. /* next output byte should be put there */
  22462. this.output = null; // JS specific, because we have no pointers
  22463. this.next_out = 0;
  22464. /* remaining free space at output */
  22465. this.avail_out = 0;
  22466. /* total number of bytes output so far */
  22467. this.total_out = 0;
  22468. /* last error message, NULL if no error */
  22469. this.msg = ''/*Z_NULL*/;
  22470. /* not visible by applications */
  22471. this.state = null;
  22472. /* best guess about the data type: binary or text */
  22473. this.data_type = 2/*Z_UNKNOWN*/;
  22474. /* adler32 value of the uncompressed data */
  22475. this.adler = 0;
  22476. }
  22477. module.exports = ZStream;
  22478. },{}],79:[function(require,module,exports){
  22479. var MediaStreamType = {
  22480. VIDEO_TYPE: "Video",
  22481. AUDIO_TYPE: "Audio"
  22482. };
  22483. module.exports = MediaStreamType;
  22484. },{}],80:[function(require,module,exports){
  22485. var RTCBrowserType = {
  22486. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  22487. RTC_BROWSER_FIREFOX: "rtc_browser.firefox"
  22488. };
  22489. module.exports = RTCBrowserType;
  22490. },{}],81:[function(require,module,exports){
  22491. var RTCEvents = {
  22492. LASTN_CHANGED: "rtc.lastn_changed",
  22493. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  22494. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  22495. SIMULCAST_LAYER_CHANGED: "rtc.simulcast_layer_changed",
  22496. SIMULCAST_LAYER_CHANGING: "rtc.simulcast_layer_changing",
  22497. SIMULCAST_START: "rtc.simlcast_start",
  22498. SIMULCAST_STOP: "rtc.simlcast_stop"
  22499. };
  22500. module.exports = RTCEvents;
  22501. },{}],82:[function(require,module,exports){
  22502. var Resolutions = {
  22503. "1080": {
  22504. width: 1920,
  22505. height: 1080,
  22506. order: 7
  22507. },
  22508. "fullhd": {
  22509. width: 1920,
  22510. height: 1080,
  22511. order: 7
  22512. },
  22513. "720": {
  22514. width: 1280,
  22515. height: 720,
  22516. order: 6
  22517. },
  22518. "hd": {
  22519. width: 1280,
  22520. height: 720,
  22521. order: 6
  22522. },
  22523. "960": {
  22524. width: 960,
  22525. height: 720,
  22526. order: 5
  22527. },
  22528. "640": {
  22529. width: 640,
  22530. height: 480,
  22531. order: 4
  22532. },
  22533. "vga": {
  22534. width: 640,
  22535. height: 480,
  22536. order: 4
  22537. },
  22538. "360": {
  22539. width: 640,
  22540. height: 360,
  22541. order: 3
  22542. },
  22543. "320": {
  22544. width: 320,
  22545. height: 240,
  22546. order: 2
  22547. },
  22548. "180": {
  22549. width: 320,
  22550. height: 180,
  22551. order: 1
  22552. }
  22553. };
  22554. module.exports = Resolutions;
  22555. },{}],83:[function(require,module,exports){
  22556. var StreamEventTypes = {
  22557. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  22558. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  22559. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  22560. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  22561. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended"
  22562. };
  22563. module.exports = StreamEventTypes;
  22564. },{}],84:[function(require,module,exports){
  22565. var UIEvents = {
  22566. NICKNAME_CHANGED: "UI.nickname_changed",
  22567. SELECTED_ENDPOINT: "UI.selected_endpoint",
  22568. PINNED_ENDPOINT: "UI.pinned_endpoint"
  22569. };
  22570. module.exports = UIEvents;
  22571. },{}],85:[function(require,module,exports){
  22572. var AuthenticationEvents = {
  22573. /**
  22574. * Event callback arguments:
  22575. * function(authenticationEnabled, userIdentity)
  22576. * authenticationEnabled - indicates whether authentication has been enabled
  22577. * in this session
  22578. * userIdentity - if user has been logged in then it contains user name. If
  22579. * contains 'null' or 'undefined' then user is not logged in.
  22580. */
  22581. IDENTITY_UPDATED: "authentication.identity_updated"
  22582. };
  22583. module.exports = AuthenticationEvents;
  22584. },{}],86:[function(require,module,exports){
  22585. var CQEvents = {
  22586. LOCALSTATS_UPDATED: "cq.localstats_updated",
  22587. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  22588. STOP: "cq.stop"
  22589. };
  22590. module.exports = CQEvents;
  22591. },{}],87:[function(require,module,exports){
  22592. var DesktopSharingEventTypes = {
  22593. INIT: "ds.init",
  22594. SWITCHING_DONE: "ds.switching_done",
  22595. NEW_STREAM_CREATED: "ds.new_stream_created"
  22596. };
  22597. module.exports = DesktopSharingEventTypes;
  22598. },{}],88:[function(require,module,exports){
  22599. module.exports = {
  22600. getLanguages : function () {
  22601. var languages = [];
  22602. for(var lang in this)
  22603. {
  22604. if(typeof this[lang] === "string")
  22605. languages.push(this[lang]);
  22606. }
  22607. return languages;
  22608. },
  22609. EN: "en",
  22610. BG: "bg",
  22611. DE: "de"
  22612. }
  22613. },{}],89:[function(require,module,exports){
  22614. var XMPPEvents = {
  22615. CONFERENCE_CERATED: "xmpp.conferenceCreated.jingle",
  22616. CALL_TERMINATED: "xmpp.callterminated.jingle",
  22617. CALL_INCOMING: "xmpp.callincoming.jingle",
  22618. DISPOSE_CONFERENCE: "xmpp.dispoce_confernce",
  22619. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  22620. KICKED: "xmpp.kicked",
  22621. BRIDGE_DOWN: "xmpp.bridge_down",
  22622. USER_ID_CHANGED: "xmpp.user_id_changed",
  22623. CHANGED_STREAMS: "xmpp.changed_streams",
  22624. MUC_JOINED: "xmpp.muc_joined",
  22625. MUC_ENTER: "xmpp.muc_enter",
  22626. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  22627. MUC_LEFT: "xmpp.muc_left",
  22628. MUC_DESTROYED: "xmpp.muc_destroyed",
  22629. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  22630. REMOTE_STATS: "xmpp.remote_stats",
  22631. LOCALROLE_CHANGED: "xmpp.localrole_changed",
  22632. PRESENCE_STATUS: "xmpp.presence_status",
  22633. RESERVATION_ERROR: "xmpp.room_reservation_error",
  22634. SUBJECT_CHANGED: "xmpp.subject_changed",
  22635. MESSAGE_RECEIVED: "xmpp.message_received",
  22636. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  22637. PASSWORD_REQUIRED: "xmpp.password_required",
  22638. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  22639. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  22640. ETHERPAD: "xmpp.etherpad"
  22641. };
  22642. module.exports = XMPPEvents;
  22643. },{}]},{},[2])(2)
  22644. });