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

app.bundle.js 859KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550
  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().userJid;
  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. dataChannel.send(JSON.stringify({
  674. 'colibriClass': 'SelectedEndpointChangedEvent',
  675. 'selectedEndpoint':
  676. (!userResource || userResource === null)?
  677. null : userResource
  678. }));
  679. return true;
  680. }
  681. });
  682. }
  683. }
  684. function onPinnedEndpointChanged(userResource)
  685. {
  686. console.log('pinned endpoint changed: ', userResource);
  687. if (_dataChannels && _dataChannels.length != 0)
  688. {
  689. _dataChannels.some(function (dataChannel) {
  690. if (dataChannel.readyState == 'open')
  691. {
  692. dataChannel.send(JSON.stringify({
  693. 'colibriClass': 'PinnedEndpointChangedEvent',
  694. 'pinnedEndpoint':
  695. (!userResource || userResource == null)?
  696. null : userResource
  697. }));
  698. return true;
  699. }
  700. });
  701. }
  702. }
  703. module.exports = DataChannels;
  704. },{"../../service/RTC/RTCEvents":81}],5:[function(require,module,exports){
  705. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  706. function LocalStream(stream, type, eventEmitter, videoType)
  707. {
  708. this.stream = stream;
  709. this.eventEmitter = eventEmitter;
  710. this.type = type;
  711. this.videoType = videoType;
  712. var self = this;
  713. if(type == "audio")
  714. {
  715. this.getTracks = function () {
  716. return self.stream.getAudioTracks();
  717. };
  718. }
  719. else
  720. {
  721. this.getTracks = function () {
  722. return self.stream.getVideoTracks();
  723. };
  724. }
  725. this.stream.onended = function()
  726. {
  727. self.streamEnded();
  728. };
  729. }
  730. LocalStream.prototype.streamEnded = function () {
  731. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  732. }
  733. LocalStream.prototype.getOriginalStream = function()
  734. {
  735. return this.stream;
  736. }
  737. LocalStream.prototype.isAudioStream = function () {
  738. return (this.stream.getAudioTracks() && this.stream.getAudioTracks().length > 0);
  739. };
  740. LocalStream.prototype.mute = function()
  741. {
  742. var ismuted = false;
  743. var tracks = this.getTracks();
  744. for (var idx = 0; idx < tracks.length; idx++) {
  745. ismuted = !tracks[idx].enabled;
  746. tracks[idx].enabled = ismuted;
  747. }
  748. return ismuted;
  749. };
  750. LocalStream.prototype.setMute = function(mute)
  751. {
  752. var tracks = this.getTracks();
  753. for (var idx = 0; idx < tracks.length; idx++) {
  754. tracks[idx].enabled = mute;
  755. }
  756. };
  757. LocalStream.prototype.isMuted = function () {
  758. var tracks = [];
  759. if(this.type == "audio")
  760. {
  761. tracks = this.stream.getAudioTracks();
  762. }
  763. else
  764. {
  765. tracks = this.stream.getVideoTracks();
  766. }
  767. for (var idx = 0; idx < tracks.length; idx++) {
  768. if(tracks[idx].enabled)
  769. return false;
  770. }
  771. return true;
  772. }
  773. LocalStream.prototype.getId = function () {
  774. return this.stream.getTracks()[0].id;
  775. }
  776. module.exports = LocalStream;
  777. },{"../../service/RTC/StreamEventTypes.js":83}],6:[function(require,module,exports){
  778. ////These lines should be uncommented when require works in app.js
  779. var RTCBrowserType = require("../../service/RTC/RTCBrowserType.js");
  780. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  781. /**
  782. * Creates a MediaStream object for the given data, session id and ssrc.
  783. * It is a wrapper class for the MediaStream.
  784. *
  785. * @param data the data object from which we obtain the stream,
  786. * the peerjid, etc.
  787. * @param sid the session id
  788. * @param ssrc the ssrc corresponding to this MediaStream
  789. *
  790. * @constructor
  791. */
  792. function MediaStream(data, sid, ssrc, browser) {
  793. // XXX(gp) to minimize headaches in the future, we should build our
  794. // abstractions around tracks and not streams. ORTC is track based API.
  795. // Mozilla expects m-lines to represent media tracks.
  796. //
  797. // Practically, what I'm saying is that we should have a MediaTrack class
  798. // and not a MediaStream class.
  799. //
  800. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  801. // a track might have an associated RTX and FEC sources.
  802. this.sid = sid;
  803. this.stream = data.stream;
  804. this.peerjid = data.peerjid;
  805. this.ssrc = ssrc;
  806. this.type = (this.stream.getVideoTracks().length > 0)?
  807. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  808. this.videoType = null;
  809. this.muted = false;
  810. if(browser == RTCBrowserType.RTC_BROWSER_FIREFOX)
  811. {
  812. if (!this.getVideoTracks)
  813. this.getVideoTracks = function () { return []; };
  814. if (!this.getAudioTracks)
  815. this.getAudioTracks = function () { return []; };
  816. }
  817. }
  818. MediaStream.prototype.getOriginalStream = function()
  819. {
  820. return this.stream;
  821. }
  822. MediaStream.prototype.setMute = function (value)
  823. {
  824. this.stream.muted = value;
  825. this.muted = value;
  826. }
  827. module.exports = MediaStream;
  828. },{"../../service/RTC/MediaStreamTypes":79,"../../service/RTC/RTCBrowserType.js":80}],7:[function(require,module,exports){
  829. var EventEmitter = require("events");
  830. var RTCUtils = require("./RTCUtils.js");
  831. var LocalStream = require("./LocalStream.js");
  832. var DataChannels = require("./DataChannels");
  833. var MediaStream = require("./MediaStream.js");
  834. var DesktopSharingEventTypes
  835. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  836. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  837. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  838. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  839. var UIEvents = require("../../service/UI/UIEvents");
  840. var eventEmitter = new EventEmitter();
  841. var RTC = {
  842. rtcUtils: null,
  843. localStreams: [],
  844. remoteStreams: {},
  845. localAudio: null,
  846. localVideo: null,
  847. addStreamListener: function (listener, eventType) {
  848. eventEmitter.on(eventType, listener);
  849. },
  850. addListener: function (type, listener) {
  851. eventEmitter.on(type, listener);
  852. },
  853. removeStreamListener: function (listener, eventType) {
  854. if(!(eventType instanceof StreamEventTypes))
  855. throw "Illegal argument";
  856. eventEmitter.removeListener(eventType, listener);
  857. },
  858. createLocalStream: function (stream, type, change) {
  859. var localStream = new LocalStream(stream, type, eventEmitter);
  860. //in firefox we have only one stream object
  861. if(this.localStreams.length == 0 ||
  862. this.localStreams[0].getOriginalStream() != stream)
  863. this.localStreams.push(localStream);
  864. if(type == "audio")
  865. {
  866. this.localAudio = localStream;
  867. }
  868. else
  869. {
  870. this.localVideo = localStream;
  871. }
  872. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  873. if(change)
  874. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  875. eventEmitter.emit(eventType, localStream);
  876. return localStream;
  877. },
  878. removeLocalStream: function (stream) {
  879. for(var i = 0; i < this.localStreams.length; i++)
  880. {
  881. if(this.localStreams[i].getOriginalStream() === stream) {
  882. delete this.localStreams[i];
  883. return;
  884. }
  885. }
  886. },
  887. createRemoteStream: function (data, sid, thessrc) {
  888. var remoteStream = new MediaStream(data, sid, thessrc,
  889. this.getBrowserType());
  890. var jid = data.peerjid || APP.xmpp.myJid();
  891. if(!this.remoteStreams[jid]) {
  892. this.remoteStreams[jid] = {};
  893. }
  894. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  895. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  896. console.debug("ADD remote stream ", remoteStream.type, " ", jid, " ", thessrc);
  897. return remoteStream;
  898. },
  899. getBrowserType: function () {
  900. return this.rtcUtils.browser;
  901. },
  902. getPCConstraints: function () {
  903. return this.rtcUtils.pc_constraints;
  904. },
  905. getUserMediaWithConstraints:function(um, success_callback,
  906. failure_callback, resolution,
  907. bandwidth, fps, desktopStream)
  908. {
  909. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  910. failure_callback, resolution, bandwidth, fps, desktopStream);
  911. },
  912. attachMediaStream: function (element, stream) {
  913. this.rtcUtils.attachMediaStream(element, stream);
  914. },
  915. getStreamID: function (stream) {
  916. return this.rtcUtils.getStreamID(stream);
  917. },
  918. getVideoSrc: function (element) {
  919. return this.rtcUtils.getVideoSrc(element);
  920. },
  921. setVideoSrc: function (element, src) {
  922. this.rtcUtils.setVideoSrc(element, src);
  923. },
  924. dispose: function() {
  925. if (this.rtcUtils) {
  926. this.rtcUtils = null;
  927. }
  928. },
  929. stop: function () {
  930. this.dispose();
  931. },
  932. start: function () {
  933. var self = this;
  934. APP.desktopsharing.addListener(
  935. function (stream, isUsingScreenStream, callback) {
  936. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  937. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  938. APP.xmpp.addListener(XMPPEvents.CHANGED_STREAMS, function (jid, changedStreams) {
  939. for(var i = 0; i < changedStreams.length; i++) {
  940. var type = changedStreams[i].type;
  941. if (type != "audio") {
  942. var peerStreams = self.remoteStreams[jid];
  943. if(!peerStreams)
  944. continue;
  945. var videoStream = peerStreams[MediaStreamType.VIDEO_TYPE];
  946. if(!videoStream)
  947. continue;
  948. videoStream.videoType = changedStreams[i].type;
  949. }
  950. }
  951. });
  952. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  953. DataChannels.init(event.peerconnection, eventEmitter);
  954. });
  955. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  956. DataChannels.handleSelectedEndpointEvent);
  957. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  958. DataChannels.handlePinnedEndpointEvent);
  959. this.rtcUtils = new RTCUtils(this);
  960. this.rtcUtils.obtainAudioAndVideoPermissions();
  961. },
  962. muteRemoteVideoStream: function (jid, value) {
  963. var stream;
  964. if(this.remoteStreams[jid] &&
  965. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE])
  966. {
  967. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  968. }
  969. if(!stream)
  970. return false;
  971. if (value != stream.muted) {
  972. stream.setMute(value);
  973. return true;
  974. }
  975. return false;
  976. },
  977. switchVideoStreams: function (new_stream) {
  978. this.localVideo.stream = new_stream;
  979. this.localStreams = [];
  980. //in firefox we have only one stream object
  981. if (this.localAudio.getOriginalStream() != new_stream)
  982. this.localStreams.push(this.localAudio);
  983. this.localStreams.push(this.localVideo);
  984. },
  985. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  986. var oldStream = this.localVideo.getOriginalStream();
  987. var type = (isUsingScreenStream? "screen" : "video");
  988. this.localVideo = this.createLocalStream(stream, "video", true, type);
  989. // Stop the stream to trigger onended event for old stream
  990. oldStream.stop();
  991. APP.xmpp.switchStreams(stream, oldStream,callback);
  992. },
  993. /**
  994. * Checks if video identified by given src is desktop stream.
  995. * @param videoSrc eg.
  996. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  997. * @returns {boolean}
  998. */
  999. isVideoSrcDesktop: function (jid) {
  1000. if(!jid)
  1001. return false;
  1002. var isDesktop = false;
  1003. var stream = null;
  1004. if (APP.xmpp.myJid() &&
  1005. APP.xmpp.myResource() === jid) {
  1006. // local video
  1007. stream = this.localVideo;
  1008. } else {
  1009. var peerStreams = this.remoteStreams[jid];
  1010. if(!peerStreams)
  1011. return false;
  1012. stream = peerStreams[MediaStreamType.VIDEO_TYPE];
  1013. }
  1014. if(stream)
  1015. isDesktop = (stream.videoType === "screen");
  1016. return isDesktop;
  1017. }
  1018. };
  1019. module.exports = RTC;
  1020. },{"../../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){
  1021. var RTCBrowserType = require("../../service/RTC/RTCBrowserType.js");
  1022. var Resolutions = require("../../service/RTC/Resolutions");
  1023. var currentResolution = null;
  1024. function getPreviousResolution(resolution) {
  1025. if(!Resolutions[resolution])
  1026. return null;
  1027. var order = Resolutions[resolution].order;
  1028. var res = null;
  1029. var resName = null;
  1030. for(var i in Resolutions)
  1031. {
  1032. var tmp = Resolutions[i];
  1033. if(res == null || (res.order < tmp.order && tmp.order < order))
  1034. {
  1035. resName = i;
  1036. res = tmp;
  1037. }
  1038. }
  1039. return resName;
  1040. }
  1041. function setResolutionConstraints(constraints, resolution, isAndroid)
  1042. {
  1043. if (resolution && !constraints.video || isAndroid) {
  1044. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  1045. }
  1046. if(Resolutions[resolution])
  1047. {
  1048. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1049. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1050. }
  1051. else
  1052. {
  1053. if (isAndroid) {
  1054. constraints.video.mandatory.minWidth = 320;
  1055. constraints.video.mandatory.minHeight = 240;
  1056. constraints.video.mandatory.maxFrameRate = 15;
  1057. }
  1058. }
  1059. if (constraints.video.mandatory.minWidth)
  1060. constraints.video.mandatory.maxWidth = constraints.video.mandatory.minWidth;
  1061. if (constraints.video.mandatory.minHeight)
  1062. constraints.video.mandatory.maxHeight = constraints.video.mandatory.minHeight;
  1063. }
  1064. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  1065. {
  1066. var constraints = {audio: false, video: false};
  1067. if (um.indexOf('video') >= 0) {
  1068. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  1069. }
  1070. if (um.indexOf('audio') >= 0) {
  1071. constraints.audio = { mandatory: {}, optional: []};// same behaviour as true
  1072. }
  1073. if (um.indexOf('screen') >= 0) {
  1074. constraints.video = {
  1075. mandatory: {
  1076. chromeMediaSource: "screen",
  1077. googLeakyBucket: true,
  1078. maxWidth: window.screen.width,
  1079. maxHeight: window.screen.height,
  1080. maxFrameRate: 3
  1081. },
  1082. optional: []
  1083. };
  1084. }
  1085. if (um.indexOf('desktop') >= 0) {
  1086. constraints.video = {
  1087. mandatory: {
  1088. chromeMediaSource: "desktop",
  1089. chromeMediaSourceId: desktopStream,
  1090. googLeakyBucket: true,
  1091. maxWidth: window.screen.width,
  1092. maxHeight: window.screen.height,
  1093. maxFrameRate: 3
  1094. },
  1095. optional: []
  1096. };
  1097. }
  1098. if (constraints.audio) {
  1099. // if it is good enough for hangouts...
  1100. constraints.audio.optional.push(
  1101. {googEchoCancellation: true},
  1102. {googAutoGainControl: true},
  1103. {googNoiseSupression: true},
  1104. {googHighpassFilter: true},
  1105. {googNoisesuppression2: true},
  1106. {googEchoCancellation2: true},
  1107. {googAutoGainControl2: true}
  1108. );
  1109. }
  1110. if (constraints.video) {
  1111. constraints.video.optional.push(
  1112. {googNoiseReduction: false} // chrome 37 workaround for issue 3807, reenable in M38
  1113. );
  1114. if (um.indexOf('video') >= 0) {
  1115. constraints.video.optional.push(
  1116. {googLeakyBucket: true}
  1117. );
  1118. }
  1119. }
  1120. if (um.indexOf('video') >= 0) {
  1121. setResolutionConstraints(constraints, resolution, isAndroid);
  1122. }
  1123. if (bandwidth) { // doesn't work currently, see webrtc issue 1846
  1124. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};//same behaviour as true
  1125. constraints.video.optional.push({bandwidth: bandwidth});
  1126. }
  1127. if (fps) { // for some cameras it might be necessary to request 30fps
  1128. // so they choose 30fps mjpg over 10fps yuy2
  1129. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};// same behaviour as true;
  1130. constraints.video.mandatory.minFrameRate = fps;
  1131. }
  1132. return constraints;
  1133. }
  1134. function RTCUtils(RTCService)
  1135. {
  1136. this.service = RTCService;
  1137. if (navigator.mozGetUserMedia) {
  1138. console.log('This appears to be Firefox');
  1139. var version = parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1140. if (version >= 22) {
  1141. this.peerconnection = mozRTCPeerConnection;
  1142. this.browser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  1143. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1144. this.pc_constraints = {};
  1145. this.attachMediaStream = function (element, stream) {
  1146. element[0].mozSrcObject = stream;
  1147. element[0].play();
  1148. };
  1149. this.getStreamID = function (stream) {
  1150. var tracks = stream.getVideoTracks();
  1151. if(!tracks || tracks.length == 0)
  1152. {
  1153. tracks = stream.getAudioTracks();
  1154. }
  1155. return tracks[0].id.replace(/[\{,\}]/g,"");
  1156. };
  1157. this.getVideoSrc = function (element) {
  1158. return element.mozSrcObject;
  1159. };
  1160. this.setVideoSrc = function (element, src) {
  1161. element.mozSrcObject = src;
  1162. };
  1163. RTCSessionDescription = mozRTCSessionDescription;
  1164. RTCIceCandidate = mozRTCIceCandidate;
  1165. }
  1166. } else if (navigator.webkitGetUserMedia) {
  1167. console.log('This appears to be Chrome');
  1168. this.peerconnection = webkitRTCPeerConnection;
  1169. this.browser = RTCBrowserType.RTC_BROWSER_CHROME;
  1170. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1171. this.attachMediaStream = function (element, stream) {
  1172. element.attr('src', webkitURL.createObjectURL(stream));
  1173. };
  1174. this.getStreamID = function (stream) {
  1175. // streams from FF endpoints have the characters '{' and '}'
  1176. // that make jQuery choke.
  1177. return stream.id.replace(/[\{,\}]/g,"");
  1178. };
  1179. this.getVideoSrc = function (element) {
  1180. return element.getAttribute("src");
  1181. };
  1182. this.setVideoSrc = function (element, src) {
  1183. element.setAttribute("src", src);
  1184. };
  1185. // DTLS should now be enabled by default but..
  1186. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  1187. if (navigator.userAgent.indexOf('Android') != -1) {
  1188. this.pc_constraints = {}; // disable DTLS on Android
  1189. }
  1190. if (!webkitMediaStream.prototype.getVideoTracks) {
  1191. webkitMediaStream.prototype.getVideoTracks = function () {
  1192. return this.videoTracks;
  1193. };
  1194. }
  1195. if (!webkitMediaStream.prototype.getAudioTracks) {
  1196. webkitMediaStream.prototype.getAudioTracks = function () {
  1197. return this.audioTracks;
  1198. };
  1199. }
  1200. }
  1201. else
  1202. {
  1203. try { console.log('Browser does not appear to be WebRTC-capable'); } catch (e) { }
  1204. window.location.href = 'webrtcrequired.html';
  1205. return;
  1206. }
  1207. if (this.browser !== RTCBrowserType.RTC_BROWSER_CHROME &&
  1208. config.enableFirefoxSupport !== true) {
  1209. window.location.href = 'chromeonly.html';
  1210. return;
  1211. }
  1212. }
  1213. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1214. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1215. desktopStream)
  1216. {
  1217. currentResolution = resolution;
  1218. // Check if we are running on Android device
  1219. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1220. var constraints = getConstraints(
  1221. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1222. var isFF = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
  1223. try {
  1224. if (config.enableSimulcast
  1225. && constraints.video
  1226. && constraints.video.chromeMediaSource !== 'screen'
  1227. && constraints.video.chromeMediaSource !== 'desktop'
  1228. && !isAndroid
  1229. // We currently do not support FF, as it doesn't have multistream support.
  1230. && !isFF) {
  1231. APP.simulcast.getUserMedia(constraints, function (stream) {
  1232. console.log('onUserMediaSuccess');
  1233. success_callback(stream);
  1234. },
  1235. function (error) {
  1236. console.warn('Failed to get access to local media. Error ', error);
  1237. if (failure_callback) {
  1238. failure_callback(error);
  1239. }
  1240. });
  1241. } else {
  1242. this.getUserMedia(constraints,
  1243. function (stream) {
  1244. console.log('onUserMediaSuccess');
  1245. success_callback(stream);
  1246. },
  1247. function (error) {
  1248. console.warn('Failed to get access to local media. Error ',
  1249. error, constraints);
  1250. if (failure_callback) {
  1251. failure_callback(error);
  1252. }
  1253. });
  1254. }
  1255. } catch (e) {
  1256. console.error('GUM failed: ', e);
  1257. if(failure_callback) {
  1258. failure_callback(e);
  1259. }
  1260. }
  1261. };
  1262. /**
  1263. * We ask for audio and video combined stream in order to get permissions and
  1264. * not to ask twice.
  1265. */
  1266. RTCUtils.prototype.obtainAudioAndVideoPermissions = function() {
  1267. var self = this;
  1268. // Get AV
  1269. this.getUserMediaWithConstraints(
  1270. ['audio', 'video'],
  1271. function (stream) {
  1272. self.successCallback(stream);
  1273. },
  1274. function (error) {
  1275. self.errorCallback(error);
  1276. },
  1277. config.resolution || '360');
  1278. }
  1279. RTCUtils.prototype.successCallback = function (stream) {
  1280. console.log('got', stream, stream.getAudioTracks().length,
  1281. stream.getVideoTracks().length);
  1282. this.handleLocalStream(stream);
  1283. };
  1284. RTCUtils.prototype.errorCallback = function (error) {
  1285. var self = this;
  1286. console.error('failed to obtain audio/video stream - trying audio only', error);
  1287. var resolution = getPreviousResolution(currentResolution);
  1288. if(typeof error == "object" && error.constraintName && error.name
  1289. && (error.name == "ConstraintNotSatisfiedError" ||
  1290. error.name == "OverconstrainedError") &&
  1291. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1292. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1293. && resolution != null)
  1294. {
  1295. self.getUserMediaWithConstraints(['audio', 'video'],
  1296. function (stream) {
  1297. return self.successCallback(stream);
  1298. }, function (error) {
  1299. return self.errorCallback(error);
  1300. }, resolution);
  1301. }
  1302. else
  1303. {
  1304. self.getUserMediaWithConstraints(
  1305. ['audio'],
  1306. function (stream) {
  1307. return self.successCallback(stream);
  1308. },
  1309. function (error) {
  1310. console.error('failed to obtain audio/video stream - stop', error);
  1311. APP.UI.messageHandler.showError("Error",
  1312. "Failed to obtain permissions to use the local microphone" +
  1313. "and/or camera.");
  1314. }
  1315. );
  1316. }
  1317. }
  1318. RTCUtils.prototype.handleLocalStream = function(stream)
  1319. {
  1320. if(window.webkitMediaStream)
  1321. {
  1322. var audioStream = new webkitMediaStream();
  1323. var videoStream = new webkitMediaStream();
  1324. var audioTracks = stream.getAudioTracks();
  1325. var videoTracks = stream.getVideoTracks();
  1326. for (var i = 0; i < audioTracks.length; i++) {
  1327. audioStream.addTrack(audioTracks[i]);
  1328. }
  1329. this.service.createLocalStream(audioStream, "audio");
  1330. for (i = 0; i < videoTracks.length; i++) {
  1331. videoStream.addTrack(videoTracks[i]);
  1332. }
  1333. this.service.createLocalStream(videoStream, "video");
  1334. }
  1335. else
  1336. {//firefox
  1337. this.service.createLocalStream(stream, "stream");
  1338. }
  1339. };
  1340. module.exports = RTCUtils;
  1341. },{"../../service/RTC/RTCBrowserType.js":80,"../../service/RTC/Resolutions":82}],9:[function(require,module,exports){
  1342. var UI = {};
  1343. var VideoLayout = require("./videolayout/VideoLayout.js");
  1344. var AudioLevels = require("./audio_levels/AudioLevels.js");
  1345. var Prezi = require("./prezi/Prezi.js");
  1346. var Etherpad = require("./etherpad/Etherpad.js");
  1347. var Chat = require("./side_pannels/chat/Chat.js");
  1348. var Toolbar = require("./toolbars/Toolbar");
  1349. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  1350. var BottomToolbar = require("./toolbars/BottomToolbar");
  1351. var ContactList = require("./side_pannels/contactlist/ContactList");
  1352. var Avatar = require("./avatar/Avatar");
  1353. var EventEmitter = require("events");
  1354. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  1355. var Settings = require("./../settings/Settings");
  1356. var PanelToggler = require("./side_pannels/SidePanelToggler");
  1357. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  1358. UI.messageHandler = require("./util/MessageHandler");
  1359. var messageHandler = UI.messageHandler;
  1360. var Authentication = require("./authentication/Authentication");
  1361. var UIUtil = require("./util/UIUtil");
  1362. var NicknameHandler = require("./util/NicknameHandler");
  1363. var CQEvents = require("../../service/connectionquality/CQEvents");
  1364. var DesktopSharingEventTypes
  1365. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1366. var RTCEvents = require("../../service/RTC/RTCEvents");
  1367. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  1368. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  1369. var eventEmitter = new EventEmitter();
  1370. var roomName = null;
  1371. function setupPrezi()
  1372. {
  1373. $("#reloadPresentationLink").click(function()
  1374. {
  1375. Prezi.reloadPresentation();
  1376. });
  1377. }
  1378. function setupChat()
  1379. {
  1380. Chat.init();
  1381. $("#toggle_smileys").click(function() {
  1382. Chat.toggleSmileys();
  1383. });
  1384. }
  1385. function setupToolbars() {
  1386. Toolbar.init(UI);
  1387. Toolbar.setupButtonsFromConfig();
  1388. BottomToolbar.init();
  1389. }
  1390. function streamHandler(stream) {
  1391. switch (stream.type)
  1392. {
  1393. case "audio":
  1394. VideoLayout.changeLocalAudio(stream);
  1395. break;
  1396. case "video":
  1397. VideoLayout.changeLocalVideo(stream);
  1398. break;
  1399. case "stream":
  1400. VideoLayout.changeLocalStream(stream);
  1401. break;
  1402. }
  1403. }
  1404. function onDisposeConference(unload) {
  1405. Toolbar.showAuthenticateButton(false);
  1406. };
  1407. function onDisplayNameChanged(jid, displayName) {
  1408. ContactList.onDisplayNameChange(jid, displayName);
  1409. SettingsMenu.onDisplayNameChange(jid, displayName);
  1410. VideoLayout.onDisplayNameChanged(jid, displayName);
  1411. }
  1412. function registerListeners() {
  1413. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  1414. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  1415. APP.RTC.addStreamListener(function (stream) {
  1416. VideoLayout.onRemoteStreamAdded(stream);
  1417. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  1418. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  1419. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (resourceJid) {
  1420. VideoLayout.onDominantSpeakerChanged(resourceJid);
  1421. });
  1422. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1423. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  1424. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  1425. endpointsEnteringLastN, stream);
  1426. });
  1427. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  1428. function (endpointSimulcastLayers) {
  1429. VideoLayout.onSimulcastLayersChanged(endpointSimulcastLayers);
  1430. });
  1431. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGING,
  1432. function (endpointSimulcastLayers) {
  1433. VideoLayout.onSimulcastLayersChanging(endpointSimulcastLayers);
  1434. });
  1435. APP.statistics.addAudioLevelListener(function(jid, audioLevel)
  1436. {
  1437. var resourceJid;
  1438. if(jid === APP.statistics.LOCAL_JID)
  1439. {
  1440. resourceJid = AudioLevels.LOCAL_LEVEL;
  1441. if(APP.RTC.localAudio.isMuted())
  1442. {
  1443. audioLevel = 0;
  1444. }
  1445. }
  1446. else
  1447. {
  1448. resourceJid = Strophe.getResourceFromJid(jid);
  1449. }
  1450. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  1451. UI.getLargeVideoState().userResourceJid);
  1452. });
  1453. APP.desktopsharing.addListener(function () {
  1454. ToolbarToggler.showDesktopSharingButton();
  1455. }, DesktopSharingEventTypes.INIT);
  1456. APP.desktopsharing.addListener(
  1457. Toolbar.changeDesktopSharingButtonState,
  1458. DesktopSharingEventTypes.SWITCHING_DONE);
  1459. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  1460. VideoLayout.updateLocalConnectionStats);
  1461. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  1462. VideoLayout.updateConnectionStats);
  1463. APP.connectionquality.addListener(CQEvents.STOP,
  1464. VideoLayout.onStatsStop);
  1465. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  1466. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  1467. messageHandler.openMessageDialog("Session Terminated",
  1468. "Ouch! You have been kicked out of the meet!");
  1469. });
  1470. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  1471. messageHandler.showError("Error",
  1472. "Jitsi Videobridge is currently unavailable. Please try again later!");
  1473. });
  1474. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  1475. Avatar.setUserAvatar(from, id);
  1476. });
  1477. APP.xmpp.addListener(XMPPEvents.CHANGED_STREAMS, function (jid, changedStreams) {
  1478. for(stream in changedStreams)
  1479. {
  1480. // might need to update the direction if participant just went from sendrecv to recvonly
  1481. if (stream.type === 'video' || stream.type === 'screen') {
  1482. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  1483. switch (stream.direction) {
  1484. case 'sendrecv':
  1485. el.show();
  1486. break;
  1487. case 'recvonly':
  1488. el.hide();
  1489. // FIXME: Check if we have to change large video
  1490. //VideoLayout.updateLargeVideo(el);
  1491. break;
  1492. }
  1493. }
  1494. }
  1495. });
  1496. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  1497. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  1498. APP.xmpp.addListener(XMPPEvents.LOCALROLE_CHANGED, onLocalRoleChange);
  1499. APP.xmpp.addListener(XMPPEvents.MUC_ENTER, onMucEntered);
  1500. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  1501. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  1502. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  1503. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  1504. APP.xmpp.addListener(XMPPEvents.MUC_LEFT, onMucLeft);
  1505. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordReqiured);
  1506. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  1507. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  1508. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED, onAuthenticationRequired);
  1509. }
  1510. /**
  1511. * Mutes/unmutes the local video.
  1512. *
  1513. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  1514. * @param options an object which specifies optional arguments such as the
  1515. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  1516. * specifies whether the method was initiated in response to a user command (in
  1517. * contrast to an automatic decision taken by the application logic)
  1518. */
  1519. function setVideoMute(mute, options) {
  1520. APP.xmpp.setVideoMute(
  1521. mute,
  1522. function (mute) {
  1523. var video = $('#video');
  1524. var communicativeClass = "icon-camera";
  1525. var muteClass = "icon-camera icon-camera-disabled";
  1526. if (mute) {
  1527. video.removeClass(communicativeClass);
  1528. video.addClass(muteClass);
  1529. } else {
  1530. video.removeClass(muteClass);
  1531. video.addClass(communicativeClass);
  1532. }
  1533. },
  1534. options);
  1535. }
  1536. function bindEvents()
  1537. {
  1538. /**
  1539. * Resizes and repositions videos in full screen mode.
  1540. */
  1541. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1542. function () {
  1543. VideoLayout.resizeLargeVideoContainer();
  1544. VideoLayout.positionLarge();
  1545. }
  1546. );
  1547. $(window).resize(function () {
  1548. VideoLayout.resizeLargeVideoContainer();
  1549. VideoLayout.positionLarge();
  1550. });
  1551. }
  1552. UI.start = function (init) {
  1553. document.title = interfaceConfig.APP_NAME;
  1554. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1555. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1556. {
  1557. $("#videoconference_page").hide();
  1558. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1559. setupWelcomePage();
  1560. return;
  1561. }
  1562. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  1563. var leftWatermarkDiv
  1564. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  1565. leftWatermarkDiv.css({display: 'block'});
  1566. leftWatermarkDiv.parent().get(0).href
  1567. = interfaceConfig.JITSI_WATERMARK_LINK;
  1568. }
  1569. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1570. var rightWatermarkDiv
  1571. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  1572. rightWatermarkDiv.css({display: 'block'});
  1573. rightWatermarkDiv.parent().get(0).href
  1574. = interfaceConfig.BRAND_WATERMARK_LINK;
  1575. rightWatermarkDiv.get(0).style.backgroundImage
  1576. = "url(images/rightwatermark.png)";
  1577. }
  1578. if (interfaceConfig.SHOW_POWERED_BY) {
  1579. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  1580. }
  1581. $("#welcome_page").hide();
  1582. VideoLayout.resizeLargeVideoContainer();
  1583. $("#videospace").mousemove(function () {
  1584. return ToolbarToggler.showToolbar();
  1585. });
  1586. // Set the defaults for prompt dialogs.
  1587. jQuery.prompt.setDefaults({persistent: false});
  1588. VideoLayout.init(eventEmitter);
  1589. AudioLevels.init();
  1590. NicknameHandler.init(eventEmitter);
  1591. registerListeners();
  1592. bindEvents();
  1593. setupPrezi();
  1594. setupToolbars();
  1595. setupChat();
  1596. document.title = interfaceConfig.APP_NAME;
  1597. $("#downloadlog").click(function (event) {
  1598. dump(event.target);
  1599. });
  1600. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1601. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1602. {
  1603. $("#videoconference_page").hide();
  1604. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1605. setupWelcomePage();
  1606. return;
  1607. }
  1608. $("#welcome_page").hide();
  1609. document.getElementById('largeVideo').volume = 0;
  1610. if (!$('#settings').is(':visible')) {
  1611. console.log('init');
  1612. init();
  1613. } else {
  1614. loginInfo.onsubmit = function (e) {
  1615. if (e.preventDefault) e.preventDefault();
  1616. $('#settings').hide();
  1617. init();
  1618. };
  1619. }
  1620. toastr.options = {
  1621. "closeButton": true,
  1622. "debug": false,
  1623. "positionClass": "notification-bottom-right",
  1624. "onclick": null,
  1625. "showDuration": "300",
  1626. "hideDuration": "1000",
  1627. "timeOut": "2000",
  1628. "extendedTimeOut": "1000",
  1629. "showEasing": "swing",
  1630. "hideEasing": "linear",
  1631. "showMethod": "fadeIn",
  1632. "hideMethod": "fadeOut",
  1633. "reposition": function() {
  1634. if(PanelToggler.isVisible()) {
  1635. $("#toast-container").addClass("notification-bottom-right-center");
  1636. } else {
  1637. $("#toast-container").removeClass("notification-bottom-right-center");
  1638. }
  1639. },
  1640. "newestOnTop": false
  1641. };
  1642. SettingsMenu.init();
  1643. };
  1644. function chatAddError(errorMessage, originalText)
  1645. {
  1646. return Chat.chatAddError(errorMessage, originalText);
  1647. };
  1648. function chatSetSubject(text)
  1649. {
  1650. return Chat.chatSetSubject(text);
  1651. };
  1652. function updateChatConversation(from, displayName, message) {
  1653. return Chat.updateChatConversation(from, displayName, message);
  1654. };
  1655. function onMucJoined(jid, info) {
  1656. Toolbar.updateRoomUrl(window.location.href);
  1657. document.getElementById('localNick').appendChild(
  1658. document.createTextNode(Strophe.getResourceFromJid(jid) + ' (me)')
  1659. );
  1660. var settings = Settings.getSettings();
  1661. // Add myself to the contact list.
  1662. ContactList.addContact(jid, settings.email || settings.uid);
  1663. // Once we've joined the muc show the toolbar
  1664. ToolbarToggler.showToolbar();
  1665. var displayName = !config.displayJids
  1666. ? info.displayName : Strophe.getResourceFromJid(jid);
  1667. if (displayName)
  1668. onDisplayNameChanged('localVideoContainer', displayName + ' (me)');
  1669. }
  1670. function initEtherpad(name) {
  1671. Etherpad.init(name);
  1672. };
  1673. function onMucLeft(jid) {
  1674. console.log('left.muc', jid);
  1675. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  1676. '>.displayname').html();
  1677. messageHandler.notify(displayName,'notify.somebody', "Somebody",
  1678. 'disconnected',
  1679. 'notify.disconnected', "disconnected");
  1680. // Need to call this with a slight delay, otherwise the element couldn't be
  1681. // found for some reason.
  1682. // XXX(gp) it works fine without the timeout for me (with Chrome 38).
  1683. window.setTimeout(function () {
  1684. var container = document.getElementById(
  1685. 'participant_' + Strophe.getResourceFromJid(jid));
  1686. if (container) {
  1687. ContactList.removeContact(jid);
  1688. VideoLayout.removeConnectionIndicator(jid);
  1689. // hide here, wait for video to close before removing
  1690. $(container).hide();
  1691. VideoLayout.resizeThumbnails();
  1692. }
  1693. }, 10);
  1694. VideoLayout.participantLeft(jid);
  1695. };
  1696. function onLocalRoleChange(jid, info, pres, isModerator)
  1697. {
  1698. console.info("My role changed, new role: " + info.role);
  1699. onModeratorStatusChanged(isModerator);
  1700. VideoLayout.showModeratorIndicator();
  1701. if (isModerator) {
  1702. Authentication.closeAuthenticationWindow();
  1703. messageHandler.notify(null, "notify.me",
  1704. 'Me', 'connected', "notify.moderator",
  1705. 'Moderator rights granted !');
  1706. }
  1707. }
  1708. function onModeratorStatusChanged(isModerator) {
  1709. Toolbar.showSipCallButton(isModerator);
  1710. Toolbar.showRecordingButton(
  1711. isModerator); //&&
  1712. // FIXME:
  1713. // Recording visible if
  1714. // there are at least 2(+ 1 focus) participants
  1715. //Object.keys(connection.emuc.members).length >= 3);
  1716. if (isModerator && config.etherpad_base) {
  1717. Etherpad.init();
  1718. }
  1719. };
  1720. function onPasswordReqiured(callback) {
  1721. // password is required
  1722. Toolbar.lockLockButton();
  1723. messageHandler.openTwoButtonDialog(null,
  1724. '<h2>Password required</h2>' +
  1725. '<input id="lockKey" type="text" placeholder="password" autofocus>',
  1726. true,
  1727. "Ok",
  1728. function (e, v, m, f) {},
  1729. function (event) {
  1730. document.getElementById('lockKey').focus();
  1731. },
  1732. function (e, v, m, f) {
  1733. if (v) {
  1734. var lockKey = document.getElementById('lockKey');
  1735. if (lockKey.value !== null) {
  1736. Toolbar.setSharedKey(lockKey.value);
  1737. callback(lockKey.value);
  1738. }
  1739. }
  1740. }
  1741. );
  1742. }
  1743. function onMucEntered(jid, id, displayName) {
  1744. messageHandler.notify(displayName,'notify.somebody', "Somebody",
  1745. 'connected',
  1746. 'notify.connected', "connected");
  1747. // Add Peer's container
  1748. VideoLayout.ensurePeerContainerExists(jid,id);
  1749. }
  1750. function onMucPresenceStatus( jid, info) {
  1751. VideoLayout.setPresenceStatus(
  1752. 'participant_' + Strophe.getResourceFromJid(jid), info.status);
  1753. }
  1754. function onMucRoleChanged(role, displayName) {
  1755. VideoLayout.showModeratorIndicator();
  1756. if (role === 'moderator') {
  1757. var messageKey, messageOptions = {};
  1758. var lDisplayName = displayName;
  1759. if (!lDisplayName) {
  1760. lDisplayName = 'Somebody';
  1761. messageKey = "notify.grantedToUnknown";
  1762. }
  1763. else
  1764. {
  1765. messageKey = "notify.grantedTo";
  1766. messageOptions = {to: displayName};
  1767. }
  1768. messageHandler.notify(
  1769. displayName,'notify.somebody', "Somebody",
  1770. 'connected', messageKey,
  1771. 'Moderator rights granted to ' + lDisplayName + '!',
  1772. messageOptions);
  1773. }
  1774. }
  1775. function onAuthenticationRequired(intervalCallback) {
  1776. Authentication.openAuthenticationDialog(
  1777. roomName, intervalCallback, function () {
  1778. Toolbar.authenticateClicked();
  1779. });
  1780. };
  1781. function onLastNChanged(oldValue, newValue) {
  1782. if (config.muteLocalVideoIfNotInLastN) {
  1783. setVideoMute(!newValue, { 'byUser': false });
  1784. }
  1785. }
  1786. UI.toggleSmileys = function () {
  1787. Chat.toggleSmileys();
  1788. };
  1789. UI.getSettings = function () {
  1790. return Settings.getSettings();
  1791. };
  1792. UI.toggleFilmStrip = function () {
  1793. return BottomToolbar.toggleFilmStrip();
  1794. };
  1795. UI.toggleChat = function () {
  1796. return BottomToolbar.toggleChat();
  1797. };
  1798. UI.toggleContactList = function () {
  1799. return BottomToolbar.toggleContactList();
  1800. };
  1801. UI.inputDisplayNameHandler = function (value) {
  1802. VideoLayout.inputDisplayNameHandler(value);
  1803. };
  1804. UI.getLargeVideoState = function()
  1805. {
  1806. return VideoLayout.getLargeVideoState();
  1807. };
  1808. UI.generateRoomName = function() {
  1809. if(roomName)
  1810. return roomName;
  1811. var roomnode = null;
  1812. var path = window.location.pathname;
  1813. // determinde the room node from the url
  1814. // TODO: just the roomnode or the whole bare jid?
  1815. if (config.getroomnode && typeof config.getroomnode === 'function') {
  1816. // custom function might be responsible for doing the pushstate
  1817. roomnode = config.getroomnode(path);
  1818. } else {
  1819. /* fall back to default strategy
  1820. * this is making assumptions about how the URL->room mapping happens.
  1821. * It currently assumes deployment at root, with a rewrite like the
  1822. * following one (for nginx):
  1823. location ~ ^/([a-zA-Z0-9]+)$ {
  1824. rewrite ^/(.*)$ / break;
  1825. }
  1826. */
  1827. if (path.length > 1) {
  1828. roomnode = path.substr(1).toLowerCase();
  1829. } else {
  1830. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  1831. roomnode = word.toLowerCase();
  1832. window.history.pushState('VideoChat',
  1833. 'Room: ' + word, window.location.pathname + word);
  1834. }
  1835. }
  1836. roomName = roomnode + '@' + config.hosts.muc;
  1837. return roomName;
  1838. };
  1839. UI.connectionIndicatorShowMore = function(id)
  1840. {
  1841. return VideoLayout.connectionIndicators[id].showMore();
  1842. };
  1843. UI.getCredentials = function () {
  1844. var settings = this.getSettings();
  1845. return {
  1846. bosh: document.getElementById('boshURL').value,
  1847. password: document.getElementById('password').value,
  1848. jid: document.getElementById('jid').value,
  1849. email: settings.email,
  1850. displayName: settings.displayName,
  1851. uid: settings.uid
  1852. };
  1853. };
  1854. UI.disableConnect = function () {
  1855. document.getElementById('connect').disabled = true;
  1856. };
  1857. UI.showLoginPopup = function(callback)
  1858. {
  1859. console.log('password is required');
  1860. UI.messageHandler.openTwoButtonDialog(null,
  1861. '<h2>Password required</h2>' +
  1862. '<input id="passwordrequired.username" type="text" placeholder="user@domain.net" autofocus>' +
  1863. '<input id="passwordrequired.password" type="password" placeholder="user password">',
  1864. true,
  1865. "Ok",
  1866. function (e, v, m, f) {
  1867. if (v) {
  1868. var username = document.getElementById('passwordrequired.username');
  1869. var password = document.getElementById('passwordrequired.password');
  1870. if (username.value !== null && password.value != null) {
  1871. callback(username.value, password.value);
  1872. }
  1873. }
  1874. },
  1875. function (event) {
  1876. document.getElementById('passwordrequired.username').focus();
  1877. }
  1878. );
  1879. }
  1880. UI.checkForNicknameAndJoin = function () {
  1881. Authentication.closeAuthenticationDialog();
  1882. Authentication.stopInterval();
  1883. var nick = null;
  1884. if (config.useNicks) {
  1885. nick = window.prompt('Your nickname (optional)');
  1886. }
  1887. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  1888. };
  1889. function dump(elem, filename) {
  1890. elem = elem.parentNode;
  1891. elem.download = filename || 'meetlog.json';
  1892. elem.href = 'data:application/json;charset=utf-8,\n';
  1893. var data = APP.xmpp.populateData();
  1894. var metadata = {};
  1895. metadata.time = new Date();
  1896. metadata.url = window.location.href;
  1897. metadata.ua = navigator.userAgent;
  1898. var log = APP.xmpp.getLogger();
  1899. if (log) {
  1900. metadata.xmpp = log;
  1901. }
  1902. data.metadata = metadata;
  1903. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  1904. return false;
  1905. }
  1906. UI.getRoomName = function () {
  1907. return roomName;
  1908. };
  1909. /**
  1910. * Mutes/unmutes the local video.
  1911. */
  1912. UI.toggleVideo = function () {
  1913. UIUtil.buttonClick("#video", "icon-camera icon-camera-disabled");
  1914. setVideoMute(!APP.RTC.localVideo.isMuted());
  1915. };
  1916. /**
  1917. * Mutes / unmutes audio for the local participant.
  1918. */
  1919. UI.toggleAudio = function() {
  1920. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  1921. };
  1922. /**
  1923. * Sets muted audio state for the local participant.
  1924. */
  1925. UI.setAudioMuted = function (mute) {
  1926. if(!APP.xmpp.setAudioMute(mute, function () {
  1927. VideoLayout.showLocalAudioIndicator(mute);
  1928. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1929. }))
  1930. {
  1931. // We still click the button.
  1932. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1933. return;
  1934. }
  1935. }
  1936. UI.addListener = function (type, listener) {
  1937. eventEmitter.on(type, listener);
  1938. }
  1939. UI.clickOnVideo = function (videoNumber) {
  1940. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  1941. if (remoteVideos.length > videoNumber) {
  1942. remoteVideos[videoNumber].click();
  1943. }
  1944. }
  1945. //Used by torture
  1946. UI.showToolbar = function () {
  1947. return ToolbarToggler.showToolbar();
  1948. }
  1949. //Used by torture
  1950. UI.dockToolbar = function (isDock) {
  1951. return ToolbarToggler.dockToolbar(isDock);
  1952. }
  1953. module.exports = UI;
  1954. },{"../../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){
  1955. var CanvasUtil = require("./CanvasUtils");
  1956. var ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  1957. function initActiveSpeakerAudioLevels() {
  1958. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  1959. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  1960. // Draw a circle.
  1961. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  1962. // Add a shadow around the circle
  1963. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  1964. ASDrawContext.shadowOffsetX = 0;
  1965. ASDrawContext.shadowOffsetY = 0;
  1966. }
  1967. /**
  1968. * The audio Levels plugin.
  1969. */
  1970. var AudioLevels = (function(my) {
  1971. var audioLevelCanvasCache = {};
  1972. my.LOCAL_LEVEL = 'local';
  1973. my.init = function () {
  1974. initActiveSpeakerAudioLevels();
  1975. }
  1976. /**
  1977. * Updates the audio level canvas for the given peerJid. If the canvas
  1978. * didn't exist we create it.
  1979. */
  1980. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  1981. var resourceJid = null;
  1982. var videoSpanId = null;
  1983. if (!peerJid)
  1984. videoSpanId = 'localVideoContainer';
  1985. else {
  1986. resourceJid = Strophe.getResourceFromJid(peerJid);
  1987. videoSpanId = 'participant_' + resourceJid;
  1988. }
  1989. var videoSpan = document.getElementById(videoSpanId);
  1990. if (!videoSpan) {
  1991. if (resourceJid)
  1992. console.error("No video element for jid", resourceJid);
  1993. else
  1994. console.error("No video element for local video.");
  1995. return;
  1996. }
  1997. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  1998. var videoSpaceWidth = $('#remoteVideos').width();
  1999. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  2000. var thumbnailWidth = thumbnailSize[0];
  2001. var thumbnailHeight = thumbnailSize[1];
  2002. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  2003. audioLevelCanvas = document.createElement('canvas');
  2004. audioLevelCanvas.className = "audiolevel";
  2005. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  2006. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  2007. resizeAudioLevelCanvas( audioLevelCanvas,
  2008. thumbnailWidth,
  2009. thumbnailHeight);
  2010. videoSpan.appendChild(audioLevelCanvas);
  2011. } else {
  2012. audioLevelCanvas = audioLevelCanvas.get(0);
  2013. resizeAudioLevelCanvas( audioLevelCanvas,
  2014. thumbnailWidth,
  2015. thumbnailHeight);
  2016. }
  2017. };
  2018. /**
  2019. * Updates the audio level UI for the given resourceJid.
  2020. *
  2021. * @param resourceJid the resource jid indicating the video element for
  2022. * which we draw the audio level
  2023. * @param audioLevel the newAudio level to render
  2024. */
  2025. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  2026. drawAudioLevelCanvas(resourceJid, audioLevel);
  2027. var videoSpanId = getVideoSpanId(resourceJid);
  2028. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  2029. if (!audioLevelCanvas)
  2030. return;
  2031. var drawContext = audioLevelCanvas.getContext('2d');
  2032. var canvasCache = audioLevelCanvasCache[resourceJid];
  2033. drawContext.clearRect (0, 0,
  2034. audioLevelCanvas.width, audioLevelCanvas.height);
  2035. drawContext.drawImage(canvasCache, 0, 0);
  2036. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  2037. if(!APP.xmpp.myJid()) {
  2038. return;
  2039. }
  2040. resourceJid = APP.xmpp.myResource();
  2041. }
  2042. if(resourceJid === largeVideoResourceJid) {
  2043. window.requestAnimationFrame(function () {
  2044. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  2045. });
  2046. }
  2047. };
  2048. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  2049. if($("#activeSpeaker").css("visibility") == "hidden")
  2050. return;
  2051. ASDrawContext.clearRect(0, 0, 300, 300);
  2052. if(audioLevel == 0)
  2053. return;
  2054. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  2055. // Fill the shape.
  2056. ASDrawContext.fill();
  2057. };
  2058. /**
  2059. * Resizes the given audio level canvas to match the given thumbnail size.
  2060. */
  2061. function resizeAudioLevelCanvas(audioLevelCanvas,
  2062. thumbnailWidth,
  2063. thumbnailHeight) {
  2064. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  2065. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  2066. }
  2067. /**
  2068. * Draws the audio level canvas into the cached canvas object.
  2069. *
  2070. * @param resourceJid the resource jid indicating the video element for
  2071. * which we draw the audio level
  2072. * @param audioLevel the newAudio level to render
  2073. */
  2074. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  2075. if (!audioLevelCanvasCache[resourceJid]) {
  2076. var videoSpanId = getVideoSpanId(resourceJid);
  2077. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  2078. /*
  2079. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  2080. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  2081. * error. Since audio levels are frequently updated, the errors have
  2082. * been observed to pile into the console, strain the CPU.
  2083. */
  2084. if (audioLevelCanvasOrig)
  2085. {
  2086. audioLevelCanvasCache[resourceJid]
  2087. = CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  2088. }
  2089. }
  2090. var canvas = audioLevelCanvasCache[resourceJid];
  2091. if (!canvas)
  2092. return;
  2093. var drawContext = canvas.getContext('2d');
  2094. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  2095. var shadowLevel = getShadowLevel(audioLevel);
  2096. if (shadowLevel > 0)
  2097. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  2098. CanvasUtil.drawRoundRectGlow( drawContext,
  2099. interfaceConfig.CANVAS_EXTRA/2, interfaceConfig.CANVAS_EXTRA/2,
  2100. canvas.width - interfaceConfig.CANVAS_EXTRA,
  2101. canvas.height - interfaceConfig.CANVAS_EXTRA,
  2102. interfaceConfig.CANVAS_RADIUS,
  2103. interfaceConfig.SHADOW_COLOR,
  2104. shadowLevel);
  2105. }
  2106. /**
  2107. * Returns the shadow/glow level for the given audio level.
  2108. *
  2109. * @param audioLevel the audio level from which we determine the shadow
  2110. * level
  2111. */
  2112. function getShadowLevel (audioLevel) {
  2113. var shadowLevel = 0;
  2114. if (audioLevel <= 0.3) {
  2115. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  2116. }
  2117. else if (audioLevel <= 0.6) {
  2118. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  2119. }
  2120. else {
  2121. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  2122. }
  2123. return shadowLevel;
  2124. }
  2125. /**
  2126. * Returns the video span id corresponding to the given resourceJid or local
  2127. * user.
  2128. */
  2129. function getVideoSpanId(resourceJid) {
  2130. var videoSpanId = null;
  2131. if (resourceJid === AudioLevels.LOCAL_LEVEL
  2132. || (APP.xmpp.myResource() && resourceJid
  2133. === APP.xmpp.myResource()))
  2134. videoSpanId = 'localVideoContainer';
  2135. else
  2136. videoSpanId = 'participant_' + resourceJid;
  2137. return videoSpanId;
  2138. }
  2139. /**
  2140. * Indicates that the remote video has been resized.
  2141. */
  2142. $(document).bind('remotevideo.resized', function (event, width, height) {
  2143. var resized = false;
  2144. $('#remoteVideos>span>canvas').each(function() {
  2145. var canvas = $(this).get(0);
  2146. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  2147. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  2148. resized = true;
  2149. }
  2150. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  2151. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  2152. resized = true;
  2153. }
  2154. });
  2155. if (resized)
  2156. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  2157. audioLevelCanvasCache[resourceJid].width
  2158. = width + interfaceConfig.CANVAS_EXTRA;
  2159. audioLevelCanvasCache[resourceJid].height
  2160. = height + interfaceConfig.CANVAS_EXTRA;
  2161. });
  2162. });
  2163. return my;
  2164. })(AudioLevels || {});
  2165. module.exports = AudioLevels;
  2166. },{"./CanvasUtils":11}],11:[function(require,module,exports){
  2167. /**
  2168. * Utility class for drawing canvas shapes.
  2169. */
  2170. var CanvasUtil = (function(my) {
  2171. /**
  2172. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  2173. * of the glow.
  2174. *
  2175. * @param drawContext the context of the canvas to draw to
  2176. * @param x the x coordinate of the round rectangle
  2177. * @param y the y coordinate of the round rectangle
  2178. * @param w the width of the round rectangle
  2179. * @param h the height of the round rectangle
  2180. * @param glowColor the color of the glow
  2181. * @param glowWidth the width of the glow
  2182. */
  2183. my.drawRoundRectGlow
  2184. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  2185. // Save the previous state of the context.
  2186. drawContext.save();
  2187. if (w < 2 * r) r = w / 2;
  2188. if (h < 2 * r) r = h / 2;
  2189. // Draw a round rectangle.
  2190. drawContext.beginPath();
  2191. drawContext.moveTo(x+r, y);
  2192. drawContext.arcTo(x+w, y, x+w, y+h, r);
  2193. drawContext.arcTo(x+w, y+h, x, y+h, r);
  2194. drawContext.arcTo(x, y+h, x, y, r);
  2195. drawContext.arcTo(x, y, x+w, y, r);
  2196. drawContext.closePath();
  2197. // Add a shadow around the rectangle
  2198. drawContext.shadowColor = glowColor;
  2199. drawContext.shadowBlur = glowWidth;
  2200. drawContext.shadowOffsetX = 0;
  2201. drawContext.shadowOffsetY = 0;
  2202. // Fill the shape.
  2203. drawContext.fill();
  2204. drawContext.save();
  2205. drawContext.restore();
  2206. // 1) Uncomment this line to use Composite Operation, which is doing the
  2207. // same as the clip function below and is also antialiasing the round
  2208. // border, but is said to be less fast performance wise.
  2209. // drawContext.globalCompositeOperation='destination-out';
  2210. drawContext.beginPath();
  2211. drawContext.moveTo(x+r, y);
  2212. drawContext.arcTo(x+w, y, x+w, y+h, r);
  2213. drawContext.arcTo(x+w, y+h, x, y+h, r);
  2214. drawContext.arcTo(x, y+h, x, y, r);
  2215. drawContext.arcTo(x, y, x+w, y, r);
  2216. drawContext.closePath();
  2217. // 2) Uncomment this line to use Composite Operation, which is doing the
  2218. // same as the clip function below and is also antialiasing the round
  2219. // border, but is said to be less fast performance wise.
  2220. // drawContext.fill();
  2221. // Comment these two lines if choosing to do the same with composite
  2222. // operation above 1 and 2.
  2223. drawContext.clip();
  2224. drawContext.clearRect(0, 0, 277, 200);
  2225. // Restore the previous context state.
  2226. drawContext.restore();
  2227. };
  2228. /**
  2229. * Clones the given canvas.
  2230. *
  2231. * @return the new cloned canvas.
  2232. */
  2233. my.cloneCanvas = function (oldCanvas) {
  2234. /*
  2235. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  2236. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  2237. * levels are frequently updated, the errors have been observed to pile
  2238. * into the console, strain the CPU.
  2239. */
  2240. if (!oldCanvas)
  2241. return oldCanvas;
  2242. //create a new canvas
  2243. var newCanvas = document.createElement('canvas');
  2244. var context = newCanvas.getContext('2d');
  2245. //set dimensions
  2246. newCanvas.width = oldCanvas.width;
  2247. newCanvas.height = oldCanvas.height;
  2248. //apply the old canvas to the new one
  2249. context.drawImage(oldCanvas, 0, 0);
  2250. //return the new canvas
  2251. return newCanvas;
  2252. };
  2253. return my;
  2254. })(CanvasUtil || {});
  2255. module.exports = CanvasUtil;
  2256. },{}],12:[function(require,module,exports){
  2257. /* Initial "authentication required" dialog */
  2258. var authDialog = null;
  2259. /* Loop retry ID that wits for other user to create the room */
  2260. var authRetryId = null;
  2261. var authenticationWindow = null;
  2262. var Authentication = {
  2263. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  2264. // This is the loop that will wait for the room to be created by
  2265. // someone else. 'auth_required.moderator' will bring us back here.
  2266. authRetryId = window.setTimeout(intervalCallback , 5000);
  2267. // Show prompt only if it's not open
  2268. if (authDialog !== null) {
  2269. return;
  2270. }
  2271. // extract room name from 'room@muc.server.net'
  2272. var room = roomName.substr(0, roomName.indexOf('@'));
  2273. authDialog = APP.UI.messageHandler.openDialog(
  2274. 'Stop',
  2275. 'Authentication is required to create room:<br/><b>' + room +
  2276. '</b></br> You can either authenticate to create the room or ' +
  2277. 'just wait for someone else to do so.',
  2278. true,
  2279. {
  2280. Authenticate: 'authNow'
  2281. },
  2282. function (onSubmitEvent, submitValue) {
  2283. // Do not close the dialog yet
  2284. onSubmitEvent.preventDefault();
  2285. // Open login popup
  2286. if (submitValue === 'authNow') {
  2287. callback();
  2288. }
  2289. }
  2290. );
  2291. },
  2292. closeAuthenticationWindow:function () {
  2293. if (authenticationWindow) {
  2294. authenticationWindow.close();
  2295. authenticationWindow = null;
  2296. }
  2297. },
  2298. focusAuthenticationWindow: function () {
  2299. // If auth window exists just bring it to the front
  2300. if (authenticationWindow) {
  2301. authenticationWindow.focus();
  2302. return;
  2303. }
  2304. },
  2305. closeAuthenticationDialog: function () {
  2306. // Close authentication dialog if opened
  2307. if (authDialog) {
  2308. APP.UI.messageHandler.closeDialog();
  2309. authDialog = null;
  2310. }
  2311. },
  2312. createAuthenticationWindow: function (callback, url) {
  2313. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  2314. url, 910, 660,
  2315. // On closed
  2316. function () {
  2317. // Close authentication dialog if opened
  2318. if (authDialog) {
  2319. messageHandler.closeDialog();
  2320. authDialog = null;
  2321. }
  2322. callback();
  2323. authenticationWindow = null;
  2324. });
  2325. return authenticationWindow;
  2326. },
  2327. stopInterval: function () {
  2328. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  2329. if (authRetryId) {
  2330. window.clearTimeout(authRetryId);
  2331. authRetryId = null;
  2332. }
  2333. }
  2334. };
  2335. module.exports = Authentication;
  2336. },{}],13:[function(require,module,exports){
  2337. var Settings = require("../../settings/Settings");
  2338. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  2339. var users = {};
  2340. var activeSpeakerJid;
  2341. function setVisibility(selector, show) {
  2342. if (selector && selector.length > 0) {
  2343. selector.css("visibility", show ? "visible" : "hidden");
  2344. }
  2345. }
  2346. function isUserMuted(jid) {
  2347. // XXX(gp) we may want to rename this method to something like
  2348. // isUserStreaming, for example.
  2349. if (jid && jid != APP.xmpp.myJid()) {
  2350. var resource = Strophe.getResourceFromJid(jid);
  2351. if (!require("../videolayout/VideoLayout").isInLastN(resource)) {
  2352. return true;
  2353. }
  2354. }
  2355. if (!APP.RTC.remoteStreams[jid] || !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  2356. return null;
  2357. }
  2358. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  2359. }
  2360. function getGravatarUrl(id, size) {
  2361. if(id === APP.xmpp.myJid() || !id) {
  2362. id = Settings.getSettings().uid;
  2363. }
  2364. return 'https://www.gravatar.com/avatar/' +
  2365. MD5.hexdigest(id.trim().toLowerCase()) +
  2366. "?d=wavatar&size=" + (size || "30");
  2367. }
  2368. var Avatar = {
  2369. /**
  2370. * Sets the user's avatar in the settings menu(if local user), contact list
  2371. * and thumbnail
  2372. * @param jid jid of the user
  2373. * @param id email or userID to be used as a hash
  2374. */
  2375. setUserAvatar: function (jid, id) {
  2376. if (id) {
  2377. if (users[jid] === id) {
  2378. return;
  2379. }
  2380. users[jid] = id;
  2381. }
  2382. var thumbUrl = getGravatarUrl(users[jid] || jid, 100);
  2383. var contactListUrl = getGravatarUrl(users[jid] || jid);
  2384. var resourceJid = Strophe.getResourceFromJid(jid);
  2385. var thumbnail = $('#participant_' + resourceJid);
  2386. var avatar = $('#avatar_' + resourceJid);
  2387. // set the avatar in the settings menu if it is local user and get the
  2388. // local video container
  2389. if (jid === APP.xmpp.myJid()) {
  2390. $('#avatar').get(0).src = thumbUrl;
  2391. thumbnail = $('#localVideoContainer');
  2392. }
  2393. // set the avatar in the contact list
  2394. var contact = $('#' + resourceJid + '>img');
  2395. if (contact && contact.length > 0) {
  2396. contact.get(0).src = contactListUrl;
  2397. }
  2398. // set the avatar in the thumbnail
  2399. if (avatar && avatar.length > 0) {
  2400. avatar[0].src = thumbUrl;
  2401. } else {
  2402. if (thumbnail && thumbnail.length > 0) {
  2403. avatar = document.createElement('img');
  2404. avatar.id = 'avatar_' + resourceJid;
  2405. avatar.className = 'userAvatar';
  2406. avatar.src = thumbUrl;
  2407. thumbnail.append(avatar);
  2408. }
  2409. }
  2410. //if the user is the current active speaker - update the active speaker
  2411. // avatar
  2412. if (jid === activeSpeakerJid) {
  2413. this.updateActiveSpeakerAvatarSrc(jid);
  2414. }
  2415. },
  2416. /**
  2417. * Hides or shows the user's avatar
  2418. * @param jid jid of the user
  2419. * @param show whether we should show the avatar or not
  2420. * video because there is no dominant speaker and no focused speaker
  2421. */
  2422. showUserAvatar: function (jid, show) {
  2423. if (users[jid]) {
  2424. var resourceJid = Strophe.getResourceFromJid(jid);
  2425. var video = $('#participant_' + resourceJid + '>video');
  2426. var avatar = $('#avatar_' + resourceJid);
  2427. if (jid === APP.xmpp.myJid()) {
  2428. video = $('#localVideoWrapper>video');
  2429. }
  2430. if (show === undefined || show === null) {
  2431. show = isUserMuted(jid);
  2432. }
  2433. //if the user is the currently focused, the dominant speaker or if
  2434. //there is no focused and no dominant speaker and the large video is
  2435. //currently shown
  2436. if (activeSpeakerJid === jid && require("../videolayout/VideoLayout").isLargeVideoOnTop()) {
  2437. setVisibility($("#largeVideo"), !show);
  2438. setVisibility($('#activeSpeaker'), show);
  2439. setVisibility(avatar, false);
  2440. setVisibility(video, false);
  2441. } else {
  2442. if (video && video.length > 0) {
  2443. setVisibility(video, !show);
  2444. setVisibility(avatar, show);
  2445. }
  2446. }
  2447. }
  2448. },
  2449. /**
  2450. * Updates the src of the active speaker avatar
  2451. * @param jid of the current active speaker
  2452. */
  2453. updateActiveSpeakerAvatarSrc: function (jid) {
  2454. if (!jid) {
  2455. jid = APP.xmpp.findJidFromResource(
  2456. require("../videolayout/VideoLayout").getLargeVideoState().userResourceJid);
  2457. }
  2458. var avatar = $("#activeSpeakerAvatar")[0];
  2459. var url = getGravatarUrl(users[jid],
  2460. interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE);
  2461. if (jid === activeSpeakerJid && avatar.src === url) {
  2462. return;
  2463. }
  2464. activeSpeakerJid = jid;
  2465. var isMuted = isUserMuted(jid);
  2466. if (jid && isMuted !== null) {
  2467. avatar.src = url;
  2468. setVisibility($("#largeVideo"), !isMuted);
  2469. Avatar.showUserAvatar(jid, isMuted);
  2470. }
  2471. }
  2472. };
  2473. module.exports = Avatar;
  2474. },{"../../../service/RTC/MediaStreamTypes":79,"../../settings/Settings":38,"../videolayout/VideoLayout":32}],14:[function(require,module,exports){
  2475. /* global $, config,
  2476. setLargeVideoVisible, Util */
  2477. var VideoLayout = require("../videolayout/VideoLayout");
  2478. var Prezi = require("../prezi/Prezi");
  2479. var UIUtil = require("../util/UIUtil");
  2480. var etherpadName = null;
  2481. var etherpadIFrame = null;
  2482. var domain = null;
  2483. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  2484. /**
  2485. * Resizes the etherpad.
  2486. */
  2487. function resize() {
  2488. if ($('#etherpad>iframe').length) {
  2489. var remoteVideos = $('#remoteVideos');
  2490. var availableHeight
  2491. = window.innerHeight - remoteVideos.outerHeight();
  2492. var availableWidth = UIUtil.getAvailableVideoWidth();
  2493. $('#etherpad>iframe').width(availableWidth);
  2494. $('#etherpad>iframe').height(availableHeight);
  2495. }
  2496. }
  2497. /**
  2498. * Shares the Etherpad name with other participants.
  2499. */
  2500. function shareEtherpad() {
  2501. APP.xmpp.addToPresence("etherpad", etherpadName);
  2502. }
  2503. /**
  2504. * Creates the Etherpad button and adds it to the toolbar.
  2505. */
  2506. function enableEtherpadButton() {
  2507. if (!$('#etherpadButton').is(":visible"))
  2508. $('#etherpadButton').css({display: 'inline-block'});
  2509. }
  2510. /**
  2511. * Creates the IFrame for the etherpad.
  2512. */
  2513. function createIFrame() {
  2514. etherpadIFrame = document.createElement('iframe');
  2515. etherpadIFrame.src = domain + etherpadName + options;
  2516. etherpadIFrame.frameBorder = 0;
  2517. etherpadIFrame.scrolling = "no";
  2518. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  2519. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  2520. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  2521. document.getElementById('etherpad').appendChild(etherpadIFrame);
  2522. etherpadIFrame.onload = function() {
  2523. document.domain = document.domain;
  2524. bubbleIframeMouseMove(etherpadIFrame);
  2525. setTimeout(function() {
  2526. // the iframes inside of the etherpad are
  2527. // not yet loaded when the etherpad iframe is loaded
  2528. var outer = etherpadIFrame.
  2529. contentDocument.getElementsByName("ace_outer")[0];
  2530. bubbleIframeMouseMove(outer);
  2531. var inner = outer.
  2532. contentDocument.getElementsByName("ace_inner")[0];
  2533. bubbleIframeMouseMove(inner);
  2534. }, 2000);
  2535. };
  2536. }
  2537. function bubbleIframeMouseMove(iframe){
  2538. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  2539. iframe.contentWindow.onmousemove = function(e){
  2540. if(existingOnMouseMove) existingOnMouseMove(e);
  2541. var evt = document.createEvent("MouseEvents");
  2542. var boundingClientRect = iframe.getBoundingClientRect();
  2543. evt.initMouseEvent(
  2544. "mousemove",
  2545. true, // bubbles
  2546. false, // not cancelable
  2547. window,
  2548. e.detail,
  2549. e.screenX,
  2550. e.screenY,
  2551. e.clientX + boundingClientRect.left,
  2552. e.clientY + boundingClientRect.top,
  2553. e.ctrlKey,
  2554. e.altKey,
  2555. e.shiftKey,
  2556. e.metaKey,
  2557. e.button,
  2558. null // no related element
  2559. );
  2560. iframe.dispatchEvent(evt);
  2561. };
  2562. }
  2563. /**
  2564. * On video selected event.
  2565. */
  2566. $(document).bind('video.selected', function (event, isPresentation) {
  2567. if (config.etherpad_base && etherpadIFrame && etherpadIFrame.style.visibility !== 'hidden')
  2568. Etherpad.toggleEtherpad(isPresentation);
  2569. });
  2570. var Etherpad = {
  2571. /**
  2572. * Initializes the etherpad.
  2573. */
  2574. init: function (name) {
  2575. if (config.etherpad_base && !etherpadName) {
  2576. domain = config.etherpad_base;
  2577. if (!name) {
  2578. // In case we're the focus we generate the name.
  2579. etherpadName = Math.random().toString(36).substring(7) +
  2580. '_' + (new Date().getTime()).toString();
  2581. shareEtherpad();
  2582. }
  2583. else
  2584. etherpadName = name;
  2585. enableEtherpadButton();
  2586. /**
  2587. * Resizes the etherpad, when the window is resized.
  2588. */
  2589. $(window).resize(function () {
  2590. resize();
  2591. });
  2592. }
  2593. },
  2594. /**
  2595. * Opens/hides the Etherpad.
  2596. */
  2597. toggleEtherpad: function (isPresentation) {
  2598. if (!etherpadIFrame)
  2599. createIFrame();
  2600. var largeVideo = null;
  2601. if (Prezi.isPresentationVisible())
  2602. largeVideo = $('#presentation>iframe');
  2603. else
  2604. largeVideo = $('#largeVideo');
  2605. if ($('#etherpad>iframe').css('visibility') === 'hidden') {
  2606. $('#activeSpeaker').css('visibility', 'hidden');
  2607. largeVideo.fadeOut(300, function () {
  2608. if (Prezi.isPresentationVisible()) {
  2609. largeVideo.css({opacity: '0'});
  2610. } else {
  2611. VideoLayout.setLargeVideoVisible(false);
  2612. }
  2613. });
  2614. $('#etherpad>iframe').fadeIn(300, function () {
  2615. document.body.style.background = '#eeeeee';
  2616. $('#etherpad>iframe').css({visibility: 'visible'});
  2617. $('#etherpad').css({zIndex: 2});
  2618. });
  2619. }
  2620. else if ($('#etherpad>iframe')) {
  2621. $('#etherpad>iframe').fadeOut(300, function () {
  2622. $('#etherpad>iframe').css({visibility: 'hidden'});
  2623. $('#etherpad').css({zIndex: 0});
  2624. document.body.style.background = 'black';
  2625. });
  2626. if (!isPresentation) {
  2627. $('#largeVideo').fadeIn(300, function () {
  2628. VideoLayout.setLargeVideoVisible(true);
  2629. });
  2630. }
  2631. }
  2632. resize();
  2633. },
  2634. isVisible: function() {
  2635. var etherpadIframe = $('#etherpad>iframe');
  2636. return etherpadIframe && etherpadIframe.is(':visible');
  2637. }
  2638. };
  2639. module.exports = Etherpad;
  2640. },{"../prezi/Prezi":15,"../util/UIUtil":30,"../videolayout/VideoLayout":32}],15:[function(require,module,exports){
  2641. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  2642. var UIUtil = require("../util/UIUtil");
  2643. var VideoLayout = require("../videolayout/VideoLayout");
  2644. var messageHandler = require("../util/MessageHandler");
  2645. var PreziPlayer = require("./PreziPlayer");
  2646. var preziPlayer = null;
  2647. var Prezi = {
  2648. /**
  2649. * Reloads the current presentation.
  2650. */
  2651. reloadPresentation: function() {
  2652. var iframe = document.getElementById(preziPlayer.options.preziId);
  2653. iframe.src = iframe.src;
  2654. },
  2655. /**
  2656. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  2657. * otherwise.
  2658. */
  2659. isPresentationVisible: function () {
  2660. return ($('#presentation>iframe') != null
  2661. && $('#presentation>iframe').css('opacity') == 1);
  2662. },
  2663. /**
  2664. * Opens the Prezi dialog, from which the user could choose a presentation
  2665. * to load.
  2666. */
  2667. openPreziDialog: function() {
  2668. var myprezi = APP.xmpp.getPrezi();
  2669. if (myprezi) {
  2670. messageHandler.openTwoButtonDialog("Remove Prezi",
  2671. "Are you sure you would like to remove your Prezi?",
  2672. false,
  2673. "Remove",
  2674. function(e,v,m,f) {
  2675. if(v) {
  2676. APP.xmpp.removePreziFromPresence();
  2677. }
  2678. }
  2679. );
  2680. }
  2681. else if (preziPlayer != null) {
  2682. messageHandler.openTwoButtonDialog("Share a Prezi",
  2683. "Another participant is already sharing a Prezi." +
  2684. "This conference allows only one Prezi at a time.",
  2685. false,
  2686. "Ok",
  2687. function(e,v,m,f) {
  2688. $.prompt.close();
  2689. }
  2690. );
  2691. }
  2692. else {
  2693. var openPreziState = {
  2694. state0: {
  2695. html: '<h2>Share a Prezi</h2>' +
  2696. '<input id="preziUrl" type="text" ' +
  2697. 'placeholder="e.g. ' +
  2698. 'http://prezi.com/wz7vhjycl7e6/my-prezi" autofocus>',
  2699. persistent: false,
  2700. buttons: { "Share": true , "Cancel": false},
  2701. defaultButton: 1,
  2702. submit: function(e,v,m,f){
  2703. e.preventDefault();
  2704. if(v)
  2705. {
  2706. var preziUrl = document.getElementById('preziUrl');
  2707. if (preziUrl.value)
  2708. {
  2709. var urlValue
  2710. = encodeURI(UIUtil.escapeHtml(preziUrl.value));
  2711. if (urlValue.indexOf('http://prezi.com/') != 0
  2712. && urlValue.indexOf('https://prezi.com/') != 0)
  2713. {
  2714. $.prompt.goToState('state1');
  2715. return false;
  2716. }
  2717. else {
  2718. var presIdTmp = urlValue.substring(
  2719. urlValue.indexOf("prezi.com/") + 10);
  2720. if (!isAlphanumeric(presIdTmp)
  2721. || presIdTmp.indexOf('/') < 2) {
  2722. $.prompt.goToState('state1');
  2723. return false;
  2724. }
  2725. else {
  2726. APP.xmpp.addToPresence("prezi", urlValue);
  2727. $.prompt.close();
  2728. }
  2729. }
  2730. }
  2731. }
  2732. else
  2733. $.prompt.close();
  2734. }
  2735. },
  2736. state1: {
  2737. html: '<h2>Share a Prezi</h2>' +
  2738. 'Please provide a correct prezi link.',
  2739. persistent: false,
  2740. buttons: { "Back": true, "Cancel": false },
  2741. defaultButton: 1,
  2742. submit:function(e,v,m,f) {
  2743. e.preventDefault();
  2744. if(v==0)
  2745. $.prompt.close();
  2746. else
  2747. $.prompt.goToState('state0');
  2748. }
  2749. }
  2750. };
  2751. var focusPreziUrl = function(e) {
  2752. document.getElementById('preziUrl').focus();
  2753. };
  2754. messageHandler.openDialogWithStates(openPreziState, focusPreziUrl, focusPreziUrl);
  2755. }
  2756. }
  2757. };
  2758. /**
  2759. * A new presentation has been added.
  2760. *
  2761. * @param event the event indicating the add of a presentation
  2762. * @param jid the jid from which the presentation was added
  2763. * @param presUrl url of the presentation
  2764. * @param currentSlide the current slide to which we should move
  2765. */
  2766. function presentationAdded(event, jid, presUrl, currentSlide) {
  2767. console.log("presentation added", presUrl);
  2768. var presId = getPresentationId(presUrl);
  2769. var elementId = 'participant_'
  2770. + Strophe.getResourceFromJid(jid)
  2771. + '_' + presId;
  2772. // We explicitly don't specify the peer jid here, because we don't want
  2773. // this video to be dealt with as a peer related one (for example we
  2774. // don't want to show a mute/kick menu for this one, etc.).
  2775. VideoLayout.addRemoteVideoContainer(null, elementId);
  2776. VideoLayout.resizeThumbnails();
  2777. var controlsEnabled = false;
  2778. if (jid === APP.xmpp.myJid())
  2779. controlsEnabled = true;
  2780. setPresentationVisible(true);
  2781. $('#largeVideoContainer').hover(
  2782. function (event) {
  2783. if (Prezi.isPresentationVisible()) {
  2784. var reloadButtonRight = window.innerWidth
  2785. - $('#presentation>iframe').offset().left
  2786. - $('#presentation>iframe').width();
  2787. $('#reloadPresentation').css({ right: reloadButtonRight,
  2788. display:'inline-block'});
  2789. }
  2790. },
  2791. function (event) {
  2792. if (!Prezi.isPresentationVisible())
  2793. $('#reloadPresentation').css({display:'none'});
  2794. else {
  2795. var e = event.toElement || event.relatedTarget;
  2796. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  2797. $('#reloadPresentation').css({display:'none'});
  2798. }
  2799. });
  2800. preziPlayer = new PreziPlayer(
  2801. 'presentation',
  2802. {preziId: presId,
  2803. width: getPresentationWidth(),
  2804. height: getPresentationHeihgt(),
  2805. controls: controlsEnabled,
  2806. debug: true
  2807. });
  2808. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  2809. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  2810. console.log("prezi status", event.value);
  2811. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  2812. if (jid != APP.xmpp.myJid())
  2813. preziPlayer.flyToStep(currentSlide);
  2814. }
  2815. });
  2816. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  2817. console.log("event value", event.value);
  2818. APP.xmpp.addToPresence("preziSlide", event.value);
  2819. });
  2820. $("#" + elementId).css( 'background-image',
  2821. 'url(../images/avatarprezi.png)');
  2822. $("#" + elementId).click(
  2823. function () {
  2824. setPresentationVisible(true);
  2825. }
  2826. );
  2827. };
  2828. /**
  2829. * A presentation has been removed.
  2830. *
  2831. * @param event the event indicating the remove of a presentation
  2832. * @param jid the jid for which the presentation was removed
  2833. * @param the url of the presentation
  2834. */
  2835. function presentationRemoved(event, jid, presUrl) {
  2836. console.log('presentation removed', presUrl);
  2837. var presId = getPresentationId(presUrl);
  2838. setPresentationVisible(false);
  2839. $('#participant_'
  2840. + Strophe.getResourceFromJid(jid)
  2841. + '_' + presId).remove();
  2842. $('#presentation>iframe').remove();
  2843. if (preziPlayer != null) {
  2844. preziPlayer.destroy();
  2845. preziPlayer = null;
  2846. }
  2847. };
  2848. /**
  2849. * Indicates if the given string is an alphanumeric string.
  2850. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  2851. * purpose of checking URIs.
  2852. */
  2853. function isAlphanumeric(unsafeText) {
  2854. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  2855. return regex.test(unsafeText);
  2856. }
  2857. /**
  2858. * Returns the presentation id from the given url.
  2859. */
  2860. function getPresentationId (presUrl) {
  2861. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  2862. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  2863. }
  2864. /**
  2865. * Returns the presentation width.
  2866. */
  2867. function getPresentationWidth() {
  2868. var availableWidth = UIUtil.getAvailableVideoWidth();
  2869. var availableHeight = getPresentationHeihgt();
  2870. var aspectRatio = 16.0 / 9.0;
  2871. if (availableHeight < availableWidth / aspectRatio) {
  2872. availableWidth = Math.floor(availableHeight * aspectRatio);
  2873. }
  2874. return availableWidth;
  2875. }
  2876. /**
  2877. * Returns the presentation height.
  2878. */
  2879. function getPresentationHeihgt() {
  2880. var remoteVideos = $('#remoteVideos');
  2881. return window.innerHeight - remoteVideos.outerHeight();
  2882. }
  2883. /**
  2884. * Resizes the presentation iframe.
  2885. */
  2886. function resize() {
  2887. if ($('#presentation>iframe')) {
  2888. $('#presentation>iframe').width(getPresentationWidth());
  2889. $('#presentation>iframe').height(getPresentationHeihgt());
  2890. }
  2891. }
  2892. /**
  2893. * Shows/hides a presentation.
  2894. */
  2895. function setPresentationVisible(visible) {
  2896. var prezi = $('#presentation>iframe');
  2897. if (visible) {
  2898. // Trigger the video.selected event to indicate a change in the
  2899. // large video.
  2900. $(document).trigger("video.selected", [true]);
  2901. $('#largeVideo').fadeOut(300);
  2902. prezi.fadeIn(300, function() {
  2903. prezi.css({opacity:'1'});
  2904. ToolbarToggler.dockToolbar(true);
  2905. VideoLayout.setLargeVideoVisible(false);
  2906. });
  2907. $('#activeSpeaker').css('visibility', 'hidden');
  2908. }
  2909. else {
  2910. if (prezi.css('opacity') == '1') {
  2911. prezi.fadeOut(300, function () {
  2912. prezi.css({opacity:'0'});
  2913. $('#reloadPresentation').css({display:'none'});
  2914. $('#largeVideo').fadeIn(300, function() {
  2915. VideoLayout.setLargeVideoVisible(true);
  2916. ToolbarToggler.dockToolbar(false);
  2917. });
  2918. });
  2919. }
  2920. }
  2921. }
  2922. /**
  2923. * Presentation has been removed.
  2924. */
  2925. $(document).bind('presentationremoved.muc', presentationRemoved);
  2926. /**
  2927. * Presentation has been added.
  2928. */
  2929. $(document).bind('presentationadded.muc', presentationAdded);
  2930. /*
  2931. * Indicates presentation slide change.
  2932. */
  2933. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  2934. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  2935. preziPlayer.flyToStep(current);
  2936. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  2937. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  2938. preziPlayer.flyToStep(current, i);
  2939. }
  2940. }
  2941. });
  2942. /**
  2943. * On video selected event.
  2944. */
  2945. $(document).bind('video.selected', function (event, isPresentation) {
  2946. if (!isPresentation && $('#presentation>iframe')) {
  2947. setPresentationVisible(false);
  2948. }
  2949. });
  2950. $(window).resize(function () {
  2951. resize();
  2952. });
  2953. module.exports = Prezi;
  2954. },{"../toolbars/ToolbarToggler":26,"../util/MessageHandler":28,"../util/UIUtil":30,"../videolayout/VideoLayout":32,"./PreziPlayer":16}],16:[function(require,module,exports){
  2955. (function() {
  2956. "use strict";
  2957. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  2958. window.PreziPlayer = (function() {
  2959. PreziPlayer.API_VERSION = 1;
  2960. PreziPlayer.CURRENT_STEP = 'currentStep';
  2961. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  2962. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  2963. PreziPlayer.STATUS_LOADING = 'loading';
  2964. PreziPlayer.STATUS_READY = 'ready';
  2965. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  2966. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  2967. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  2968. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  2969. PreziPlayer.EVENT_STATUS = "statusChange";
  2970. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  2971. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  2972. PreziPlayer.domain = "https://prezi.com";
  2973. PreziPlayer.path = "/player/";
  2974. PreziPlayer.players = {};
  2975. PreziPlayer.binded_methods = ['changesHandler'];
  2976. PreziPlayer.createMultiplePlayers = function(optionArray){
  2977. for(var i=0; i<optionArray.length; i++) {
  2978. var optionSet = optionArray[i];
  2979. new PreziPlayer(optionSet.id, optionSet);
  2980. };
  2981. };
  2982. PreziPlayer.messageReceived = function(event){
  2983. var message, item, player;
  2984. try {
  2985. message = JSON.parse(event.data);
  2986. if (message.id && (player = PreziPlayer.players[message.id])) {
  2987. if (player.options.debug === true) {
  2988. if (console && console.log)
  2989. console.log('received', message);
  2990. }
  2991. if (message.type === "changes") {
  2992. player.changesHandler(message);
  2993. }
  2994. for (var i = 0; i < player.callbacks.length; i++) {
  2995. item = player.callbacks[i];
  2996. if (item && message.type === item.event) {
  2997. item.callback(message);
  2998. }
  2999. }
  3000. }
  3001. } catch (e) { }
  3002. };
  3003. function PreziPlayer(id, options) {
  3004. var params, paramString = "", _this = this;
  3005. if (PreziPlayer.players[id]){
  3006. PreziPlayer.players[id].destroy();
  3007. }
  3008. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  3009. var method_name = PreziPlayer.binded_methods[i];
  3010. _this[method_name] = __bind(_this[method_name], _this);
  3011. };
  3012. options = options || {};
  3013. this.options = options;
  3014. this.values = {'status': PreziPlayer.STATUS_LOADING};
  3015. this.values[PreziPlayer.CURRENT_STEP] = 0;
  3016. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  3017. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  3018. this.callbacks = [];
  3019. this.id = id;
  3020. this.embedTo = document.getElementById(id);
  3021. if (!this.embedTo) {
  3022. throw "The element id is not available.";
  3023. }
  3024. this.iframe = document.createElement('iframe');
  3025. params = [
  3026. { name: 'oid', value: options.preziId },
  3027. { name: 'explorable', value: options.explorable ? 1 : 0 },
  3028. { name: 'controls', value: options.controls ? 1 : 0 }
  3029. ];
  3030. for(var i=0; i<params.length; i++) {
  3031. var param = params[i];
  3032. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  3033. };
  3034. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  3035. this.iframe.frameBorder = 0;
  3036. this.iframe.scrolling = "no";
  3037. this.iframe.width = options.width || 640;
  3038. this.iframe.height = options.height || 480;
  3039. this.embedTo.innerHTML = '';
  3040. // JITSI: IN CASE SOMETHING GOES WRONG.
  3041. try {
  3042. this.embedTo.appendChild(this.iframe);
  3043. }
  3044. catch (err) {
  3045. console.log("CATCH ERROR");
  3046. }
  3047. // JITSI: Increase interval from 200 to 500, which fixes prezi
  3048. // crashes for us.
  3049. this.initPollInterval = setInterval(function(){
  3050. _this.sendMessage({'action': 'init'});
  3051. }, 500);
  3052. PreziPlayer.players[id] = this;
  3053. }
  3054. PreziPlayer.prototype.changesHandler = function(message) {
  3055. var key, value, j, item;
  3056. if (this.initPollInterval) {
  3057. clearInterval(this.initPollInterval);
  3058. this.initPollInterval = false;
  3059. }
  3060. for (key in message.data) {
  3061. if (message.data.hasOwnProperty(key)){
  3062. value = message.data[key];
  3063. this.values[key] = value;
  3064. for (j=0; j<this.callbacks.length; j++) {
  3065. item = this.callbacks[j];
  3066. if (item && item.event === key + "Change"){
  3067. item.callback({type: item.event, value: value});
  3068. }
  3069. }
  3070. }
  3071. }
  3072. };
  3073. PreziPlayer.prototype.destroy = function() {
  3074. if (this.initPollInterval) {
  3075. clearInterval(this.initPollInterval);
  3076. this.initPollInterval = false;
  3077. }
  3078. this.embedTo.innerHTML = '';
  3079. };
  3080. PreziPlayer.prototype.sendMessage = function(message) {
  3081. if (this.options.debug === true) {
  3082. if (console && console.log) console.log('sent', message);
  3083. }
  3084. message.version = PreziPlayer.API_VERSION;
  3085. message.id = this.id;
  3086. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  3087. };
  3088. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  3089. PreziPlayer.prototype.flyToNextStep = function() {
  3090. return this.sendMessage({
  3091. 'action': 'present',
  3092. 'data': ['moveToNextStep']
  3093. });
  3094. };
  3095. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  3096. PreziPlayer.prototype.flyToPreviousStep = function() {
  3097. return this.sendMessage({
  3098. 'action': 'present',
  3099. 'data': ['moveToPrevStep']
  3100. });
  3101. };
  3102. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  3103. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  3104. var obj = this;
  3105. // check animation_step
  3106. if (animation_step > 0 &&
  3107. obj.values.animationCountOnSteps &&
  3108. obj.values.animationCountOnSteps[step] <= animation_step) {
  3109. animation_step = obj.values.animationCountOnSteps[step];
  3110. }
  3111. // jump to animation steps by calling flyToNextStep()
  3112. function doAnimationSteps() {
  3113. if (obj.values.isMoving == true) {
  3114. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  3115. return;
  3116. }
  3117. while (animation_step-- > 0) {
  3118. obj.flyToNextStep(); // do the animation steps
  3119. }
  3120. }
  3121. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  3122. // jump to the step
  3123. return this.sendMessage({
  3124. 'action': 'present',
  3125. 'data': ['moveToStep', step]
  3126. });
  3127. };
  3128. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  3129. PreziPlayer.prototype.flyToObject = function(objectId) {
  3130. return this.sendMessage({
  3131. 'action': 'present',
  3132. 'data': ['moveToObject', objectId]
  3133. });
  3134. };
  3135. PreziPlayer.prototype.play = function(defaultDelay) {
  3136. return this.sendMessage({
  3137. 'action': 'present',
  3138. 'data': ['startAutoPlay', defaultDelay]
  3139. });
  3140. };
  3141. PreziPlayer.prototype.stop = function() {
  3142. return this.sendMessage({
  3143. 'action': 'present',
  3144. 'data': ['stopAutoPlay']
  3145. });
  3146. };
  3147. PreziPlayer.prototype.pause = function(defaultDelay) {
  3148. return this.sendMessage({
  3149. 'action': 'present',
  3150. 'data': ['pauseAutoPlay', defaultDelay]
  3151. });
  3152. };
  3153. PreziPlayer.prototype.getCurrentStep = function() {
  3154. return this.values.currentStep;
  3155. };
  3156. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  3157. return this.values.currentAnimationStep;
  3158. };
  3159. PreziPlayer.prototype.getCurrentObject = function() {
  3160. return this.values.currentObject;
  3161. };
  3162. PreziPlayer.prototype.getStatus = function() {
  3163. return this.values.status;
  3164. };
  3165. PreziPlayer.prototype.isPlaying = function() {
  3166. return this.values.isAutoPlaying;
  3167. };
  3168. PreziPlayer.prototype.getStepCount = function() {
  3169. return this.values.stepCount;
  3170. };
  3171. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  3172. return this.values.animationCountOnSteps;
  3173. };
  3174. PreziPlayer.prototype.getTitle = function() {
  3175. return this.values.title;
  3176. };
  3177. PreziPlayer.prototype.setDimensions = function(dims) {
  3178. for (var parameter in dims) {
  3179. this.iframe[parameter] = dims[parameter];
  3180. }
  3181. }
  3182. PreziPlayer.prototype.getDimensions = function() {
  3183. return {
  3184. width: parseInt(this.iframe.width, 10),
  3185. height: parseInt(this.iframe.height, 10)
  3186. }
  3187. }
  3188. PreziPlayer.prototype.on = function(event, callback) {
  3189. this.callbacks.push({
  3190. event: event,
  3191. callback: callback
  3192. });
  3193. };
  3194. PreziPlayer.prototype.off = function(event, callback) {
  3195. var j, item;
  3196. if (event === undefined) {
  3197. this.callbacks = [];
  3198. }
  3199. j = this.callbacks.length;
  3200. while (j--) {
  3201. item = this.callbacks[j];
  3202. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  3203. this.callbacks.splice(j, 1);
  3204. }
  3205. }
  3206. };
  3207. if (window.addEventListener) {
  3208. window.addEventListener('message', PreziPlayer.messageReceived, false);
  3209. } else {
  3210. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  3211. }
  3212. return PreziPlayer;
  3213. })();
  3214. })();
  3215. module.exports = PreziPlayer;
  3216. },{}],17:[function(require,module,exports){
  3217. var Chat = require("./chat/Chat");
  3218. var ContactList = require("./contactlist/ContactList");
  3219. var Settings = require("./../../settings/Settings");
  3220. var SettingsMenu = require("./settings/SettingsMenu");
  3221. var VideoLayout = require("../videolayout/VideoLayout");
  3222. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  3223. var UIUtil = require("../util/UIUtil");
  3224. /**
  3225. * Toggler for the chat, contact list, settings menu, etc..
  3226. */
  3227. var PanelToggler = (function(my) {
  3228. var currentlyOpen = null;
  3229. var buttons = {
  3230. '#chatspace': '#chatBottomButton',
  3231. '#contactlist': '#contactListButton',
  3232. '#settingsmenu': '#settingsButton'
  3233. };
  3234. /**
  3235. * Resizes the video area
  3236. * @param isClosing whether the side panel is going to be closed or is going to open / remain opened
  3237. * @param completeFunction a function to be called when the video space is resized
  3238. */
  3239. var resizeVideoArea = function(isClosing, completeFunction) {
  3240. var videospace = $('#videospace');
  3241. var panelSize = isClosing ? [0, 0] : PanelToggler.getPanelSize();
  3242. var videospaceWidth = window.innerWidth - panelSize[0];
  3243. var videospaceHeight = window.innerHeight;
  3244. var videoSize
  3245. = VideoLayout.getVideoSize(null, null, videospaceWidth, videospaceHeight);
  3246. var videoWidth = videoSize[0];
  3247. var videoHeight = videoSize[1];
  3248. var videoPosition = VideoLayout.getVideoPosition(videoWidth,
  3249. videoHeight,
  3250. videospaceWidth,
  3251. videospaceHeight);
  3252. var horizontalIndent = videoPosition[0];
  3253. var verticalIndent = videoPosition[1];
  3254. var thumbnailSize = VideoLayout.calculateThumbnailSize(videospaceWidth);
  3255. var thumbnailsWidth = thumbnailSize[0];
  3256. var thumbnailsHeight = thumbnailSize[1];
  3257. //for chat
  3258. videospace.animate({
  3259. right: panelSize[0],
  3260. width: videospaceWidth,
  3261. height: videospaceHeight
  3262. },
  3263. {
  3264. queue: false,
  3265. duration: 500,
  3266. complete: completeFunction
  3267. });
  3268. $('#remoteVideos').animate({
  3269. height: thumbnailsHeight
  3270. },
  3271. {
  3272. queue: false,
  3273. duration: 500
  3274. });
  3275. $('#remoteVideos>span').animate({
  3276. height: thumbnailsHeight,
  3277. width: thumbnailsWidth
  3278. },
  3279. {
  3280. queue: false,
  3281. duration: 500,
  3282. complete: function () {
  3283. $(document).trigger(
  3284. "remotevideo.resized",
  3285. [thumbnailsWidth,
  3286. thumbnailsHeight]);
  3287. }
  3288. });
  3289. $('#largeVideoContainer').animate({
  3290. width: videospaceWidth,
  3291. height: videospaceHeight
  3292. },
  3293. {
  3294. queue: false,
  3295. duration: 500
  3296. });
  3297. $('#largeVideo').animate({
  3298. width: videoWidth,
  3299. height: videoHeight,
  3300. top: verticalIndent,
  3301. bottom: verticalIndent,
  3302. left: horizontalIndent,
  3303. right: horizontalIndent
  3304. },
  3305. {
  3306. queue: false,
  3307. duration: 500
  3308. });
  3309. };
  3310. /**
  3311. * Toggles the windows in the side panel
  3312. * @param object the window that should be shown
  3313. * @param selector the selector for the element containing the panel
  3314. * @param onOpenComplete function to be called when the panel is opened
  3315. * @param onOpen function to be called if the window is going to be opened
  3316. * @param onClose function to be called if the window is going to be closed
  3317. */
  3318. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  3319. UIUtil.buttonClick(buttons[selector], "active");
  3320. if (object.isVisible()) {
  3321. $("#toast-container").animate({
  3322. right: '5px'
  3323. },
  3324. {
  3325. queue: false,
  3326. duration: 500
  3327. });
  3328. $(selector).hide("slide", {
  3329. direction: "right",
  3330. queue: false,
  3331. duration: 500
  3332. });
  3333. if(typeof onClose === "function") {
  3334. onClose();
  3335. }
  3336. currentlyOpen = null;
  3337. }
  3338. else {
  3339. // Undock the toolbar when the chat is shown and if we're in a
  3340. // video mode.
  3341. if (VideoLayout.isLargeVideoVisible()) {
  3342. ToolbarToggler.dockToolbar(false);
  3343. }
  3344. if(currentlyOpen) {
  3345. var current = $(currentlyOpen);
  3346. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  3347. current.css('z-index', 4);
  3348. setTimeout(function () {
  3349. current.css('display', 'none');
  3350. current.css('z-index', 5);
  3351. }, 500);
  3352. }
  3353. $("#toast-container").animate({
  3354. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  3355. },
  3356. {
  3357. queue: false,
  3358. duration: 500
  3359. });
  3360. $(selector).show("slide", {
  3361. direction: "right",
  3362. queue: false,
  3363. duration: 500,
  3364. complete: onOpenComplete
  3365. });
  3366. if(typeof onOpen === "function") {
  3367. onOpen();
  3368. }
  3369. currentlyOpen = selector;
  3370. }
  3371. };
  3372. /**
  3373. * Opens / closes the chat area.
  3374. */
  3375. my.toggleChat = function() {
  3376. var chatCompleteFunction = Chat.isVisible() ?
  3377. function() {} : function () {
  3378. Chat.scrollChatToBottom();
  3379. $('#chatspace').trigger('shown');
  3380. };
  3381. resizeVideoArea(Chat.isVisible(), chatCompleteFunction);
  3382. toggle(Chat,
  3383. '#chatspace',
  3384. function () {
  3385. // Request the focus in the nickname field or the chat input field.
  3386. if ($('#nickname').css('visibility') === 'visible') {
  3387. $('#nickinput').focus();
  3388. } else {
  3389. $('#usermsg').focus();
  3390. }
  3391. },
  3392. null,
  3393. Chat.resizeChat,
  3394. null);
  3395. };
  3396. /**
  3397. * Opens / closes the contact list area.
  3398. */
  3399. my.toggleContactList = function () {
  3400. var completeFunction = ContactList.isVisible() ?
  3401. function() {} : function () { $('#contactlist').trigger('shown');};
  3402. resizeVideoArea(ContactList.isVisible(), completeFunction);
  3403. toggle(ContactList,
  3404. '#contactlist',
  3405. null,
  3406. function() {
  3407. ContactList.setVisualNotification(false);
  3408. },
  3409. null);
  3410. };
  3411. /**
  3412. * Opens / closes the settings menu
  3413. */
  3414. my.toggleSettingsMenu = function() {
  3415. resizeVideoArea(SettingsMenu.isVisible(), function (){});
  3416. toggle(SettingsMenu,
  3417. '#settingsmenu',
  3418. null,
  3419. function() {
  3420. var settings = Settings.getSettings();
  3421. $('#setDisplayName').get(0).value = settings.displayName;
  3422. $('#setEmail').get(0).value = settings.email;
  3423. },
  3424. null);
  3425. };
  3426. /**
  3427. * Returns the size of the side panel.
  3428. */
  3429. my.getPanelSize = function () {
  3430. var availableHeight = window.innerHeight;
  3431. var availableWidth = window.innerWidth;
  3432. var panelWidth = 200;
  3433. if (availableWidth * 0.2 < 200) {
  3434. panelWidth = availableWidth * 0.2;
  3435. }
  3436. return [panelWidth, availableHeight];
  3437. };
  3438. my.isVisible = function() {
  3439. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  3440. };
  3441. return my;
  3442. }(PanelToggler || {}));
  3443. module.exports = PanelToggler;
  3444. },{"../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){
  3445. /* global $, Util, nickname:true */
  3446. var Replacement = require("./Replacement");
  3447. var CommandsProcessor = require("./Commands");
  3448. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  3449. var smileys = require("./smileys.json").smileys;
  3450. var NicknameHandler = require("../../util/NicknameHandler");
  3451. var UIUtil = require("../../util/UIUtil");
  3452. var UIEvents = require("../../../../service/UI/UIEvents");
  3453. var notificationInterval = false;
  3454. var unreadMessages = 0;
  3455. /**
  3456. * Shows/hides a visual notification, indicating that a message has arrived.
  3457. */
  3458. function setVisualNotification(show) {
  3459. var unreadMsgElement = document.getElementById('unreadMessages');
  3460. var unreadMsgBottomElement
  3461. = document.getElementById('bottomUnreadMessages');
  3462. var glower = $('#chatButton');
  3463. var bottomGlower = $('#chatBottomButton');
  3464. if (unreadMessages) {
  3465. unreadMsgElement.innerHTML = unreadMessages.toString();
  3466. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  3467. ToolbarToggler.dockToolbar(true);
  3468. var chatButtonElement
  3469. = document.getElementById('chatButton').parentNode;
  3470. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  3471. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  3472. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  3473. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  3474. unreadMsgElement.setAttribute(
  3475. 'style',
  3476. 'top:' + topIndent +
  3477. '; left:' + leftIndent + ';');
  3478. var chatBottomButtonElement
  3479. = document.getElementById('chatBottomButton').parentNode;
  3480. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  3481. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  3482. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  3483. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  3484. unreadMsgBottomElement.setAttribute(
  3485. 'style',
  3486. 'top:' + bottomTopIndent +
  3487. '; left:' + bottomLeftIndent + ';');
  3488. if (!glower.hasClass('icon-chat-simple')) {
  3489. glower.removeClass('icon-chat');
  3490. glower.addClass('icon-chat-simple');
  3491. }
  3492. }
  3493. else {
  3494. unreadMsgElement.innerHTML = '';
  3495. unreadMsgBottomElement.innerHTML = '';
  3496. glower.removeClass('icon-chat-simple');
  3497. glower.addClass('icon-chat');
  3498. }
  3499. if (show && !notificationInterval) {
  3500. notificationInterval = window.setInterval(function () {
  3501. glower.toggleClass('active');
  3502. bottomGlower.toggleClass('active glowing');
  3503. }, 800);
  3504. }
  3505. else if (!show && notificationInterval) {
  3506. window.clearInterval(notificationInterval);
  3507. notificationInterval = false;
  3508. glower.removeClass('active');
  3509. bottomGlower.removeClass('glowing');
  3510. bottomGlower.addClass('active');
  3511. }
  3512. }
  3513. /**
  3514. * Returns the current time in the format it is shown to the user
  3515. * @returns {string}
  3516. */
  3517. function getCurrentTime() {
  3518. var now = new Date();
  3519. var hour = now.getHours();
  3520. var minute = now.getMinutes();
  3521. var second = now.getSeconds();
  3522. if(hour.toString().length === 1) {
  3523. hour = '0'+hour;
  3524. }
  3525. if(minute.toString().length === 1) {
  3526. minute = '0'+minute;
  3527. }
  3528. if(second.toString().length === 1) {
  3529. second = '0'+second;
  3530. }
  3531. return hour+':'+minute+':'+second;
  3532. }
  3533. function toggleSmileys()
  3534. {
  3535. var smileys = $('#smileysContainer');
  3536. if(!smileys.is(':visible')) {
  3537. smileys.show("slide", { direction: "down", duration: 300});
  3538. } else {
  3539. smileys.hide("slide", { direction: "down", duration: 300});
  3540. }
  3541. $('#usermsg').focus();
  3542. }
  3543. function addClickFunction(smiley, number) {
  3544. smiley.onclick = function addSmileyToMessage() {
  3545. var usermsg = $('#usermsg');
  3546. var message = usermsg.val();
  3547. message += smileys['smiley' + number];
  3548. usermsg.val(message);
  3549. usermsg.get(0).setSelectionRange(message.length, message.length);
  3550. toggleSmileys();
  3551. usermsg.focus();
  3552. };
  3553. }
  3554. /**
  3555. * Adds the smileys container to the chat
  3556. */
  3557. function addSmileys() {
  3558. var smileysContainer = document.createElement('div');
  3559. smileysContainer.id = 'smileysContainer';
  3560. for(var i = 1; i <= 21; i++) {
  3561. var smileyContainer = document.createElement('div');
  3562. smileyContainer.id = 'smiley' + i;
  3563. smileyContainer.className = 'smileyContainer';
  3564. var smiley = document.createElement('img');
  3565. smiley.src = 'images/smileys/smiley' + i + '.svg';
  3566. smiley.className = 'smiley';
  3567. addClickFunction(smiley, i);
  3568. smileyContainer.appendChild(smiley);
  3569. smileysContainer.appendChild(smileyContainer);
  3570. }
  3571. $("#chatspace").append(smileysContainer);
  3572. }
  3573. /**
  3574. * Resizes the chat conversation.
  3575. */
  3576. function resizeChatConversation() {
  3577. var msgareaHeight = $('#usermsg').outerHeight();
  3578. var chatspace = $('#chatspace');
  3579. var width = chatspace.width();
  3580. var chat = $('#chatconversation');
  3581. var smileys = $('#smileysarea');
  3582. smileys.height(msgareaHeight);
  3583. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  3584. $('#smileysContainer').css('bottom', msgareaHeight);
  3585. chat.width(width - 10);
  3586. chat.height(window.innerHeight - 15 - msgareaHeight);
  3587. }
  3588. /**
  3589. * Chat related user interface.
  3590. */
  3591. var Chat = (function (my) {
  3592. /**
  3593. * Initializes chat related interface.
  3594. */
  3595. my.init = function () {
  3596. if(NicknameHandler.getNickname())
  3597. Chat.setChatConversationMode(true);
  3598. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  3599. function (nickname) {
  3600. Chat.setChatConversationMode(true);
  3601. });
  3602. $('#nickinput').keydown(function (event) {
  3603. if (event.keyCode === 13) {
  3604. event.preventDefault();
  3605. var val = UIUtil.escapeHtml(this.value);
  3606. this.value = '';
  3607. if (!NicknameHandler.getNickname()) {
  3608. NicknameHandler.setNickname(val);
  3609. return;
  3610. }
  3611. }
  3612. });
  3613. $('#usermsg').keydown(function (event) {
  3614. if (event.keyCode === 13) {
  3615. event.preventDefault();
  3616. var value = this.value;
  3617. $('#usermsg').val('').trigger('autosize.resize');
  3618. this.focus();
  3619. var command = new CommandsProcessor(value);
  3620. if(command.isCommand())
  3621. {
  3622. command.processCommand();
  3623. }
  3624. else
  3625. {
  3626. var message = UIUtil.escapeHtml(value);
  3627. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  3628. }
  3629. }
  3630. });
  3631. var onTextAreaResize = function () {
  3632. resizeChatConversation();
  3633. Chat.scrollChatToBottom();
  3634. };
  3635. $('#usermsg').autosize({callback: onTextAreaResize});
  3636. $("#chatspace").bind("shown",
  3637. function () {
  3638. unreadMessages = 0;
  3639. setVisualNotification(false);
  3640. });
  3641. addSmileys();
  3642. };
  3643. /**
  3644. * Appends the given message to the chat conversation.
  3645. */
  3646. my.updateChatConversation = function (from, displayName, message) {
  3647. var divClassName = '';
  3648. if (APP.xmpp.myJid() === from) {
  3649. divClassName = "localuser";
  3650. }
  3651. else {
  3652. divClassName = "remoteuser";
  3653. if (!Chat.isVisible()) {
  3654. unreadMessages++;
  3655. UIUtil.playSoundNotification('chatNotification');
  3656. setVisualNotification(true);
  3657. }
  3658. }
  3659. // replace links and smileys
  3660. // Strophe already escapes special symbols on sending,
  3661. // so we escape here only tags to avoid double &amp;
  3662. var escMessage = message.replace(/</g, '&lt;').
  3663. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  3664. var escDisplayName = UIUtil.escapeHtml(displayName);
  3665. message = Replacement.processReplacements(escMessage);
  3666. var messageContainer =
  3667. '<div class="chatmessage">'+
  3668. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  3669. '<div class="username ' + divClassName +'">' + escDisplayName +
  3670. '</div>' + '<div class="timestamp">' + getCurrentTime() +
  3671. '</div>' + '<div class="usermessage">' + message + '</div>' +
  3672. '</div>';
  3673. $('#chatconversation').append(messageContainer);
  3674. $('#chatconversation').animate(
  3675. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3676. };
  3677. /**
  3678. * Appends error message to the conversation
  3679. * @param errorMessage the received error message.
  3680. * @param originalText the original message.
  3681. */
  3682. my.chatAddError = function(errorMessage, originalText)
  3683. {
  3684. errorMessage = UIUtil.escapeHtml(errorMessage);
  3685. originalText = UIUtil.escapeHtml(originalText);
  3686. $('#chatconversation').append(
  3687. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  3688. (originalText? (' \"'+ originalText + '\"') : "") +
  3689. ' was not sent.' +
  3690. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  3691. $('#chatconversation').animate(
  3692. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3693. };
  3694. /**
  3695. * Sets the subject to the UI
  3696. * @param subject the subject
  3697. */
  3698. my.chatSetSubject = function(subject)
  3699. {
  3700. if(subject)
  3701. subject = subject.trim();
  3702. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  3703. if(subject === "")
  3704. {
  3705. $("#subject").css({display: "none"});
  3706. }
  3707. else
  3708. {
  3709. $("#subject").css({display: "block"});
  3710. }
  3711. };
  3712. /**
  3713. * Sets the chat conversation mode.
  3714. */
  3715. my.setChatConversationMode = function (isConversationMode) {
  3716. if (isConversationMode) {
  3717. $('#nickname').css({visibility: 'hidden'});
  3718. $('#chatconversation').css({visibility: 'visible'});
  3719. $('#usermsg').css({visibility: 'visible'});
  3720. $('#smileysarea').css({visibility: 'visible'});
  3721. $('#usermsg').focus();
  3722. }
  3723. };
  3724. /**
  3725. * Resizes the chat area.
  3726. */
  3727. my.resizeChat = function () {
  3728. var chatSize = require("../SidePanelToggler").getPanelSize();
  3729. $('#chatspace').width(chatSize[0]);
  3730. $('#chatspace').height(chatSize[1]);
  3731. resizeChatConversation();
  3732. };
  3733. /**
  3734. * Indicates if the chat is currently visible.
  3735. */
  3736. my.isVisible = function () {
  3737. return $('#chatspace').is(":visible");
  3738. };
  3739. /**
  3740. * Shows and hides the window with the smileys
  3741. */
  3742. my.toggleSmileys = toggleSmileys;
  3743. /**
  3744. * Scrolls chat to the bottom.
  3745. */
  3746. my.scrollChatToBottom = function() {
  3747. setTimeout(function () {
  3748. $('#chatconversation').scrollTop(
  3749. $('#chatconversation')[0].scrollHeight);
  3750. }, 5);
  3751. };
  3752. return my;
  3753. }(Chat || {}));
  3754. module.exports = Chat;
  3755. },{"../../../../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){
  3756. var UIUtil = require("../../util/UIUtil");
  3757. /**
  3758. * List with supported commands. The keys are the names of the commands and
  3759. * the value is the function that processes the message.
  3760. * @type {{String: function}}
  3761. */
  3762. var commands = {
  3763. "topic" : processTopic
  3764. };
  3765. /**
  3766. * Extracts the command from the message.
  3767. * @param message the received message
  3768. * @returns {string} the command
  3769. */
  3770. function getCommand(message)
  3771. {
  3772. if(message)
  3773. {
  3774. for(var command in commands)
  3775. {
  3776. if(message.indexOf("/" + command) == 0)
  3777. return command;
  3778. }
  3779. }
  3780. return "";
  3781. };
  3782. /**
  3783. * Processes the data for topic command.
  3784. * @param commandArguments the arguments of the topic command.
  3785. */
  3786. function processTopic(commandArguments)
  3787. {
  3788. var topic = UIUtil.escapeHtml(commandArguments);
  3789. APP.xmpp.setSubject(topic);
  3790. }
  3791. /**
  3792. * Constructs new CommandProccessor instance from a message that
  3793. * handles commands received via chat messages.
  3794. * @param message the message
  3795. * @constructor
  3796. */
  3797. function CommandsProcessor(message)
  3798. {
  3799. var command = getCommand(message);
  3800. /**
  3801. * Returns the name of the command.
  3802. * @returns {String} the command
  3803. */
  3804. this.getCommand = function()
  3805. {
  3806. return command;
  3807. };
  3808. var messageArgument = message.substr(command.length + 2);
  3809. /**
  3810. * Returns the arguments of the command.
  3811. * @returns {string}
  3812. */
  3813. this.getArgument = function()
  3814. {
  3815. return messageArgument;
  3816. };
  3817. }
  3818. /**
  3819. * Checks whether this instance is valid command or not.
  3820. * @returns {boolean}
  3821. */
  3822. CommandsProcessor.prototype.isCommand = function()
  3823. {
  3824. if(this.getCommand())
  3825. return true;
  3826. return false;
  3827. };
  3828. /**
  3829. * Processes the command.
  3830. */
  3831. CommandsProcessor.prototype.processCommand = function()
  3832. {
  3833. if(!this.isCommand())
  3834. return;
  3835. commands[this.getCommand()](this.getArgument());
  3836. };
  3837. module.exports = CommandsProcessor;
  3838. },{"../../util/UIUtil":30}],20:[function(require,module,exports){
  3839. var Smileys = require("./smileys.json");
  3840. /**
  3841. * Processes links and smileys in "body"
  3842. */
  3843. function processReplacements(body)
  3844. {
  3845. //make links clickable
  3846. body = linkify(body);
  3847. //add smileys
  3848. body = smilify(body);
  3849. return body;
  3850. }
  3851. /**
  3852. * Finds and replaces all links in the links in "body"
  3853. * with their <a href=""></a>
  3854. */
  3855. function linkify(inputText)
  3856. {
  3857. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  3858. //URLs starting with http://, https://, or ftp://
  3859. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  3860. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  3861. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  3862. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  3863. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  3864. //Change email addresses to mailto:: links.
  3865. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  3866. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  3867. return replacedText;
  3868. }
  3869. /**
  3870. * Replaces common smiley strings with images
  3871. */
  3872. function smilify(body)
  3873. {
  3874. if(!body) {
  3875. return body;
  3876. }
  3877. var regexs = Smileys["regexs"];
  3878. for(var smiley in regexs) {
  3879. if(regexs.hasOwnProperty(smiley)) {
  3880. body = body.replace(regexs[smiley],
  3881. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  3882. }
  3883. }
  3884. return body;
  3885. }
  3886. module.exports = {
  3887. processReplacements: processReplacements,
  3888. linkify: linkify
  3889. };
  3890. },{"./smileys.json":21}],21:[function(require,module,exports){
  3891. module.exports={
  3892. "smileys": {
  3893. "smiley1": ":)",
  3894. "smiley2": ":(",
  3895. "smiley3": ":D",
  3896. "smiley4": "(y)",
  3897. "smiley5": " :P",
  3898. "smiley6": "(wave)",
  3899. "smiley7": "(blush)",
  3900. "smiley8": "(chuckle)",
  3901. "smiley9": "(shocked)",
  3902. "smiley10": ":*",
  3903. "smiley11": "(n)",
  3904. "smiley12": "(search)",
  3905. "smiley13": " <3",
  3906. "smiley14": "(oops)",
  3907. "smiley15": "(angry)",
  3908. "smiley16": "(angel)",
  3909. "smiley17": "(sick)",
  3910. "smiley18": ";(",
  3911. "smiley19": "(bomb)",
  3912. "smiley20": "(clap)",
  3913. "smiley21": " ;)"
  3914. },
  3915. "regexs": {
  3916. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  3917. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  3918. "smiley1": /(:-\)|:\))/gi,
  3919. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  3920. "smiley5": /(:-P|:P|:-p|:p)/gi,
  3921. "smiley6": /(\(wave\))/gi,
  3922. "smiley7": /(\(blush\))/gi,
  3923. "smiley8": /(\(chuckle\))/gi,
  3924. "smiley9": /(:-0|\(shocked\))/gi,
  3925. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  3926. "smiley11": /(\(n\))/gi,
  3927. "smiley12": /(\(search\))/g,
  3928. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  3929. "smiley14": /(\(oops\))/gi,
  3930. "smiley15": /(\(angry\))/gi,
  3931. "smiley16": /(\(angel\))/gi,
  3932. "smiley17": /(\(sick\))/gi,
  3933. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  3934. "smiley19": /(\(bomb\))/gi,
  3935. "smiley20": /(\(clap\))/gi,
  3936. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  3937. }
  3938. }
  3939. },{}],22:[function(require,module,exports){
  3940. var numberOfContacts = 0;
  3941. var notificationInterval;
  3942. /**
  3943. * Updates the number of participants in the contact list button and sets
  3944. * the glow
  3945. * @param delta indicates whether a new user has joined (1) or someone has
  3946. * left(-1)
  3947. */
  3948. function updateNumberOfParticipants(delta) {
  3949. //when the user is alone we don't show the number of participants
  3950. if(numberOfContacts === 0) {
  3951. $("#numberOfParticipants").text('');
  3952. numberOfContacts += delta;
  3953. } else if(numberOfContacts !== 0 && !ContactList.isVisible()) {
  3954. ContactList.setVisualNotification(true);
  3955. numberOfContacts += delta;
  3956. $("#numberOfParticipants").text(numberOfContacts);
  3957. }
  3958. }
  3959. /**
  3960. * Creates the avatar element.
  3961. *
  3962. * @return the newly created avatar element
  3963. */
  3964. function createAvatar(id) {
  3965. var avatar = document.createElement('img');
  3966. avatar.className = "icon-avatar avatar";
  3967. avatar.src = "https://www.gravatar.com/avatar/" + id + "?d=wavatar&size=30";
  3968. return avatar;
  3969. }
  3970. /**
  3971. * Creates the display name paragraph.
  3972. *
  3973. * @param displayName the display name to set
  3974. */
  3975. function createDisplayNameParagraph(displayName) {
  3976. var p = document.createElement('p');
  3977. p.innerText = displayName;
  3978. return p;
  3979. }
  3980. function stopGlowing(glower) {
  3981. window.clearInterval(notificationInterval);
  3982. notificationInterval = false;
  3983. glower.removeClass('glowing');
  3984. if (!ContactList.isVisible()) {
  3985. glower.removeClass('active');
  3986. }
  3987. }
  3988. /**
  3989. * Contact list.
  3990. */
  3991. var ContactList = {
  3992. /**
  3993. * Indicates if the chat is currently visible.
  3994. *
  3995. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  3996. * otherwise
  3997. */
  3998. isVisible: function () {
  3999. return $('#contactlist').is(":visible");
  4000. },
  4001. /**
  4002. * Adds a contact for the given peerJid if such doesn't yet exist.
  4003. *
  4004. * @param peerJid the peerJid corresponding to the contact
  4005. * @param id the user's email or userId used to get the user's avatar
  4006. */
  4007. ensureAddContact: function (peerJid, id) {
  4008. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4009. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4010. if (!contact || contact.length <= 0)
  4011. ContactList.addContact(peerJid, id);
  4012. },
  4013. /**
  4014. * Adds a contact for the given peer jid.
  4015. *
  4016. * @param peerJid the jid of the contact to add
  4017. * @param id the email or userId of the user
  4018. */
  4019. addContact: function (peerJid, id) {
  4020. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4021. var contactlist = $('#contactlist>ul');
  4022. var newContact = document.createElement('li');
  4023. newContact.id = resourceJid;
  4024. newContact.className = "clickable";
  4025. newContact.onclick = function (event) {
  4026. if (event.currentTarget.className === "clickable") {
  4027. $(ContactList).trigger('contactclicked', [peerJid]);
  4028. }
  4029. };
  4030. newContact.appendChild(createAvatar(id));
  4031. newContact.appendChild(createDisplayNameParagraph("Participant"));
  4032. var clElement = contactlist.get(0);
  4033. if (resourceJid === APP.xmpp.myResource()
  4034. && $('#contactlist>ul .title')[0].nextSibling.nextSibling) {
  4035. clElement.insertBefore(newContact,
  4036. $('#contactlist>ul .title')[0].nextSibling.nextSibling);
  4037. }
  4038. else {
  4039. clElement.appendChild(newContact);
  4040. }
  4041. updateNumberOfParticipants(1);
  4042. },
  4043. /**
  4044. * Removes a contact for the given peer jid.
  4045. *
  4046. * @param peerJid the peerJid corresponding to the contact to remove
  4047. */
  4048. removeContact: function (peerJid) {
  4049. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4050. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4051. if (contact && contact.length > 0) {
  4052. var contactlist = $('#contactlist>ul');
  4053. contactlist.get(0).removeChild(contact.get(0));
  4054. updateNumberOfParticipants(-1);
  4055. }
  4056. },
  4057. setVisualNotification: function (show, stopGlowingIn) {
  4058. var glower = $('#contactListButton');
  4059. if (show && !notificationInterval) {
  4060. notificationInterval = window.setInterval(function () {
  4061. glower.toggleClass('active glowing');
  4062. }, 800);
  4063. }
  4064. else if (!show && notificationInterval) {
  4065. stopGlowing(glower);
  4066. }
  4067. if (stopGlowingIn) {
  4068. setTimeout(function () {
  4069. stopGlowing(glower);
  4070. }, stopGlowingIn);
  4071. }
  4072. },
  4073. setClickable: function (resourceJid, isClickable) {
  4074. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4075. if (isClickable) {
  4076. contact.addClass('clickable');
  4077. } else {
  4078. contact.removeClass('clickable');
  4079. }
  4080. },
  4081. onDisplayNameChange: function (peerJid, displayName) {
  4082. if (peerJid === 'localVideoContainer')
  4083. peerJid = APP.xmpp.myJid();
  4084. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4085. var contactName = $('#contactlist #' + resourceJid + '>p');
  4086. if (contactName && displayName && displayName.length > 0)
  4087. contactName.html(displayName);
  4088. }
  4089. };
  4090. module.exports = ContactList;
  4091. },{}],23:[function(require,module,exports){
  4092. var Avatar = require("../../avatar/Avatar");
  4093. var Settings = require("./../../../settings/Settings");
  4094. var UIUtil = require("../../util/UIUtil");
  4095. var languages = require("../../../../service/translation/languages");
  4096. function generateLanguagesSelectBox()
  4097. {
  4098. var currentLang = APP.translation.getCurrentLanguage();
  4099. var html = "<select id=\"languages_selectbox\">";
  4100. var langArray = languages.getLanguages();
  4101. for(var i = 0; i < langArray.length; i++)
  4102. {
  4103. var lang = langArray[i];
  4104. html += "<option ";
  4105. if(lang === currentLang)
  4106. html += "selected ";
  4107. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  4108. html += "</option>";
  4109. }
  4110. return html + "</select>";
  4111. }
  4112. var SettingsMenu = {
  4113. init: function () {
  4114. $("#updateSettings").before(generateLanguagesSelectBox());
  4115. $('#settingsmenu>input').keyup(function(event){
  4116. if(event.keyCode === 13) {//enter
  4117. SettingsMenu.update();
  4118. }
  4119. });
  4120. $("#updateSettings").click(function () {
  4121. SettingsMenu.update();
  4122. });
  4123. },
  4124. update: function() {
  4125. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  4126. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  4127. if(newDisplayName) {
  4128. var displayName = Settings.setDisplayName(newDisplayName);
  4129. APP.xmpp.addToPresence("displayName", displayName, true);
  4130. }
  4131. APP.translation.setLanguage($("#languages_selectbox").val());
  4132. APP.xmpp.addToPresence("email", newEmail);
  4133. var email = Settings.setEmail(newEmail);
  4134. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  4135. },
  4136. isVisible: function() {
  4137. return $('#settingsmenu').is(':visible');
  4138. },
  4139. setDisplayName: function(newDisplayName) {
  4140. var displayName = Settings.setDisplayName(newDisplayName);
  4141. $('#setDisplayName').get(0).value = displayName;
  4142. },
  4143. onDisplayNameChange: function(peerJid, newDisplayName) {
  4144. if(peerJid === 'localVideoContainer' ||
  4145. peerJid === APP.xmpp.myJid()) {
  4146. this.setDisplayName(newDisplayName);
  4147. }
  4148. }
  4149. };
  4150. module.exports = SettingsMenu;
  4151. },{"../../../../service/translation/languages":88,"../../avatar/Avatar":13,"../../util/UIUtil":30,"./../../../settings/Settings":38}],24:[function(require,module,exports){
  4152. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4153. var buttonHandlers = {
  4154. "bottom_toolbar_contact_list": function () {
  4155. BottomToolbar.toggleContactList();
  4156. },
  4157. "bottom_toolbar_film_strip": function () {
  4158. BottomToolbar.toggleFilmStrip();
  4159. },
  4160. "bottom_toolbar_chat": function () {
  4161. BottomToolbar.toggleChat();
  4162. }
  4163. };
  4164. var BottomToolbar = (function (my) {
  4165. my.init = function () {
  4166. for(var k in buttonHandlers)
  4167. $("#" + k).click(buttonHandlers[k]);
  4168. };
  4169. my.toggleChat = function() {
  4170. PanelToggler.toggleChat();
  4171. };
  4172. my.toggleContactList = function() {
  4173. PanelToggler.toggleContactList();
  4174. };
  4175. my.toggleFilmStrip = function() {
  4176. var filmstrip = $("#remoteVideos");
  4177. filmstrip.toggleClass("hidden");
  4178. };
  4179. $(document).bind("remotevideo.resized", function (event, width, height) {
  4180. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  4181. $('#bottomToolbar').css({bottom: bottom + 'px'});
  4182. });
  4183. return my;
  4184. }(BottomToolbar || {}));
  4185. module.exports = BottomToolbar;
  4186. },{"../side_pannels/SidePanelToggler":17}],25:[function(require,module,exports){
  4187. /* global APP,$, buttonClick, config, lockRoom,
  4188. setSharedKey, Util */
  4189. var messageHandler = require("../util/MessageHandler");
  4190. var BottomToolbar = require("./BottomToolbar");
  4191. var Prezi = require("../prezi/Prezi");
  4192. var Etherpad = require("../etherpad/Etherpad");
  4193. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4194. var Authentication = require("../authentication/Authentication");
  4195. var UIUtil = require("../util/UIUtil");
  4196. var AuthenticationEvents
  4197. = require("../../../service/authentication/AuthenticationEvents");
  4198. var roomUrl = null;
  4199. var sharedKey = '';
  4200. var UI = null;
  4201. var buttonHandlers =
  4202. {
  4203. "toolbar_button_mute": function () {
  4204. return APP.UI.toggleAudio();
  4205. },
  4206. "toolbar_button_camera": function () {
  4207. return APP.UI.toggleVideo();
  4208. },
  4209. /*"toolbar_button_authentication": function () {
  4210. return Toolbar.authenticateClicked();
  4211. },*/
  4212. "toolbar_button_record": function () {
  4213. return toggleRecording();
  4214. },
  4215. "toolbar_button_security": function () {
  4216. return Toolbar.openLockDialog();
  4217. },
  4218. "toolbar_button_link": function () {
  4219. return Toolbar.openLinkDialog();
  4220. },
  4221. "toolbar_button_chat": function () {
  4222. return BottomToolbar.toggleChat();
  4223. },
  4224. "toolbar_button_prezi": function () {
  4225. return Prezi.openPreziDialog();
  4226. },
  4227. "toolbar_button_etherpad": function () {
  4228. return Etherpad.toggleEtherpad(0);
  4229. },
  4230. "toolbar_button_desktopsharing": function () {
  4231. return APP.desktopsharing.toggleScreenSharing();
  4232. },
  4233. "toolbar_button_fullScreen": function()
  4234. {
  4235. UIUtil.buttonClick("#fullScreen", "icon-full-screen icon-exit-full-screen");
  4236. return Toolbar.toggleFullScreen();
  4237. },
  4238. "toolbar_button_sip": function () {
  4239. return callSipButtonClicked();
  4240. },
  4241. "toolbar_button_settings": function () {
  4242. PanelToggler.toggleSettingsMenu();
  4243. },
  4244. "toolbar_button_hangup": function () {
  4245. return hangup();
  4246. },
  4247. "toolbar_button_login": function () {
  4248. Toolbar.authenticateClicked();
  4249. },
  4250. "toolbar_button_logout": function () {
  4251. // Ask for confirmation
  4252. messageHandler.openTwoButtonDialog(
  4253. "Logout",
  4254. "Are you sure you want to logout and stop the conference ?",
  4255. false, "Yes",
  4256. function (evt, yes) {
  4257. if (yes) {
  4258. APP.xmpp.logout(function (url) {
  4259. if (url) {
  4260. window.location.href = url;
  4261. } else {
  4262. hangup();
  4263. }
  4264. });
  4265. }
  4266. });
  4267. }
  4268. };
  4269. function hangup() {
  4270. APP.xmpp.disposeConference();
  4271. if(config.enableWelcomePage)
  4272. {
  4273. setTimeout(function()
  4274. {
  4275. window.localStorage.welcomePageDisabled = false;
  4276. window.location.pathname = "/";
  4277. }, 10000);
  4278. }
  4279. UI.messageHandler.openDialog(
  4280. "Session Terminated",
  4281. "You hung up the call",
  4282. true,
  4283. { "Join again": true },
  4284. function(event, value, message, formVals)
  4285. {
  4286. window.location.reload();
  4287. return false;
  4288. }
  4289. );
  4290. }
  4291. /**
  4292. * Starts or stops the recording for the conference.
  4293. */
  4294. function toggleRecording() {
  4295. APP.xmpp.toggleRecording(function (callback) {
  4296. APP.UI.messageHandler.openTwoButtonDialog(null,
  4297. '<h2>Enter recording token</h2>' +
  4298. '<input id="recordingToken" type="text" ' +
  4299. 'placeholder="token" autofocus>',
  4300. false,
  4301. "Save",
  4302. function (e, v, m, f) {
  4303. if (v) {
  4304. var token = document.getElementById('recordingToken');
  4305. if (token.value) {
  4306. callback(UIUtil.escapeHtml(token.value));
  4307. }
  4308. }
  4309. },
  4310. function (event) {
  4311. document.getElementById('recordingToken').focus();
  4312. },
  4313. function () {
  4314. }
  4315. );
  4316. }, Toolbar.setRecordingButtonState, Toolbar.setRecordingButtonState);
  4317. }
  4318. /**
  4319. * Locks / unlocks the room.
  4320. */
  4321. function lockRoom(lock) {
  4322. var currentSharedKey = '';
  4323. if (lock)
  4324. currentSharedKey = sharedKey;
  4325. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  4326. // password is required
  4327. if (sharedKey)
  4328. {
  4329. console.log('set room password');
  4330. Toolbar.lockLockButton();
  4331. }
  4332. else
  4333. {
  4334. console.log('removed room password');
  4335. Toolbar.unlockLockButton();
  4336. }
  4337. }, function (err) {
  4338. console.warn('setting password failed', err);
  4339. messageHandler.showError('Lock failed',
  4340. 'Failed to lock conference.',
  4341. err);
  4342. Toolbar.setSharedKey('');
  4343. }, function () {
  4344. console.warn('room passwords not supported');
  4345. messageHandler.showError('Warning',
  4346. 'Room passwords are currently not supported.');
  4347. Toolbar.setSharedKey('');
  4348. });
  4349. };
  4350. /**
  4351. * Invite participants to conference.
  4352. */
  4353. function inviteParticipants() {
  4354. if (roomUrl === null)
  4355. return;
  4356. var sharedKeyText = "";
  4357. if (sharedKey && sharedKey.length > 0) {
  4358. sharedKeyText =
  4359. "This conference is password protected. Please use the " +
  4360. "following pin when joining:%0D%0A%0D%0A" +
  4361. sharedKey + "%0D%0A%0D%0A";
  4362. }
  4363. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  4364. var subject = "Invitation to a " + interfaceConfig.APP_NAME + " (" + conferenceName + ")";
  4365. var body = "Hey there, I%27d like to invite you to a " + interfaceConfig.APP_NAME +
  4366. " conference I%27ve just set up.%0D%0A%0D%0A" +
  4367. "Please click on the following link in order" +
  4368. " to join the conference.%0D%0A%0D%0A" +
  4369. roomUrl +
  4370. "%0D%0A%0D%0A" +
  4371. sharedKeyText +
  4372. "Note that " + interfaceConfig.APP_NAME + " is currently" +
  4373. " only supported by Chromium," +
  4374. " Google Chrome and Opera, so you need" +
  4375. " to be using one of these browsers.%0D%0A%0D%0A" +
  4376. "Talk to you in a sec!";
  4377. if (window.localStorage.displayname) {
  4378. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  4379. }
  4380. if (interfaceConfig.INVITATION_POWERED_BY) {
  4381. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  4382. }
  4383. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  4384. }
  4385. function callSipButtonClicked()
  4386. {
  4387. var defaultNumber
  4388. = config.defaultSipNumber ? config.defaultSipNumber : '';
  4389. messageHandler.openTwoButtonDialog(null,
  4390. '<h2>Enter SIP number</h2>' +
  4391. '<input id="sipNumber" type="text"' +
  4392. ' value="' + defaultNumber + '" autofocus>',
  4393. false,
  4394. "Dial",
  4395. function (e, v, m, f) {
  4396. if (v) {
  4397. var numberInput = document.getElementById('sipNumber');
  4398. if (numberInput.value) {
  4399. APP.xmpp.dial(numberInput.value, 'fromnumber',
  4400. UI.getRoomName(), sharedKey);
  4401. }
  4402. }
  4403. },
  4404. function (event) {
  4405. document.getElementById('sipNumber').focus();
  4406. }
  4407. );
  4408. }
  4409. var Toolbar = (function (my) {
  4410. my.init = function (ui) {
  4411. for(var k in buttonHandlers)
  4412. $("#" + k).click(buttonHandlers[k]);
  4413. UI = ui;
  4414. // Update login info
  4415. APP.xmpp.addListener(
  4416. AuthenticationEvents.IDENTITY_UPDATED,
  4417. function (authenticationEnabled, userIdentity) {
  4418. var loggedIn = false;
  4419. if (userIdentity) {
  4420. loggedIn = true;
  4421. }
  4422. //FIXME: XMPP authentication need improvements for "live" login
  4423. if (!APP.xmpp.isExternalAuthEnabled() && !loggedIn)
  4424. {
  4425. authenticationEnabled = false;
  4426. }
  4427. Toolbar.showAuthenticateButton(authenticationEnabled);
  4428. if (authenticationEnabled) {
  4429. Toolbar.setAuthenticatedIdentity(userIdentity);
  4430. Toolbar.showLoginButton(!loggedIn);
  4431. Toolbar.showLogoutButton(loggedIn);
  4432. }
  4433. }
  4434. );
  4435. },
  4436. /**
  4437. * Sets shared key
  4438. * @param sKey the shared key
  4439. */
  4440. my.setSharedKey = function (sKey) {
  4441. sharedKey = sKey;
  4442. };
  4443. my.authenticateClicked = function () {
  4444. Authentication.focusAuthenticationWindow();
  4445. // Get authentication URL
  4446. if (!APP.xmpp.getMUCJoined()) {
  4447. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  4448. // If conference has not been started yet - redirect to login page
  4449. window.location.href = url;
  4450. });
  4451. } else {
  4452. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  4453. // Otherwise - open popup with authentication URL
  4454. var authenticationWindow = Authentication.createAuthenticationWindow(
  4455. function () {
  4456. // On popup closed - retry room allocation
  4457. APP.xmpp.allocateConferenceFocus(
  4458. APP.UI.getRoomName(),
  4459. function () { console.info("AUTH DONE"); }
  4460. );
  4461. }, url);
  4462. if (!authenticationWindow) {
  4463. messageHandler.openMessageDialog(
  4464. null, "Your browser is blocking popup windows from this site." +
  4465. " Please enable popups in your browser security settings" +
  4466. " and try again.");
  4467. }
  4468. });
  4469. }
  4470. };
  4471. /**
  4472. * Updates the room invite url.
  4473. */
  4474. my.updateRoomUrl = function (newRoomUrl) {
  4475. roomUrl = newRoomUrl;
  4476. // If the invite dialog has been already opened we update the information.
  4477. var inviteLink = document.getElementById('inviteLinkRef');
  4478. if (inviteLink) {
  4479. inviteLink.value = roomUrl;
  4480. inviteLink.select();
  4481. document.getElementById('jqi_state0_buttonInvite').disabled = false;
  4482. }
  4483. };
  4484. /**
  4485. * Disables and enables some of the buttons.
  4486. */
  4487. my.setupButtonsFromConfig = function () {
  4488. if (config.disablePrezi)
  4489. {
  4490. $("#prezi_button").css({display: "none"});
  4491. }
  4492. };
  4493. /**
  4494. * Opens the lock room dialog.
  4495. */
  4496. my.openLockDialog = function () {
  4497. // Only the focus is able to set a shared key.
  4498. if (!APP.xmpp.isModerator()) {
  4499. if (sharedKey) {
  4500. messageHandler.openMessageDialog(null,
  4501. "This conversation is currently protected by" +
  4502. " a password. Only the owner of the conference" +
  4503. " could set a password.",
  4504. false,
  4505. "Password");
  4506. } else {
  4507. messageHandler.openMessageDialog(null,
  4508. "This conversation isn't currently protected by" +
  4509. " a password. Only the owner of the conference" +
  4510. " could set a password.",
  4511. false,
  4512. "Password");
  4513. }
  4514. } else {
  4515. if (sharedKey) {
  4516. messageHandler.openTwoButtonDialog(null,
  4517. "Are you sure you would like to remove your password?",
  4518. false,
  4519. "Remove",
  4520. function (e, v) {
  4521. if (v) {
  4522. Toolbar.setSharedKey('');
  4523. lockRoom(false);
  4524. }
  4525. });
  4526. } else {
  4527. messageHandler.openTwoButtonDialog(null,
  4528. '<h2>Set a password to lock your room</h2>' +
  4529. '<input id="lockKey" type="text"' +
  4530. 'placeholder="your password" autofocus>',
  4531. false,
  4532. "Save",
  4533. function (e, v) {
  4534. if (v) {
  4535. var lockKey = document.getElementById('lockKey');
  4536. if (lockKey.value) {
  4537. Toolbar.setSharedKey(UIUtil.escapeHtml(lockKey.value));
  4538. lockRoom(true);
  4539. }
  4540. }
  4541. },
  4542. function () {
  4543. document.getElementById('lockKey').focus();
  4544. }
  4545. );
  4546. }
  4547. }
  4548. };
  4549. /**
  4550. * Opens the invite link dialog.
  4551. */
  4552. my.openLinkDialog = function () {
  4553. var inviteLink;
  4554. if (roomUrl === null) {
  4555. inviteLink = "Your conference is currently being created...";
  4556. } else {
  4557. inviteLink = encodeURI(roomUrl);
  4558. }
  4559. messageHandler.openTwoButtonDialog(
  4560. "Share this link with everyone you want to invite",
  4561. '<input id="inviteLinkRef" type="text" value="' +
  4562. inviteLink + '" onclick="this.select();" readonly>',
  4563. false,
  4564. "Invite",
  4565. function (e, v) {
  4566. if (v) {
  4567. if (roomUrl) {
  4568. inviteParticipants();
  4569. }
  4570. }
  4571. },
  4572. function () {
  4573. if (roomUrl) {
  4574. document.getElementById('inviteLinkRef').select();
  4575. } else {
  4576. document.getElementById('jqi_state0_buttonInvite')
  4577. .disabled = true;
  4578. }
  4579. }
  4580. );
  4581. };
  4582. /**
  4583. * Opens the settings dialog.
  4584. */
  4585. my.openSettingsDialog = function () {
  4586. messageHandler.openTwoButtonDialog(
  4587. '<h2>Configure your conference</h2>' +
  4588. '<input type="checkbox" id="initMuted">' +
  4589. 'Participants join muted<br/>' +
  4590. '<input type="checkbox" id="requireNicknames">' +
  4591. 'Require nicknames<br/><br/>' +
  4592. 'Set a password to lock your room:' +
  4593. '<input id="lockKey" type="text" placeholder="your password"' +
  4594. 'autofocus>',
  4595. null,
  4596. false,
  4597. "Save",
  4598. function () {
  4599. document.getElementById('lockKey').focus();
  4600. },
  4601. function (e, v) {
  4602. if (v) {
  4603. if ($('#initMuted').is(":checked")) {
  4604. // it is checked
  4605. }
  4606. if ($('#requireNicknames').is(":checked")) {
  4607. // it is checked
  4608. }
  4609. /*
  4610. var lockKey = document.getElementById('lockKey');
  4611. if (lockKey.value) {
  4612. setSharedKey(lockKey.value);
  4613. lockRoom(true);
  4614. }
  4615. */
  4616. }
  4617. }
  4618. );
  4619. };
  4620. /**
  4621. * Toggles the application in and out of full screen mode
  4622. * (a.k.a. presentation mode in Chrome).
  4623. */
  4624. my.toggleFullScreen = function () {
  4625. var fsElement = document.documentElement;
  4626. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  4627. //Enter Full Screen
  4628. if (fsElement.mozRequestFullScreen) {
  4629. fsElement.mozRequestFullScreen();
  4630. }
  4631. else {
  4632. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  4633. }
  4634. } else {
  4635. //Exit Full Screen
  4636. if (document.mozCancelFullScreen) {
  4637. document.mozCancelFullScreen();
  4638. } else {
  4639. document.webkitCancelFullScreen();
  4640. }
  4641. }
  4642. };
  4643. /**
  4644. * Unlocks the lock button state.
  4645. */
  4646. my.unlockLockButton = function () {
  4647. if ($("#lockIcon").hasClass("icon-security-locked"))
  4648. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  4649. };
  4650. /**
  4651. * Updates the lock button state to locked.
  4652. */
  4653. my.lockLockButton = function () {
  4654. if ($("#lockIcon").hasClass("icon-security"))
  4655. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  4656. };
  4657. /**
  4658. * Shows or hides authentication button
  4659. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  4660. */
  4661. my.showAuthenticateButton = function (show) {
  4662. if (show) {
  4663. $('#authentication').css({display: "inline"});
  4664. }
  4665. else {
  4666. $('#authentication').css({display: "none"});
  4667. }
  4668. };
  4669. // Shows or hides the 'recording' button.
  4670. my.showRecordingButton = function (show) {
  4671. if (!config.enableRecording) {
  4672. return;
  4673. }
  4674. if (show) {
  4675. $('#recording').css({display: "inline"});
  4676. }
  4677. else {
  4678. $('#recording').css({display: "none"});
  4679. }
  4680. };
  4681. // Sets the state of the recording button
  4682. my.setRecordingButtonState = function (isRecording) {
  4683. if (isRecording) {
  4684. $('#recordButton').removeClass("icon-recEnable");
  4685. $('#recordButton').addClass("icon-recEnable active");
  4686. } else {
  4687. $('#recordButton').removeClass("icon-recEnable active");
  4688. $('#recordButton').addClass("icon-recEnable");
  4689. }
  4690. };
  4691. // Shows or hides SIP calls button
  4692. my.showSipCallButton = function (show) {
  4693. if (APP.xmpp.isSipGatewayEnabled() && show) {
  4694. $('#sipCallButton').css({display: "inline-block"});
  4695. } else {
  4696. $('#sipCallButton').css({display: "none"});
  4697. }
  4698. };
  4699. /**
  4700. * Displays user authenticated identity name(login).
  4701. * @param authIdentity identity name to be displayed.
  4702. */
  4703. my.setAuthenticatedIdentity = function (authIdentity) {
  4704. if (authIdentity) {
  4705. $('#toolbar_auth_identity').css({display: "list-item"});
  4706. $('#toolbar_auth_identity').text(authIdentity);
  4707. } else {
  4708. $('#toolbar_auth_identity').css({display: "none"});
  4709. }
  4710. };
  4711. /**
  4712. * Shows/hides login button.
  4713. * @param show <tt>true</tt> to show
  4714. */
  4715. my.showLoginButton = function (show) {
  4716. if (show) {
  4717. $('#toolbar_button_login').css({display: "list-item"});
  4718. } else {
  4719. $('#toolbar_button_login').css({display: "none"});
  4720. }
  4721. };
  4722. /**
  4723. * Shows/hides logout button.
  4724. * @param show <tt>true</tt> to show
  4725. */
  4726. my.showLogoutButton = function (show) {
  4727. if (show) {
  4728. $('#toolbar_button_logout').css({display: "list-item"});
  4729. } else {
  4730. $('#toolbar_button_logout').css({display: "none"});
  4731. }
  4732. };
  4733. /**
  4734. * Sets the state of the button. The button has blue glow if desktop
  4735. * streaming is active.
  4736. * @param active the state of the desktop streaming.
  4737. */
  4738. my.changeDesktopSharingButtonState = function (active) {
  4739. var button = $("#desktopsharing > a");
  4740. if (active)
  4741. {
  4742. button.addClass("glow");
  4743. }
  4744. else
  4745. {
  4746. button.removeClass("glow");
  4747. }
  4748. };
  4749. return my;
  4750. }(Toolbar || {}));
  4751. module.exports = Toolbar;
  4752. },{"../../../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){
  4753. /* global $, interfaceConfig, Moderator, DesktopStreaming.showDesktopSharingButton */
  4754. var toolbarTimeoutObject,
  4755. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  4756. function showDesktopSharingButton() {
  4757. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  4758. $('#desktopsharing').css({display: "inline"});
  4759. } else {
  4760. $('#desktopsharing').css({display: "none"});
  4761. }
  4762. }
  4763. /**
  4764. * Hides the toolbar.
  4765. */
  4766. function hideToolbar() {
  4767. var header = $("#header"),
  4768. bottomToolbar = $("#bottomToolbar");
  4769. var isToolbarHover = false;
  4770. header.find('*').each(function () {
  4771. var id = $(this).attr('id');
  4772. if ($("#" + id + ":hover").length > 0) {
  4773. isToolbarHover = true;
  4774. }
  4775. });
  4776. if ($("#bottomToolbar:hover").length > 0) {
  4777. isToolbarHover = true;
  4778. }
  4779. clearTimeout(toolbarTimeoutObject);
  4780. toolbarTimeoutObject = null;
  4781. if (!isToolbarHover) {
  4782. header.hide("slide", { direction: "up", duration: 300});
  4783. $('#subject').animate({top: "-=40"}, 300);
  4784. if ($("#remoteVideos").hasClass("hidden")) {
  4785. bottomToolbar.hide(
  4786. "slide", {direction: "right", duration: 300});
  4787. }
  4788. }
  4789. else {
  4790. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4791. }
  4792. }
  4793. var ToolbarToggler = {
  4794. /**
  4795. * Shows the main toolbar.
  4796. */
  4797. showToolbar: function () {
  4798. var header = $("#header"),
  4799. bottomToolbar = $("#bottomToolbar");
  4800. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  4801. header.show("slide", { direction: "up", duration: 300});
  4802. $('#subject').animate({top: "+=40"}, 300);
  4803. if (!bottomToolbar.is(":visible")) {
  4804. bottomToolbar.show(
  4805. "slide", {direction: "right", duration: 300});
  4806. }
  4807. if (toolbarTimeoutObject) {
  4808. clearTimeout(toolbarTimeoutObject);
  4809. toolbarTimeoutObject = null;
  4810. }
  4811. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4812. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  4813. }
  4814. if (APP.xmpp.isModerator())
  4815. {
  4816. // TODO: Enable settings functionality.
  4817. // Need to uncomment the settings button in index.html.
  4818. // $('#settingsButton').css({visibility:"visible"});
  4819. }
  4820. // Show/hide desktop sharing button
  4821. showDesktopSharingButton();
  4822. },
  4823. /**
  4824. * Docks/undocks the toolbar.
  4825. *
  4826. * @param isDock indicates what operation to perform
  4827. */
  4828. dockToolbar: function (isDock) {
  4829. if (isDock) {
  4830. // First make sure the toolbar is shown.
  4831. if (!$('#header').is(':visible')) {
  4832. this.showToolbar();
  4833. }
  4834. // Then clear the time out, to dock the toolbar.
  4835. if (toolbarTimeoutObject) {
  4836. clearTimeout(toolbarTimeoutObject);
  4837. toolbarTimeoutObject = null;
  4838. }
  4839. }
  4840. else {
  4841. if (!$('#header').is(':visible')) {
  4842. this.showToolbar();
  4843. }
  4844. else {
  4845. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4846. }
  4847. }
  4848. },
  4849. showDesktopSharingButton: showDesktopSharingButton
  4850. };
  4851. module.exports = ToolbarToggler;
  4852. },{}],27:[function(require,module,exports){
  4853. var JitsiPopover = (function () {
  4854. /**
  4855. * Constructs new JitsiPopover and attaches it to the element
  4856. * @param element jquery selector
  4857. * @param options the options for the popover.
  4858. * @constructor
  4859. */
  4860. function JitsiPopover(element, options)
  4861. {
  4862. this.options = {
  4863. skin: "white",
  4864. content: ""
  4865. };
  4866. if(options)
  4867. {
  4868. if(options.skin)
  4869. this.options.skin = options.skin;
  4870. if(options.content)
  4871. this.options.content = options.content;
  4872. }
  4873. this.elementIsHovered = false;
  4874. this.popoverIsHovered = false;
  4875. this.popoverShown = false;
  4876. element.data("jitsi_popover", this);
  4877. this.element = element;
  4878. this.template = ' <div class="jitsipopover ' + this.options.skin +
  4879. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  4880. '<div class="jitsiPopupmenuPadding"></div></div>';
  4881. var self = this;
  4882. this.element.on("mouseenter", function () {
  4883. self.elementIsHovered = true;
  4884. self.show();
  4885. }).on("mouseleave", function () {
  4886. self.elementIsHovered = false;
  4887. setTimeout(function () {
  4888. self.hide();
  4889. }, 10);
  4890. });
  4891. }
  4892. /**
  4893. * Shows the popover
  4894. */
  4895. JitsiPopover.prototype.show = function () {
  4896. this.createPopover();
  4897. this.popoverShown = true;
  4898. };
  4899. /**
  4900. * Hides the popover
  4901. */
  4902. JitsiPopover.prototype.hide = function () {
  4903. if(!this.elementIsHovered && !this.popoverIsHovered && this.popoverShown)
  4904. {
  4905. this.forceHide();
  4906. }
  4907. };
  4908. /**
  4909. * Hides the popover
  4910. */
  4911. JitsiPopover.prototype.forceHide = function () {
  4912. $(".jitsipopover").remove();
  4913. this.popoverShown = false;
  4914. };
  4915. /**
  4916. * Creates the popover html
  4917. */
  4918. JitsiPopover.prototype.createPopover = function () {
  4919. $("body").append(this.template);
  4920. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  4921. var self = this;
  4922. $(".jitsipopover").on("mouseenter", function () {
  4923. self.popoverIsHovered = true;
  4924. }).on("mouseleave", function () {
  4925. self.popoverIsHovered = false;
  4926. self.hide();
  4927. });
  4928. this.refreshPosition();
  4929. };
  4930. /**
  4931. * Refreshes the position of the popover
  4932. */
  4933. JitsiPopover.prototype.refreshPosition = function () {
  4934. $(".jitsipopover").position({
  4935. my: "bottom",
  4936. at: "top",
  4937. collision: "fit",
  4938. of: this.element,
  4939. using: function (position, elements) {
  4940. var calcLeft = elements.target.left - elements.element.left + elements.target.width/2;
  4941. $(".jitsipopover").css({top: position.top, left: position.left, display: "table"});
  4942. $(".jitsipopover > .arrow").css({left: calcLeft});
  4943. $(".jitsipopover > .jitsiPopupmenuPadding").css({left: calcLeft - 50});
  4944. }
  4945. });
  4946. };
  4947. /**
  4948. * Updates the content of popover.
  4949. * @param content new content
  4950. */
  4951. JitsiPopover.prototype.updateContent = function (content) {
  4952. this.options.content = content;
  4953. if(!this.popoverShown)
  4954. return;
  4955. $(".jitsipopover").remove();
  4956. this.createPopover();
  4957. };
  4958. return JitsiPopover;
  4959. })();
  4960. module.exports = JitsiPopover;
  4961. },{}],28:[function(require,module,exports){
  4962. /* global $, jQuery */
  4963. var messageHandler = (function(my) {
  4964. /**
  4965. * Shows a message to the user.
  4966. *
  4967. * @param titleString the title of the message
  4968. * @param messageString the text of the message
  4969. */
  4970. my.openMessageDialog = function(titleString, messageString) {
  4971. $.prompt(messageString,
  4972. {
  4973. title: titleString,
  4974. persistent: false
  4975. }
  4976. );
  4977. };
  4978. /**
  4979. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  4980. *
  4981. * @param titleString the title of the message
  4982. * @param msgString the text of the message
  4983. * @param persistent boolean value which determines whether the message is persistent or not
  4984. * @param leftButton the fist button's text
  4985. * @param submitFunction function to be called on submit
  4986. * @param loadedFunction function to be called after the prompt is fully loaded
  4987. * @param closeFunction function to be called after the prompt is closed
  4988. */
  4989. my.openTwoButtonDialog = function(titleString, msgString, persistent, leftButton,
  4990. submitFunction, loadedFunction, closeFunction) {
  4991. var buttons = {};
  4992. buttons[leftButton] = true;
  4993. buttons.Cancel = false;
  4994. $.prompt(msgString, {
  4995. title: titleString,
  4996. persistent: false,
  4997. buttons: buttons,
  4998. defaultButton: 1,
  4999. loaded: loadedFunction,
  5000. submit: submitFunction,
  5001. close: closeFunction
  5002. });
  5003. };
  5004. /**
  5005. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  5006. *
  5007. * @param titleString the title of the message
  5008. * @param msgString the text of the message
  5009. * @param persistent boolean value which determines whether the message is persistent or not
  5010. * @param buttons object with the buttons. The keys must be the name of the button and value is the value
  5011. * that will be passed to submitFunction
  5012. * @param submitFunction function to be called on submit
  5013. * @param loadedFunction function to be called after the prompt is fully loaded
  5014. */
  5015. my.openDialog = function (titleString, msgString, persistent, buttons,
  5016. submitFunction, loadedFunction) {
  5017. var args = {
  5018. title: titleString,
  5019. persistent: persistent,
  5020. buttons: buttons,
  5021. defaultButton: 1,
  5022. loaded: loadedFunction,
  5023. submit: submitFunction
  5024. };
  5025. if (persistent) {
  5026. args.closeText = '';
  5027. }
  5028. return $.prompt(msgString, args);
  5029. };
  5030. /**
  5031. * Closes currently opened dialog.
  5032. */
  5033. my.closeDialog = function () {
  5034. $.prompt.close();
  5035. };
  5036. /**
  5037. * Shows a dialog with different states to the user.
  5038. *
  5039. * @param statesObject object containing all the states of the dialog
  5040. * @param loadedFunction function to be called after the prompt is fully loaded
  5041. * @param stateChangedFunction function to be called when the state of the dialog is changed
  5042. */
  5043. my.openDialogWithStates = function(statesObject, loadedFunction, stateChangedFunction) {
  5044. var myPrompt = $.prompt(statesObject);
  5045. myPrompt.on('impromptu:loaded', loadedFunction);
  5046. myPrompt.on('impromptu:statechanged', stateChangedFunction);
  5047. };
  5048. /**
  5049. * Opens new popup window for given <tt>url</tt> centered over current
  5050. * window.
  5051. *
  5052. * @param url the URL to be displayed in the popup window
  5053. * @param w the width of the popup window
  5054. * @param h the height of the popup window
  5055. * @param onPopupClosed optional callback function called when popup window
  5056. * has been closed.
  5057. *
  5058. * @returns popup window object if opened successfully or undefined
  5059. * in case we failed to open it(popup blocked)
  5060. */
  5061. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  5062. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  5063. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  5064. var popup = window.open(
  5065. url, '_blank',
  5066. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  5067. if (popup && onPopupClosed) {
  5068. var pollTimer = window.setInterval(function () {
  5069. if (popup.closed !== false) {
  5070. window.clearInterval(pollTimer);
  5071. onPopupClosed();
  5072. }
  5073. }, 200);
  5074. }
  5075. return popup;
  5076. };
  5077. /**
  5078. * Shows a dialog prompting the user to send an error report.
  5079. *
  5080. * @param titleString the title of the message
  5081. * @param msgString the text of the message
  5082. * @param error the error that is being reported
  5083. */
  5084. my.openReportDialog = function(titleString, msgString, error) {
  5085. my.openMessageDialog(titleString, msgString);
  5086. console.log(error);
  5087. //FIXME send the error to the server
  5088. };
  5089. /**
  5090. * Shows an error dialog to the user.
  5091. * @param title the title of the message
  5092. * @param message the text of the messafe
  5093. */
  5094. my.showError = function(title, message) {
  5095. if(!(title || message)) {
  5096. title = title || "Oops!";
  5097. message = message || "There was some kind of error";
  5098. }
  5099. messageHandler.openMessageDialog(title, message);
  5100. };
  5101. my.notify = function(displayName, displayNameKey, displayNameDefault,
  5102. cls, messageKey, messageDefault, messageArguments) {
  5103. var displayNameSpan = '<span class="nickname" ';
  5104. if(displayName)
  5105. {
  5106. displayNameSpan += ">" + displayName;
  5107. }
  5108. else
  5109. {
  5110. displayNameSpan += "data-i18n='" + displayNameKey +
  5111. "'>" + APP.translation.translateString(displayNameKey, null,
  5112. {defaultValue: displayNameDefault});
  5113. }
  5114. displayNameSpan += "</span>";
  5115. var lMessageArguments = messageArguments;
  5116. if(!messageArguments)
  5117. lMessageArguments = {};
  5118. lMessageArguments.defaultValue = messageDefault;
  5119. toastr.info(
  5120. displayNameSpan + '<br>' +
  5121. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  5122. (messageArguments?
  5123. " i18n-options='" + JSON.stringify(messageArguments) + "'"
  5124. : "") + ">" +
  5125. APP.translation.translateString(messageKey, null,
  5126. lMessageArguments) +
  5127. '</span>');
  5128. };
  5129. return my;
  5130. }(messageHandler || {}));
  5131. module.exports = messageHandler;
  5132. },{}],29:[function(require,module,exports){
  5133. var UIEvents = require("../../../service/UI/UIEvents");
  5134. var nickname = null;
  5135. var eventEmitter = null;
  5136. var NickanameHandler = {
  5137. init: function (emitter) {
  5138. eventEmitter = emitter;
  5139. var storedDisplayName = window.localStorage.displayname;
  5140. if (storedDisplayName) {
  5141. nickname = storedDisplayName;
  5142. }
  5143. },
  5144. setNickname: function (newNickname) {
  5145. if (!newNickname || nickname === newNickname)
  5146. return;
  5147. nickname = newNickname;
  5148. window.localStorage.displayname = nickname;
  5149. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  5150. },
  5151. getNickname: function () {
  5152. return nickname;
  5153. },
  5154. addListener: function (type, listener) {
  5155. eventEmitter.on(type, listener);
  5156. }
  5157. };
  5158. module.exports = NickanameHandler;
  5159. },{"../../../service/UI/UIEvents":84}],30:[function(require,module,exports){
  5160. /**
  5161. * Created by hristo on 12/22/14.
  5162. */
  5163. module.exports = {
  5164. /**
  5165. * Returns the available video width.
  5166. */
  5167. getAvailableVideoWidth: function () {
  5168. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5169. var rightPanelWidth
  5170. = PanelToggler.isVisible() ? PanelToggler.getPanelSize()[0] : 0;
  5171. return window.innerWidth - rightPanelWidth;
  5172. },
  5173. /**
  5174. * Changes the style class of the element given by id.
  5175. */
  5176. buttonClick: function(id, classname) {
  5177. $(id).toggleClass(classname); // add the class to the clicked element
  5178. },
  5179. /**
  5180. * Returns the text width for the given element.
  5181. *
  5182. * @param el the element
  5183. */
  5184. getTextWidth: function (el) {
  5185. return (el.clientWidth + 1);
  5186. },
  5187. /**
  5188. * Returns the text height for the given element.
  5189. *
  5190. * @param el the element
  5191. */
  5192. getTextHeight: function (el) {
  5193. return (el.clientHeight + 1);
  5194. },
  5195. /**
  5196. * Plays the sound given by id.
  5197. *
  5198. * @param id the identifier of the audio element.
  5199. */
  5200. playSoundNotification: function (id) {
  5201. document.getElementById(id).play();
  5202. },
  5203. /**
  5204. * Escapes the given text.
  5205. */
  5206. escapeHtml: function (unsafeText) {
  5207. return $('<div/>').text(unsafeText).html();
  5208. },
  5209. imageToGrayScale: function (canvas) {
  5210. var context = canvas.getContext('2d');
  5211. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  5212. var pixels = imgData.data;
  5213. for (var i = 0, n = pixels.length; i < n; i += 4) {
  5214. var grayscale
  5215. = pixels[i] * .3 + pixels[i+1] * .59 + pixels[i+2] * .11;
  5216. pixels[i ] = grayscale; // red
  5217. pixels[i+1] = grayscale; // green
  5218. pixels[i+2] = grayscale; // blue
  5219. // pixels[i+3] is alpha
  5220. }
  5221. // redraw the image in black & white
  5222. context.putImageData(imgData, 0, 0);
  5223. },
  5224. setTooltip: function (element, key, position) {
  5225. element.setAttribute("data-i18n", "[data-content]" + key);
  5226. element.setAttribute("data-toggle", "popover");
  5227. element.setAttribute("data-placement", position);
  5228. element.setAttribute("data-html", true);
  5229. element.setAttribute("data-container", "body");
  5230. }
  5231. };
  5232. },{"../side_pannels/SidePanelToggler":17}],31:[function(require,module,exports){
  5233. var JitsiPopover = require("../util/JitsiPopover");
  5234. /**
  5235. * Constructs new connection indicator.
  5236. * @param videoContainer the video container associated with the indicator.
  5237. * @constructor
  5238. */
  5239. function ConnectionIndicator(videoContainer, jid, VideoLayout)
  5240. {
  5241. this.videoContainer = videoContainer;
  5242. this.bandwidth = null;
  5243. this.packetLoss = null;
  5244. this.bitrate = null;
  5245. this.showMoreValue = false;
  5246. this.resolution = null;
  5247. this.transport = [];
  5248. this.popover = null;
  5249. this.jid = jid;
  5250. this.create();
  5251. this.videoLayout = VideoLayout;
  5252. }
  5253. /**
  5254. * Values for the connection quality
  5255. * @type {{98: string,
  5256. * 81: string,
  5257. * 64: string,
  5258. * 47: string,
  5259. * 30: string,
  5260. * 0: string}}
  5261. */
  5262. ConnectionIndicator.connectionQualityValues = {
  5263. 98: "18px", //full
  5264. 81: "15px",//4 bars
  5265. 64: "11px",//3 bars
  5266. 47: "7px",//2 bars
  5267. 30: "3px",//1 bar
  5268. 0: "0px"//empty
  5269. };
  5270. ConnectionIndicator.getIP = function(value)
  5271. {
  5272. return value.substring(0, value.lastIndexOf(":"));
  5273. };
  5274. ConnectionIndicator.getPort = function(value)
  5275. {
  5276. return value.substring(value.lastIndexOf(":") + 1, value.length);
  5277. };
  5278. ConnectionIndicator.getStringFromArray = function (array) {
  5279. var res = "";
  5280. for(var i = 0; i < array.length; i++)
  5281. {
  5282. res += (i === 0? "" : ", ") + array[i];
  5283. }
  5284. return res;
  5285. };
  5286. /**
  5287. * Generates the html content.
  5288. * @returns {string} the html content.
  5289. */
  5290. ConnectionIndicator.prototype.generateText = function () {
  5291. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  5292. var translate = APP.translation.translateString;
  5293. if(this.bitrate === null)
  5294. {
  5295. downloadBitrate = "N/A";
  5296. uploadBitrate = "N/A";
  5297. }
  5298. else
  5299. {
  5300. downloadBitrate =
  5301. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  5302. uploadBitrate =
  5303. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  5304. }
  5305. if(this.packetLoss === null)
  5306. {
  5307. packetLoss = "N/A";
  5308. }
  5309. else
  5310. {
  5311. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  5312. (this.packetLoss.download !== null? this.packetLoss.download : "N/A") +
  5313. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  5314. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") + "%";
  5315. }
  5316. var resolutionValue = null;
  5317. if(this.resolution && this.jid != null)
  5318. {
  5319. var keys = Object.keys(this.resolution);
  5320. if(keys.length == 1)
  5321. {
  5322. for(var ssrc in this.resolution)
  5323. {
  5324. resolutionValue = this.resolution[ssrc];
  5325. }
  5326. }
  5327. else if(keys.length > 1)
  5328. {
  5329. var displayedSsrc = APP.simulcast.getReceivingSSRC(this.jid);
  5330. resolutionValue = this.resolution[displayedSsrc];
  5331. }
  5332. }
  5333. if(this.jid === null)
  5334. {
  5335. resolution = "";
  5336. if(this.resolution === null || !Object.keys(this.resolution) ||
  5337. Object.keys(this.resolution).length === 0)
  5338. {
  5339. resolution = "N/A";
  5340. }
  5341. else
  5342. for(i in this.resolution)
  5343. {
  5344. resolutionValue = this.resolution[i];
  5345. if(resolutionValue)
  5346. {
  5347. if(resolutionValue.height &&
  5348. resolutionValue.width)
  5349. {
  5350. resolution += (resolution === ""? "" : ", ") +
  5351. resolutionValue.width + "x" +
  5352. resolutionValue.height;
  5353. }
  5354. }
  5355. }
  5356. }
  5357. else if(!resolutionValue ||
  5358. !resolutionValue.height ||
  5359. !resolutionValue.width)
  5360. {
  5361. resolution = "N/A";
  5362. }
  5363. else
  5364. {
  5365. resolution = resolutionValue.width + "x" + resolutionValue.height;
  5366. }
  5367. var result = "<table style='width:100%'>" +
  5368. "<tr>" +
  5369. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  5370. translate("connectionindicator.bitrate") + "</span></td>" +
  5371. "<td><span class='jitsipopover_green'>&darr;</span>" +
  5372. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  5373. uploadBitrate + "</td>" +
  5374. "</tr><tr>" +
  5375. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  5376. translate("connectionindicator.packetloss") + "</span></td>" +
  5377. "<td>" + packetLoss + "</td>" +
  5378. "</tr><tr>" +
  5379. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  5380. translate("connectionindicator.resolution") + "</span></td>" +
  5381. "<td>" + resolution + "</td></tr></table>";
  5382. if(this.videoContainer.id == "localVideoContainer") {
  5383. result += "<div class=\"jitsipopover_showmore\" " +
  5384. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  5385. this.videoContainer.id + "')\" data-i18n='connectionindicator." +
  5386. (this.showMoreValue ? "less" : "more") + "'>" +
  5387. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  5388. "</div><br />";
  5389. }
  5390. if(this.showMoreValue)
  5391. {
  5392. var downloadBandwidth, uploadBandwidth, transport;
  5393. if(this.bandwidth === null)
  5394. {
  5395. downloadBandwidth = "N/A";
  5396. uploadBandwidth = "N/A";
  5397. }
  5398. else
  5399. {
  5400. downloadBandwidth = this.bandwidth.download?
  5401. this.bandwidth.download + " Kbps" :
  5402. "N/A";
  5403. uploadBandwidth = this.bandwidth.upload?
  5404. this.bandwidth.upload + " Kbps" :
  5405. "N/A";
  5406. }
  5407. if(!this.transport || this.transport.length === 0)
  5408. {
  5409. transport = "<tr>" +
  5410. "<td><span class='jitsipopover_blue' " +
  5411. "data-i18n='connectionindicator.address'>" +
  5412. translate("connectionindicator.address") + "</span></td>" +
  5413. "<td> N/A</td></tr>";
  5414. }
  5415. else
  5416. {
  5417. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  5418. for(i = 0; i < this.transport.length; i++)
  5419. {
  5420. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  5421. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  5422. var localIP =
  5423. ConnectionIndicator.getIP(this.transport[i].localip);
  5424. var localPort =
  5425. ConnectionIndicator.getPort(this.transport[i].localip);
  5426. if(data.remoteIP.indexOf(ip) == -1)
  5427. {
  5428. data.remoteIP.push(ip);
  5429. }
  5430. if(data.remotePort.indexOf(port) == -1)
  5431. {
  5432. data.remotePort.push(port);
  5433. }
  5434. if(data.localIP.indexOf(localIP) == -1)
  5435. {
  5436. data.localIP.push(localIP);
  5437. }
  5438. if(data.localPort.indexOf(localPort) == -1)
  5439. {
  5440. data.localPort.push(localPort);
  5441. }
  5442. }
  5443. var local_address_key = "connectionindicator." +
  5444. (data.localIP.length > 1? "localaddresses" : "localaddress");
  5445. var remote_address_key = "connectionindicator." +
  5446. (data.remoteIP.length > 1? "remoteaddresses" : "remoteaddress");
  5447. var localTransport =
  5448. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5449. local_address_key +"'>" +
  5450. translate(local_address_key) + "</span></td><td> " +
  5451. ConnectionIndicator.getStringFromArray(data.localIP) +
  5452. "</td></tr>";
  5453. transport =
  5454. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5455. remote_address_key + "'>" +
  5456. translate(remote_address_key) + "</span></td><td> " +
  5457. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  5458. "</td></tr>";
  5459. var key_remote = "connectionindicator.",
  5460. key_local = "connectionindicator.";
  5461. if(this.transport.length > 1)
  5462. {
  5463. key_remote += "remoteports";
  5464. key_local += "localports";
  5465. }
  5466. else
  5467. {
  5468. key_remote += "remoteport";
  5469. key_local += "localport";
  5470. }
  5471. transport += "<tr>" +
  5472. "<td>" +
  5473. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  5474. "'>" +
  5475. translate(key_remote) + "</span></td><td>";
  5476. localTransport += "<tr>" +
  5477. "<td>" +
  5478. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  5479. "'>" +
  5480. translate(key_local) + "</span></td><td>";
  5481. transport +=
  5482. ConnectionIndicator.getStringFromArray(data.remotePort);
  5483. localTransport +=
  5484. ConnectionIndicator.getStringFromArray(data.localPort);
  5485. transport += "</td></tr>";
  5486. transport += localTransport + "</td></tr>";
  5487. transport +="<tr>" +
  5488. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  5489. translate("connectionindicator.transport") + "</span></td>" +
  5490. "<td>" + this.transport[0].type + "</td></tr>";
  5491. }
  5492. result += "<table style='width:100%'>" +
  5493. "<tr>" +
  5494. "<td>" +
  5495. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  5496. translate("connectionindicator.bandwidth") + "</span>" +
  5497. "</td><td>" +
  5498. "<span class='jitsipopover_green'>&darr;</span>" +
  5499. downloadBandwidth +
  5500. " <span class='jitsipopover_orange'>&uarr;</span>" +
  5501. uploadBandwidth + "</td></tr>";
  5502. result += transport + "</table>";
  5503. }
  5504. return result;
  5505. };
  5506. /**
  5507. * Shows or hide the additional information.
  5508. */
  5509. ConnectionIndicator.prototype.showMore = function () {
  5510. this.showMoreValue = !this.showMoreValue;
  5511. this.updatePopoverData();
  5512. };
  5513. function createIcon(classes)
  5514. {
  5515. var icon = document.createElement("span");
  5516. for(var i in classes)
  5517. {
  5518. icon.classList.add(classes[i]);
  5519. }
  5520. icon.appendChild(
  5521. document.createElement("i")).classList.add("icon-connection");
  5522. return icon;
  5523. }
  5524. /**
  5525. * Creates the indicator
  5526. */
  5527. ConnectionIndicator.prototype.create = function () {
  5528. this.connectionIndicatorContainer = document.createElement("div");
  5529. this.connectionIndicatorContainer.className = "connectionindicator";
  5530. this.connectionIndicatorContainer.style.display = "none";
  5531. this.videoContainer.appendChild(this.connectionIndicatorContainer);
  5532. this.popover = new JitsiPopover(
  5533. $("#" + this.videoContainer.id + " > .connectionindicator"),
  5534. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  5535. APP.translation.translateString("connectionindicator.na") + "</div>",
  5536. skin: "black"});
  5537. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  5538. createIcon(["connection", "connection_empty"]));
  5539. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  5540. createIcon(["connection", "connection_full"]));
  5541. };
  5542. /**
  5543. * Removes the indicator
  5544. */
  5545. ConnectionIndicator.prototype.remove = function()
  5546. {
  5547. this.connectionIndicatorContainer.remove();
  5548. this.popover.forceHide();
  5549. };
  5550. /**
  5551. * Updates the data of the indicator
  5552. * @param percent the percent of connection quality
  5553. * @param object the statistics data.
  5554. */
  5555. ConnectionIndicator.prototype.updateConnectionQuality =
  5556. function (percent, object) {
  5557. if(percent === null)
  5558. {
  5559. this.connectionIndicatorContainer.style.display = "none";
  5560. this.popover.forceHide();
  5561. return;
  5562. }
  5563. else
  5564. {
  5565. if(this.connectionIndicatorContainer.style.display == "none") {
  5566. this.connectionIndicatorContainer.style.display = "block";
  5567. this.videoLayout.updateMutePosition(this.videoContainer.id);
  5568. }
  5569. }
  5570. this.bandwidth = object.bandwidth;
  5571. this.bitrate = object.bitrate;
  5572. this.packetLoss = object.packetLoss;
  5573. this.transport = object.transport;
  5574. if(object.resolution)
  5575. {
  5576. this.resolution = object.resolution;
  5577. }
  5578. for(var quality in ConnectionIndicator.connectionQualityValues)
  5579. {
  5580. if(percent >= quality)
  5581. {
  5582. this.fullIcon.style.width =
  5583. ConnectionIndicator.connectionQualityValues[quality];
  5584. }
  5585. }
  5586. this.updatePopoverData();
  5587. };
  5588. /**
  5589. * Updates the resolution
  5590. * @param resolution the new resolution
  5591. */
  5592. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  5593. this.resolution = resolution;
  5594. this.updatePopoverData();
  5595. };
  5596. /**
  5597. * Updates the content of the popover
  5598. */
  5599. ConnectionIndicator.prototype.updatePopoverData = function () {
  5600. this.popover.updateContent(
  5601. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  5602. APP.translation.translateElement($(".connection_info"));
  5603. };
  5604. /**
  5605. * Hides the popover
  5606. */
  5607. ConnectionIndicator.prototype.hide = function () {
  5608. this.popover.forceHide();
  5609. };
  5610. /**
  5611. * Hides the indicator
  5612. */
  5613. ConnectionIndicator.prototype.hideIndicator = function () {
  5614. this.connectionIndicatorContainer.style.display = "none";
  5615. if(this.popover)
  5616. this.popover.forceHide();
  5617. };
  5618. module.exports = ConnectionIndicator;
  5619. },{"../util/JitsiPopover":27}],32:[function(require,module,exports){
  5620. var AudioLevels = require("../audio_levels/AudioLevels");
  5621. var Avatar = require("../avatar/Avatar");
  5622. var Chat = require("../side_pannels/chat/Chat");
  5623. var ContactList = require("../side_pannels/contactlist/ContactList");
  5624. var UIUtil = require("../util/UIUtil");
  5625. var ConnectionIndicator = require("./ConnectionIndicator");
  5626. var NicknameHandler = require("../util/NicknameHandler");
  5627. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  5628. var UIEvents = require("../../../service/UI/UIEvents");
  5629. var currentDominantSpeaker = null;
  5630. var lastNCount = config.channelLastN;
  5631. var localLastNCount = config.channelLastN;
  5632. var localLastNSet = [];
  5633. var lastNEndpointsCache = [];
  5634. var lastNPickupJid = null;
  5635. var largeVideoState = {
  5636. updateInProgress: false,
  5637. newSrc: ''
  5638. };
  5639. var eventEmitter = null;
  5640. /**
  5641. * Currently focused video "src"(displayed in large video).
  5642. * @type {String}
  5643. */
  5644. var focusedVideoInfo = null;
  5645. /**
  5646. * Indicates if we have muted our audio before the conference has started.
  5647. * @type {boolean}
  5648. */
  5649. var preMuted = false;
  5650. var mutedAudios = {};
  5651. var flipXLocalVideo = true;
  5652. var currentVideoWidth = null;
  5653. var currentVideoHeight = null;
  5654. var localVideoSrc = null;
  5655. function videoactive( videoelem) {
  5656. if (videoelem.attr('id').indexOf('mixedmslabel') === -1) {
  5657. // ignore mixedmslabela0 and v0
  5658. videoelem.show();
  5659. VideoLayout.resizeThumbnails();
  5660. var videoParent = videoelem.parent();
  5661. var parentResourceJid = null;
  5662. if (videoParent)
  5663. parentResourceJid
  5664. = VideoLayout.getPeerContainerResourceJid(videoParent[0]);
  5665. // Update the large video to the last added video only if there's no
  5666. // current dominant, focused speaker or prezi playing or update it to
  5667. // the current dominant speaker.
  5668. if ((!focusedVideoInfo &&
  5669. !VideoLayout.getDominantSpeakerResourceJid() &&
  5670. !require("../prezi/Prezi").isPresentationVisible()) ||
  5671. (parentResourceJid &&
  5672. VideoLayout.getDominantSpeakerResourceJid() === parentResourceJid)) {
  5673. VideoLayout.updateLargeVideo(
  5674. APP.RTC.getVideoSrc(videoelem[0]),
  5675. 1,
  5676. parentResourceJid);
  5677. }
  5678. VideoLayout.showModeratorIndicator();
  5679. }
  5680. }
  5681. function waitForRemoteVideo(selector, ssrc, stream, jid) {
  5682. // XXX(gp) so, every call to this function is *always* preceded by a call
  5683. // to the RTC.attachMediaStream() function but that call is *not* followed
  5684. // by an update to the videoSrcToSsrc map!
  5685. //
  5686. // The above way of doing things results in video SRCs that don't correspond
  5687. // to any SSRC for a short period of time (to be more precise, for as long
  5688. // the waitForRemoteVideo takes to complete). This causes problems (see
  5689. // bellow).
  5690. //
  5691. // I'm wondering why we need to do that; i.e. why call RTC.attachMediaStream()
  5692. // a second time in here and only then update the videoSrcToSsrc map? Why
  5693. // not simply update the videoSrcToSsrc map when the RTC.attachMediaStream()
  5694. // is called the first time? I actually do that in the lastN changed event
  5695. // handler because the "orphan" video SRC is causing troubles there. The
  5696. // purpose of this method would then be to fire the "videoactive.jingle".
  5697. //
  5698. // Food for though I guess :-)
  5699. if (selector.removed || !selector.parent().is(":visible")) {
  5700. console.warn("Media removed before had started", selector);
  5701. return;
  5702. }
  5703. if (stream.id === 'mixedmslabel') return;
  5704. if (selector[0].currentTime > 0) {
  5705. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  5706. APP.RTC.attachMediaStream(selector, videoStream); // FIXME: why do i have to do this for FF?
  5707. videoactive(selector);
  5708. } else {
  5709. setTimeout(function () {
  5710. waitForRemoteVideo(selector, ssrc, stream, jid);
  5711. }, 250);
  5712. }
  5713. }
  5714. /**
  5715. * Returns an array of the video horizontal and vertical indents,
  5716. * so that if fits its parent.
  5717. *
  5718. * @return an array with 2 elements, the horizontal indent and the vertical
  5719. * indent
  5720. */
  5721. function getCameraVideoPosition(videoWidth,
  5722. videoHeight,
  5723. videoSpaceWidth,
  5724. videoSpaceHeight) {
  5725. // Parent height isn't completely calculated when we position the video in
  5726. // full screen mode and this is why we use the screen height in this case.
  5727. // Need to think it further at some point and implement it properly.
  5728. var isFullScreen = document.fullScreen ||
  5729. document.mozFullScreen ||
  5730. document.webkitIsFullScreen;
  5731. if (isFullScreen)
  5732. videoSpaceHeight = window.innerHeight;
  5733. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  5734. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  5735. return [horizontalIndent, verticalIndent];
  5736. }
  5737. /**
  5738. * Returns an array of the video horizontal and vertical indents.
  5739. * Centers horizontally and top aligns vertically.
  5740. *
  5741. * @return an array with 2 elements, the horizontal indent and the vertical
  5742. * indent
  5743. */
  5744. function getDesktopVideoPosition(videoWidth,
  5745. videoHeight,
  5746. videoSpaceWidth,
  5747. videoSpaceHeight) {
  5748. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  5749. var verticalIndent = 0;// Top aligned
  5750. return [horizontalIndent, verticalIndent];
  5751. }
  5752. /**
  5753. * Returns an array of the video dimensions, so that it covers the screen.
  5754. * It leaves no empty areas, but some parts of the video might not be visible.
  5755. *
  5756. * @return an array with 2 elements, the video width and the video height
  5757. */
  5758. function getCameraVideoSize(videoWidth,
  5759. videoHeight,
  5760. videoSpaceWidth,
  5761. videoSpaceHeight) {
  5762. if (!videoWidth)
  5763. videoWidth = currentVideoWidth;
  5764. if (!videoHeight)
  5765. videoHeight = currentVideoHeight;
  5766. var aspectRatio = videoWidth / videoHeight;
  5767. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  5768. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  5769. if (availableWidth / aspectRatio < videoSpaceHeight) {
  5770. availableHeight = videoSpaceHeight;
  5771. availableWidth = availableHeight * aspectRatio;
  5772. }
  5773. if (availableHeight * aspectRatio < videoSpaceWidth) {
  5774. availableWidth = videoSpaceWidth;
  5775. availableHeight = availableWidth / aspectRatio;
  5776. }
  5777. return [availableWidth, availableHeight];
  5778. }
  5779. /**
  5780. * Sets the display name for the given video span id.
  5781. */
  5782. function setDisplayName(videoSpanId, displayName) {
  5783. var nameSpan = $('#' + videoSpanId + '>span.displayname');
  5784. var defaultLocalDisplayName = interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME;
  5785. // If we already have a display name for this video.
  5786. if (nameSpan.length > 0) {
  5787. var nameSpanElement = nameSpan.get(0);
  5788. if (nameSpanElement.id === 'localDisplayName' &&
  5789. $('#localDisplayName').text() !== displayName) {
  5790. if (displayName && displayName.length > 0)
  5791. $('#localDisplayName').html(displayName + ' (me)');
  5792. else
  5793. $('#localDisplayName').text(defaultLocalDisplayName);
  5794. } else {
  5795. if (displayName && displayName.length > 0)
  5796. $('#' + videoSpanId + '_name').html(displayName);
  5797. else
  5798. $('#' + videoSpanId + '_name').text(interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  5799. }
  5800. } else {
  5801. var editButton = null;
  5802. nameSpan = document.createElement('span');
  5803. nameSpan.className = 'displayname';
  5804. $('#' + videoSpanId)[0].appendChild(nameSpan);
  5805. if (videoSpanId === 'localVideoContainer') {
  5806. editButton = createEditDisplayNameButton();
  5807. nameSpan.innerText = defaultLocalDisplayName;
  5808. }
  5809. else {
  5810. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  5811. }
  5812. if (displayName && displayName.length > 0) {
  5813. nameSpan.innerText = displayName;
  5814. }
  5815. if (!editButton) {
  5816. nameSpan.id = videoSpanId + '_name';
  5817. } else {
  5818. nameSpan.id = 'localDisplayName';
  5819. $('#' + videoSpanId)[0].appendChild(editButton);
  5820. //translates popover of edit button
  5821. APP.translation.translateElement($("a.displayname"));
  5822. var editableText = document.createElement('input');
  5823. editableText.className = 'displayname';
  5824. editableText.type = 'text';
  5825. editableText.id = 'editDisplayName';
  5826. if (displayName && displayName.length) {
  5827. editableText.value
  5828. = displayName.substring(0, displayName.indexOf(' (me)'));
  5829. }
  5830. editableText.setAttribute('style', 'display:none;');
  5831. editableText.setAttribute('placeholder', 'ex. Jane Pink');
  5832. $('#' + videoSpanId)[0].appendChild(editableText);
  5833. $('#localVideoContainer .displayname')
  5834. .bind("click", function (e) {
  5835. e.preventDefault();
  5836. e.stopPropagation();
  5837. $('#localDisplayName').hide();
  5838. $('#editDisplayName').show();
  5839. $('#editDisplayName').focus();
  5840. $('#editDisplayName').select();
  5841. $('#editDisplayName').one("focusout", function (e) {
  5842. VideoLayout.inputDisplayNameHandler(this.value);
  5843. });
  5844. $('#editDisplayName').on('keydown', function (e) {
  5845. if (e.keyCode === 13) {
  5846. e.preventDefault();
  5847. VideoLayout.inputDisplayNameHandler(this.value);
  5848. }
  5849. });
  5850. });
  5851. }
  5852. }
  5853. }
  5854. /**
  5855. * Gets the selector of video thumbnail container for the user identified by
  5856. * given <tt>userJid</tt>
  5857. * @param resourceJid user's Jid for whom we want to get the video container.
  5858. */
  5859. function getParticipantContainer(resourceJid)
  5860. {
  5861. if (!resourceJid)
  5862. return null;
  5863. if (resourceJid === APP.xmpp.myResource())
  5864. return $("#localVideoContainer");
  5865. else
  5866. return $("#participant_" + resourceJid);
  5867. }
  5868. /**
  5869. * Sets the size and position of the given video element.
  5870. *
  5871. * @param video the video element to position
  5872. * @param width the desired video width
  5873. * @param height the desired video height
  5874. * @param horizontalIndent the left and right indent
  5875. * @param verticalIndent the top and bottom indent
  5876. */
  5877. function positionVideo(video,
  5878. width,
  5879. height,
  5880. horizontalIndent,
  5881. verticalIndent) {
  5882. video.width(width);
  5883. video.height(height);
  5884. video.css({ top: verticalIndent + 'px',
  5885. bottom: verticalIndent + 'px',
  5886. left: horizontalIndent + 'px',
  5887. right: horizontalIndent + 'px'});
  5888. }
  5889. /**
  5890. * Adds the remote video menu element for the given <tt>jid</tt> in the
  5891. * given <tt>parentElement</tt>.
  5892. *
  5893. * @param jid the jid indicating the video for which we're adding a menu.
  5894. * @param parentElement the parent element where this menu will be added
  5895. */
  5896. function addRemoteVideoMenu(jid, parentElement) {
  5897. var spanElement = document.createElement('span');
  5898. spanElement.className = 'remotevideomenu';
  5899. parentElement.appendChild(spanElement);
  5900. var menuElement = document.createElement('i');
  5901. menuElement.className = 'fa fa-angle-down';
  5902. menuElement.title = 'Remote user controls';
  5903. spanElement.appendChild(menuElement);
  5904. // <ul class="popupmenu">
  5905. // <li><a href="#">Mute</a></li>
  5906. // <li><a href="#">Eject</a></li>
  5907. // </ul>
  5908. var popupmenuElement = document.createElement('ul');
  5909. popupmenuElement.className = 'popupmenu';
  5910. popupmenuElement.id
  5911. = 'remote_popupmenu_' + Strophe.getResourceFromJid(jid);
  5912. spanElement.appendChild(popupmenuElement);
  5913. var muteMenuItem = document.createElement('li');
  5914. var muteLinkItem = document.createElement('a');
  5915. var mutedIndicator = "<i style='float:left;' class='icon-mic-disabled'></i>";
  5916. if (!mutedAudios[jid]) {
  5917. muteLinkItem.innerHTML = mutedIndicator +
  5918. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  5919. muteLinkItem.className = 'mutelink';
  5920. }
  5921. else {
  5922. muteLinkItem.innerHTML = mutedIndicator +
  5923. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  5924. muteLinkItem.className = 'mutelink disabled';
  5925. }
  5926. muteLinkItem.onclick = function(){
  5927. if ($(this).attr('disabled') != undefined) {
  5928. event.preventDefault();
  5929. }
  5930. var isMute = mutedAudios[jid] == true;
  5931. APP.xmpp.setMute(jid, !isMute);
  5932. popupmenuElement.setAttribute('style', 'display:none;');
  5933. if (isMute) {
  5934. this.innerHTML = mutedIndicator +
  5935. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  5936. this.className = 'mutelink disabled';
  5937. }
  5938. else {
  5939. this.innerHTML = mutedIndicator +
  5940. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  5941. this.className = 'mutelink';
  5942. }
  5943. };
  5944. muteMenuItem.appendChild(muteLinkItem);
  5945. popupmenuElement.appendChild(muteMenuItem);
  5946. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  5947. var ejectMenuItem = document.createElement('li');
  5948. var ejectLinkItem = document.createElement('a');
  5949. var ejectText = "<div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.kick'>&nbsp;</div>";
  5950. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  5951. ejectLinkItem.onclick = function(){
  5952. APP.xmpp.eject(jid);
  5953. popupmenuElement.setAttribute('style', 'display:none;');
  5954. };
  5955. ejectMenuItem.appendChild(ejectLinkItem);
  5956. popupmenuElement.appendChild(ejectMenuItem);
  5957. var paddingSpan = document.createElement('span');
  5958. paddingSpan.className = 'popupmenuPadding';
  5959. popupmenuElement.appendChild(paddingSpan);
  5960. APP.translation.translateElement($("#" + popupmenuElement.id + " > li > a > div"));
  5961. }
  5962. /**
  5963. * Removes remote video menu element from video element identified by
  5964. * given <tt>videoElementId</tt>.
  5965. *
  5966. * @param videoElementId the id of local or remote video element.
  5967. */
  5968. function removeRemoteVideoMenu(videoElementId) {
  5969. var menuSpan = $('#' + videoElementId + '>span.remotevideomenu');
  5970. if (menuSpan.length) {
  5971. menuSpan.remove();
  5972. }
  5973. }
  5974. /**
  5975. * Updates the data for the indicator
  5976. * @param id the id of the indicator
  5977. * @param percent the percent for connection quality
  5978. * @param object the data
  5979. */
  5980. function updateStatsIndicator(id, percent, object) {
  5981. if(VideoLayout.connectionIndicators[id])
  5982. VideoLayout.connectionIndicators[id].updateConnectionQuality(percent, object);
  5983. }
  5984. /**
  5985. * Returns an array of the video dimensions, so that it keeps it's aspect
  5986. * ratio and fits available area with it's larger dimension. This method
  5987. * ensures that whole video will be visible and can leave empty areas.
  5988. *
  5989. * @return an array with 2 elements, the video width and the video height
  5990. */
  5991. function getDesktopVideoSize(videoWidth,
  5992. videoHeight,
  5993. videoSpaceWidth,
  5994. videoSpaceHeight) {
  5995. if (!videoWidth)
  5996. videoWidth = currentVideoWidth;
  5997. if (!videoHeight)
  5998. videoHeight = currentVideoHeight;
  5999. var aspectRatio = videoWidth / videoHeight;
  6000. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  6001. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  6002. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  6003. if (availableWidth / aspectRatio >= videoSpaceHeight)
  6004. {
  6005. availableHeight = videoSpaceHeight;
  6006. availableWidth = availableHeight * aspectRatio;
  6007. }
  6008. if (availableHeight * aspectRatio >= videoSpaceWidth)
  6009. {
  6010. availableWidth = videoSpaceWidth;
  6011. availableHeight = availableWidth / aspectRatio;
  6012. }
  6013. return [availableWidth, availableHeight];
  6014. }
  6015. /**
  6016. * Creates the edit display name button.
  6017. *
  6018. * @returns the edit button
  6019. */
  6020. function createEditDisplayNameButton() {
  6021. var editButton = document.createElement('a');
  6022. editButton.className = 'displayname';
  6023. UIUtil.setTooltip(editButton,
  6024. "videothumbnail.editnickname",
  6025. "top");
  6026. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  6027. return editButton;
  6028. }
  6029. /**
  6030. * Creates the element indicating the moderator(owner) of the conference.
  6031. *
  6032. * @param parentElement the parent element where the owner indicator will
  6033. * be added
  6034. */
  6035. function createModeratorIndicatorElement(parentElement) {
  6036. var moderatorIndicator = document.createElement('i');
  6037. moderatorIndicator.className = 'fa fa-star';
  6038. parentElement.appendChild(moderatorIndicator);
  6039. UIUtil.setTooltip(parentElement,
  6040. "videothumbnail.moderator",
  6041. "top");
  6042. }
  6043. var VideoLayout = (function (my) {
  6044. my.connectionIndicators = {};
  6045. // By default we use camera
  6046. my.getVideoSize = getCameraVideoSize;
  6047. my.getVideoPosition = getCameraVideoPosition;
  6048. my.init = function (emitter) {
  6049. // Listen for large video size updates
  6050. document.getElementById('largeVideo')
  6051. .addEventListener('loadedmetadata', function (e) {
  6052. currentVideoWidth = this.videoWidth;
  6053. currentVideoHeight = this.videoHeight;
  6054. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  6055. });
  6056. eventEmitter = emitter;
  6057. };
  6058. my.isInLastN = function(resource) {
  6059. return lastNCount < 0 // lastN is disabled, return true
  6060. || (lastNCount > 0 && lastNEndpointsCache.length == 0) // lastNEndpoints cache not built yet, return true
  6061. || (lastNEndpointsCache && lastNEndpointsCache.indexOf(resource) !== -1);
  6062. };
  6063. my.changeLocalStream = function (stream) {
  6064. VideoLayout.changeLocalVideo(stream);
  6065. };
  6066. my.changeLocalAudio = function(stream) {
  6067. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  6068. document.getElementById('localAudio').autoplay = true;
  6069. document.getElementById('localAudio').volume = 0;
  6070. if (preMuted) {
  6071. if(!APP.UI.setAudioMuted(true))
  6072. {
  6073. preMuted = mute;
  6074. }
  6075. preMuted = false;
  6076. }
  6077. };
  6078. my.changeLocalVideo = function(stream) {
  6079. var flipX = true;
  6080. if(stream.videoType == "screen")
  6081. flipX = false;
  6082. var localVideo = document.createElement('video');
  6083. localVideo.id = 'localVideo_' +
  6084. APP.RTC.getStreamID(stream.getOriginalStream());
  6085. localVideo.autoplay = true;
  6086. localVideo.volume = 0; // is it required if audio is separated ?
  6087. localVideo.oncontextmenu = function () { return false; };
  6088. var localVideoContainer = document.getElementById('localVideoWrapper');
  6089. localVideoContainer.appendChild(localVideo);
  6090. // Set default display name.
  6091. setDisplayName('localVideoContainer');
  6092. if(!VideoLayout.connectionIndicators["localVideoContainer"]) {
  6093. VideoLayout.connectionIndicators["localVideoContainer"]
  6094. = new ConnectionIndicator($("#localVideoContainer")[0], null, VideoLayout);
  6095. }
  6096. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  6097. var localVideoSelector = $('#' + localVideo.id);
  6098. function localVideoClick(event) {
  6099. event.stopPropagation();
  6100. VideoLayout.handleVideoThumbClicked(
  6101. APP.RTC.getVideoSrc(localVideo),
  6102. false,
  6103. APP.xmpp.myResource());
  6104. }
  6105. // Add click handler to both video and video wrapper elements in case
  6106. // there's no video.
  6107. localVideoSelector.click(localVideoClick);
  6108. $('#localVideoContainer').click(localVideoClick);
  6109. // Add hover handler
  6110. $('#localVideoContainer').hover(
  6111. function() {
  6112. VideoLayout.showDisplayName('localVideoContainer', true);
  6113. },
  6114. function() {
  6115. if (!VideoLayout.isLargeVideoVisible()
  6116. || APP.RTC.getVideoSrc(localVideo) !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  6117. VideoLayout.showDisplayName('localVideoContainer', false);
  6118. }
  6119. );
  6120. // Add stream ended handler
  6121. stream.getOriginalStream().onended = function () {
  6122. localVideoContainer.removeChild(localVideo);
  6123. VideoLayout.updateRemovedVideo(APP.RTC.getVideoSrc(localVideo));
  6124. };
  6125. // Flip video x axis if needed
  6126. flipXLocalVideo = flipX;
  6127. if (flipX) {
  6128. localVideoSelector.addClass("flipVideoX");
  6129. }
  6130. // Attach WebRTC stream
  6131. var videoStream = APP.simulcast.getLocalVideoStream();
  6132. APP.RTC.attachMediaStream(localVideoSelector, videoStream);
  6133. localVideoSrc = APP.RTC.getVideoSrc(localVideo);
  6134. var myResourceJid = APP.xmpp.myResource();
  6135. VideoLayout.updateLargeVideo(localVideoSrc, 0,
  6136. myResourceJid);
  6137. };
  6138. /**
  6139. * Checks if removed video is currently displayed and tries to display
  6140. * another one instead.
  6141. * @param removedVideoSrc src stream identifier of the video.
  6142. */
  6143. my.updateRemovedVideo = function(removedVideoSrc) {
  6144. if (removedVideoSrc === APP.RTC.getVideoSrc($('#largeVideo')[0])) {
  6145. // this is currently displayed as large
  6146. // pick the last visible video in the row
  6147. // if nobody else is left, this picks the local video
  6148. var pick
  6149. = $('#remoteVideos>span[id!="mixedstream"]:visible:last>video')
  6150. .get(0);
  6151. if (!pick) {
  6152. console.info("Last visible video no longer exists");
  6153. pick = $('#remoteVideos>span[id!="mixedstream"]>video').get(0);
  6154. if (!pick || !APP.RTC.getVideoSrc(pick)) {
  6155. // Try local video
  6156. console.info("Fallback to local video...");
  6157. pick = $('#remoteVideos>span>span>video').get(0);
  6158. }
  6159. }
  6160. // mute if localvideo
  6161. if (pick) {
  6162. var container = pick.parentNode;
  6163. var jid = null;
  6164. if(container)
  6165. {
  6166. if(container.id == "localVideoWrapper")
  6167. {
  6168. jid = APP.xmpp.myResource();
  6169. }
  6170. else
  6171. {
  6172. jid = VideoLayout.getPeerContainerResourceJid(container);
  6173. }
  6174. }
  6175. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(pick), pick.volume, jid);
  6176. } else {
  6177. console.warn("Failed to elect large video");
  6178. }
  6179. }
  6180. };
  6181. my.onRemoteStreamAdded = function (stream) {
  6182. var container;
  6183. var remotes = document.getElementById('remoteVideos');
  6184. if (stream.peerjid) {
  6185. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  6186. container = document.getElementById(
  6187. 'participant_' + Strophe.getResourceFromJid(stream.peerjid));
  6188. } else {
  6189. var id = stream.getOriginalStream().id;
  6190. if (id !== 'mixedmslabel'
  6191. // FIXME: default stream is added always with new focus
  6192. // (to be investigated)
  6193. && id !== 'default') {
  6194. console.error('can not associate stream',
  6195. id,
  6196. 'with a participant');
  6197. // We don't want to add it here since it will cause troubles
  6198. return;
  6199. }
  6200. // FIXME: for the mixed ms we dont need a video -- currently
  6201. container = document.createElement('span');
  6202. container.id = 'mixedstream';
  6203. container.className = 'videocontainer';
  6204. remotes.appendChild(container);
  6205. UIUtil.playSoundNotification('userJoined');
  6206. }
  6207. if (container) {
  6208. VideoLayout.addRemoteStreamElement( container,
  6209. stream.sid,
  6210. stream.getOriginalStream(),
  6211. stream.peerjid,
  6212. stream.ssrc);
  6213. }
  6214. }
  6215. my.getLargeVideoState = function () {
  6216. return largeVideoState;
  6217. };
  6218. /**
  6219. * Updates the large video with the given new video source.
  6220. */
  6221. my.updateLargeVideo = function(newSrc, vol, resourceJid) {
  6222. console.log('hover in', newSrc);
  6223. if (APP.RTC.getVideoSrc($('#largeVideo')[0]) !== newSrc) {
  6224. $('#activeSpeaker').css('visibility', 'hidden');
  6225. // Due to the simulcast the localVideoSrc may have changed when the
  6226. // fadeOut event triggers. In that case the getJidFromVideoSrc and
  6227. // isVideoSrcDesktop methods will not function correctly.
  6228. //
  6229. // Also, again due to the simulcast, the updateLargeVideo method can
  6230. // be called multiple times almost simultaneously. Therefore, we
  6231. // store the state here and update only once.
  6232. largeVideoState.newSrc = newSrc;
  6233. largeVideoState.isVisible = $('#largeVideo').is(':visible');
  6234. largeVideoState.isDesktop = APP.RTC.isVideoSrcDesktop(resourceJid);
  6235. if(largeVideoState.userResourceJid) {
  6236. largeVideoState.oldResourceJid = largeVideoState.userResourceJid;
  6237. } else {
  6238. largeVideoState.oldResourceJid = null;
  6239. }
  6240. largeVideoState.userResourceJid = resourceJid;
  6241. // Screen stream is already rotated
  6242. largeVideoState.flipX = (newSrc === localVideoSrc) && flipXLocalVideo;
  6243. var userChanged = false;
  6244. if (largeVideoState.oldResourceJid !== largeVideoState.userResourceJid) {
  6245. userChanged = true;
  6246. // we want the notification to trigger even if userJid is undefined,
  6247. // or null.
  6248. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT,
  6249. largeVideoState.userResourceJid);
  6250. }
  6251. if (!largeVideoState.updateInProgress) {
  6252. largeVideoState.updateInProgress = true;
  6253. var doUpdate = function () {
  6254. Avatar.updateActiveSpeakerAvatarSrc(
  6255. APP.xmpp.findJidFromResource(
  6256. largeVideoState.userResourceJid));
  6257. if (!userChanged && largeVideoState.preload &&
  6258. largeVideoState.preload !== null &&
  6259. APP.RTC.getVideoSrc($(largeVideoState.preload)[0]) === newSrc)
  6260. {
  6261. console.info('Switching to preloaded video');
  6262. var attributes = $('#largeVideo').prop("attributes");
  6263. // loop through largeVideo attributes and apply them on
  6264. // preload.
  6265. $.each(attributes, function () {
  6266. if (this.name !== 'id' && this.name !== 'src') {
  6267. largeVideoState.preload.attr(this.name, this.value);
  6268. }
  6269. });
  6270. largeVideoState.preload.appendTo($('#largeVideoContainer'));
  6271. $('#largeVideo').attr('id', 'previousLargeVideo');
  6272. largeVideoState.preload.attr('id', 'largeVideo');
  6273. $('#previousLargeVideo').remove();
  6274. largeVideoState.preload.on('loadedmetadata', function (e) {
  6275. currentVideoWidth = this.videoWidth;
  6276. currentVideoHeight = this.videoHeight;
  6277. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  6278. });
  6279. largeVideoState.preload = null;
  6280. largeVideoState.preload_ssrc = 0;
  6281. } else {
  6282. APP.RTC.setVideoSrc($('#largeVideo')[0], largeVideoState.newSrc);
  6283. }
  6284. var videoTransform = document.getElementById('largeVideo')
  6285. .style.webkitTransform;
  6286. if (largeVideoState.flipX && videoTransform !== 'scaleX(-1)') {
  6287. document.getElementById('largeVideo').style.webkitTransform
  6288. = "scaleX(-1)";
  6289. }
  6290. else if (!largeVideoState.flipX && videoTransform === 'scaleX(-1)') {
  6291. document.getElementById('largeVideo').style.webkitTransform
  6292. = "none";
  6293. }
  6294. // Change the way we'll be measuring and positioning large video
  6295. VideoLayout.getVideoSize = largeVideoState.isDesktop
  6296. ? getDesktopVideoSize
  6297. : getCameraVideoSize;
  6298. VideoLayout.getVideoPosition = largeVideoState.isDesktop
  6299. ? getDesktopVideoPosition
  6300. : getCameraVideoPosition;
  6301. // Only if the large video is currently visible.
  6302. // Disable previous dominant speaker video.
  6303. if (largeVideoState.oldResourceJid) {
  6304. VideoLayout.enableDominantSpeaker(
  6305. largeVideoState.oldResourceJid,
  6306. false);
  6307. }
  6308. // Enable new dominant speaker in the remote videos section.
  6309. if (largeVideoState.userResourceJid) {
  6310. VideoLayout.enableDominantSpeaker(
  6311. largeVideoState.userResourceJid,
  6312. true);
  6313. }
  6314. if (userChanged && largeVideoState.isVisible) {
  6315. // using "this" should be ok because we're called
  6316. // from within the fadeOut event.
  6317. $(this).fadeIn(300);
  6318. }
  6319. if(userChanged) {
  6320. Avatar.showUserAvatar(
  6321. APP.xmpp.findJidFromResource(
  6322. largeVideoState.oldResourceJid));
  6323. }
  6324. largeVideoState.updateInProgress = false;
  6325. };
  6326. if (userChanged) {
  6327. $('#largeVideo').fadeOut(300, doUpdate);
  6328. } else {
  6329. doUpdate();
  6330. }
  6331. }
  6332. } else {
  6333. Avatar.showUserAvatar(
  6334. APP.xmpp.findJidFromResource(
  6335. largeVideoState.userResourceJid));
  6336. }
  6337. };
  6338. my.handleVideoThumbClicked = function(videoSrc,
  6339. noPinnedEndpointChangedEvent,
  6340. resourceJid) {
  6341. // Restore style for previously focused video
  6342. var oldContainer = null;
  6343. if(focusedVideoInfo) {
  6344. var focusResourceJid = focusedVideoInfo.resourceJid;
  6345. oldContainer = getParticipantContainer(focusResourceJid);
  6346. }
  6347. if (oldContainer) {
  6348. oldContainer.removeClass("videoContainerFocused");
  6349. }
  6350. // Unlock current focused.
  6351. if (focusedVideoInfo && focusedVideoInfo.src === videoSrc)
  6352. {
  6353. focusedVideoInfo = null;
  6354. var dominantSpeakerVideo = null;
  6355. // Enable the currently set dominant speaker.
  6356. if (currentDominantSpeaker) {
  6357. dominantSpeakerVideo
  6358. = $('#participant_' + currentDominantSpeaker + '>video')
  6359. .get(0);
  6360. if (dominantSpeakerVideo) {
  6361. VideoLayout.updateLargeVideo(
  6362. APP.RTC.getVideoSrc(dominantSpeakerVideo),
  6363. 1,
  6364. currentDominantSpeaker);
  6365. }
  6366. }
  6367. if (!noPinnedEndpointChangedEvent) {
  6368. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  6369. }
  6370. return;
  6371. }
  6372. // Lock new video
  6373. focusedVideoInfo = {
  6374. src: videoSrc,
  6375. resourceJid: resourceJid
  6376. };
  6377. // Update focused/pinned interface.
  6378. if (resourceJid)
  6379. {
  6380. var container = getParticipantContainer(resourceJid);
  6381. container.addClass("videoContainerFocused");
  6382. if (!noPinnedEndpointChangedEvent) {
  6383. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  6384. }
  6385. }
  6386. if ($('#largeVideo').attr('src') === videoSrc &&
  6387. VideoLayout.isLargeVideoOnTop()) {
  6388. return;
  6389. }
  6390. // Triggers a "video.selected" event. The "false" parameter indicates
  6391. // this isn't a prezi.
  6392. $(document).trigger("video.selected", [false]);
  6393. VideoLayout.updateLargeVideo(videoSrc, 1, resourceJid);
  6394. $('audio').each(function (idx, el) {
  6395. if (el.id.indexOf('mixedmslabel') !== -1) {
  6396. el.volume = 0;
  6397. el.volume = 1;
  6398. }
  6399. });
  6400. };
  6401. /**
  6402. * Positions the large video.
  6403. *
  6404. * @param videoWidth the stream video width
  6405. * @param videoHeight the stream video height
  6406. */
  6407. my.positionLarge = function (videoWidth, videoHeight) {
  6408. var videoSpaceWidth = $('#videospace').width();
  6409. var videoSpaceHeight = window.innerHeight;
  6410. var videoSize = VideoLayout.getVideoSize(videoWidth,
  6411. videoHeight,
  6412. videoSpaceWidth,
  6413. videoSpaceHeight);
  6414. var largeVideoWidth = videoSize[0];
  6415. var largeVideoHeight = videoSize[1];
  6416. var videoPosition = VideoLayout.getVideoPosition(largeVideoWidth,
  6417. largeVideoHeight,
  6418. videoSpaceWidth,
  6419. videoSpaceHeight);
  6420. var horizontalIndent = videoPosition[0];
  6421. var verticalIndent = videoPosition[1];
  6422. positionVideo($('#largeVideo'),
  6423. largeVideoWidth,
  6424. largeVideoHeight,
  6425. horizontalIndent, verticalIndent);
  6426. };
  6427. /**
  6428. * Shows/hides the large video.
  6429. */
  6430. my.setLargeVideoVisible = function(isVisible) {
  6431. var resourceJid = largeVideoState.userResourceJid;
  6432. if (isVisible) {
  6433. $('#largeVideo').css({visibility: 'visible'});
  6434. $('.watermark').css({visibility: 'visible'});
  6435. VideoLayout.enableDominantSpeaker(resourceJid, true);
  6436. }
  6437. else {
  6438. $('#largeVideo').css({visibility: 'hidden'});
  6439. $('#activeSpeaker').css('visibility', 'hidden');
  6440. $('.watermark').css({visibility: 'hidden'});
  6441. VideoLayout.enableDominantSpeaker(resourceJid, false);
  6442. if(focusedVideoInfo) {
  6443. var focusResourceJid = focusedVideoInfo.resourceJid;
  6444. var oldContainer = getParticipantContainer(focusResourceJid);
  6445. if (oldContainer && oldContainer.length > 0) {
  6446. oldContainer.removeClass("videoContainerFocused");
  6447. }
  6448. focusedVideoInfo = null;
  6449. if(focusResourceJid) {
  6450. Avatar.showUserAvatar(
  6451. APP.xmpp.findJidFromResource(focusResourceJid));
  6452. }
  6453. }
  6454. }
  6455. };
  6456. /**
  6457. * Indicates if the large video is currently visible.
  6458. *
  6459. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  6460. */
  6461. my.isLargeVideoVisible = function() {
  6462. return $('#largeVideo').is(':visible');
  6463. };
  6464. my.isLargeVideoOnTop = function () {
  6465. var Etherpad = require("../etherpad/Etherpad");
  6466. var Prezi = require("../prezi/Prezi");
  6467. return !Prezi.isPresentationVisible() && !Etherpad.isVisible();
  6468. };
  6469. /**
  6470. * Checks if container for participant identified by given peerJid exists
  6471. * in the document and creates it eventually.
  6472. *
  6473. * @param peerJid peer Jid to check.
  6474. * @param userId user email or id for setting the avatar
  6475. *
  6476. * @return Returns <tt>true</tt> if the peer container exists,
  6477. * <tt>false</tt> - otherwise
  6478. */
  6479. my.ensurePeerContainerExists = function(peerJid, userId) {
  6480. ContactList.ensureAddContact(peerJid, userId);
  6481. var resourceJid = Strophe.getResourceFromJid(peerJid);
  6482. var videoSpanId = 'participant_' + resourceJid;
  6483. if (!$('#' + videoSpanId).length) {
  6484. var container =
  6485. VideoLayout.addRemoteVideoContainer(peerJid, videoSpanId, userId);
  6486. Avatar.setUserAvatar(peerJid, userId);
  6487. // Set default display name.
  6488. setDisplayName(videoSpanId);
  6489. VideoLayout.connectionIndicators[videoSpanId] =
  6490. new ConnectionIndicator(container, peerJid, VideoLayout);
  6491. var nickfield = document.createElement('span');
  6492. nickfield.className = "nick";
  6493. nickfield.appendChild(document.createTextNode(resourceJid));
  6494. container.appendChild(nickfield);
  6495. // In case this is not currently in the last n we don't show it.
  6496. if (localLastNCount
  6497. && localLastNCount > 0
  6498. && $('#remoteVideos>span').length >= localLastNCount + 2) {
  6499. showPeerContainer(resourceJid, 'hide');
  6500. }
  6501. else
  6502. VideoLayout.resizeThumbnails();
  6503. }
  6504. };
  6505. my.addRemoteVideoContainer = function(peerJid, spanId) {
  6506. var container = document.createElement('span');
  6507. container.id = spanId;
  6508. container.className = 'videocontainer';
  6509. var remotes = document.getElementById('remoteVideos');
  6510. remotes.appendChild(container);
  6511. // If the peerJid is null then this video span couldn't be directly
  6512. // associated with a participant (this could happen in the case of prezi).
  6513. if (APP.xmpp.isModerator() && peerJid !== null)
  6514. addRemoteVideoMenu(peerJid, container);
  6515. AudioLevels.updateAudioLevelCanvas(peerJid, VideoLayout);
  6516. return container;
  6517. };
  6518. /**
  6519. * Creates an audio or video stream element.
  6520. */
  6521. my.createStreamElement = function (sid, stream) {
  6522. var isVideo = stream.getVideoTracks().length > 0;
  6523. var element = isVideo
  6524. ? document.createElement('video')
  6525. : document.createElement('audio');
  6526. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_')
  6527. + sid + '_' + APP.RTC.getStreamID(stream);
  6528. element.id = id;
  6529. element.autoplay = true;
  6530. element.oncontextmenu = function () { return false; };
  6531. return element;
  6532. };
  6533. my.addRemoteStreamElement
  6534. = function (container, sid, stream, peerJid, thessrc) {
  6535. var newElementId = null;
  6536. var isVideo = stream.getVideoTracks().length > 0;
  6537. if (container) {
  6538. var streamElement = VideoLayout.createStreamElement(sid, stream);
  6539. newElementId = streamElement.id;
  6540. container.appendChild(streamElement);
  6541. var sel = $('#' + newElementId);
  6542. sel.hide();
  6543. // If the container is currently visible we attach the stream.
  6544. if (!isVideo
  6545. || (container.offsetParent !== null && isVideo)) {
  6546. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  6547. APP.RTC.attachMediaStream(sel, videoStream);
  6548. if (isVideo)
  6549. waitForRemoteVideo(sel, thessrc, stream, peerJid);
  6550. }
  6551. stream.onended = function () {
  6552. console.log('stream ended', this);
  6553. VideoLayout.removeRemoteStreamElement(
  6554. stream, isVideo, container);
  6555. // NOTE(gp) it seems that under certain circumstances, the
  6556. // onended event is not fired and thus the contact list is not
  6557. // updated.
  6558. //
  6559. // The onended event of a stream should be fired when the SSRCs
  6560. // corresponding to that stream are removed from the SDP; but
  6561. // this doesn't seem to always be the case, resulting in ghost
  6562. // contacts.
  6563. //
  6564. // In an attempt to fix the ghost contacts problem, I'm moving
  6565. // the removeContact() method call in app.js, inside the
  6566. // 'muc.left' event handler.
  6567. //if (peerJid)
  6568. // ContactList.removeContact(peerJid);
  6569. };
  6570. // Add click handler.
  6571. container.onclick = function (event) {
  6572. /*
  6573. * FIXME It turns out that videoThumb may not exist (if there is
  6574. * no actual video).
  6575. */
  6576. var videoThumb = $('#' + container.id + '>video').get(0);
  6577. if (videoThumb) {
  6578. VideoLayout.handleVideoThumbClicked(
  6579. APP.RTC.getVideoSrc(videoThumb),
  6580. false,
  6581. Strophe.getResourceFromJid(peerJid));
  6582. }
  6583. event.stopPropagation();
  6584. event.preventDefault();
  6585. return false;
  6586. };
  6587. // Add hover handler
  6588. $(container).hover(
  6589. function() {
  6590. VideoLayout.showDisplayName(container.id, true);
  6591. },
  6592. function() {
  6593. var videoSrc = null;
  6594. if ($('#' + container.id + '>video')
  6595. && $('#' + container.id + '>video').length > 0) {
  6596. videoSrc = APP.RTC.getVideoSrc($('#' + container.id + '>video').get(0));
  6597. }
  6598. // If the video has been "pinned" by the user we want to
  6599. // keep the display name on place.
  6600. if (!VideoLayout.isLargeVideoVisible()
  6601. || videoSrc !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  6602. VideoLayout.showDisplayName(container.id, false);
  6603. }
  6604. );
  6605. }
  6606. return newElementId;
  6607. };
  6608. /**
  6609. * Removes the remote stream element corresponding to the given stream and
  6610. * parent container.
  6611. *
  6612. * @param stream the stream
  6613. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  6614. * @param container
  6615. */
  6616. my.removeRemoteStreamElement = function (stream, isVideo, container) {
  6617. if (!container)
  6618. return;
  6619. var select = null;
  6620. var removedVideoSrc = null;
  6621. if (isVideo) {
  6622. select = $('#' + container.id + '>video');
  6623. removedVideoSrc = APP.RTC.getVideoSrc(select.get(0));
  6624. }
  6625. else
  6626. select = $('#' + container.id + '>audio');
  6627. // Mark video as removed to cancel waiting loop(if video is removed
  6628. // before has started)
  6629. select.removed = true;
  6630. select.remove();
  6631. var audioCount = $('#' + container.id + '>audio').length;
  6632. var videoCount = $('#' + container.id + '>video').length;
  6633. if (!audioCount && !videoCount) {
  6634. console.log("Remove whole user", container.id);
  6635. if(VideoLayout.connectionIndicators[container.id])
  6636. VideoLayout.connectionIndicators[container.id].remove();
  6637. // Remove whole container
  6638. container.remove();
  6639. UIUtil.playSoundNotification('userLeft');
  6640. VideoLayout.resizeThumbnails();
  6641. }
  6642. if (removedVideoSrc)
  6643. VideoLayout.updateRemovedVideo(removedVideoSrc);
  6644. };
  6645. /**
  6646. * Show/hide peer container for the given resourceJid.
  6647. */
  6648. function showPeerContainer(resourceJid, state) {
  6649. var peerContainer = $('#participant_' + resourceJid);
  6650. if (!peerContainer)
  6651. return;
  6652. var isHide = state === 'hide';
  6653. var resizeThumbnails = false;
  6654. if (!isHide) {
  6655. if (!peerContainer.is(':visible')) {
  6656. resizeThumbnails = true;
  6657. peerContainer.show();
  6658. }
  6659. var jid = APP.xmpp.findJidFromResource(resourceJid);
  6660. if (state == 'show')
  6661. {
  6662. // peerContainer.css('-webkit-filter', '');
  6663. Avatar.showUserAvatar(jid, false);
  6664. }
  6665. else // if (state == 'avatar')
  6666. {
  6667. // peerContainer.css('-webkit-filter', 'grayscale(100%)');
  6668. Avatar.showUserAvatar(jid, true);
  6669. }
  6670. }
  6671. else if (peerContainer.is(':visible') && isHide)
  6672. {
  6673. resizeThumbnails = true;
  6674. peerContainer.hide();
  6675. if(VideoLayout.connectionIndicators['participant_' + resourceJid])
  6676. VideoLayout.connectionIndicators['participant_' + resourceJid].hide();
  6677. }
  6678. if (resizeThumbnails) {
  6679. VideoLayout.resizeThumbnails();
  6680. }
  6681. // We want to be able to pin a participant from the contact list, even
  6682. // if he's not in the lastN set!
  6683. // ContactList.setClickable(resourceJid, !isHide);
  6684. };
  6685. my.inputDisplayNameHandler = function (name) {
  6686. NicknameHandler.setNickname(name);
  6687. if (!$('#localDisplayName').is(":visible")) {
  6688. if (NicknameHandler.getNickname())
  6689. $('#localDisplayName').text(NicknameHandler.getNickname() + " (me)");
  6690. else
  6691. $('#localDisplayName')
  6692. .text(interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  6693. $('#localDisplayName').show();
  6694. }
  6695. $('#editDisplayName').hide();
  6696. };
  6697. /**
  6698. * Shows/hides the display name on the remote video.
  6699. * @param videoSpanId the identifier of the video span element
  6700. * @param isShow indicates if the display name should be shown or hidden
  6701. */
  6702. my.showDisplayName = function(videoSpanId, isShow) {
  6703. var nameSpan = $('#' + videoSpanId + '>span.displayname').get(0);
  6704. if (isShow) {
  6705. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  6706. nameSpan.setAttribute("style", "display:inline-block;");
  6707. }
  6708. else {
  6709. if (nameSpan)
  6710. nameSpan.setAttribute("style", "display:none;");
  6711. }
  6712. };
  6713. /**
  6714. * Shows the presence status message for the given video.
  6715. */
  6716. my.setPresenceStatus = function (videoSpanId, statusMsg) {
  6717. if (!$('#' + videoSpanId).length) {
  6718. // No container
  6719. return;
  6720. }
  6721. var statusSpan = $('#' + videoSpanId + '>span.status');
  6722. if (!statusSpan.length) {
  6723. //Add status span
  6724. statusSpan = document.createElement('span');
  6725. statusSpan.className = 'status';
  6726. statusSpan.id = videoSpanId + '_status';
  6727. $('#' + videoSpanId)[0].appendChild(statusSpan);
  6728. statusSpan = $('#' + videoSpanId + '>span.status');
  6729. }
  6730. // Display status
  6731. if (statusMsg && statusMsg.length) {
  6732. $('#' + videoSpanId + '_status').text(statusMsg);
  6733. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  6734. }
  6735. else {
  6736. // Hide
  6737. statusSpan.get(0).setAttribute("style", "display:none;");
  6738. }
  6739. };
  6740. /**
  6741. * Shows a visual indicator for the moderator of the conference.
  6742. */
  6743. my.showModeratorIndicator = function () {
  6744. var isModerator = APP.xmpp.isModerator();
  6745. if (isModerator) {
  6746. var indicatorSpan = $('#localVideoContainer .focusindicator');
  6747. if (indicatorSpan.children().length === 0)
  6748. {
  6749. createModeratorIndicatorElement(indicatorSpan[0]);
  6750. //translates text in focus indicator
  6751. APP.translation.translateElement($('#localVideoContainer .focusindicator'));
  6752. }
  6753. }
  6754. var members = APP.xmpp.getMembers();
  6755. Object.keys(members).forEach(function (jid) {
  6756. if (Strophe.getResourceFromJid(jid) === 'focus') {
  6757. // Skip server side focus
  6758. return;
  6759. }
  6760. var resourceJid = Strophe.getResourceFromJid(jid);
  6761. var videoSpanId = 'participant_' + resourceJid;
  6762. var videoContainer = document.getElementById(videoSpanId);
  6763. if (!videoContainer) {
  6764. console.error("No video container for " + jid);
  6765. return;
  6766. }
  6767. var member = members[jid];
  6768. if (member.role === 'moderator') {
  6769. // Remove menu if peer is moderator
  6770. var menuSpan = $('#' + videoSpanId + '>span.remotevideomenu');
  6771. if (menuSpan.length) {
  6772. removeRemoteVideoMenu(videoSpanId);
  6773. }
  6774. // Show moderator indicator
  6775. var indicatorSpan
  6776. = $('#' + videoSpanId + ' .focusindicator');
  6777. if (!indicatorSpan || indicatorSpan.length === 0) {
  6778. indicatorSpan = document.createElement('span');
  6779. indicatorSpan.className = 'focusindicator';
  6780. videoContainer.appendChild(indicatorSpan);
  6781. createModeratorIndicatorElement(indicatorSpan);
  6782. //translates text in focus indicators
  6783. APP.translation.translateElement($('#' + videoSpanId + ' .focusindicator'));
  6784. }
  6785. } else if (isModerator) {
  6786. // We are moderator, but user is not - add menu
  6787. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  6788. addRemoteVideoMenu(
  6789. jid,
  6790. document.getElementById('participant_' + resourceJid));
  6791. }
  6792. }
  6793. });
  6794. };
  6795. /**
  6796. * Shows video muted indicator over small videos.
  6797. */
  6798. my.showVideoIndicator = function(videoSpanId, isMuted) {
  6799. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  6800. if (isMuted === 'false') {
  6801. if (videoMutedSpan.length > 0) {
  6802. videoMutedSpan.remove();
  6803. }
  6804. }
  6805. else {
  6806. if(videoMutedSpan.length == 0) {
  6807. videoMutedSpan = document.createElement('span');
  6808. videoMutedSpan.className = 'videoMuted';
  6809. $('#' + videoSpanId)[0].appendChild(videoMutedSpan);
  6810. var mutedIndicator = document.createElement('i');
  6811. mutedIndicator.className = 'icon-camera-disabled';
  6812. UIUtil.setTooltip(mutedIndicator,
  6813. "videothumbnail.videomute",
  6814. "top");
  6815. videoMutedSpan.appendChild(mutedIndicator);
  6816. //translate texts for muted indicator
  6817. APP.translation.translateElement($('#' + videoSpanId + " > span > i"));
  6818. }
  6819. VideoLayout.updateMutePosition(videoSpanId);
  6820. }
  6821. };
  6822. my.updateMutePosition = function (videoSpanId) {
  6823. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  6824. var connectionIndicator = $('#' + videoSpanId + '>div.connectionindicator');
  6825. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  6826. if(connectionIndicator.length > 0
  6827. && connectionIndicator[0].style.display != "none") {
  6828. audioMutedSpan.css({right: "23px"});
  6829. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  6830. }
  6831. else
  6832. {
  6833. audioMutedSpan.css({right: "0px"});
  6834. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  6835. }
  6836. }
  6837. /**
  6838. * Shows audio muted indicator over small videos.
  6839. * @param {string} isMuted
  6840. */
  6841. my.showAudioIndicator = function(videoSpanId, isMuted) {
  6842. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  6843. if (isMuted === 'false') {
  6844. if (audioMutedSpan.length > 0) {
  6845. audioMutedSpan.popover('hide');
  6846. audioMutedSpan.remove();
  6847. }
  6848. }
  6849. else {
  6850. if(audioMutedSpan.length == 0 ) {
  6851. audioMutedSpan = document.createElement('span');
  6852. audioMutedSpan.className = 'audioMuted';
  6853. UIUtil.setTooltip(audioMutedSpan,
  6854. "videothumbnail.mute",
  6855. "top");
  6856. $('#' + videoSpanId)[0].appendChild(audioMutedSpan);
  6857. APP.translation.translateElement($('#' + videoSpanId + " > span"));
  6858. var mutedIndicator = document.createElement('i');
  6859. mutedIndicator.className = 'icon-mic-disabled';
  6860. audioMutedSpan.appendChild(mutedIndicator);
  6861. }
  6862. VideoLayout.updateMutePosition(videoSpanId);
  6863. }
  6864. };
  6865. /*
  6866. * Shows or hides the audio muted indicator over the local thumbnail video.
  6867. * @param {boolean} isMuted
  6868. */
  6869. my.showLocalAudioIndicator = function(isMuted) {
  6870. VideoLayout.showAudioIndicator('localVideoContainer', isMuted.toString());
  6871. };
  6872. /**
  6873. * Resizes the large video container.
  6874. */
  6875. my.resizeLargeVideoContainer = function () {
  6876. Chat.resizeChat();
  6877. var availableHeight = window.innerHeight;
  6878. var availableWidth = UIUtil.getAvailableVideoWidth();
  6879. if (availableWidth < 0 || availableHeight < 0) return;
  6880. $('#videospace').width(availableWidth);
  6881. $('#videospace').height(availableHeight);
  6882. $('#largeVideoContainer').width(availableWidth);
  6883. $('#largeVideoContainer').height(availableHeight);
  6884. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  6885. var top = availableHeight / 2 - avatarSize / 4 * 3;
  6886. $('#activeSpeaker').css('top', top);
  6887. VideoLayout.resizeThumbnails();
  6888. };
  6889. /**
  6890. * Resizes thumbnails.
  6891. */
  6892. my.resizeThumbnails = function() {
  6893. var videoSpaceWidth = $('#remoteVideos').width();
  6894. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  6895. var width = thumbnailSize[0];
  6896. var height = thumbnailSize[1];
  6897. // size videos so that while keeping AR and max height, we have a
  6898. // nice fit
  6899. $('#remoteVideos').height(height);
  6900. $('#remoteVideos>span').width(width);
  6901. $('#remoteVideos>span').height(height);
  6902. $('.userAvatar').css('left', (width - height) / 2);
  6903. $(document).trigger("remotevideo.resized", [width, height]);
  6904. };
  6905. /**
  6906. * Enables the dominant speaker UI.
  6907. *
  6908. * @param resourceJid the jid indicating the video element to
  6909. * activate/deactivate
  6910. * @param isEnable indicates if the dominant speaker should be enabled or
  6911. * disabled
  6912. */
  6913. my.enableDominantSpeaker = function(resourceJid, isEnable) {
  6914. var videoSpanId = null;
  6915. var videoContainerId = null;
  6916. if (resourceJid
  6917. === APP.xmpp.myResource()) {
  6918. videoSpanId = 'localVideoWrapper';
  6919. videoContainerId = 'localVideoContainer';
  6920. }
  6921. else {
  6922. videoSpanId = 'participant_' + resourceJid;
  6923. videoContainerId = videoSpanId;
  6924. }
  6925. var displayName = resourceJid;
  6926. var nameSpan = $('#' + videoContainerId + '>span.displayname');
  6927. if (nameSpan.length > 0)
  6928. displayName = nameSpan.html();
  6929. console.log("UI enable dominant speaker",
  6930. displayName,
  6931. resourceJid,
  6932. isEnable);
  6933. videoSpan = document.getElementById(videoContainerId);
  6934. if (!videoSpan) {
  6935. return;
  6936. }
  6937. var video = $('#' + videoSpanId + '>video');
  6938. if (video && video.length > 0) {
  6939. if (isEnable) {
  6940. var isLargeVideoVisible = VideoLayout.isLargeVideoOnTop();
  6941. VideoLayout.showDisplayName(videoContainerId, isLargeVideoVisible);
  6942. if (!videoSpan.classList.contains("dominantspeaker"))
  6943. videoSpan.classList.add("dominantspeaker");
  6944. }
  6945. else {
  6946. VideoLayout.showDisplayName(videoContainerId, false);
  6947. if (videoSpan.classList.contains("dominantspeaker"))
  6948. videoSpan.classList.remove("dominantspeaker");
  6949. }
  6950. Avatar.showUserAvatar(
  6951. APP.xmpp.findJidFromResource(resourceJid));
  6952. }
  6953. };
  6954. /**
  6955. * Calculates the thumbnail size.
  6956. *
  6957. * @param videoSpaceWidth the width of the video space
  6958. */
  6959. my.calculateThumbnailSize = function (videoSpaceWidth) {
  6960. // Calculate the available height, which is the inner window height minus
  6961. // 39px for the header minus 2px for the delimiter lines on the top and
  6962. // bottom of the large video, minus the 36px space inside the remoteVideos
  6963. // container used for highlighting shadow.
  6964. var availableHeight = 100;
  6965. var numvids = $('#remoteVideos>span:visible').length;
  6966. if (localLastNCount && localLastNCount > 0) {
  6967. numvids = Math.min(localLastNCount + 1, numvids);
  6968. }
  6969. // Remove the 3px borders arround videos and border around the remote
  6970. // videos area and the 4 pixels between the local video and the others
  6971. //TODO: Find out where the 4 pixels come from and remove them
  6972. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  6973. var availableWidth = availableWinWidth / numvids;
  6974. var aspectRatio = 16.0 / 9.0;
  6975. var maxHeight = Math.min(160, availableHeight);
  6976. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  6977. if (availableHeight < availableWidth / aspectRatio) {
  6978. availableWidth = Math.floor(availableHeight * aspectRatio);
  6979. }
  6980. return [availableWidth, availableHeight];
  6981. };
  6982. /**
  6983. * Updates the remote video menu.
  6984. *
  6985. * @param jid the jid indicating the video for which we're adding a menu.
  6986. * @param isMuted indicates the current mute state
  6987. */
  6988. my.updateRemoteVideoMenu = function(jid, isMuted) {
  6989. var muteMenuItem
  6990. = $('#remote_popupmenu_'
  6991. + Strophe.getResourceFromJid(jid)
  6992. + '>li>a.mutelink');
  6993. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  6994. if (muteMenuItem.length) {
  6995. var muteLink = muteMenuItem.get(0);
  6996. if (isMuted === 'true') {
  6997. muteLink.innerHTML = mutedIndicator + ' Muted';
  6998. muteLink.className = 'mutelink disabled';
  6999. }
  7000. else {
  7001. muteLink.innerHTML = mutedIndicator + ' Mute';
  7002. muteLink.className = 'mutelink';
  7003. }
  7004. }
  7005. };
  7006. /**
  7007. * Returns the current dominant speaker resource jid.
  7008. */
  7009. my.getDominantSpeakerResourceJid = function () {
  7010. return currentDominantSpeaker;
  7011. };
  7012. /**
  7013. * Returns the corresponding resource jid to the given peer container
  7014. * DOM element.
  7015. *
  7016. * @return the corresponding resource jid to the given peer container
  7017. * DOM element
  7018. */
  7019. my.getPeerContainerResourceJid = function (containerElement) {
  7020. var i = containerElement.id.indexOf('participant_');
  7021. if (i >= 0)
  7022. return containerElement.id.substring(i + 12);
  7023. };
  7024. /**
  7025. * On contact list item clicked.
  7026. */
  7027. $(ContactList).bind('contactclicked', function(event, jid) {
  7028. if (!jid) {
  7029. return;
  7030. }
  7031. var resource = Strophe.getResourceFromJid(jid);
  7032. var videoContainer = $("#participant_" + resource);
  7033. if (videoContainer.length > 0) {
  7034. var videoThumb = $('video', videoContainer).get(0);
  7035. // It is not always the case that a videoThumb exists (if there is
  7036. // no actual video).
  7037. if (videoThumb) {
  7038. if (videoThumb.src && videoThumb.src != '') {
  7039. // We have a video src, great! Let's update the large video
  7040. // now.
  7041. VideoLayout.handleVideoThumbClicked(
  7042. videoThumb.src,
  7043. false,
  7044. Strophe.getResourceFromJid(jid));
  7045. } else {
  7046. // If we don't have a video src for jid, there's absolutely
  7047. // no point in calling handleVideoThumbClicked; Quite
  7048. // simply, it won't work because it needs an src to attach
  7049. // to the large video.
  7050. //
  7051. // Instead, we trigger the pinned endpoint changed event to
  7052. // let the bridge adjust its lastN set for myjid and store
  7053. // the pinned user in the lastNPickupJid variable to be
  7054. // picked up later by the lastN changed event handler.
  7055. lastNPickupJid = jid;
  7056. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  7057. Strophe.getResourceFromJid(jid));
  7058. }
  7059. } else if (jid == APP.xmpp.myJid()) {
  7060. $("#localVideoContainer").click();
  7061. }
  7062. }
  7063. });
  7064. /**
  7065. * On audio muted event.
  7066. */
  7067. $(document).bind('audiomuted.muc', function (event, jid, isMuted) {
  7068. /*
  7069. // FIXME: but focus can not mute in this case ? - check
  7070. if (jid === xmpp.myJid()) {
  7071. // The local mute indicator is controlled locally
  7072. return;
  7073. }*/
  7074. var videoSpanId = null;
  7075. if (jid === APP.xmpp.myJid()) {
  7076. videoSpanId = 'localVideoContainer';
  7077. } else {
  7078. VideoLayout.ensurePeerContainerExists(jid);
  7079. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  7080. }
  7081. mutedAudios[jid] = isMuted;
  7082. if (APP.xmpp.isModerator()) {
  7083. VideoLayout.updateRemoteVideoMenu(jid, isMuted);
  7084. }
  7085. if (videoSpanId)
  7086. VideoLayout.showAudioIndicator(videoSpanId, isMuted);
  7087. });
  7088. /**
  7089. * On video muted event.
  7090. */
  7091. $(document).bind('videomuted.muc', function (event, jid, value) {
  7092. var isMuted = (value === "true");
  7093. if(!APP.RTC.muteRemoteVideoStream(jid, isMuted))
  7094. return;
  7095. Avatar.showUserAvatar(jid, isMuted);
  7096. var videoSpanId = null;
  7097. if (jid === APP.xmpp.myJid()) {
  7098. videoSpanId = 'localVideoContainer';
  7099. } else {
  7100. VideoLayout.ensurePeerContainerExists(jid);
  7101. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  7102. }
  7103. if (videoSpanId)
  7104. VideoLayout.showVideoIndicator(videoSpanId, value);
  7105. });
  7106. /**
  7107. * Display name changed.
  7108. */
  7109. my.onDisplayNameChanged =
  7110. function (jid, displayName, status) {
  7111. if (jid === 'localVideoContainer'
  7112. || jid === APP.xmpp.myJid()) {
  7113. setDisplayName('localVideoContainer',
  7114. displayName);
  7115. } else {
  7116. VideoLayout.ensurePeerContainerExists(jid);
  7117. setDisplayName(
  7118. 'participant_' + Strophe.getResourceFromJid(jid),
  7119. displayName,
  7120. status);
  7121. }
  7122. };
  7123. /**
  7124. * On dominant speaker changed event.
  7125. */
  7126. my.onDominantSpeakerChanged = function (resourceJid) {
  7127. // We ignore local user events.
  7128. if (resourceJid
  7129. === APP.xmpp.myResource())
  7130. return;
  7131. // Update the current dominant speaker.
  7132. if (resourceJid !== currentDominantSpeaker) {
  7133. var oldSpeakerVideoSpanId = "participant_" + currentDominantSpeaker,
  7134. newSpeakerVideoSpanId = "participant_" + resourceJid;
  7135. if($("#" + oldSpeakerVideoSpanId + ">span.displayname").text() ===
  7136. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME) {
  7137. setDisplayName(oldSpeakerVideoSpanId, null);
  7138. }
  7139. if($("#" + newSpeakerVideoSpanId + ">span.displayname").text() ===
  7140. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME) {
  7141. setDisplayName(newSpeakerVideoSpanId,
  7142. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  7143. }
  7144. currentDominantSpeaker = resourceJid;
  7145. } else {
  7146. return;
  7147. }
  7148. // Obtain container for new dominant speaker.
  7149. var container = document.getElementById(
  7150. 'participant_' + resourceJid);
  7151. // Local video will not have container found, but that's ok
  7152. // since we don't want to switch to local video.
  7153. if (container && !focusedVideoInfo)
  7154. {
  7155. var video = container.getElementsByTagName("video");
  7156. // Update the large video if the video source is already available,
  7157. // otherwise wait for the "videoactive.jingle" event.
  7158. if (video.length && video[0].currentTime > 0)
  7159. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(video[0]), resourceJid);
  7160. }
  7161. };
  7162. /**
  7163. * On last N change event.
  7164. *
  7165. * @param lastNEndpoints the list of last N endpoints
  7166. * @param endpointsEnteringLastN the list currently entering last N
  7167. * endpoints
  7168. */
  7169. my.onLastNEndpointsChanged = function ( lastNEndpoints,
  7170. endpointsEnteringLastN,
  7171. stream) {
  7172. if (lastNCount !== lastNEndpoints.length)
  7173. lastNCount = lastNEndpoints.length;
  7174. lastNEndpointsCache = lastNEndpoints;
  7175. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  7176. //
  7177. // If LastN drops to, say, 2, because of adaptivity, then E should see
  7178. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  7179. // so E sees them. C is only in E's local LastN set.
  7180. //
  7181. // If F starts talking and LastN = 3, then E should see thumbnails for
  7182. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  7183. // enters E's local LastN ejecting C.
  7184. // Increase the local LastN set size, if necessary.
  7185. if (lastNCount > localLastNCount) {
  7186. localLastNCount = lastNCount;
  7187. }
  7188. // Update the local LastN set preserving the order in which the
  7189. // endpoints appeared in the LastN/local LastN set.
  7190. var nextLocalLastNSet = lastNEndpoints.slice(0);
  7191. for (var i = 0; i < localLastNSet.length; i++) {
  7192. if (nextLocalLastNSet.length >= localLastNCount) {
  7193. break;
  7194. }
  7195. var resourceJid = localLastNSet[i];
  7196. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  7197. nextLocalLastNSet.push(resourceJid);
  7198. }
  7199. }
  7200. localLastNSet = nextLocalLastNSet;
  7201. var updateLargeVideo = false;
  7202. // Handle LastN/local LastN changes.
  7203. $('#remoteVideos>span').each(function( index, element ) {
  7204. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  7205. var isReceived = true;
  7206. if (resourceJid
  7207. && lastNEndpoints.indexOf(resourceJid) < 0
  7208. && localLastNSet.indexOf(resourceJid) < 0) {
  7209. console.log("Remove from last N", resourceJid);
  7210. showPeerContainer(resourceJid, 'hide');
  7211. isReceived = false;
  7212. } else if (resourceJid
  7213. && $('#participant_' + resourceJid).is(':visible')
  7214. && lastNEndpoints.indexOf(resourceJid) < 0
  7215. && localLastNSet.indexOf(resourceJid) >= 0) {
  7216. showPeerContainer(resourceJid, 'avatar');
  7217. isReceived = false;
  7218. }
  7219. if (!isReceived) {
  7220. // resourceJid has dropped out of the server side lastN set, so
  7221. // it is no longer being received. If resourceJid was being
  7222. // displayed in the large video we have to switch to another
  7223. // user.
  7224. var largeVideoResource = largeVideoState.userResourceJid;
  7225. if (!updateLargeVideo && resourceJid === largeVideoResource) {
  7226. updateLargeVideo = true;
  7227. }
  7228. }
  7229. });
  7230. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  7231. endpointsEnteringLastN = lastNEndpoints;
  7232. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  7233. endpointsEnteringLastN.forEach(function (resourceJid) {
  7234. var isVisible = $('#participant_' + resourceJid).is(':visible');
  7235. showPeerContainer(resourceJid, 'show');
  7236. if (!isVisible) {
  7237. console.log("Add to last N", resourceJid);
  7238. var jid = APP.xmpp.findJidFromResource(resourceJid);
  7239. var mediaStream = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  7240. var sel = $('#participant_' + resourceJid + '>video');
  7241. var videoStream = APP.simulcast.getReceivingVideoStream(
  7242. mediaStream.stream);
  7243. APP.RTC.attachMediaStream(sel, videoStream);
  7244. if (lastNPickupJid == mediaStream.peerjid) {
  7245. // Clean up the lastN pickup jid.
  7246. lastNPickupJid = null;
  7247. // Don't fire the events again, they've already
  7248. // been fired in the contact list click handler.
  7249. VideoLayout.handleVideoThumbClicked(
  7250. $(sel).attr('src'),
  7251. false,
  7252. Strophe.getResourceFromJid(mediaStream.peerjid));
  7253. updateLargeVideo = false;
  7254. }
  7255. waitForRemoteVideo(sel, mediaStream.ssrc, mediaStream.stream, resourceJid);
  7256. }
  7257. })
  7258. }
  7259. // The endpoint that was being shown in the large video has dropped out
  7260. // of the lastN set and there was no lastN pickup jid. We need to update
  7261. // the large video now.
  7262. if (updateLargeVideo) {
  7263. var resource, container, src;
  7264. var myResource
  7265. = APP.xmpp.myResource();
  7266. // Find out which endpoint to show in the large video.
  7267. for (var i = 0; i < lastNEndpoints.length; i++) {
  7268. resource = lastNEndpoints[i];
  7269. if (!resource || resource === myResource)
  7270. continue;
  7271. container = $("#participant_" + resource);
  7272. if (container.length == 0)
  7273. continue;
  7274. src = $('video', container).attr('src');
  7275. if (!src)
  7276. continue;
  7277. // videoSrcToSsrc needs to be update for this call to succeed.
  7278. VideoLayout.updateLargeVideo(src);
  7279. break;
  7280. }
  7281. }
  7282. };
  7283. my.onSimulcastLayersChanging = function (endpointSimulcastLayers) {
  7284. endpointSimulcastLayers.forEach(function (esl) {
  7285. var resource = esl.endpoint;
  7286. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7287. // then ignore the event (= do not preload anything).
  7288. //
  7289. // The bridge could probably stop sending this message if it's for
  7290. // an endpoint that's not in lastN.
  7291. if (lastNCount != -1
  7292. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7293. return;
  7294. }
  7295. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7296. // Get session and stream from primary ssrc.
  7297. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7298. var sid = res.sid;
  7299. var electedStream = res.stream;
  7300. if (sid && electedStream) {
  7301. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7302. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7303. var preload = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC)) == largeVideoState.userResourceJid);
  7304. if (preload) {
  7305. if (largeVideoState.preload)
  7306. {
  7307. $(largeVideoState.preload).remove();
  7308. }
  7309. console.info('Preloading remote video');
  7310. largeVideoState.preload = $('<video autoplay></video>');
  7311. // ssrcs are unique in an rtp session
  7312. largeVideoState.preload_ssrc = primarySSRC;
  7313. APP.RTC.attachMediaStream(largeVideoState.preload, electedStream)
  7314. }
  7315. } else {
  7316. console.error('Could not find a stream or a session.', sid, electedStream);
  7317. }
  7318. });
  7319. };
  7320. /**
  7321. * On simulcast layers changed event.
  7322. */
  7323. my.onSimulcastLayersChanged = function (endpointSimulcastLayers) {
  7324. endpointSimulcastLayers.forEach(function (esl) {
  7325. var resource = esl.endpoint;
  7326. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7327. // then ignore the event (= do not change large video/thumbnail
  7328. // SRCs).
  7329. //
  7330. // Note that even if we ignore the "changed" event in this event
  7331. // handler, the bridge must continue sending these events because
  7332. // the simulcast code in simulcast.js uses it to know what's going
  7333. // to be streamed by the bridge when/if the endpoint gets back into
  7334. // the lastN set.
  7335. if (lastNCount != -1
  7336. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7337. return;
  7338. }
  7339. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7340. // Get session and stream from primary ssrc.
  7341. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7342. var sid = res.sid;
  7343. var electedStream = res.stream;
  7344. if (sid && electedStream) {
  7345. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7346. console.info('Switching simulcast substream.');
  7347. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7348. var msidParts = msid.split(' ');
  7349. var selRemoteVideo = $(['#', 'remoteVideo_', sid, '_', msidParts[0]].join(''));
  7350. var updateLargeVideo = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC))
  7351. == largeVideoState.userResourceJid);
  7352. var updateFocusedVideoSrc = (focusedVideoInfo && focusedVideoInfo.src && focusedVideoInfo.src != '' &&
  7353. (APP.RTC.getVideoSrc(selRemoteVideo[0]) == focusedVideoInfo.src));
  7354. var electedStreamUrl;
  7355. if (largeVideoState.preload_ssrc == primarySSRC)
  7356. {
  7357. APP.RTC.setVideoSrc(selRemoteVideo[0], APP.RTC.getVideoSrc(largeVideoState.preload[0]));
  7358. }
  7359. else
  7360. {
  7361. if (largeVideoState.preload
  7362. && largeVideoState.preload != null) {
  7363. $(largeVideoState.preload).remove();
  7364. }
  7365. largeVideoState.preload_ssrc = 0;
  7366. APP.RTC.attachMediaStream(selRemoteVideo, electedStream);
  7367. }
  7368. var jid = APP.xmpp.getJidFromSSRC(primarySSRC);
  7369. if (updateLargeVideo) {
  7370. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(selRemoteVideo[0]), null,
  7371. Strophe.getResourceFromJid(jid));
  7372. }
  7373. if (updateFocusedVideoSrc) {
  7374. focusedVideoInfo.src = APP.RTC.getVideoSrc(selRemoteVideo[0]);
  7375. }
  7376. var videoId;
  7377. if(resource == APP.xmpp.myResource())
  7378. {
  7379. videoId = "localVideoContainer";
  7380. }
  7381. else
  7382. {
  7383. videoId = "participant_" + resource;
  7384. }
  7385. var connectionIndicator = VideoLayout.connectionIndicators[videoId];
  7386. if(connectionIndicator)
  7387. connectionIndicator.updatePopoverData();
  7388. } else {
  7389. console.error('Could not find a stream or a sid.', sid, electedStream);
  7390. }
  7391. });
  7392. };
  7393. /**
  7394. * Updates local stats
  7395. * @param percent
  7396. * @param object
  7397. */
  7398. my.updateLocalConnectionStats = function (percent, object) {
  7399. var resolution = null;
  7400. if(object.resolution !== null)
  7401. {
  7402. resolution = object.resolution;
  7403. object.resolution = resolution[APP.xmpp.myJid()];
  7404. delete resolution[APP.xmpp.myJid()];
  7405. }
  7406. updateStatsIndicator("localVideoContainer", percent, object);
  7407. for(var jid in resolution)
  7408. {
  7409. if(resolution[jid] === null)
  7410. continue;
  7411. var id = 'participant_' + Strophe.getResourceFromJid(jid);
  7412. if(VideoLayout.connectionIndicators[id])
  7413. {
  7414. VideoLayout.connectionIndicators[id].updateResolution(resolution[jid]);
  7415. }
  7416. }
  7417. };
  7418. /**
  7419. * Updates remote stats.
  7420. * @param jid the jid associated with the stats
  7421. * @param percent the connection quality percent
  7422. * @param object the stats data
  7423. */
  7424. my.updateConnectionStats = function (jid, percent, object) {
  7425. var resourceJid = Strophe.getResourceFromJid(jid);
  7426. var videoSpanId = 'participant_' + resourceJid;
  7427. updateStatsIndicator(videoSpanId, percent, object);
  7428. };
  7429. /**
  7430. * Removes the connection
  7431. * @param jid
  7432. */
  7433. my.removeConnectionIndicator = function (jid) {
  7434. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7435. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].remove();
  7436. };
  7437. /**
  7438. * Hides the connection indicator
  7439. * @param jid
  7440. */
  7441. my.hideConnectionIndicator = function (jid) {
  7442. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7443. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].hide();
  7444. };
  7445. /**
  7446. * Hides all the indicators
  7447. */
  7448. my.onStatsStop = function () {
  7449. for(var indicator in VideoLayout.connectionIndicators)
  7450. {
  7451. VideoLayout.connectionIndicators[indicator].hideIndicator();
  7452. }
  7453. };
  7454. my.participantLeft = function (jid) {
  7455. // Unlock large video
  7456. if (focusedVideoInfo && focusedVideoInfo.jid === jid)
  7457. {
  7458. console.info("Focused video owner has left the conference");
  7459. focusedVideoInfo = null;
  7460. }
  7461. }
  7462. return my;
  7463. }(VideoLayout || {}));
  7464. module.exports = VideoLayout;
  7465. },{"../../../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){
  7466. //var nouns = [
  7467. //];
  7468. var pluralNouns = [
  7469. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  7470. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  7471. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  7472. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  7473. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  7474. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  7475. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  7476. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  7477. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  7478. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  7479. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  7480. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  7481. ];
  7482. //var places = [
  7483. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  7484. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  7485. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  7486. // "Bridge"
  7487. //];
  7488. var verbs = [
  7489. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  7490. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  7491. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  7492. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  7493. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  7494. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  7495. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  7496. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  7497. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  7498. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  7499. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  7500. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  7501. ];
  7502. var adverbs = [
  7503. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  7504. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  7505. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  7506. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  7507. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  7508. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  7509. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  7510. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  7511. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  7512. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  7513. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  7514. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  7515. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  7516. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  7517. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly", "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  7518. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  7519. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  7520. ];
  7521. var adjectives = [
  7522. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  7523. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  7524. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  7525. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  7526. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  7527. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  7528. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  7529. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  7530. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  7531. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  7532. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  7533. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  7534. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  7535. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  7536. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  7537. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  7538. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  7539. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  7540. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  7541. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  7542. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  7543. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  7544. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  7545. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  7546. "Zealous"
  7547. ];
  7548. //var pronouns = [
  7549. //];
  7550. //var conjunctions = [
  7551. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  7552. //];
  7553. /*
  7554. * Maps a string (category name) to the array of words from that category.
  7555. */
  7556. var CATEGORIES =
  7557. {
  7558. //"_NOUN_": nouns,
  7559. "_PLURALNOUN_": pluralNouns,
  7560. //"_PLACE_": places,
  7561. "_VERB_": verbs,
  7562. "_ADVERB_": adverbs,
  7563. "_ADJECTIVE_": adjectives
  7564. //"_PRONOUN_": pronouns,
  7565. //"_CONJUNCTION_": conjunctions,
  7566. };
  7567. var PATTERNS = [
  7568. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  7569. // BeautifulFungiOrSpaghetti
  7570. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  7571. // AmazinglyScaryToy
  7572. //"_ADVERB__ADJECTIVE__NOUN_",
  7573. // NeitherTrashNorRifle
  7574. //"Neither_NOUN_Nor_NOUN_",
  7575. //"Either_NOUN_Or_NOUN_",
  7576. // EitherCopulateOrInvestigate
  7577. //"Either_VERB_Or_VERB_",
  7578. //"Neither_VERB_Nor_VERB_",
  7579. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  7580. //"The_ADVERB__ADJECTIVE__NOUN_",
  7581. //"The_ADVERB__ADJECTIVE__NOUN_s",
  7582. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  7583. // WolvesComputeBadly
  7584. //"_PLURALNOUN__VERB__ADVERB_",
  7585. // UniteFacilitateAndMerge
  7586. //"_VERB__VERB_And_VERB_",
  7587. //NastyWitchesAtThePub
  7588. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  7589. ];
  7590. /*
  7591. * Returns a random element from the array 'arr'
  7592. */
  7593. function randomElement(arr)
  7594. {
  7595. return arr[Math.floor(Math.random() * arr.length)];
  7596. }
  7597. /*
  7598. * Returns true if the string 's' contains one of the
  7599. * template strings.
  7600. */
  7601. function hasTemplate(s)
  7602. {
  7603. for (var template in CATEGORIES){
  7604. if (s.indexOf(template) >= 0){
  7605. return true;
  7606. }
  7607. }
  7608. }
  7609. /**
  7610. * Generates new room name.
  7611. */
  7612. var RoomNameGenerator = {
  7613. generateRoomWithoutSeparator: function()
  7614. {
  7615. // Note that if more than one pattern is available, the choice of 'name' won't be random (names from patterns
  7616. // with fewer options will have higher probability of being chosen that names from patterns with more options).
  7617. var name = randomElement(PATTERNS);
  7618. var word;
  7619. while (hasTemplate(name)){
  7620. for (var template in CATEGORIES){
  7621. word = randomElement(CATEGORIES[template]);
  7622. name = name.replace(template, word);
  7623. }
  7624. }
  7625. return name;
  7626. }
  7627. }
  7628. module.exports = RoomNameGenerator;
  7629. },{}],34:[function(require,module,exports){
  7630. var animateTimeout, updateTimeout;
  7631. var RoomNameGenerator = require("./RoomnameGenerator");
  7632. function enter_room()
  7633. {
  7634. var val = $("#enter_room_field").val();
  7635. if(!val) {
  7636. val = $("#enter_room_field").attr("room_name");
  7637. }
  7638. if (val) {
  7639. window.location.pathname = "/" + val;
  7640. }
  7641. }
  7642. function animate(word) {
  7643. var currentVal = $("#enter_room_field").attr("placeholder");
  7644. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  7645. animateTimeout = setTimeout(function() {
  7646. animate(word.substring(1, word.length))
  7647. }, 70);
  7648. }
  7649. function update_roomname()
  7650. {
  7651. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  7652. $("#enter_room_field").attr("room_name", word);
  7653. $("#enter_room_field").attr("placeholder", "");
  7654. clearTimeout(animateTimeout);
  7655. animate(word);
  7656. updateTimeout = setTimeout(update_roomname, 10000);
  7657. }
  7658. function setupWelcomePage()
  7659. {
  7660. $("#videoconference_page").hide();
  7661. $("#domain_name").text(
  7662. window.location.protocol + "//" + window.location.host + "/");
  7663. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  7664. var leftWatermarkDiv
  7665. = $("#welcome_page_header div[class='watermark leftwatermark']");
  7666. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  7667. {
  7668. leftWatermarkDiv.css({display: 'block'});
  7669. leftWatermarkDiv.parent().get(0).href
  7670. = interfaceConfig.JITSI_WATERMARK_LINK;
  7671. }
  7672. }
  7673. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  7674. var rightWatermarkDiv
  7675. = $("#welcome_page_header div[class='watermark rightwatermark']");
  7676. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  7677. rightWatermarkDiv.css({display: 'block'});
  7678. rightWatermarkDiv.parent().get(0).href
  7679. = interfaceConfig.BRAND_WATERMARK_LINK;
  7680. rightWatermarkDiv.get(0).style.backgroundImage
  7681. = "url(images/rightwatermark.png)";
  7682. }
  7683. }
  7684. if (interfaceConfig.SHOW_POWERED_BY) {
  7685. $("#welcome_page_header>a[class='poweredby']")
  7686. .css({display: 'block'});
  7687. }
  7688. $("#enter_room_button").click(function()
  7689. {
  7690. enter_room();
  7691. });
  7692. $("#enter_room_field").keydown(function (event) {
  7693. if (event.keyCode === 13 /* enter */) {
  7694. enter_room();
  7695. }
  7696. });
  7697. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  7698. var updateTimeout;
  7699. var animateTimeout;
  7700. $("#reload_roomname").click(function () {
  7701. clearTimeout(updateTimeout);
  7702. clearTimeout(animateTimeout);
  7703. update_roomname();
  7704. });
  7705. $("#reload_roomname").show();
  7706. update_roomname();
  7707. }
  7708. $("#disable_welcome").click(function () {
  7709. window.localStorage.welcomePageDisabled
  7710. = $("#disable_welcome").is(":checked");
  7711. });
  7712. }
  7713. module.exports = setupWelcomePage;
  7714. },{"./RoomnameGenerator":33}],35:[function(require,module,exports){
  7715. var EventEmitter = require("events");
  7716. var eventEmitter = new EventEmitter();
  7717. var CQEvents = require("../../service/connectionquality/CQEvents");
  7718. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7719. /**
  7720. * local stats
  7721. * @type {{}}
  7722. */
  7723. var stats = {};
  7724. /**
  7725. * remote stats
  7726. * @type {{}}
  7727. */
  7728. var remoteStats = {};
  7729. /**
  7730. * Interval for sending statistics to other participants
  7731. * @type {null}
  7732. */
  7733. var sendIntervalId = null;
  7734. /**
  7735. * Start statistics sending.
  7736. */
  7737. function startSendingStats() {
  7738. sendStats();
  7739. sendIntervalId = setInterval(sendStats, 10000);
  7740. }
  7741. /**
  7742. * Sends statistics to other participants
  7743. */
  7744. function sendStats() {
  7745. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  7746. }
  7747. /**
  7748. * Converts statistics to format for sending through XMPP
  7749. * @param stats the statistics
  7750. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  7751. */
  7752. function convertToMUCStats(stats) {
  7753. return {
  7754. "bitrate_download": stats.bitrate.download,
  7755. "bitrate_upload": stats.bitrate.upload,
  7756. "packetLoss_total": stats.packetLoss.total,
  7757. "packetLoss_download": stats.packetLoss.download,
  7758. "packetLoss_upload": stats.packetLoss.upload
  7759. };
  7760. }
  7761. /**
  7762. * Converts statitistics to format used by VideoLayout
  7763. * @param stats
  7764. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  7765. */
  7766. function parseMUCStats(stats) {
  7767. return {
  7768. bitrate: {
  7769. download: stats.bitrate_download,
  7770. upload: stats.bitrate_upload
  7771. },
  7772. packetLoss: {
  7773. total: stats.packetLoss_total,
  7774. download: stats.packetLoss_download,
  7775. upload: stats.packetLoss_upload
  7776. }
  7777. };
  7778. }
  7779. var ConnectionQuality = {
  7780. init: function () {
  7781. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  7782. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  7783. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  7784. },
  7785. /**
  7786. * Updates the local statistics
  7787. * @param data new statistics
  7788. */
  7789. updateLocalStats: function (data) {
  7790. stats = data;
  7791. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  7792. if (sendIntervalId == null) {
  7793. startSendingStats();
  7794. }
  7795. },
  7796. /**
  7797. * Updates remote statistics
  7798. * @param jid the jid associated with the statistics
  7799. * @param data the statistics
  7800. */
  7801. updateRemoteStats: function (jid, data) {
  7802. if (data == null || data.packetLoss_total == null) {
  7803. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  7804. return;
  7805. }
  7806. remoteStats[jid] = parseMUCStats(data);
  7807. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  7808. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  7809. },
  7810. /**
  7811. * Stops statistics sending.
  7812. */
  7813. stopSendingStats: function () {
  7814. clearInterval(sendIntervalId);
  7815. sendIntervalId = null;
  7816. //notify UI about stopping statistics gathering
  7817. eventEmitter.emit(CQEvents.STOP);
  7818. },
  7819. /**
  7820. * Returns the local statistics.
  7821. */
  7822. getStats: function () {
  7823. return stats;
  7824. },
  7825. addListener: function (type, listener) {
  7826. eventEmitter.on(type, listener);
  7827. }
  7828. };
  7829. module.exports = ConnectionQuality;
  7830. },{"../../service/connectionquality/CQEvents":86,"../../service/xmpp/XMPPEvents":89,"events":1}],36:[function(require,module,exports){
  7831. /* global $, alert, changeLocalVideo, chrome, config, getConferenceHandler, getUserMediaWithConstraints */
  7832. /**
  7833. * Indicates that desktop stream is currently in use(for toggle purpose).
  7834. * @type {boolean}
  7835. */
  7836. var isUsingScreenStream = false;
  7837. /**
  7838. * Indicates that switch stream operation is in progress and prevent from triggering new events.
  7839. * @type {boolean}
  7840. */
  7841. var switchInProgress = false;
  7842. /**
  7843. * Method used to get screen sharing stream.
  7844. *
  7845. * @type {function (stream_callback, failure_callback}
  7846. */
  7847. var obtainDesktopStream = null;
  7848. /**
  7849. * Flag used to cache desktop sharing enabled state. Do not use directly as it can be <tt>null</tt>.
  7850. * @type {null|boolean}
  7851. */
  7852. var _desktopSharingEnabled = null;
  7853. var EventEmitter = require("events");
  7854. var eventEmitter = new EventEmitter();
  7855. var DesktopSharingEventTypes = require("../../service/desktopsharing/DesktopSharingEventTypes");
  7856. /**
  7857. * Method obtains desktop stream from WebRTC 'screen' source.
  7858. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  7859. */
  7860. function obtainWebRTCScreen(streamCallback, failCallback) {
  7861. APP.RTC.getUserMediaWithConstraints(
  7862. ['screen'],
  7863. streamCallback,
  7864. failCallback
  7865. );
  7866. }
  7867. /**
  7868. * Constructs inline install URL for Chrome desktop streaming extension.
  7869. * The 'chromeExtensionId' must be defined in config.js.
  7870. * @returns {string}
  7871. */
  7872. function getWebStoreInstallUrl()
  7873. {
  7874. return "https://chrome.google.com/webstore/detail/" + config.chromeExtensionId;
  7875. }
  7876. /**
  7877. * Checks whether extension update is required.
  7878. * @param minVersion minimal required version
  7879. * @param extVersion current extension version
  7880. * @returns {boolean}
  7881. */
  7882. function isUpdateRequired(minVersion, extVersion)
  7883. {
  7884. try
  7885. {
  7886. var s1 = minVersion.split('.');
  7887. var s2 = extVersion.split('.');
  7888. var len = Math.max(s1.length, s2.length);
  7889. for (var i = 0; i < len; i++)
  7890. {
  7891. var n1 = 0,
  7892. n2 = 0;
  7893. if (i < s1.length)
  7894. n1 = parseInt(s1[i]);
  7895. if (i < s2.length)
  7896. n2 = parseInt(s2[i]);
  7897. if (isNaN(n1) || isNaN(n2))
  7898. {
  7899. return true;
  7900. }
  7901. else if (n1 !== n2)
  7902. {
  7903. return n1 > n2;
  7904. }
  7905. }
  7906. // will happen if boths version has identical numbers in
  7907. // their components (even if one of them is longer, has more components)
  7908. return false;
  7909. }
  7910. catch (e)
  7911. {
  7912. console.error("Failed to parse extension version", e);
  7913. APP.UI.messageHandler.showError('Error',
  7914. 'Error when trying to detect desktopsharing extension.');
  7915. return true;
  7916. }
  7917. }
  7918. function checkExtInstalled(isInstalledCallback) {
  7919. if (!chrome.runtime) {
  7920. // No API, so no extension for sure
  7921. isInstalledCallback(false);
  7922. return;
  7923. }
  7924. chrome.runtime.sendMessage(
  7925. config.chromeExtensionId,
  7926. { getVersion: true },
  7927. function (response) {
  7928. if (!response || !response.version) {
  7929. // Communication failure - assume that no endpoint exists
  7930. console.warn("Extension not installed?: " + chrome.runtime.lastError);
  7931. isInstalledCallback(false);
  7932. } else {
  7933. // Check installed extension version
  7934. var extVersion = response.version;
  7935. console.log('Extension version is: ' + extVersion);
  7936. var updateRequired = isUpdateRequired(config.minChromeExtVersion, extVersion);
  7937. if (updateRequired) {
  7938. alert(
  7939. 'Jitsi Desktop Streamer requires update. ' +
  7940. 'Changes will take effect after next Chrome restart.');
  7941. }
  7942. isInstalledCallback(!updateRequired);
  7943. }
  7944. }
  7945. );
  7946. }
  7947. function doGetStreamFromExtension(streamCallback, failCallback) {
  7948. // Sends 'getStream' msg to the extension. Extension id must be defined in the config.
  7949. chrome.runtime.sendMessage(
  7950. config.chromeExtensionId,
  7951. { getStream: true, sources: config.desktopSharingSources },
  7952. function (response) {
  7953. if (!response) {
  7954. failCallback(chrome.runtime.lastError);
  7955. return;
  7956. }
  7957. console.log("Response from extension: " + response);
  7958. if (response.streamId) {
  7959. APP.RTC.getUserMediaWithConstraints(
  7960. ['desktop'],
  7961. function (stream) {
  7962. streamCallback(stream);
  7963. },
  7964. failCallback,
  7965. null, null, null,
  7966. response.streamId);
  7967. } else {
  7968. failCallback("Extension failed to get the stream");
  7969. }
  7970. }
  7971. );
  7972. }
  7973. /**
  7974. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop' stream for returned stream token.
  7975. */
  7976. function obtainScreenFromExtension(streamCallback, failCallback) {
  7977. checkExtInstalled(
  7978. function (isInstalled) {
  7979. if (isInstalled) {
  7980. doGetStreamFromExtension(streamCallback, failCallback);
  7981. } else {
  7982. chrome.webstore.install(
  7983. getWebStoreInstallUrl(),
  7984. function (arg) {
  7985. console.log("Extension installed successfully", arg);
  7986. // We need to reload the page in order to get the access to chrome.runtime
  7987. window.location.reload(false);
  7988. },
  7989. function (arg) {
  7990. console.log("Failed to install the extension", arg);
  7991. failCallback(arg);
  7992. APP.UI.messageHandler.showError('Error',
  7993. 'Failed to install desktop sharing extension');
  7994. }
  7995. );
  7996. }
  7997. }
  7998. );
  7999. }
  8000. /**
  8001. * Call this method to toggle desktop sharing feature.
  8002. * @param method pass "ext" to use chrome extension for desktop capture(chrome extension required),
  8003. * pass "webrtc" to use WebRTC "screen" desktop source('chrome://flags/#enable-usermedia-screen-capture'
  8004. * must be enabled), pass any other string or nothing in order to disable this feature completely.
  8005. */
  8006. function setDesktopSharing(method) {
  8007. // Check if we are running chrome
  8008. if (!navigator.webkitGetUserMedia) {
  8009. obtainDesktopStream = null;
  8010. console.info("Desktop sharing disabled");
  8011. } else if (method == "ext") {
  8012. obtainDesktopStream = obtainScreenFromExtension;
  8013. console.info("Using Chrome extension for desktop sharing");
  8014. } else if (method == "webrtc") {
  8015. obtainDesktopStream = obtainWebRTCScreen;
  8016. console.info("Using Chrome WebRTC for desktop sharing");
  8017. }
  8018. // Reset enabled cache
  8019. _desktopSharingEnabled = null;
  8020. }
  8021. /**
  8022. * Initializes <link rel=chrome-webstore-item /> with extension id set in config.js to support inline installs.
  8023. * Host site must be selected as main website of published extension.
  8024. */
  8025. function initInlineInstalls()
  8026. {
  8027. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  8028. }
  8029. function getSwitchStreamFailed(error) {
  8030. console.error("Failed to obtain the stream to switch to", error);
  8031. switchInProgress = false;
  8032. }
  8033. function streamSwitchDone() {
  8034. switchInProgress = false;
  8035. eventEmitter.emit(
  8036. DesktopSharingEventTypes.SWITCHING_DONE,
  8037. isUsingScreenStream);
  8038. }
  8039. function newStreamCreated(stream)
  8040. {
  8041. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  8042. stream, isUsingScreenStream, streamSwitchDone);
  8043. }
  8044. module.exports = {
  8045. isUsingScreenStream: function () {
  8046. return isUsingScreenStream;
  8047. },
  8048. /**
  8049. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available and enabled.
  8050. */
  8051. isDesktopSharingEnabled: function () {
  8052. if (_desktopSharingEnabled === null) {
  8053. if (obtainDesktopStream === obtainScreenFromExtension) {
  8054. // Parse chrome version
  8055. var userAgent = navigator.userAgent.toLowerCase();
  8056. // We can assume that user agent is chrome, because it's enforced when 'ext' streaming method is set
  8057. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  8058. console.log("Chrome version" + userAgent, ver);
  8059. _desktopSharingEnabled = ver >= 34;
  8060. } else {
  8061. _desktopSharingEnabled = obtainDesktopStream === obtainWebRTCScreen;
  8062. }
  8063. }
  8064. return _desktopSharingEnabled;
  8065. },
  8066. init: function () {
  8067. setDesktopSharing(config.desktopSharing);
  8068. // Initialize Chrome extension inline installs
  8069. if (config.chromeExtensionId) {
  8070. initInlineInstalls();
  8071. }
  8072. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  8073. },
  8074. addListener: function(listener, type)
  8075. {
  8076. eventEmitter.on(type, listener);
  8077. },
  8078. removeListener: function (listener,type) {
  8079. eventEmitter.removeListener(type, listener);
  8080. },
  8081. /*
  8082. * Toggles screen sharing.
  8083. */
  8084. toggleScreenSharing: function () {
  8085. if (switchInProgress || !obtainDesktopStream) {
  8086. console.warn("Switch in progress or no method defined");
  8087. return;
  8088. }
  8089. switchInProgress = true;
  8090. if (!isUsingScreenStream)
  8091. {
  8092. // Switch to desktop stream
  8093. obtainDesktopStream(
  8094. function (stream) {
  8095. // We now use screen stream
  8096. isUsingScreenStream = true;
  8097. // Hook 'ended' event to restore camera when screen stream stops
  8098. stream.addEventListener('ended',
  8099. function (e) {
  8100. if (!switchInProgress && isUsingScreenStream) {
  8101. toggleScreenSharing();
  8102. }
  8103. }
  8104. );
  8105. newStreamCreated(stream);
  8106. },
  8107. getSwitchStreamFailed);
  8108. } else {
  8109. // Disable screen stream
  8110. APP.RTC.getUserMediaWithConstraints(
  8111. ['video'],
  8112. function (stream) {
  8113. // We are now using camera stream
  8114. isUsingScreenStream = false;
  8115. newStreamCreated(stream);
  8116. },
  8117. getSwitchStreamFailed, config.resolution || '360'
  8118. );
  8119. }
  8120. }
  8121. };
  8122. },{"../../service/desktopsharing/DesktopSharingEventTypes":87,"events":1}],37:[function(require,module,exports){
  8123. //maps keycode to character, id of popover for given function and function
  8124. var shortcuts = {
  8125. 67: {
  8126. character: "C",
  8127. id: "toggleChatPopover",
  8128. function: APP.UI.toggleChat
  8129. },
  8130. 70: {
  8131. character: "F",
  8132. id: "filmstripPopover",
  8133. function: APP.UI.toggleFilmStrip
  8134. },
  8135. 77: {
  8136. character: "M",
  8137. id: "mutePopover",
  8138. function: APP.UI.toggleAudio
  8139. },
  8140. 84: {
  8141. character: "T",
  8142. function: function() {
  8143. if(!APP.RTC.localAudio.isMuted()) {
  8144. APP.UI.toggleAudio();
  8145. }
  8146. }
  8147. },
  8148. 86: {
  8149. character: "V",
  8150. id: "toggleVideoPopover",
  8151. function: APP.UI.toggleVideo
  8152. }
  8153. };
  8154. var KeyboardShortcut = {
  8155. init: function () {
  8156. window.onkeyup = function(e) {
  8157. var keycode = e.which;
  8158. if(!($(":focus").is("input[type=text]") ||
  8159. $(":focus").is("input[type=password]") ||
  8160. $(":focus").is("textarea"))) {
  8161. if (typeof shortcuts[keycode] === "object") {
  8162. shortcuts[keycode].function();
  8163. }
  8164. else if (keycode >= "0".charCodeAt(0) &&
  8165. keycode <= "9".charCodeAt(0)) {
  8166. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  8167. }
  8168. //esc while the smileys are visible hides them
  8169. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  8170. APP.UI.toggleSmileys();
  8171. }
  8172. };
  8173. window.onkeydown = function(e) {
  8174. if(!($(":focus").is("input[type=text]") ||
  8175. $(":focus").is("input[type=password]") ||
  8176. $(":focus").is("textarea"))) {
  8177. if(e.which === "T".charCodeAt(0)) {
  8178. if(APP.RTC.localAudio.isMuted()) {
  8179. APP.UI.toggleAudio();
  8180. }
  8181. }
  8182. }
  8183. };
  8184. var self = this;
  8185. $('body').popover({ selector: '[data-toggle=popover]',
  8186. trigger: 'click hover',
  8187. content: function() {
  8188. return this.getAttribute("content") +
  8189. self.getShortcut(this.getAttribute("shortcut"));
  8190. }
  8191. });
  8192. },
  8193. /**
  8194. *
  8195. * @param id indicates the popover associated with the shortcut
  8196. * @returns {string} the keyboard shortcut used for the id given
  8197. */
  8198. getShortcut: function (id) {
  8199. for (var keycode in shortcuts) {
  8200. if (shortcuts.hasOwnProperty(keycode)) {
  8201. if (shortcuts[keycode].id === id) {
  8202. return " (" + shortcuts[keycode].character + ")";
  8203. }
  8204. }
  8205. }
  8206. return "";
  8207. }
  8208. };
  8209. module.exports = KeyboardShortcut;
  8210. },{}],38:[function(require,module,exports){
  8211. var email = '';
  8212. var displayName = '';
  8213. var userId;
  8214. function supportsLocalStorage() {
  8215. try {
  8216. return 'localStorage' in window && window.localStorage !== null;
  8217. } catch (e) {
  8218. console.log("localstorage is not supported");
  8219. return false;
  8220. }
  8221. }
  8222. function generateUniqueId() {
  8223. function _p8() {
  8224. return (Math.random().toString(16) + "000000000").substr(2, 8);
  8225. }
  8226. return _p8() + _p8() + _p8() + _p8();
  8227. }
  8228. if (supportsLocalStorage()) {
  8229. if (!window.localStorage.jitsiMeetId) {
  8230. window.localStorage.jitsiMeetId = generateUniqueId();
  8231. console.log("generated id", window.localStorage.jitsiMeetId);
  8232. }
  8233. userId = window.localStorage.jitsiMeetId || '';
  8234. email = window.localStorage.email || '';
  8235. displayName = window.localStorage.displayname || '';
  8236. } else {
  8237. console.log("local storage is not supported");
  8238. userId = generateUniqueId();
  8239. }
  8240. var Settings =
  8241. {
  8242. setDisplayName: function (newDisplayName) {
  8243. displayName = newDisplayName;
  8244. window.localStorage.displayname = displayName;
  8245. return displayName;
  8246. },
  8247. setEmail: function (newEmail)
  8248. {
  8249. email = newEmail;
  8250. window.localStorage.email = newEmail;
  8251. return email;
  8252. },
  8253. getSettings: function () {
  8254. return {
  8255. email: email,
  8256. displayName: displayName,
  8257. uid: userId
  8258. };
  8259. }
  8260. };
  8261. module.exports = Settings;
  8262. },{}],39:[function(require,module,exports){
  8263. /**
  8264. *
  8265. * @constructor
  8266. */
  8267. function SimulcastLogger(name, lvl) {
  8268. this.name = name;
  8269. this.lvl = lvl;
  8270. }
  8271. SimulcastLogger.prototype.log = function (text) {
  8272. if (this.lvl) {
  8273. console.log(text);
  8274. }
  8275. };
  8276. SimulcastLogger.prototype.info = function (text) {
  8277. if (this.lvl > 1) {
  8278. console.info(text);
  8279. }
  8280. };
  8281. SimulcastLogger.prototype.fine = function (text) {
  8282. if (this.lvl > 2) {
  8283. console.log(text);
  8284. }
  8285. };
  8286. SimulcastLogger.prototype.error = function (text) {
  8287. console.error(text);
  8288. };
  8289. module.exports = SimulcastLogger;
  8290. },{}],40:[function(require,module,exports){
  8291. var SimulcastLogger = require("./SimulcastLogger");
  8292. var SimulcastUtils = require("./SimulcastUtils");
  8293. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  8294. function SimulcastReceiver() {
  8295. this.simulcastUtils = new SimulcastUtils();
  8296. this.logger = new SimulcastLogger('SimulcastReceiver', 1);
  8297. }
  8298. SimulcastReceiver.prototype._remoteVideoSourceCache = '';
  8299. SimulcastReceiver.prototype._remoteMaps = {
  8300. msid2Quality: {},
  8301. ssrc2Msid: {},
  8302. msid2ssrc: {},
  8303. receivingVideoStreams: {}
  8304. };
  8305. SimulcastReceiver.prototype._cacheRemoteVideoSources = function (lines) {
  8306. this._remoteVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  8307. };
  8308. SimulcastReceiver.prototype._restoreRemoteVideoSources = function (lines) {
  8309. this.simulcastUtils._replaceVideoSources(lines, this._remoteVideoSourceCache);
  8310. };
  8311. SimulcastReceiver.prototype._ensureGoogConference = function (lines) {
  8312. var sb;
  8313. this.logger.info('Ensuring x-google-conference flag...')
  8314. if (this.simulcastUtils._indexOfArray('a=x-google-flag:conference', lines) === this.simulcastUtils._emptyCompoundIndex) {
  8315. // TODO(gp) do that for the audio as well as suggested by fippo.
  8316. // Add the google conference flag
  8317. sb = this.simulcastUtils._getVideoSources(lines);
  8318. sb = ['a=x-google-flag:conference'].concat(sb);
  8319. this.simulcastUtils._replaceVideoSources(lines, sb);
  8320. }
  8321. };
  8322. SimulcastReceiver.prototype._restoreSimulcastGroups = function (sb) {
  8323. this._restoreRemoteVideoSources(sb);
  8324. };
  8325. /**
  8326. * Restores the simulcast groups of the remote description. In
  8327. * transformRemoteDescription we remove those in order for the set remote
  8328. * description to succeed. The focus needs the signal the groups to new
  8329. * participants.
  8330. *
  8331. * @param desc
  8332. * @returns {*}
  8333. */
  8334. SimulcastReceiver.prototype.reverseTransformRemoteDescription = function (desc) {
  8335. var sb;
  8336. if (!this.simulcastUtils.isValidDescription(desc)) {
  8337. return desc;
  8338. }
  8339. if (config.enableSimulcast) {
  8340. sb = desc.sdp.split('\r\n');
  8341. this._restoreSimulcastGroups(sb);
  8342. desc = new RTCSessionDescription({
  8343. type: desc.type,
  8344. sdp: sb.join('\r\n')
  8345. });
  8346. }
  8347. return desc;
  8348. };
  8349. SimulcastUtils.prototype._ensureOrder = function (lines) {
  8350. var videoSources, sb;
  8351. videoSources = this.parseMedia(lines, ['video'])[0];
  8352. sb = this._compileVideoSources(videoSources);
  8353. this._replaceVideoSources(lines, sb);
  8354. };
  8355. SimulcastReceiver.prototype._updateRemoteMaps = function (lines) {
  8356. var remoteVideoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0],
  8357. videoSource, quality;
  8358. // (re) initialize the remote maps.
  8359. this._remoteMaps.msid2Quality = {};
  8360. this._remoteMaps.ssrc2Msid = {};
  8361. this._remoteMaps.msid2ssrc = {};
  8362. var self = this;
  8363. if (remoteVideoSources.groups && remoteVideoSources.groups.length !== 0) {
  8364. remoteVideoSources.groups.forEach(function (group) {
  8365. if (group.semantics === 'SIM' && group.ssrcs && group.ssrcs.length !== 0) {
  8366. quality = 0;
  8367. group.ssrcs.forEach(function (ssrc) {
  8368. videoSource = remoteVideoSources.sources[ssrc];
  8369. self._remoteMaps.msid2Quality[videoSource.msid] = quality++;
  8370. self._remoteMaps.ssrc2Msid[videoSource.ssrc] = videoSource.msid;
  8371. self._remoteMaps.msid2ssrc[videoSource.msid] = videoSource.ssrc;
  8372. });
  8373. }
  8374. });
  8375. }
  8376. };
  8377. SimulcastReceiver.prototype._setReceivingVideoStream = function (resource, ssrc) {
  8378. this._remoteMaps.receivingVideoStreams[resource] = ssrc;
  8379. };
  8380. /**
  8381. * Returns a stream with single video track, the one currently being
  8382. * received by this endpoint.
  8383. *
  8384. * @param stream the remote simulcast stream.
  8385. * @returns {webkitMediaStream}
  8386. */
  8387. SimulcastReceiver.prototype.getReceivingVideoStream = function (stream) {
  8388. var tracks, i, electedTrack, msid, quality = 0, receivingTrackId;
  8389. var self = this;
  8390. if (config.enableSimulcast) {
  8391. stream.getVideoTracks().some(function (track) {
  8392. return Object.keys(self._remoteMaps.receivingVideoStreams).some(function (resource) {
  8393. var ssrc = self._remoteMaps.receivingVideoStreams[resource];
  8394. var msid = self._remoteMaps.ssrc2Msid[ssrc];
  8395. if (msid == [stream.id, track.id].join(' ')) {
  8396. electedTrack = track;
  8397. return true;
  8398. }
  8399. });
  8400. });
  8401. if (!electedTrack) {
  8402. // we don't have an elected track, choose by initial quality.
  8403. tracks = stream.getVideoTracks();
  8404. for (i = 0; i < tracks.length; i++) {
  8405. msid = [stream.id, tracks[i].id].join(' ');
  8406. if (this._remoteMaps.msid2Quality[msid] === quality) {
  8407. electedTrack = tracks[i];
  8408. break;
  8409. }
  8410. }
  8411. // TODO(gp) if the initialQuality could not be satisfied, lower
  8412. // the requirement and try again.
  8413. }
  8414. }
  8415. return (electedTrack)
  8416. ? new webkitMediaStream([electedTrack])
  8417. : stream;
  8418. };
  8419. SimulcastReceiver.prototype.getReceivingSSRC = function (jid) {
  8420. var resource = Strophe.getResourceFromJid(jid);
  8421. var ssrc = this._remoteMaps.receivingVideoStreams[resource];
  8422. // If we haven't receiving a "changed" event yet, then we must be receiving
  8423. // low quality (that the sender always streams).
  8424. if(!ssrc)
  8425. {
  8426. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  8427. var remoteStream = remoteStreamObject.getOriginalStream();
  8428. var tracks = remoteStream.getVideoTracks();
  8429. if (tracks) {
  8430. for (var k = 0; k < tracks.length; k++) {
  8431. var track = tracks[k];
  8432. var msid = [remoteStream.id, track.id].join(' ');
  8433. var _ssrc = this._remoteMaps.msid2ssrc[msid];
  8434. var quality = this._remoteMaps.msid2Quality[msid];
  8435. if (quality == 0) {
  8436. ssrc = _ssrc;
  8437. }
  8438. }
  8439. }
  8440. }
  8441. return ssrc;
  8442. };
  8443. SimulcastReceiver.prototype.getReceivingVideoStreamBySSRC = function (ssrc)
  8444. {
  8445. var sid, electedStream;
  8446. var i, j, k;
  8447. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  8448. if(jid && APP.RTC.remoteStreams[jid])
  8449. {
  8450. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  8451. var remoteStream = remoteStreamObject.getOriginalStream();
  8452. var tracks = remoteStream.getVideoTracks();
  8453. if (tracks) {
  8454. for (k = 0; k < tracks.length; k++) {
  8455. var track = tracks[k];
  8456. var msid = [remoteStream.id, track.id].join(' ');
  8457. var tmp = this._remoteMaps.msid2ssrc[msid];
  8458. if (tmp == ssrc) {
  8459. electedStream = new webkitMediaStream([track]);
  8460. sid = remoteStreamObject.sid;
  8461. // stream found, stop.
  8462. break;
  8463. }
  8464. }
  8465. }
  8466. }
  8467. else
  8468. {
  8469. console.debug(APP.RTC.remoteStreams, jid, ssrc);
  8470. }
  8471. return {
  8472. sid: sid,
  8473. stream: electedStream
  8474. };
  8475. };
  8476. /**
  8477. * Gets the fully qualified msid (stream.id + track.id) associated to the
  8478. * SSRC.
  8479. *
  8480. * @param ssrc
  8481. * @returns {*}
  8482. */
  8483. SimulcastReceiver.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  8484. return this._remoteMaps.ssrc2Msid[ssrc];
  8485. };
  8486. /**
  8487. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  8488. * either gets confused and thinks this is an FID group or, if an FID group
  8489. * is already present, it fails to set the remote description.
  8490. *
  8491. * @param desc
  8492. * @returns {*}
  8493. */
  8494. SimulcastReceiver.prototype.transformRemoteDescription = function (desc) {
  8495. if (desc && desc.sdp) {
  8496. var sb = desc.sdp.split('\r\n');
  8497. this._updateRemoteMaps(sb);
  8498. this._cacheRemoteVideoSources(sb);
  8499. // NOTE(gp) this needs to be called after updateRemoteMaps because we
  8500. // need the simulcast group in the _updateRemoteMaps() method.
  8501. this.simulcastUtils._removeSimulcastGroup(sb);
  8502. if (desc.sdp.indexOf('a=ssrc-group:SIM') !== -1) {
  8503. // We don't need the goog conference flag if we're not doing
  8504. // simulcast.
  8505. this._ensureGoogConference(sb);
  8506. }
  8507. desc = new RTCSessionDescription({
  8508. type: desc.type,
  8509. sdp: sb.join('\r\n')
  8510. });
  8511. this.logger.fine(['Transformed remote description', desc.sdp].join(' '));
  8512. }
  8513. return desc;
  8514. };
  8515. module.exports = SimulcastReceiver;
  8516. },{"../../service/RTC/MediaStreamTypes":79,"./SimulcastLogger":39,"./SimulcastUtils":42}],41:[function(require,module,exports){
  8517. var SimulcastLogger = require("./SimulcastLogger");
  8518. var SimulcastUtils = require("./SimulcastUtils");
  8519. function SimulcastSender() {
  8520. this.simulcastUtils = new SimulcastUtils();
  8521. this.logger = new SimulcastLogger('SimulcastSender', 1);
  8522. }
  8523. SimulcastSender.prototype.displayedLocalVideoStream = null;
  8524. SimulcastSender.prototype._generateGuid = (function () {
  8525. function s4() {
  8526. return Math.floor((1 + Math.random()) * 0x10000)
  8527. .toString(16)
  8528. .substring(1);
  8529. }
  8530. return function () {
  8531. return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
  8532. s4() + '-' + s4() + s4() + s4();
  8533. };
  8534. }());
  8535. // Returns a random integer between min (included) and max (excluded)
  8536. // Using Math.round() gives a non-uniform distribution!
  8537. SimulcastSender.prototype._generateRandomSSRC = function () {
  8538. var min = 0, max = 0xffffffff;
  8539. return Math.floor(Math.random() * (max - min)) + min;
  8540. };
  8541. SimulcastSender.prototype.getLocalVideoStream = function () {
  8542. return (this.displayedLocalVideoStream != null)
  8543. ? this.displayedLocalVideoStream
  8544. // in case we have no simulcast at all, i.e. we didn't perform the GUM
  8545. : APP.RTC.localVideo.getOriginalStream();
  8546. };
  8547. function NativeSimulcastSender() {
  8548. SimulcastSender.call(this); // call the super constructor.
  8549. }
  8550. NativeSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8551. NativeSimulcastSender.prototype._localExplosionMap = {};
  8552. NativeSimulcastSender.prototype._isUsingScreenStream = false;
  8553. NativeSimulcastSender.prototype._localVideoSourceCache = '';
  8554. NativeSimulcastSender.prototype.reset = function () {
  8555. this._localExplosionMap = {};
  8556. this._isUsingScreenStream = APP.desktopsharing.isUsingScreenStream();
  8557. };
  8558. NativeSimulcastSender.prototype._cacheLocalVideoSources = function (lines) {
  8559. this._localVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  8560. };
  8561. NativeSimulcastSender.prototype._restoreLocalVideoSources = function (lines) {
  8562. this.simulcastUtils._replaceVideoSources(lines, this._localVideoSourceCache);
  8563. };
  8564. NativeSimulcastSender.prototype._appendSimulcastGroup = function (lines) {
  8565. var videoSources, ssrcGroup, simSSRC, numOfSubs = 2, i, sb, msid;
  8566. this.logger.info('Appending simulcast group...');
  8567. // Get the primary SSRC information.
  8568. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8569. // Start building the SIM SSRC group.
  8570. ssrcGroup = ['a=ssrc-group:SIM'];
  8571. // The video source buffer.
  8572. sb = [];
  8573. // Create the simulcast sub-streams.
  8574. for (i = 0; i < numOfSubs; i++) {
  8575. // TODO(gp) prevent SSRC collision.
  8576. simSSRC = this._generateRandomSSRC();
  8577. ssrcGroup.push(simSSRC);
  8578. if (videoSources.base) {
  8579. sb.splice.apply(sb, [sb.length, 0].concat(
  8580. [["a=ssrc:", simSSRC, " cname:", videoSources.base.cname].join(''),
  8581. ["a=ssrc:", simSSRC, " msid:", videoSources.base.msid].join('')]
  8582. ));
  8583. }
  8584. this.logger.info(['Generated substream ', i, ' with SSRC ', simSSRC, '.'].join(''));
  8585. }
  8586. // Add the group sim layers.
  8587. sb.splice(0, 0, ssrcGroup.join(' '))
  8588. this.simulcastUtils._replaceVideoSources(lines, sb);
  8589. };
  8590. // Does the actual patching.
  8591. NativeSimulcastSender.prototype._ensureSimulcastGroup = function (lines) {
  8592. this.logger.info('Ensuring simulcast group...');
  8593. if (this.simulcastUtils._indexOfArray('a=ssrc-group:SIM', lines) === this.simulcastUtils._emptyCompoundIndex) {
  8594. this._appendSimulcastGroup(lines);
  8595. this._cacheLocalVideoSources(lines);
  8596. } else {
  8597. // verify that the ssrcs participating in the SIM group are present
  8598. // in the SDP (needed for presence).
  8599. this._restoreLocalVideoSources(lines);
  8600. }
  8601. };
  8602. /**
  8603. * Produces a single stream with multiple tracks for local video sources.
  8604. *
  8605. * @param lines
  8606. * @private
  8607. */
  8608. NativeSimulcastSender.prototype._explodeSimulcastSenderSources = function (lines) {
  8609. var sb, msid, sid, tid, videoSources, self;
  8610. this.logger.info('Exploding local video sources...');
  8611. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8612. self = this;
  8613. if (videoSources.groups && videoSources.groups.length !== 0) {
  8614. videoSources.groups.forEach(function (group) {
  8615. if (group.semantics === 'SIM') {
  8616. group.ssrcs.forEach(function (ssrc) {
  8617. // Get the msid for this ssrc..
  8618. if (self._localExplosionMap[ssrc]) {
  8619. // .. either from the explosion map..
  8620. msid = self._localExplosionMap[ssrc];
  8621. } else {
  8622. // .. or generate a new one (msid).
  8623. sid = videoSources.sources[ssrc].msid
  8624. .substring(0, videoSources.sources[ssrc].msid.indexOf(' '));
  8625. tid = self._generateGuid();
  8626. msid = [sid, tid].join(' ');
  8627. self._localExplosionMap[ssrc] = msid;
  8628. }
  8629. // Assign it to the source object.
  8630. videoSources.sources[ssrc].msid = msid;
  8631. // TODO(gp) Change the msid of associated sources.
  8632. });
  8633. }
  8634. });
  8635. }
  8636. sb = this.simulcastUtils._compileVideoSources(videoSources);
  8637. this.simulcastUtils._replaceVideoSources(lines, sb);
  8638. };
  8639. /**
  8640. * GUM for simulcast.
  8641. *
  8642. * @param constraints
  8643. * @param success
  8644. * @param err
  8645. */
  8646. NativeSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8647. // There's nothing special to do for native simulcast, so just do a normal GUM.
  8648. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8649. success(hqStream);
  8650. }, err);
  8651. };
  8652. /**
  8653. * Prepares the local description for public usage (i.e. to be signaled
  8654. * through Jingle to the focus).
  8655. *
  8656. * @param desc
  8657. * @returns {RTCSessionDescription}
  8658. */
  8659. NativeSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8660. var sb;
  8661. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  8662. return desc;
  8663. }
  8664. sb = desc.sdp.split('\r\n');
  8665. this._explodeSimulcastSenderSources(sb);
  8666. desc = new RTCSessionDescription({
  8667. type: desc.type,
  8668. sdp: sb.join('\r\n')
  8669. });
  8670. this.logger.fine(['Exploded local video sources', desc.sdp].join(' '));
  8671. return desc;
  8672. };
  8673. /**
  8674. * Ensures that the simulcast group is present in the answer, _if_ native
  8675. * simulcast is enabled,
  8676. *
  8677. * @param desc
  8678. * @returns {*}
  8679. */
  8680. NativeSimulcastSender.prototype.transformAnswer = function (desc) {
  8681. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  8682. return desc;
  8683. }
  8684. var sb = desc.sdp.split('\r\n');
  8685. // Even if we have enabled native simulcasting previously
  8686. // (with a call to SLD with an appropriate SDP, for example),
  8687. // createAnswer seems to consistently generate incomplete SDP
  8688. // with missing SSRCS.
  8689. //
  8690. // So, subsequent calls to SLD will have missing SSRCS and presence
  8691. // won't have the complete list of SRCs.
  8692. this._ensureSimulcastGroup(sb);
  8693. desc = new RTCSessionDescription({
  8694. type: desc.type,
  8695. sdp: sb.join('\r\n')
  8696. });
  8697. this.logger.fine(['Transformed answer', desc.sdp].join(' '));
  8698. return desc;
  8699. };
  8700. /**
  8701. *
  8702. *
  8703. * @param desc
  8704. * @returns {*}
  8705. */
  8706. NativeSimulcastSender.prototype.transformLocalDescription = function (desc) {
  8707. return desc;
  8708. };
  8709. NativeSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  8710. // Nothing to do here, native simulcast does that auto-magically.
  8711. };
  8712. NativeSimulcastSender.prototype.constructor = NativeSimulcastSender;
  8713. function SimpleSimulcastSender() {
  8714. SimulcastSender.call(this);
  8715. }
  8716. SimpleSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8717. SimpleSimulcastSender.prototype.localStream = null;
  8718. SimpleSimulcastSender.prototype._localMaps = {
  8719. msids: [],
  8720. msid2ssrc: {}
  8721. };
  8722. /**
  8723. * Groups local video sources together in the ssrc-group:SIM group.
  8724. *
  8725. * @param lines
  8726. * @private
  8727. */
  8728. SimpleSimulcastSender.prototype._groupLocalVideoSources = function (lines) {
  8729. var sb, videoSources, ssrcs = [], ssrc;
  8730. this.logger.info('Grouping local video sources...');
  8731. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8732. for (ssrc in videoSources.sources) {
  8733. // jitsi-meet destroys/creates streams at various places causing
  8734. // the original local stream ids to change. The only thing that
  8735. // remains unchanged is the trackid.
  8736. this._localMaps.msid2ssrc[videoSources.sources[ssrc].msid.split(' ')[1]] = ssrc;
  8737. }
  8738. var self = this;
  8739. // TODO(gp) add only "free" sources.
  8740. this._localMaps.msids.forEach(function (msid) {
  8741. ssrcs.push(self._localMaps.msid2ssrc[msid]);
  8742. });
  8743. if (!videoSources.groups) {
  8744. videoSources.groups = [];
  8745. }
  8746. videoSources.groups.push({
  8747. 'semantics': 'SIM',
  8748. 'ssrcs': ssrcs
  8749. });
  8750. sb = this.simulcastUtils._compileVideoSources(videoSources);
  8751. this.simulcastUtils._replaceVideoSources(lines, sb);
  8752. };
  8753. /**
  8754. * GUM for simulcast.
  8755. *
  8756. * @param constraints
  8757. * @param success
  8758. * @param err
  8759. */
  8760. SimpleSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8761. // TODO(gp) what if we request a resolution not supported by the hardware?
  8762. // TODO(gp) make the lq stream configurable; although this wouldn't work with native simulcast
  8763. var lqConstraints = {
  8764. audio: false,
  8765. video: {
  8766. mandatory: {
  8767. maxWidth: 320,
  8768. maxHeight: 180,
  8769. maxFrameRate: 15
  8770. }
  8771. }
  8772. };
  8773. this.logger.info('HQ constraints: ', constraints);
  8774. this.logger.info('LQ constraints: ', lqConstraints);
  8775. // NOTE(gp) if we request the lq stream first webkitGetUserMedia
  8776. // fails randomly. Tested with Chrome 37. As fippo suggested, the
  8777. // reason appears to be that Chrome only acquires the cam once and
  8778. // then downscales the picture (https://code.google.com/p/chromium/issues/detail?id=346616#c11)
  8779. var self = this;
  8780. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8781. self.localStream = hqStream;
  8782. // reset local maps.
  8783. self._localMaps.msids = [];
  8784. self._localMaps.msid2ssrc = {};
  8785. // add hq trackid to local map
  8786. self._localMaps.msids.push(hqStream.getVideoTracks()[0].id);
  8787. navigator.webkitGetUserMedia(lqConstraints, function (lqStream) {
  8788. self.displayedLocalVideoStream = lqStream;
  8789. // NOTE(gp) The specification says Array.forEach() will visit
  8790. // the array elements in numeric order, and that it doesn't
  8791. // visit elements that don't exist.
  8792. // add lq trackid to local map
  8793. self._localMaps.msids.splice(0, 0, lqStream.getVideoTracks()[0].id);
  8794. self.localStream.addTrack(lqStream.getVideoTracks()[0]);
  8795. success(self.localStream);
  8796. }, err);
  8797. }, err);
  8798. };
  8799. /**
  8800. * Prepares the local description for public usage (i.e. to be signaled
  8801. * through Jingle to the focus).
  8802. *
  8803. * @param desc
  8804. * @returns {RTCSessionDescription}
  8805. */
  8806. SimpleSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8807. var sb;
  8808. if (!this.simulcastUtils.isValidDescription(desc)) {
  8809. return desc;
  8810. }
  8811. sb = desc.sdp.split('\r\n');
  8812. this._groupLocalVideoSources(sb);
  8813. desc = new RTCSessionDescription({
  8814. type: desc.type,
  8815. sdp: sb.join('\r\n')
  8816. });
  8817. this.logger.fine('Grouped local video sources');
  8818. this.logger.fine(desc.sdp);
  8819. return desc;
  8820. };
  8821. /**
  8822. * Ensures that the simulcast group is present in the answer, _if_ native
  8823. * simulcast is enabled,
  8824. *
  8825. * @param desc
  8826. * @returns {*}
  8827. */
  8828. SimpleSimulcastSender.prototype.transformAnswer = function (desc) {
  8829. return desc;
  8830. };
  8831. /**
  8832. *
  8833. *
  8834. * @param desc
  8835. * @returns {*}
  8836. */
  8837. SimpleSimulcastSender.prototype.transformLocalDescription = function (desc) {
  8838. var sb = desc.sdp.split('\r\n');
  8839. this.simulcastUtils._removeSimulcastGroup(sb);
  8840. desc = new RTCSessionDescription({
  8841. type: desc.type,
  8842. sdp: sb.join('\r\n')
  8843. });
  8844. this.logger.fine('Transformed local description');
  8845. this.logger.fine(desc.sdp);
  8846. return desc;
  8847. };
  8848. SimpleSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  8849. var trackid;
  8850. var self = this;
  8851. this.logger.log(['Requested to', enabled ? 'enable' : 'disable', ssrc].join(' '));
  8852. if (Object.keys(this._localMaps.msid2ssrc).some(function (tid) {
  8853. // Search for the track id that corresponds to the ssrc
  8854. if (self._localMaps.msid2ssrc[tid] == ssrc) {
  8855. trackid = tid;
  8856. return true;
  8857. }
  8858. }) && self.localStream.getVideoTracks().some(function (track) {
  8859. // Start/stop the track that corresponds to the track id
  8860. if (track.id === trackid) {
  8861. track.enabled = enabled;
  8862. return true;
  8863. }
  8864. })) {
  8865. this.logger.log([trackid, enabled ? 'enabled' : 'disabled'].join(' '));
  8866. $(document).trigger(enabled
  8867. ? 'simulcastlayerstarted'
  8868. : 'simulcastlayerstopped');
  8869. } else {
  8870. this.logger.error("I don't have a local stream with SSRC " + ssrc);
  8871. }
  8872. };
  8873. SimpleSimulcastSender.prototype.constructor = SimpleSimulcastSender;
  8874. function NoSimulcastSender() {
  8875. SimulcastSender.call(this);
  8876. }
  8877. NoSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8878. /**
  8879. * GUM for simulcast.
  8880. *
  8881. * @param constraints
  8882. * @param success
  8883. * @param err
  8884. */
  8885. NoSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8886. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8887. success(hqStream);
  8888. }, err);
  8889. };
  8890. /**
  8891. * Prepares the local description for public usage (i.e. to be signaled
  8892. * through Jingle to the focus).
  8893. *
  8894. * @param desc
  8895. * @returns {RTCSessionDescription}
  8896. */
  8897. NoSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8898. return desc;
  8899. };
  8900. /**
  8901. * Ensures that the simulcast group is present in the answer, _if_ native
  8902. * simulcast is enabled,
  8903. *
  8904. * @param desc
  8905. * @returns {*}
  8906. */
  8907. NoSimulcastSender.prototype.transformAnswer = function (desc) {
  8908. return desc;
  8909. };
  8910. /**
  8911. *
  8912. *
  8913. * @param desc
  8914. * @returns {*}
  8915. */
  8916. NoSimulcastSender.prototype.transformLocalDescription = function (desc) {
  8917. return desc;
  8918. };
  8919. NoSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  8920. };
  8921. NoSimulcastSender.prototype.constructor = NoSimulcastSender;
  8922. module.exports = {
  8923. "native": NativeSimulcastSender,
  8924. "no": NoSimulcastSender
  8925. }
  8926. },{"./SimulcastLogger":39,"./SimulcastUtils":42}],42:[function(require,module,exports){
  8927. var SimulcastLogger = require("./SimulcastLogger");
  8928. /**
  8929. *
  8930. * @constructor
  8931. */
  8932. function SimulcastUtils() {
  8933. this.logger = new SimulcastLogger("SimulcastUtils", 1);
  8934. }
  8935. /**
  8936. *
  8937. * @type {{}}
  8938. * @private
  8939. */
  8940. SimulcastUtils.prototype._emptyCompoundIndex = {};
  8941. /**
  8942. *
  8943. * @param lines
  8944. * @param videoSources
  8945. * @private
  8946. */
  8947. SimulcastUtils.prototype._replaceVideoSources = function (lines, videoSources) {
  8948. var i, inVideo = false, index = -1, howMany = 0;
  8949. this.logger.info('Replacing video sources...');
  8950. for (i = 0; i < lines.length; i++) {
  8951. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  8952. // Out of video.
  8953. break;
  8954. }
  8955. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  8956. // In video.
  8957. inVideo = true;
  8958. }
  8959. if (inVideo && (lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:'
  8960. || lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:')) {
  8961. if (index === -1) {
  8962. index = i;
  8963. }
  8964. howMany++;
  8965. }
  8966. }
  8967. // efficiency baby ;)
  8968. lines.splice.apply(lines,
  8969. [index, howMany].concat(videoSources));
  8970. };
  8971. SimulcastUtils.prototype.isValidDescription = function (desc)
  8972. {
  8973. return desc && desc != null
  8974. && desc.type && desc.type != ''
  8975. && desc.sdp && desc.sdp != '';
  8976. };
  8977. SimulcastUtils.prototype._getVideoSources = function (lines) {
  8978. var i, inVideo = false, sb = [];
  8979. this.logger.info('Getting video sources...');
  8980. for (i = 0; i < lines.length; i++) {
  8981. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  8982. // Out of video.
  8983. break;
  8984. }
  8985. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  8986. // In video.
  8987. inVideo = true;
  8988. }
  8989. if (inVideo && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  8990. // In SSRC.
  8991. sb.push(lines[i]);
  8992. }
  8993. if (inVideo && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  8994. sb.push(lines[i]);
  8995. }
  8996. }
  8997. return sb;
  8998. };
  8999. SimulcastUtils.prototype.parseMedia = function (lines, mediatypes) {
  9000. var i, res = [], type, cur_media, idx, ssrcs, cur_ssrc, ssrc,
  9001. ssrc_attribute, group, semantics, skip = true;
  9002. this.logger.info('Parsing media sources...');
  9003. for (i = 0; i < lines.length; i++) {
  9004. if (lines[i].substring(0, 'm='.length) === 'm=') {
  9005. type = lines[i]
  9006. .substr('m='.length, lines[i].indexOf(' ') - 'm='.length);
  9007. skip = mediatypes !== undefined && mediatypes.indexOf(type) === -1;
  9008. if (!skip) {
  9009. cur_media = {
  9010. 'type': type,
  9011. 'sources': {},
  9012. 'groups': []
  9013. };
  9014. res.push(cur_media);
  9015. }
  9016. } else if (!skip && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  9017. idx = lines[i].indexOf(' ');
  9018. ssrc = lines[i].substring('a=ssrc:'.length, idx);
  9019. if (cur_media.sources[ssrc] === undefined) {
  9020. cur_ssrc = {'ssrc': ssrc};
  9021. cur_media.sources[ssrc] = cur_ssrc;
  9022. }
  9023. ssrc_attribute = lines[i].substr(idx + 1).split(':', 2)[0];
  9024. cur_ssrc[ssrc_attribute] = lines[i].substr(idx + 1).split(':', 2)[1];
  9025. if (cur_media.base === undefined) {
  9026. cur_media.base = cur_ssrc;
  9027. }
  9028. } else if (!skip && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  9029. idx = lines[i].indexOf(' ');
  9030. semantics = lines[i].substr(0, idx).substr('a=ssrc-group:'.length);
  9031. ssrcs = lines[i].substr(idx).trim().split(' ');
  9032. group = {
  9033. 'semantics': semantics,
  9034. 'ssrcs': ssrcs
  9035. };
  9036. cur_media.groups.push(group);
  9037. } else if (!skip && (lines[i].substring(0, 'a=sendrecv'.length) === 'a=sendrecv' ||
  9038. lines[i].substring(0, 'a=recvonly'.length) === 'a=recvonly' ||
  9039. lines[i].substring(0, 'a=sendonly'.length) === 'a=sendonly' ||
  9040. lines[i].substring(0, 'a=inactive'.length) === 'a=inactive')) {
  9041. cur_media.direction = lines[i].substring('a='.length);
  9042. }
  9043. }
  9044. return res;
  9045. };
  9046. /**
  9047. * The _indexOfArray() method returns the first a CompoundIndex at which a
  9048. * given element can be found in the array, or _emptyCompoundIndex if it is
  9049. * not present.
  9050. *
  9051. * Example:
  9052. *
  9053. * _indexOfArray('3', [ 'this is line 1', 'this is line 2', 'this is line 3' ])
  9054. *
  9055. * returns {row: 2, column: 14}
  9056. *
  9057. * @param needle
  9058. * @param haystack
  9059. * @param start
  9060. * @returns {}
  9061. * @private
  9062. */
  9063. SimulcastUtils.prototype._indexOfArray = function (needle, haystack, start) {
  9064. var length = haystack.length, idx, i;
  9065. if (!start) {
  9066. start = 0;
  9067. }
  9068. for (i = start; i < length; i++) {
  9069. idx = haystack[i].indexOf(needle);
  9070. if (idx !== -1) {
  9071. return {row: i, column: idx};
  9072. }
  9073. }
  9074. return this._emptyCompoundIndex;
  9075. };
  9076. SimulcastUtils.prototype._removeSimulcastGroup = function (lines) {
  9077. var i;
  9078. for (i = lines.length - 1; i >= 0; i--) {
  9079. if (lines[i].indexOf('a=ssrc-group:SIM') !== -1) {
  9080. lines.splice(i, 1);
  9081. }
  9082. }
  9083. };
  9084. SimulcastUtils.prototype._compileVideoSources = function (videoSources) {
  9085. var sb = [], ssrc, addedSSRCs = [];
  9086. this.logger.info('Compiling video sources...');
  9087. // Add the groups
  9088. if (videoSources.groups && videoSources.groups.length !== 0) {
  9089. videoSources.groups.forEach(function (group) {
  9090. if (group.ssrcs && group.ssrcs.length !== 0) {
  9091. sb.push([['a=ssrc-group:', group.semantics].join(''), group.ssrcs.join(' ')].join(' '));
  9092. // if (group.semantics !== 'SIM') {
  9093. group.ssrcs.forEach(function (ssrc) {
  9094. addedSSRCs.push(ssrc);
  9095. sb.splice.apply(sb, [sb.length, 0].concat([
  9096. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  9097. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  9098. });
  9099. //}
  9100. }
  9101. });
  9102. }
  9103. // Then add any free sources.
  9104. if (videoSources.sources) {
  9105. for (ssrc in videoSources.sources) {
  9106. if (addedSSRCs.indexOf(ssrc) === -1) {
  9107. sb.splice.apply(sb, [sb.length, 0].concat([
  9108. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  9109. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  9110. }
  9111. }
  9112. }
  9113. return sb;
  9114. };
  9115. module.exports = SimulcastUtils;
  9116. },{"./SimulcastLogger":39}],43:[function(require,module,exports){
  9117. /*jslint plusplus: true */
  9118. /*jslint nomen: true*/
  9119. var SimulcastSender = require("./SimulcastSender");
  9120. var NoSimulcastSender = SimulcastSender["no"];
  9121. var NativeSimulcastSender = SimulcastSender["native"];
  9122. var SimulcastReceiver = require("./SimulcastReceiver");
  9123. var SimulcastUtils = require("./SimulcastUtils");
  9124. var RTCEvents = require("../../service/RTC/RTCEvents");
  9125. /**
  9126. *
  9127. * @constructor
  9128. */
  9129. function SimulcastManager() {
  9130. // Create the simulcast utilities.
  9131. this.simulcastUtils = new SimulcastUtils();
  9132. // Create remote simulcast.
  9133. this.simulcastReceiver = new SimulcastReceiver();
  9134. // Initialize local simulcast.
  9135. // TODO(gp) move into SimulcastManager.prototype.getUserMedia and take into
  9136. // account constraints.
  9137. if (!config.enableSimulcast) {
  9138. this.simulcastSender = new NoSimulcastSender();
  9139. } else {
  9140. var isChromium = window.chrome,
  9141. vendorName = window.navigator.vendor;
  9142. if(isChromium !== null && isChromium !== undefined
  9143. /* skip opera */
  9144. && vendorName === "Google Inc."
  9145. /* skip Chromium as suggested by fippo */
  9146. && !window.navigator.appVersion.match(/Chromium\//) ) {
  9147. var ver = parseInt(window.navigator.appVersion.match(/Chrome\/(\d+)\./)[1], 10);
  9148. if (ver > 37) {
  9149. this.simulcastSender = new NativeSimulcastSender();
  9150. } else {
  9151. this.simulcastSender = new NoSimulcastSender();
  9152. }
  9153. } else {
  9154. this.simulcastSender = new NoSimulcastSender();
  9155. }
  9156. }
  9157. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  9158. function (endpointSimulcastLayers) {
  9159. endpointSimulcastLayers.forEach(function (esl) {
  9160. var ssrc = esl.simulcastLayer.primarySSRC;
  9161. simulcast._setReceivingVideoStream(esl.endpoint, ssrc);
  9162. });
  9163. });
  9164. APP.RTC.addListener(RTCEvents.SIMULCAST_START, function (simulcastLayer) {
  9165. var ssrc = simulcastLayer.primarySSRC;
  9166. simulcast._setLocalVideoStreamEnabled(ssrc, true);
  9167. });
  9168. APP.RTC.addListener(RTCEvents.SIMULCAST_STOP, function (simulcastLayer) {
  9169. var ssrc = simulcastLayer.primarySSRC;
  9170. simulcast._setLocalVideoStreamEnabled(ssrc, false);
  9171. });
  9172. }
  9173. /**
  9174. * Restores the simulcast groups of the remote description. In
  9175. * transformRemoteDescription we remove those in order for the set remote
  9176. * description to succeed. The focus needs the signal the groups to new
  9177. * participants.
  9178. *
  9179. * @param desc
  9180. * @returns {*}
  9181. */
  9182. SimulcastManager.prototype.reverseTransformRemoteDescription = function (desc) {
  9183. return this.simulcastReceiver.reverseTransformRemoteDescription(desc);
  9184. };
  9185. /**
  9186. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  9187. * either gets confused and thinks this is an FID group or, if an FID group
  9188. * is already present, it fails to set the remote description.
  9189. *
  9190. * @param desc
  9191. * @returns {*}
  9192. */
  9193. SimulcastManager.prototype.transformRemoteDescription = function (desc) {
  9194. return this.simulcastReceiver.transformRemoteDescription(desc);
  9195. };
  9196. /**
  9197. * Gets the fully qualified msid (stream.id + track.id) associated to the
  9198. * SSRC.
  9199. *
  9200. * @param ssrc
  9201. * @returns {*}
  9202. */
  9203. SimulcastManager.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  9204. return this.simulcastReceiver.getRemoteVideoStreamIdBySSRC(ssrc);
  9205. };
  9206. /**
  9207. * Returns a stream with single video track, the one currently being
  9208. * received by this endpoint.
  9209. *
  9210. * @param stream the remote simulcast stream.
  9211. * @returns {webkitMediaStream}
  9212. */
  9213. SimulcastManager.prototype.getReceivingVideoStream = function (stream) {
  9214. return this.simulcastReceiver.getReceivingVideoStream(stream);
  9215. };
  9216. /**
  9217. *
  9218. *
  9219. * @param desc
  9220. * @returns {*}
  9221. */
  9222. SimulcastManager.prototype.transformLocalDescription = function (desc) {
  9223. return this.simulcastSender.transformLocalDescription(desc);
  9224. };
  9225. /**
  9226. *
  9227. * @returns {*}
  9228. */
  9229. SimulcastManager.prototype.getLocalVideoStream = function() {
  9230. return this.simulcastSender.getLocalVideoStream();
  9231. };
  9232. /**
  9233. * GUM for simulcast.
  9234. *
  9235. * @param constraints
  9236. * @param success
  9237. * @param err
  9238. */
  9239. SimulcastManager.prototype.getUserMedia = function (constraints, success, err) {
  9240. this.simulcastSender.getUserMedia(constraints, success, err);
  9241. };
  9242. /**
  9243. * Prepares the local description for public usage (i.e. to be signaled
  9244. * through Jingle to the focus).
  9245. *
  9246. * @param desc
  9247. * @returns {RTCSessionDescription}
  9248. */
  9249. SimulcastManager.prototype.reverseTransformLocalDescription = function (desc) {
  9250. return this.simulcastSender.reverseTransformLocalDescription(desc);
  9251. };
  9252. /**
  9253. * Ensures that the simulcast group is present in the answer, _if_ native
  9254. * simulcast is enabled,
  9255. *
  9256. * @param desc
  9257. * @returns {*}
  9258. */
  9259. SimulcastManager.prototype.transformAnswer = function (desc) {
  9260. return this.simulcastSender.transformAnswer(desc);
  9261. };
  9262. SimulcastManager.prototype.getReceivingSSRC = function (jid) {
  9263. return this.simulcastReceiver.getReceivingSSRC(jid);
  9264. };
  9265. SimulcastManager.prototype.getReceivingVideoStreamBySSRC = function (msid) {
  9266. return this.simulcastReceiver.getReceivingVideoStreamBySSRC(msid);
  9267. };
  9268. /**
  9269. *
  9270. * @param lines
  9271. * @param mediatypes
  9272. * @returns {*}
  9273. */
  9274. SimulcastManager.prototype.parseMedia = function(lines, mediatypes) {
  9275. var sb = lines.sdp.split('\r\n');
  9276. return this.simulcastUtils.parseMedia(sb, mediatypes);
  9277. };
  9278. SimulcastManager.prototype._setReceivingVideoStream = function(resource, ssrc) {
  9279. this.simulcastReceiver._setReceivingVideoStream(resource, ssrc);
  9280. };
  9281. SimulcastManager.prototype._setLocalVideoStreamEnabled = function(ssrc, enabled) {
  9282. this.simulcastSender._setLocalVideoStreamEnabled(ssrc, enabled);
  9283. };
  9284. SimulcastManager.prototype.resetSender = function() {
  9285. if (typeof this.simulcastSender.reset === 'function'){
  9286. this.simulcastSender.reset();
  9287. }
  9288. };
  9289. var simulcast = new SimulcastManager();
  9290. module.exports = simulcast;
  9291. },{"../../service/RTC/RTCEvents":81,"./SimulcastReceiver":40,"./SimulcastSender":41,"./SimulcastUtils":42}],44:[function(require,module,exports){
  9292. /**
  9293. * Provides statistics for the local stream.
  9294. */
  9295. /**
  9296. * Size of the webaudio analizer buffer.
  9297. * @type {number}
  9298. */
  9299. var WEBAUDIO_ANALIZER_FFT_SIZE = 2048;
  9300. /**
  9301. * Value of the webaudio analizer smoothing time parameter.
  9302. * @type {number}
  9303. */
  9304. var WEBAUDIO_ANALIZER_SMOOTING_TIME = 0.8;
  9305. /**
  9306. * Converts time domain data array to audio level.
  9307. * @param array the time domain data array.
  9308. * @returns {number} the audio level
  9309. */
  9310. function timeDomainDataToAudioLevel(samples) {
  9311. var maxVolume = 0;
  9312. var length = samples.length;
  9313. for (var i = 0; i < length; i++) {
  9314. if (maxVolume < samples[i])
  9315. maxVolume = samples[i];
  9316. }
  9317. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  9318. };
  9319. /**
  9320. * Animates audio level change
  9321. * @param newLevel the new audio level
  9322. * @param lastLevel the last audio level
  9323. * @returns {Number} the audio level to be set
  9324. */
  9325. function animateLevel(newLevel, lastLevel)
  9326. {
  9327. var value = 0;
  9328. var diff = lastLevel - newLevel;
  9329. if(diff > 0.2)
  9330. {
  9331. value = lastLevel - 0.2;
  9332. }
  9333. else if(diff < -0.4)
  9334. {
  9335. value = lastLevel + 0.4;
  9336. }
  9337. else
  9338. {
  9339. value = newLevel;
  9340. }
  9341. return parseFloat(value.toFixed(3));
  9342. }
  9343. /**
  9344. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  9345. *
  9346. * @param stream the local stream
  9347. * @param interval stats refresh interval given in ms.
  9348. * @param {function(LocalStatsCollector)} updateCallback the callback called on stats
  9349. * update.
  9350. * @constructor
  9351. */
  9352. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  9353. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  9354. this.stream = stream;
  9355. this.intervalId = null;
  9356. this.intervalMilis = interval;
  9357. this.eventEmitter = eventEmitter;
  9358. this.audioLevel = 0;
  9359. this.statisticsService = statisticsService;
  9360. }
  9361. /**
  9362. * Starts the collecting the statistics.
  9363. */
  9364. LocalStatsCollector.prototype.start = function () {
  9365. if (config.disableAudioLevels || !window.AudioContext)
  9366. return;
  9367. var context = new AudioContext();
  9368. var analyser = context.createAnalyser();
  9369. analyser.smoothingTimeConstant = WEBAUDIO_ANALIZER_SMOOTING_TIME;
  9370. analyser.fftSize = WEBAUDIO_ANALIZER_FFT_SIZE;
  9371. var source = context.createMediaStreamSource(this.stream);
  9372. source.connect(analyser);
  9373. var self = this;
  9374. this.intervalId = setInterval(
  9375. function () {
  9376. var array = new Uint8Array(analyser.frequencyBinCount);
  9377. analyser.getByteTimeDomainData(array);
  9378. var audioLevel = timeDomainDataToAudioLevel(array);
  9379. if(audioLevel != self.audioLevel) {
  9380. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  9381. self.eventEmitter.emit(
  9382. "statistics.audioLevel",
  9383. self.statisticsService.LOCAL_JID,
  9384. self.audioLevel);
  9385. }
  9386. },
  9387. this.intervalMilis
  9388. );
  9389. };
  9390. /**
  9391. * Stops collecting the statistics.
  9392. */
  9393. LocalStatsCollector.prototype.stop = function () {
  9394. if (this.intervalId) {
  9395. clearInterval(this.intervalId);
  9396. this.intervalId = null;
  9397. }
  9398. };
  9399. module.exports = LocalStatsCollector;
  9400. },{}],45:[function(require,module,exports){
  9401. /* global ssrc2jid */
  9402. /* jshint -W117 */
  9403. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  9404. /**
  9405. * Calculates packet lost percent using the number of lost packets and the
  9406. * number of all packet.
  9407. * @param lostPackets the number of lost packets
  9408. * @param totalPackets the number of all packets.
  9409. * @returns {number} packet loss percent
  9410. */
  9411. function calculatePacketLoss(lostPackets, totalPackets) {
  9412. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  9413. return 0;
  9414. return Math.round((lostPackets/totalPackets)*100);
  9415. }
  9416. function getStatValue(item, name) {
  9417. if(!keyMap[APP.RTC.getBrowserType()][name])
  9418. throw "The property isn't supported!";
  9419. var key = keyMap[APP.RTC.getBrowserType()][name];
  9420. return APP.RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_CHROME? item.stat(key) : item[key];
  9421. }
  9422. /**
  9423. * Peer statistics data holder.
  9424. * @constructor
  9425. */
  9426. function PeerStats()
  9427. {
  9428. this.ssrc2Loss = {};
  9429. this.ssrc2AudioLevel = {};
  9430. this.ssrc2bitrate = {};
  9431. this.ssrc2resolution = {};
  9432. }
  9433. /**
  9434. * The bandwidth
  9435. * @type {{}}
  9436. */
  9437. PeerStats.bandwidth = {};
  9438. /**
  9439. * The bit rate
  9440. * @type {{}}
  9441. */
  9442. PeerStats.bitrate = {};
  9443. /**
  9444. * The packet loss rate
  9445. * @type {{}}
  9446. */
  9447. PeerStats.packetLoss = null;
  9448. /**
  9449. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  9450. * represented by this instance.
  9451. * @param ssrc audio or video RTP stream SSRC.
  9452. * @param lossRate new packet loss rate value to be set.
  9453. */
  9454. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  9455. {
  9456. this.ssrc2Loss[ssrc] = lossRate;
  9457. };
  9458. /**
  9459. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  9460. * represented by this instance.
  9461. * @param ssrc audio or video RTP stream SSRC.
  9462. * @param resolution new resolution value to be set.
  9463. */
  9464. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  9465. {
  9466. if(resolution === null && this.ssrc2resolution[ssrc])
  9467. {
  9468. delete this.ssrc2resolution[ssrc];
  9469. }
  9470. else if(resolution !== null)
  9471. this.ssrc2resolution[ssrc] = resolution;
  9472. };
  9473. /**
  9474. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  9475. * represented by this instance.
  9476. * @param ssrc audio or video RTP stream SSRC.
  9477. * @param bitrate new bitrate value to be set.
  9478. */
  9479. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  9480. {
  9481. if(this.ssrc2bitrate[ssrc])
  9482. {
  9483. this.ssrc2bitrate[ssrc].download += bitrate.download;
  9484. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  9485. }
  9486. else {
  9487. this.ssrc2bitrate[ssrc] = bitrate;
  9488. }
  9489. };
  9490. /**
  9491. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  9492. * the stream which belongs to the peer represented by this instance.
  9493. * @param ssrc RTP stream SSRC for which current audio level value will be
  9494. * updated.
  9495. * @param audioLevel the new audio level value to be set. Value is truncated to
  9496. * fit the range from 0 to 1.
  9497. */
  9498. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  9499. {
  9500. // Range limit 0 - 1
  9501. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  9502. };
  9503. function formatAudioLevel(audioLevel) {
  9504. return Math.min(Math.max(audioLevel, 0), 1);
  9505. }
  9506. /**
  9507. * Array with the transport information.
  9508. * @type {Array}
  9509. */
  9510. PeerStats.transport = [];
  9511. /**
  9512. * <tt>StatsCollector</tt> registers for stats updates of given
  9513. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  9514. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  9515. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  9516. * instance as an event source.
  9517. *
  9518. * @param peerconnection webRTC peer connection object.
  9519. * @param interval stats refresh interval given in ms.
  9520. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  9521. * called on stats update.
  9522. * @constructor
  9523. */
  9524. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  9525. {
  9526. this.peerconnection = peerconnection;
  9527. this.baselineAudioLevelsReport = null;
  9528. this.currentAudioLevelsReport = null;
  9529. this.currentStatsReport = null;
  9530. this.baselineStatsReport = null;
  9531. this.audioLevelsIntervalId = null;
  9532. this.eventEmitter = eventEmitter;
  9533. /**
  9534. * Gather PeerConnection stats once every this many milliseconds.
  9535. */
  9536. this.GATHER_INTERVAL = 10000;
  9537. /**
  9538. * Log stats via the focus once every this many milliseconds.
  9539. */
  9540. this.LOG_INTERVAL = 60000;
  9541. /**
  9542. * Gather stats and store them in this.statsToBeLogged.
  9543. */
  9544. this.gatherStatsIntervalId = null;
  9545. /**
  9546. * Send the stats already saved in this.statsToBeLogged to be logged via
  9547. * the focus.
  9548. */
  9549. this.logStatsIntervalId = null;
  9550. /**
  9551. * Stores the statistics which will be send to the focus to be logged.
  9552. */
  9553. this.statsToBeLogged =
  9554. {
  9555. timestamps: [],
  9556. stats: {}
  9557. };
  9558. // Updates stats interval
  9559. this.audioLevelsIntervalMilis = audioLevelsInterval;
  9560. this.statsIntervalId = null;
  9561. this.statsIntervalMilis = statsInterval;
  9562. // Map of jids to PeerStats
  9563. this.jid2stats = {};
  9564. }
  9565. module.exports = StatsCollector;
  9566. /**
  9567. * Stops stats updates.
  9568. */
  9569. StatsCollector.prototype.stop = function () {
  9570. if (this.audioLevelsIntervalId) {
  9571. clearInterval(this.audioLevelsIntervalId);
  9572. this.audioLevelsIntervalId = null;
  9573. }
  9574. if (this.statsIntervalId)
  9575. {
  9576. clearInterval(this.statsIntervalId);
  9577. this.statsIntervalId = null;
  9578. }
  9579. if(this.logStatsIntervalId)
  9580. {
  9581. clearInterval(this.logStatsIntervalId);
  9582. this.logStatsIntervalId = null;
  9583. }
  9584. if(this.gatherStatsIntervalId)
  9585. {
  9586. clearInterval(this.gatherStatsIntervalId);
  9587. this.gatherStatsIntervalId = null;
  9588. }
  9589. };
  9590. /**
  9591. * Callback passed to <tt>getStats</tt> method.
  9592. * @param error an error that occurred on <tt>getStats</tt> call.
  9593. */
  9594. StatsCollector.prototype.errorCallback = function (error)
  9595. {
  9596. console.error("Get stats error", error);
  9597. this.stop();
  9598. };
  9599. /**
  9600. * Starts stats updates.
  9601. */
  9602. StatsCollector.prototype.start = function ()
  9603. {
  9604. var self = this;
  9605. if(!config.disableAudioLevels) {
  9606. console.debug("set audio levels interval");
  9607. this.audioLevelsIntervalId = setInterval(
  9608. function () {
  9609. // Interval updates
  9610. self.peerconnection.getStats(
  9611. function (report) {
  9612. var results = null;
  9613. if (!report || !report.result ||
  9614. typeof report.result != 'function') {
  9615. results = report;
  9616. }
  9617. else {
  9618. results = report.result();
  9619. }
  9620. //console.error("Got interval report", results);
  9621. self.currentAudioLevelsReport = results;
  9622. self.processAudioLevelReport();
  9623. self.baselineAudioLevelsReport =
  9624. self.currentAudioLevelsReport;
  9625. },
  9626. self.errorCallback
  9627. );
  9628. },
  9629. self.audioLevelsIntervalMilis
  9630. );
  9631. }
  9632. if(!config.disableStats) {
  9633. console.debug("set stats interval");
  9634. this.statsIntervalId = setInterval(
  9635. function () {
  9636. // Interval updates
  9637. self.peerconnection.getStats(
  9638. function (report) {
  9639. var results = null;
  9640. if (!report || !report.result ||
  9641. typeof report.result != 'function') {
  9642. //firefox
  9643. results = report;
  9644. }
  9645. else {
  9646. //chrome
  9647. results = report.result();
  9648. }
  9649. //console.error("Got interval report", results);
  9650. self.currentStatsReport = results;
  9651. try {
  9652. self.processStatsReport();
  9653. }
  9654. catch (e) {
  9655. console.error("Unsupported key:" + e, e);
  9656. }
  9657. self.baselineStatsReport = self.currentStatsReport;
  9658. },
  9659. self.errorCallback
  9660. );
  9661. },
  9662. self.statsIntervalMilis
  9663. );
  9664. }
  9665. if (config.logStats) {
  9666. this.gatherStatsIntervalId = setInterval(
  9667. function () {
  9668. self.peerconnection.getStats(
  9669. function (report) {
  9670. self.addStatsToBeLogged(report.result());
  9671. },
  9672. function () {
  9673. }
  9674. );
  9675. },
  9676. this.GATHER_INTERVAL
  9677. );
  9678. this.logStatsIntervalId = setInterval(
  9679. function() { self.logStats(); },
  9680. this.LOG_INTERVAL);
  9681. }
  9682. };
  9683. /**
  9684. * Converts the stats to the format used for logging, and saves the data in
  9685. * this.statsToBeLogged.
  9686. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  9687. */
  9688. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  9689. var self = this;
  9690. var num_records = this.statsToBeLogged.timestamps.length;
  9691. this.statsToBeLogged.timestamps.push(new Date().getTime());
  9692. reports.map(function (report) {
  9693. var stat = self.statsToBeLogged.stats[report.id];
  9694. if (!stat) {
  9695. stat = self.statsToBeLogged.stats[report.id] = {};
  9696. }
  9697. stat.type = report.type;
  9698. report.names().map(function (name) {
  9699. var values = stat[name];
  9700. if (!values) {
  9701. values = stat[name] = [];
  9702. }
  9703. while (values.length < num_records) {
  9704. values.push(null);
  9705. }
  9706. values.push(report.stat(name));
  9707. });
  9708. });
  9709. };
  9710. StatsCollector.prototype.logStats = function () {
  9711. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  9712. return;
  9713. // Reset the stats
  9714. this.statsToBeLogged.stats = {};
  9715. this.statsToBeLogged.timestamps = [];
  9716. };
  9717. var keyMap = {};
  9718. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  9719. "ssrc": "ssrc",
  9720. "packetsReceived": "packetsReceived",
  9721. "packetsLost": "packetsLost",
  9722. "packetsSent": "packetsSent",
  9723. "bytesReceived": "bytesReceived",
  9724. "bytesSent": "bytesSent"
  9725. };
  9726. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  9727. "receiveBandwidth": "googAvailableReceiveBandwidth",
  9728. "sendBandwidth": "googAvailableSendBandwidth",
  9729. "remoteAddress": "googRemoteAddress",
  9730. "transportType": "googTransportType",
  9731. "localAddress": "googLocalAddress",
  9732. "activeConnection": "googActiveConnection",
  9733. "ssrc": "ssrc",
  9734. "packetsReceived": "packetsReceived",
  9735. "packetsSent": "packetsSent",
  9736. "packetsLost": "packetsLost",
  9737. "bytesReceived": "bytesReceived",
  9738. "bytesSent": "bytesSent",
  9739. "googFrameHeightReceived": "googFrameHeightReceived",
  9740. "googFrameWidthReceived": "googFrameWidthReceived",
  9741. "googFrameHeightSent": "googFrameHeightSent",
  9742. "googFrameWidthSent": "googFrameWidthSent",
  9743. "audioInputLevel": "audioInputLevel",
  9744. "audioOutputLevel": "audioOutputLevel"
  9745. };
  9746. /**
  9747. * Stats processing logic.
  9748. */
  9749. StatsCollector.prototype.processStatsReport = function () {
  9750. if (!this.baselineStatsReport) {
  9751. return;
  9752. }
  9753. for (var idx in this.currentStatsReport) {
  9754. var now = this.currentStatsReport[idx];
  9755. try {
  9756. if (getStatValue(now, 'receiveBandwidth') ||
  9757. getStatValue(now, 'sendBandwidth')) {
  9758. PeerStats.bandwidth = {
  9759. "download": Math.round(
  9760. (getStatValue(now, 'receiveBandwidth')) / 1000),
  9761. "upload": Math.round(
  9762. (getStatValue(now, 'sendBandwidth')) / 1000)
  9763. };
  9764. }
  9765. }
  9766. catch(e){/*not supported*/}
  9767. if(now.type == 'googCandidatePair')
  9768. {
  9769. var ip, type, localIP, active;
  9770. try {
  9771. ip = getStatValue(now, 'remoteAddress');
  9772. type = getStatValue(now, "transportType");
  9773. localIP = getStatValue(now, "localAddress");
  9774. active = getStatValue(now, "activeConnection");
  9775. }
  9776. catch(e){/*not supported*/}
  9777. if(!ip || !type || !localIP || active != "true")
  9778. continue;
  9779. var addressSaved = false;
  9780. for(var i = 0; i < PeerStats.transport.length; i++)
  9781. {
  9782. if(PeerStats.transport[i].ip == ip &&
  9783. PeerStats.transport[i].type == type &&
  9784. PeerStats.transport[i].localip == localIP)
  9785. {
  9786. addressSaved = true;
  9787. }
  9788. }
  9789. if(addressSaved)
  9790. continue;
  9791. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  9792. continue;
  9793. }
  9794. if(now.type == "candidatepair")
  9795. {
  9796. if(now.state == "succeeded")
  9797. continue;
  9798. var local = this.currentStatsReport[now.localCandidateId];
  9799. var remote = this.currentStatsReport[now.remoteCandidateId];
  9800. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  9801. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  9802. }
  9803. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  9804. now.type != "inboundrtp") {
  9805. continue;
  9806. }
  9807. var before = this.baselineStatsReport[idx];
  9808. if (!before) {
  9809. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  9810. continue;
  9811. }
  9812. var ssrc = getStatValue(now, 'ssrc');
  9813. if(!ssrc)
  9814. continue;
  9815. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  9816. if (!jid && (Date.now() - now.timestamp) < 3000) {
  9817. console.warn("No jid for ssrc: " + ssrc);
  9818. continue;
  9819. }
  9820. var jidStats = this.jid2stats[jid];
  9821. if (!jidStats) {
  9822. jidStats = new PeerStats();
  9823. this.jid2stats[jid] = jidStats;
  9824. }
  9825. var isDownloadStream = true;
  9826. var key = 'packetsReceived';
  9827. if (!getStatValue(now, key))
  9828. {
  9829. isDownloadStream = false;
  9830. key = 'packetsSent';
  9831. if (!getStatValue(now, key))
  9832. {
  9833. console.warn("No packetsReceived nor packetSent stat found");
  9834. continue;
  9835. }
  9836. }
  9837. var packetsNow = getStatValue(now, key);
  9838. if(!packetsNow || packetsNow < 0)
  9839. packetsNow = 0;
  9840. var packetsBefore = getStatValue(before, key);
  9841. if(!packetsBefore || packetsBefore < 0)
  9842. packetsBefore = 0;
  9843. var packetRate = packetsNow - packetsBefore;
  9844. if(!packetRate || packetRate < 0)
  9845. packetRate = 0;
  9846. var currentLoss = getStatValue(now, 'packetsLost');
  9847. if(!currentLoss || currentLoss < 0)
  9848. currentLoss = 0;
  9849. var previousLoss = getStatValue(before, 'packetsLost');
  9850. if(!previousLoss || previousLoss < 0)
  9851. previousLoss = 0;
  9852. var lossRate = currentLoss - previousLoss;
  9853. if(!lossRate || lossRate < 0)
  9854. lossRate = 0;
  9855. var packetsTotal = (packetRate + lossRate);
  9856. jidStats.setSsrcLoss(ssrc,
  9857. {"packetsTotal": packetsTotal,
  9858. "packetsLost": lossRate,
  9859. "isDownloadStream": isDownloadStream});
  9860. var bytesReceived = 0, bytesSent = 0;
  9861. if(getStatValue(now, "bytesReceived"))
  9862. {
  9863. bytesReceived = getStatValue(now, "bytesReceived") -
  9864. getStatValue(before, "bytesReceived");
  9865. }
  9866. if(getStatValue(now, "bytesSent"))
  9867. {
  9868. bytesSent = getStatValue(now, "bytesSent") -
  9869. getStatValue(before, "bytesSent");
  9870. }
  9871. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  9872. if(bytesReceived <= 0 || time <= 0)
  9873. {
  9874. bytesReceived = 0;
  9875. }
  9876. else
  9877. {
  9878. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  9879. }
  9880. if(bytesSent <= 0 || time <= 0)
  9881. {
  9882. bytesSent = 0;
  9883. }
  9884. else
  9885. {
  9886. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  9887. }
  9888. jidStats.setSsrcBitrate(ssrc, {
  9889. "download": bytesReceived,
  9890. "upload": bytesSent});
  9891. var resolution = {height: null, width: null};
  9892. try {
  9893. if (getStatValue(now, "googFrameHeightReceived") &&
  9894. getStatValue(now, "googFrameWidthReceived")) {
  9895. resolution.height = getStatValue(now, "googFrameHeightReceived");
  9896. resolution.width = getStatValue(now, "googFrameWidthReceived");
  9897. }
  9898. else if (getStatValue(now, "googFrameHeightSent") &&
  9899. getStatValue(now, "googFrameWidthSent")) {
  9900. resolution.height = getStatValue(now, "googFrameHeightSent");
  9901. resolution.width = getStatValue(now, "googFrameWidthSent");
  9902. }
  9903. }
  9904. catch(e){/*not supported*/}
  9905. if(resolution.height && resolution.width)
  9906. {
  9907. jidStats.setSsrcResolution(ssrc, resolution);
  9908. }
  9909. else
  9910. {
  9911. jidStats.setSsrcResolution(ssrc, null);
  9912. }
  9913. }
  9914. var self = this;
  9915. // Jid stats
  9916. var totalPackets = {download: 0, upload: 0};
  9917. var lostPackets = {download: 0, upload: 0};
  9918. var bitrateDownload = 0;
  9919. var bitrateUpload = 0;
  9920. var resolutions = {};
  9921. Object.keys(this.jid2stats).forEach(
  9922. function (jid)
  9923. {
  9924. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  9925. function (ssrc)
  9926. {
  9927. var type = "upload";
  9928. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  9929. type = "download";
  9930. totalPackets[type] +=
  9931. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  9932. lostPackets[type] +=
  9933. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  9934. }
  9935. );
  9936. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  9937. function (ssrc) {
  9938. bitrateDownload +=
  9939. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  9940. bitrateUpload +=
  9941. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  9942. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  9943. }
  9944. );
  9945. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  9946. }
  9947. );
  9948. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  9949. PeerStats.packetLoss = {
  9950. total:
  9951. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  9952. totalPackets.download + totalPackets.upload),
  9953. download:
  9954. calculatePacketLoss(lostPackets.download, totalPackets.download),
  9955. upload:
  9956. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  9957. };
  9958. this.eventEmitter.emit("statistics.connectionstats",
  9959. {
  9960. "bitrate": PeerStats.bitrate,
  9961. "packetLoss": PeerStats.packetLoss,
  9962. "bandwidth": PeerStats.bandwidth,
  9963. "resolution": resolutions,
  9964. "transport": PeerStats.transport
  9965. });
  9966. PeerStats.transport = [];
  9967. };
  9968. /**
  9969. * Stats processing logic.
  9970. */
  9971. StatsCollector.prototype.processAudioLevelReport = function ()
  9972. {
  9973. if (!this.baselineAudioLevelsReport)
  9974. {
  9975. return;
  9976. }
  9977. for (var idx in this.currentAudioLevelsReport)
  9978. {
  9979. var now = this.currentAudioLevelsReport[idx];
  9980. if (now.type != 'ssrc')
  9981. {
  9982. continue;
  9983. }
  9984. var before = this.baselineAudioLevelsReport[idx];
  9985. if (!before)
  9986. {
  9987. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  9988. continue;
  9989. }
  9990. var ssrc = getStatValue(now, 'ssrc');
  9991. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  9992. if (!jid && (Date.now() - now.timestamp) < 3000)
  9993. {
  9994. console.warn("No jid for ssrc: " + ssrc);
  9995. continue;
  9996. }
  9997. var jidStats = this.jid2stats[jid];
  9998. if (!jidStats)
  9999. {
  10000. jidStats = new PeerStats();
  10001. this.jid2stats[jid] = jidStats;
  10002. }
  10003. // Audio level
  10004. var audioLevel = null;
  10005. try {
  10006. audioLevel = getStatValue(now, 'audioInputLevel');
  10007. if (!audioLevel)
  10008. audioLevel = getStatValue(now, 'audioOutputLevel');
  10009. }
  10010. catch(e) {/*not supported*/
  10011. console.warn("Audio Levels are not available in the statistics.");
  10012. clearInterval(this.audioLevelsIntervalId);
  10013. return;
  10014. }
  10015. if (audioLevel)
  10016. {
  10017. // TODO: can't find specs about what this value really is,
  10018. // but it seems to vary between 0 and around 32k.
  10019. audioLevel = formatAudioLevel(audioLevel / 32767);
  10020. var oldLevel = jidStats.ssrc2AudioLevel[ssrc];
  10021. if(jid != APP.xmpp.myJid() && (!oldLevel || oldLevel != audioLevel))
  10022. {
  10023. jidStats.ssrc2AudioLevel[ssrc] = audioLevel;
  10024. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  10025. }
  10026. }
  10027. }
  10028. };
  10029. },{"../../service/RTC/RTCBrowserType":80}],46:[function(require,module,exports){
  10030. /**
  10031. * Created by hristo on 8/4/14.
  10032. */
  10033. var LocalStats = require("./LocalStatsCollector.js");
  10034. var RTPStats = require("./RTPStatsCollector.js");
  10035. var EventEmitter = require("events");
  10036. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  10037. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10038. var eventEmitter = new EventEmitter();
  10039. var localStats = null;
  10040. var rtpStats = null;
  10041. function stopLocal()
  10042. {
  10043. if(localStats)
  10044. {
  10045. localStats.stop();
  10046. localStats = null;
  10047. }
  10048. }
  10049. function stopRemote()
  10050. {
  10051. if(rtpStats)
  10052. {
  10053. rtpStats.stop();
  10054. eventEmitter.emit("statistics.stop");
  10055. rtpStats = null;
  10056. }
  10057. }
  10058. function startRemoteStats (peerconnection) {
  10059. if(rtpStats)
  10060. {
  10061. rtpStats.stop();
  10062. rtpStats = null;
  10063. }
  10064. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  10065. rtpStats.start();
  10066. }
  10067. function onStreamCreated(stream)
  10068. {
  10069. if(stream.getOriginalStream().getAudioTracks().length === 0)
  10070. return;
  10071. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  10072. eventEmitter);
  10073. localStats.start();
  10074. }
  10075. function onDisposeConference(onUnload) {
  10076. stopRemote();
  10077. if(onUnload) {
  10078. stopLocal();
  10079. eventEmitter.removeAllListeners();
  10080. }
  10081. }
  10082. var statistics =
  10083. {
  10084. /**
  10085. * Indicates that this audio level is for local jid.
  10086. * @type {string}
  10087. */
  10088. LOCAL_JID: 'local',
  10089. addAudioLevelListener: function(listener)
  10090. {
  10091. eventEmitter.on("statistics.audioLevel", listener);
  10092. },
  10093. removeAudioLevelListener: function(listener)
  10094. {
  10095. eventEmitter.removeListener("statistics.audioLevel", listener);
  10096. },
  10097. addConnectionStatsListener: function(listener)
  10098. {
  10099. eventEmitter.on("statistics.connectionstats", listener);
  10100. },
  10101. removeConnectionStatsListener: function(listener)
  10102. {
  10103. eventEmitter.removeListener("statistics.connectionstats", listener);
  10104. },
  10105. addRemoteStatsStopListener: function(listener)
  10106. {
  10107. eventEmitter.on("statistics.stop", listener);
  10108. },
  10109. removeRemoteStatsStopListener: function(listener)
  10110. {
  10111. eventEmitter.removeListener("statistics.stop", listener);
  10112. },
  10113. stop: function () {
  10114. stopLocal();
  10115. stopRemote();
  10116. if(eventEmitter)
  10117. {
  10118. eventEmitter.removeAllListeners();
  10119. }
  10120. },
  10121. stopRemoteStatistics: function()
  10122. {
  10123. stopRemote();
  10124. },
  10125. start: function () {
  10126. APP.RTC.addStreamListener(onStreamCreated,
  10127. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  10128. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  10129. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  10130. startRemoteStats(event.peerconnection);
  10131. });
  10132. }
  10133. };
  10134. module.exports = statistics;
  10135. },{"../../service/RTC/StreamEventTypes.js":83,"../../service/xmpp/XMPPEvents":89,"./LocalStatsCollector.js":44,"./RTPStatsCollector.js":45,"events":1}],47:[function(require,module,exports){
  10136. var i18n = require("i18next-client");
  10137. var languages = require("../../service/translation/languages");
  10138. var DEFAULT_LANG = languages.EN;
  10139. var initialized = false;
  10140. var waitingForInit = [];
  10141. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  10142. return value.replace("__app__", interfaceConfig.APP_NAME);
  10143. });
  10144. var defaultOptions = {
  10145. detectLngQS: "lang",
  10146. useCookie: false,
  10147. fallbackLng: DEFAULT_LANG,
  10148. load: "unspecific",
  10149. resGetPath: 'lang/__ns__-__lng__.json',
  10150. ns: {
  10151. namespaces: ['main', 'languages'],
  10152. defaultNs: 'main'
  10153. },
  10154. lngWhitelist : languages.getLanguages(),
  10155. fallbackOnNull: true,
  10156. useDataAttrOptions: true,
  10157. app: interfaceConfig.APP_NAME,
  10158. getAsync: true,
  10159. customLoad: function(lng, ns, options, done) {
  10160. var resPath = "lang/__ns__-__lng__.json";
  10161. if(lng === languages.EN)
  10162. resPath = "lang/__ns__.json";
  10163. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  10164. initialized = false;
  10165. i18n.functions.ajax({
  10166. url: url,
  10167. success: function(data, status, xhr) {
  10168. i18n.functions.log('loaded: ' + url);
  10169. done(null, data);
  10170. },
  10171. error : function(xhr, status, error) {
  10172. if ((status && status == 200) ||
  10173. (xhr && xhr.status && xhr.status == 200)) {
  10174. // file loaded but invalid json, stop waste time !
  10175. i18n.functions.error('There is a typo in: ' + url);
  10176. } else if ((status && status == 404) ||
  10177. (xhr && xhr.status && xhr.status == 404)) {
  10178. i18n.functions.log('Does not exist: ' + url);
  10179. } else {
  10180. var theStatus = status ? status :
  10181. ((xhr && xhr.status) ? xhr.status : null);
  10182. i18n.functions.log(theStatus + ' when loading ' + url);
  10183. }
  10184. done(error, {});
  10185. },
  10186. dataType: "json",
  10187. async : options.getAsync
  10188. });
  10189. }
  10190. // options for caching
  10191. // useLocalStorage: true,
  10192. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  10193. };
  10194. function initCompleted(t)
  10195. {
  10196. initialized = true;
  10197. $("[data-i18n]").i18n();
  10198. for(var i = 0; i < waitingForInit.length; i++)
  10199. {
  10200. var obj = waitingForInit[i];
  10201. obj.callback(i18n.t(obj.key));
  10202. }
  10203. waitingForInit = [];
  10204. }
  10205. module.exports = {
  10206. init: function (lang) {
  10207. initialized = false;
  10208. var options = defaultOptions;
  10209. if(lang)
  10210. options.lng = lang;
  10211. i18n.init(options, initCompleted);
  10212. },
  10213. translateString: function (key, cb, defaultValue) {
  10214. if(!cb)
  10215. return i18n.t(key, defaultValue);
  10216. if(initialized)
  10217. {
  10218. cb(i18n.t(key, defaultValue));
  10219. }
  10220. else
  10221. {
  10222. waitingForInit.push({"callback": cb, "key": key});
  10223. }
  10224. },
  10225. setLanguage: function (lang) {
  10226. initialized = false;
  10227. if(!lang)
  10228. lang = DEFAULT_LANG;
  10229. i18n.setLng(lang, defaultOptions, initCompleted);
  10230. },
  10231. getCurrentLanguage: function () {
  10232. return i18n.lng();
  10233. },
  10234. translateElement: function (selector) {
  10235. selector.i18n();
  10236. }
  10237. };
  10238. },{"../../service/translation/languages":88,"i18next-client":62}],48:[function(require,module,exports){
  10239. /* jshint -W117 */
  10240. var TraceablePeerConnection = require("./TraceablePeerConnection");
  10241. var SDPDiffer = require("./SDPDiffer");
  10242. var SDPUtil = require("./SDPUtil");
  10243. var SDP = require("./SDP");
  10244. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  10245. // Jingle stuff
  10246. function JingleSession(me, sid, connection, service) {
  10247. this.me = me;
  10248. this.sid = sid;
  10249. this.connection = connection;
  10250. this.initiator = null;
  10251. this.responder = null;
  10252. this.isInitiator = null;
  10253. this.peerjid = null;
  10254. this.state = null;
  10255. this.localSDP = null;
  10256. this.remoteSDP = null;
  10257. this.relayedStreams = [];
  10258. this.startTime = null;
  10259. this.stopTime = null;
  10260. this.media_constraints = null;
  10261. this.pc_constraints = null;
  10262. this.ice_config = {};
  10263. this.drip_container = [];
  10264. this.service = service;
  10265. this.usetrickle = true;
  10266. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  10267. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  10268. this.hadstuncandidate = false;
  10269. this.hadturncandidate = false;
  10270. this.lasticecandidate = false;
  10271. this.statsinterval = null;
  10272. this.reason = null;
  10273. this.addssrc = [];
  10274. this.removessrc = [];
  10275. this.pendingop = null;
  10276. this.switchstreams = false;
  10277. this.wait = true;
  10278. this.localStreamsSSRC = null;
  10279. /**
  10280. * The indicator which determines whether the (local) video has been muted
  10281. * in response to a user command in contrast to an automatic decision made
  10282. * by the application logic.
  10283. */
  10284. this.videoMuteByUser = false;
  10285. }
  10286. //TODO: this array must be removed when firefox implement multistream support
  10287. JingleSession.notReceivedSSRCs = [];
  10288. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  10289. var self = this;
  10290. if (this.state !== null) {
  10291. console.error('attempt to initiate on session ' + this.sid +
  10292. 'in state ' + this.state);
  10293. return;
  10294. }
  10295. this.isInitiator = isInitiator;
  10296. this.state = 'pending';
  10297. this.initiator = isInitiator ? this.me : peerjid;
  10298. this.responder = !isInitiator ? this.me : peerjid;
  10299. this.peerjid = peerjid;
  10300. this.hadstuncandidate = false;
  10301. this.hadturncandidate = false;
  10302. this.lasticecandidate = false;
  10303. this.peerconnection
  10304. = new TraceablePeerConnection(
  10305. this.connection.jingle.ice_config,
  10306. this.connection.jingle.pc_constraints );
  10307. this.peerconnection.onicecandidate = function (event) {
  10308. self.sendIceCandidate(event.candidate);
  10309. };
  10310. this.peerconnection.onaddstream = function (event) {
  10311. console.log("REMOTE STREAM ADDED: " + event.stream + " - " + event.stream.id);
  10312. self.remoteStreamAdded(event);
  10313. };
  10314. this.peerconnection.onremovestream = function (event) {
  10315. // Remove the stream from remoteStreams
  10316. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  10317. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  10318. };
  10319. this.peerconnection.onsignalingstatechange = function (event) {
  10320. if (!(self && self.peerconnection)) return;
  10321. };
  10322. this.peerconnection.oniceconnectionstatechange = function (event) {
  10323. if (!(self && self.peerconnection)) return;
  10324. switch (self.peerconnection.iceConnectionState) {
  10325. case 'connected':
  10326. this.startTime = new Date();
  10327. break;
  10328. case 'disconnected':
  10329. this.stopTime = new Date();
  10330. break;
  10331. }
  10332. onIceConnectionStateChange(self.sid, self);
  10333. };
  10334. // add any local and relayed stream
  10335. APP.RTC.localStreams.forEach(function(stream) {
  10336. self.peerconnection.addStream(stream.getOriginalStream());
  10337. });
  10338. this.relayedStreams.forEach(function(stream) {
  10339. self.peerconnection.addStream(stream);
  10340. });
  10341. };
  10342. function onIceConnectionStateChange(sid, session) {
  10343. switch (session.peerconnection.iceConnectionState) {
  10344. case 'checking':
  10345. session.timeChecking = (new Date()).getTime();
  10346. session.firstconnect = true;
  10347. break;
  10348. case 'completed': // on caller side
  10349. case 'connected':
  10350. if (session.firstconnect) {
  10351. session.firstconnect = false;
  10352. var metadata = {};
  10353. metadata.setupTime
  10354. = (new Date()).getTime() - session.timeChecking;
  10355. session.peerconnection.getStats(function (res) {
  10356. if(res && res.result) {
  10357. res.result().forEach(function (report) {
  10358. if (report.type == 'googCandidatePair' &&
  10359. report.stat('googActiveConnection') == 'true') {
  10360. metadata.localCandidateType
  10361. = report.stat('googLocalCandidateType');
  10362. metadata.remoteCandidateType
  10363. = report.stat('googRemoteCandidateType');
  10364. // log pair as well so we can get nice pie
  10365. // charts
  10366. metadata.candidatePair
  10367. = report.stat('googLocalCandidateType') +
  10368. ';' +
  10369. report.stat('googRemoteCandidateType');
  10370. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  10371. {
  10372. metadata.ipv6 = true;
  10373. }
  10374. }
  10375. });
  10376. }
  10377. });
  10378. }
  10379. break;
  10380. }
  10381. }
  10382. JingleSession.prototype.accept = function () {
  10383. var self = this;
  10384. this.state = 'active';
  10385. var pranswer = this.peerconnection.localDescription;
  10386. if (!pranswer || pranswer.type != 'pranswer') {
  10387. return;
  10388. }
  10389. console.log('going from pranswer to answer');
  10390. if (this.usetrickle) {
  10391. // remove candidates already sent from session-accept
  10392. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  10393. for (var i = 0; i < lines.length; i++) {
  10394. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  10395. }
  10396. }
  10397. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  10398. // FIXME: change any inactive to sendrecv or whatever they were originally
  10399. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  10400. }
  10401. pranswer = APP.simulcast.reverseTransformLocalDescription(pranswer);
  10402. var prsdp = new SDP(pranswer.sdp);
  10403. var accept = $iq({to: this.peerjid,
  10404. type: 'set'})
  10405. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10406. action: 'session-accept',
  10407. initiator: this.initiator,
  10408. responder: this.responder,
  10409. sid: this.sid });
  10410. prsdp.toJingle(accept, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10411. var sdp = this.peerconnection.localDescription.sdp;
  10412. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  10413. // FIXME: change any inactive to sendrecv or whatever they were originally
  10414. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  10415. }
  10416. var self = this;
  10417. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  10418. function () {
  10419. //console.log('setLocalDescription success');
  10420. self.setLocalDescription();
  10421. self.connection.sendIQ(accept,
  10422. function () {
  10423. var ack = {};
  10424. ack.source = 'answer';
  10425. $(document).trigger('ack.jingle', [self.sid, ack]);
  10426. },
  10427. function (stanza) {
  10428. var error = ($(stanza).find('error').length) ? {
  10429. code: $(stanza).find('error').attr('code'),
  10430. reason: $(stanza).find('error :first')[0].tagName
  10431. }:{};
  10432. error.source = 'answer';
  10433. JingleSession.onJingleError(self.sid, error);
  10434. },
  10435. 10000);
  10436. },
  10437. function (e) {
  10438. console.error('setLocalDescription failed', e);
  10439. }
  10440. );
  10441. };
  10442. JingleSession.prototype.terminate = function (reason) {
  10443. this.state = 'ended';
  10444. this.reason = reason;
  10445. this.peerconnection.close();
  10446. if (this.statsinterval !== null) {
  10447. window.clearInterval(this.statsinterval);
  10448. this.statsinterval = null;
  10449. }
  10450. };
  10451. JingleSession.prototype.active = function () {
  10452. return this.state == 'active';
  10453. };
  10454. JingleSession.prototype.sendIceCandidate = function (candidate) {
  10455. var self = this;
  10456. if (candidate && !this.lasticecandidate) {
  10457. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  10458. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  10459. if (!(ice && jcand)) {
  10460. console.error('failed to get ice && jcand');
  10461. return;
  10462. }
  10463. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10464. if (jcand.type === 'srflx') {
  10465. this.hadstuncandidate = true;
  10466. } else if (jcand.type === 'relay') {
  10467. this.hadturncandidate = true;
  10468. }
  10469. if (this.usetrickle) {
  10470. if (this.usedrip) {
  10471. if (this.drip_container.length === 0) {
  10472. // start 20ms callout
  10473. window.setTimeout(function () {
  10474. if (self.drip_container.length === 0) return;
  10475. self.sendIceCandidates(self.drip_container);
  10476. self.drip_container = [];
  10477. }, 20);
  10478. }
  10479. this.drip_container.push(candidate);
  10480. return;
  10481. } else {
  10482. self.sendIceCandidate([candidate]);
  10483. }
  10484. }
  10485. } else {
  10486. //console.log('sendIceCandidate: last candidate.');
  10487. if (!this.usetrickle) {
  10488. //console.log('should send full offer now...');
  10489. var init = $iq({to: this.peerjid,
  10490. type: 'set'})
  10491. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10492. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  10493. initiator: this.initiator,
  10494. sid: this.sid});
  10495. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  10496. var self = this;
  10497. var sendJingle = function (ssrc) {
  10498. if(!ssrc)
  10499. ssrc = {};
  10500. self.localSDP.toJingle(init, self.initiator == self.me ? 'initiator' : 'responder', ssrc);
  10501. self.connection.sendIQ(init,
  10502. function () {
  10503. //console.log('session initiate ack');
  10504. var ack = {};
  10505. ack.source = 'offer';
  10506. $(document).trigger('ack.jingle', [self.sid, ack]);
  10507. },
  10508. function (stanza) {
  10509. self.state = 'error';
  10510. self.peerconnection.close();
  10511. var error = ($(stanza).find('error').length) ? {
  10512. code: $(stanza).find('error').attr('code'),
  10513. reason: $(stanza).find('error :first')[0].tagName,
  10514. }:{};
  10515. error.source = 'offer';
  10516. JingleSession.onJingleError(self.sid, error);
  10517. },
  10518. 10000);
  10519. }
  10520. sendJingle();
  10521. }
  10522. this.lasticecandidate = true;
  10523. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  10524. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  10525. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  10526. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  10527. }
  10528. }
  10529. };
  10530. JingleSession.prototype.sendIceCandidates = function (candidates) {
  10531. console.log('sendIceCandidates', candidates);
  10532. var cand = $iq({to: this.peerjid, type: 'set'})
  10533. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10534. action: 'transport-info',
  10535. initiator: this.initiator,
  10536. sid: this.sid});
  10537. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  10538. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  10539. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  10540. if (cands.length > 0) {
  10541. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  10542. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10543. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  10544. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  10545. }).c('transport', ice);
  10546. for (var i = 0; i < cands.length; i++) {
  10547. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  10548. }
  10549. // add fingerprint
  10550. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  10551. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  10552. tmp.required = true;
  10553. cand.c(
  10554. 'fingerprint',
  10555. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  10556. .t(tmp.fingerprint);
  10557. delete tmp.fingerprint;
  10558. cand.attrs(tmp);
  10559. cand.up();
  10560. }
  10561. cand.up(); // transport
  10562. cand.up(); // content
  10563. }
  10564. }
  10565. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  10566. //console.log('was this the last candidate', this.lasticecandidate);
  10567. this.connection.sendIQ(cand,
  10568. function () {
  10569. var ack = {};
  10570. ack.source = 'transportinfo';
  10571. $(document).trigger('ack.jingle', [this.sid, ack]);
  10572. },
  10573. function (stanza) {
  10574. var error = ($(stanza).find('error').length) ? {
  10575. code: $(stanza).find('error').attr('code'),
  10576. reason: $(stanza).find('error :first')[0].tagName,
  10577. }:{};
  10578. error.source = 'transportinfo';
  10579. JingleSession.onJingleError(this.sid, error);
  10580. },
  10581. 10000);
  10582. };
  10583. JingleSession.prototype.sendOffer = function () {
  10584. //console.log('sendOffer...');
  10585. var self = this;
  10586. this.peerconnection.createOffer(function (sdp) {
  10587. self.createdOffer(sdp);
  10588. },
  10589. function (e) {
  10590. console.error('createOffer failed', e);
  10591. },
  10592. this.media_constraints
  10593. );
  10594. };
  10595. JingleSession.prototype.createdOffer = function (sdp) {
  10596. //console.log('createdOffer', sdp);
  10597. var self = this;
  10598. this.localSDP = new SDP(sdp.sdp);
  10599. //this.localSDP.mangle();
  10600. var sendJingle = function () {
  10601. var init = $iq({to: this.peerjid,
  10602. type: 'set'})
  10603. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10604. action: 'session-initiate',
  10605. initiator: this.initiator,
  10606. sid: this.sid});
  10607. self.localSDP.toJingle(init, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10608. self.connection.sendIQ(init,
  10609. function () {
  10610. var ack = {};
  10611. ack.source = 'offer';
  10612. $(document).trigger('ack.jingle', [self.sid, ack]);
  10613. },
  10614. function (stanza) {
  10615. self.state = 'error';
  10616. self.peerconnection.close();
  10617. var error = ($(stanza).find('error').length) ? {
  10618. code: $(stanza).find('error').attr('code'),
  10619. reason: $(stanza).find('error :first')[0].tagName,
  10620. }:{};
  10621. error.source = 'offer';
  10622. JingleSession.onJingleError(self.sid, error);
  10623. },
  10624. 10000);
  10625. }
  10626. sdp.sdp = this.localSDP.raw;
  10627. this.peerconnection.setLocalDescription(sdp,
  10628. function () {
  10629. if(self.usetrickle)
  10630. {
  10631. sendJingle();
  10632. }
  10633. self.setLocalDescription();
  10634. //console.log('setLocalDescription success');
  10635. },
  10636. function (e) {
  10637. console.error('setLocalDescription failed', e);
  10638. }
  10639. );
  10640. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  10641. for (var i = 0; i < cands.length; i++) {
  10642. var cand = SDPUtil.parse_icecandidate(cands[i]);
  10643. if (cand.type == 'srflx') {
  10644. this.hadstuncandidate = true;
  10645. } else if (cand.type == 'relay') {
  10646. this.hadturncandidate = true;
  10647. }
  10648. }
  10649. };
  10650. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  10651. //console.log('setting remote description... ', desctype);
  10652. this.remoteSDP = new SDP('');
  10653. this.remoteSDP.fromJingle(elem);
  10654. if (this.peerconnection.remoteDescription !== null) {
  10655. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  10656. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  10657. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  10658. for (var i = 0; i < pranswer.media.length; i++) {
  10659. // make sure we have ice ufrag and pwd
  10660. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  10661. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  10662. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  10663. } else {
  10664. console.warn('no ice ufrag?');
  10665. }
  10666. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  10667. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  10668. } else {
  10669. console.warn('no ice pwd?');
  10670. }
  10671. }
  10672. // copy over candidates
  10673. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  10674. for (var j = 0; j < lines.length; j++) {
  10675. this.remoteSDP.media[i] += lines[j] + '\r\n';
  10676. }
  10677. }
  10678. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  10679. }
  10680. }
  10681. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  10682. this.peerconnection.setRemoteDescription(remotedesc,
  10683. function () {
  10684. //console.log('setRemoteDescription success');
  10685. },
  10686. function (e) {
  10687. console.error('setRemoteDescription error', e);
  10688. JingleSession.onJingleFatalError(self, e);
  10689. }
  10690. );
  10691. };
  10692. JingleSession.prototype.addIceCandidate = function (elem) {
  10693. var self = this;
  10694. if (this.peerconnection.signalingState == 'closed') {
  10695. return;
  10696. }
  10697. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  10698. console.log('trickle ice candidate arriving before session accept...');
  10699. // create a PRANSWER for setRemoteDescription
  10700. if (!this.remoteSDP) {
  10701. var cobbled = 'v=0\r\n' +
  10702. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  10703. 's=-\r\n' +
  10704. 't=0 0\r\n';
  10705. // first, take some things from the local description
  10706. for (var i = 0; i < this.localSDP.media.length; i++) {
  10707. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  10708. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  10709. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  10710. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  10711. }
  10712. cobbled += 'a=inactive\r\n';
  10713. }
  10714. this.remoteSDP = new SDP(cobbled);
  10715. }
  10716. // then add things like ice and dtls from remote candidate
  10717. elem.each(function () {
  10718. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  10719. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10720. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10721. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  10722. var tmp = $(this).find('transport');
  10723. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  10724. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  10725. tmp = $(this).find('transport>fingerprint');
  10726. if (tmp.length) {
  10727. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  10728. } else {
  10729. console.log('no dtls fingerprint (webrtc issue #1718?)');
  10730. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  10731. }
  10732. break;
  10733. }
  10734. }
  10735. }
  10736. });
  10737. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  10738. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  10739. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  10740. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  10741. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  10742. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  10743. }).length == this.remoteSDP.media.length;
  10744. if (iscomplete) {
  10745. console.log('setting pranswer');
  10746. try {
  10747. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  10748. function() {
  10749. },
  10750. function(e) {
  10751. console.log('setRemoteDescription pranswer failed', e.toString());
  10752. });
  10753. } catch (e) {
  10754. console.error('setting pranswer failed', e);
  10755. }
  10756. } else {
  10757. //console.log('not yet setting pranswer');
  10758. }
  10759. }
  10760. // operate on each content element
  10761. elem.each(function () {
  10762. // would love to deactivate this, but firefox still requires it
  10763. var idx = -1;
  10764. var i;
  10765. for (i = 0; i < self.remoteSDP.media.length; i++) {
  10766. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10767. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10768. idx = i;
  10769. break;
  10770. }
  10771. }
  10772. if (idx == -1) { // fall back to localdescription
  10773. for (i = 0; i < self.localSDP.media.length; i++) {
  10774. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10775. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10776. idx = i;
  10777. break;
  10778. }
  10779. }
  10780. }
  10781. var name = $(this).attr('name');
  10782. // TODO: check ice-pwd and ice-ufrag?
  10783. $(this).find('transport>candidate').each(function () {
  10784. var line, candidate;
  10785. line = SDPUtil.candidateFromJingle(this);
  10786. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  10787. sdpMid: name,
  10788. candidate: line});
  10789. try {
  10790. self.peerconnection.addIceCandidate(candidate);
  10791. } catch (e) {
  10792. console.error('addIceCandidate failed', e.toString(), line);
  10793. }
  10794. });
  10795. });
  10796. };
  10797. JingleSession.prototype.sendAnswer = function (provisional) {
  10798. //console.log('createAnswer', provisional);
  10799. var self = this;
  10800. this.peerconnection.createAnswer(
  10801. function (sdp) {
  10802. self.createdAnswer(sdp, provisional);
  10803. },
  10804. function (e) {
  10805. console.error('createAnswer failed', e);
  10806. },
  10807. this.media_constraints
  10808. );
  10809. };
  10810. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  10811. //console.log('createAnswer callback');
  10812. var self = this;
  10813. this.localSDP = new SDP(sdp.sdp);
  10814. //this.localSDP.mangle();
  10815. this.usepranswer = provisional === true;
  10816. if (this.usetrickle) {
  10817. if (this.usepranswer) {
  10818. sdp.type = 'pranswer';
  10819. for (var i = 0; i < this.localSDP.media.length; i++) {
  10820. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  10821. }
  10822. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  10823. }
  10824. }
  10825. var self = this;
  10826. var sendJingle = function (ssrcs) {
  10827. var accept = $iq({to: self.peerjid,
  10828. type: 'set'})
  10829. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10830. action: 'session-accept',
  10831. initiator: self.initiator,
  10832. responder: self.responder,
  10833. sid: self.sid });
  10834. var publicLocalDesc = APP.simulcast.reverseTransformLocalDescription(sdp);
  10835. var publicLocalSDP = new SDP(publicLocalDesc.sdp);
  10836. publicLocalSDP.toJingle(accept, self.initiator == self.me ? 'initiator' : 'responder', ssrcs);
  10837. self.connection.sendIQ(accept,
  10838. function () {
  10839. var ack = {};
  10840. ack.source = 'answer';
  10841. $(document).trigger('ack.jingle', [self.sid, ack]);
  10842. },
  10843. function (stanza) {
  10844. var error = ($(stanza).find('error').length) ? {
  10845. code: $(stanza).find('error').attr('code'),
  10846. reason: $(stanza).find('error :first')[0].tagName,
  10847. }:{};
  10848. error.source = 'answer';
  10849. JingleSession.onJingleError(self.sid, error);
  10850. },
  10851. 10000);
  10852. }
  10853. sdp.sdp = this.localSDP.raw;
  10854. this.peerconnection.setLocalDescription(sdp,
  10855. function () {
  10856. //console.log('setLocalDescription success');
  10857. if (self.usetrickle && !self.usepranswer) {
  10858. sendJingle();
  10859. }
  10860. self.setLocalDescription();
  10861. },
  10862. function (e) {
  10863. console.error('setLocalDescription failed', e);
  10864. }
  10865. );
  10866. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  10867. for (var j = 0; j < cands.length; j++) {
  10868. var cand = SDPUtil.parse_icecandidate(cands[j]);
  10869. if (cand.type == 'srflx') {
  10870. this.hadstuncandidate = true;
  10871. } else if (cand.type == 'relay') {
  10872. this.hadturncandidate = true;
  10873. }
  10874. }
  10875. };
  10876. JingleSession.prototype.sendTerminate = function (reason, text) {
  10877. var self = this,
  10878. term = $iq({to: this.peerjid,
  10879. type: 'set'})
  10880. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10881. action: 'session-terminate',
  10882. initiator: this.initiator,
  10883. sid: this.sid})
  10884. .c('reason')
  10885. .c(reason || 'success');
  10886. if (text) {
  10887. term.up().c('text').t(text);
  10888. }
  10889. this.connection.sendIQ(term,
  10890. function () {
  10891. self.peerconnection.close();
  10892. self.peerconnection = null;
  10893. self.terminate();
  10894. var ack = {};
  10895. ack.source = 'terminate';
  10896. $(document).trigger('ack.jingle', [self.sid, ack]);
  10897. },
  10898. function (stanza) {
  10899. var error = ($(stanza).find('error').length) ? {
  10900. code: $(stanza).find('error').attr('code'),
  10901. reason: $(stanza).find('error :first')[0].tagName,
  10902. }:{};
  10903. $(document).trigger('ack.jingle', [self.sid, error]);
  10904. },
  10905. 10000);
  10906. if (this.statsinterval !== null) {
  10907. window.clearInterval(this.statsinterval);
  10908. this.statsinterval = null;
  10909. }
  10910. };
  10911. JingleSession.prototype.addSource = function (elem, fromJid) {
  10912. var self = this;
  10913. // FIXME: dirty waiting
  10914. if (!this.peerconnection.localDescription)
  10915. {
  10916. console.warn("addSource - localDescription not ready yet")
  10917. setTimeout(function()
  10918. {
  10919. self.addSource(elem, fromJid);
  10920. },
  10921. 200
  10922. );
  10923. return;
  10924. }
  10925. console.log('addssrc', new Date().getTime());
  10926. console.log('ice', this.peerconnection.iceConnectionState);
  10927. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  10928. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  10929. $(elem).each(function (idx, content) {
  10930. var name = $(content).attr('name');
  10931. var lines = '';
  10932. tmp = $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  10933. var semantics = this.getAttribute('semantics');
  10934. var ssrcs = $(this).find('>source').map(function () {
  10935. return this.getAttribute('ssrc');
  10936. }).get();
  10937. if (ssrcs.length != 0) {
  10938. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  10939. }
  10940. });
  10941. tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  10942. tmp.each(function () {
  10943. var ssrc = $(this).attr('ssrc');
  10944. if(mySdp.containsSSRC(ssrc)){
  10945. /**
  10946. * This happens when multiple participants change their streams at the same time and
  10947. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  10948. * addssrc are scheduled for update IQ. See
  10949. */
  10950. console.warn("Got add stream request for my own ssrc: "+ssrc);
  10951. return;
  10952. }
  10953. $(this).find('>parameter').each(function () {
  10954. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  10955. if ($(this).attr('value') && $(this).attr('value').length)
  10956. lines += ':' + $(this).attr('value');
  10957. lines += '\r\n';
  10958. });
  10959. });
  10960. sdp.media.forEach(function(media, idx) {
  10961. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  10962. return;
  10963. sdp.media[idx] += lines;
  10964. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  10965. self.addssrc[idx] += lines;
  10966. });
  10967. sdp.raw = sdp.session + sdp.media.join('');
  10968. });
  10969. this.modifySources();
  10970. };
  10971. JingleSession.prototype.removeSource = function (elem, fromJid) {
  10972. var self = this;
  10973. // FIXME: dirty waiting
  10974. if (!this.peerconnection.localDescription)
  10975. {
  10976. console.warn("removeSource - localDescription not ready yet")
  10977. setTimeout(function()
  10978. {
  10979. self.removeSource(elem, fromJid);
  10980. },
  10981. 200
  10982. );
  10983. return;
  10984. }
  10985. console.log('removessrc', new Date().getTime());
  10986. console.log('ice', this.peerconnection.iceConnectionState);
  10987. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  10988. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  10989. $(elem).each(function (idx, content) {
  10990. var name = $(content).attr('name');
  10991. var lines = '';
  10992. tmp = $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  10993. var semantics = this.getAttribute('semantics');
  10994. var ssrcs = $(this).find('>source').map(function () {
  10995. return this.getAttribute('ssrc');
  10996. }).get();
  10997. if (ssrcs.length != 0) {
  10998. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  10999. }
  11000. });
  11001. tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  11002. tmp.each(function () {
  11003. var ssrc = $(this).attr('ssrc');
  11004. // This should never happen, but can be useful for bug detection
  11005. if(mySdp.containsSSRC(ssrc)){
  11006. console.error("Got remove stream request for my own ssrc: "+ssrc);
  11007. return;
  11008. }
  11009. $(this).find('>parameter').each(function () {
  11010. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  11011. if ($(this).attr('value') && $(this).attr('value').length)
  11012. lines += ':' + $(this).attr('value');
  11013. lines += '\r\n';
  11014. });
  11015. });
  11016. sdp.media.forEach(function(media, idx) {
  11017. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  11018. return;
  11019. sdp.media[idx] += lines;
  11020. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  11021. self.removessrc[idx] += lines;
  11022. });
  11023. sdp.raw = sdp.session + sdp.media.join('');
  11024. });
  11025. this.modifySources();
  11026. };
  11027. JingleSession.prototype.modifySources = function (successCallback) {
  11028. var self = this;
  11029. if (this.peerconnection.signalingState == 'closed') return;
  11030. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  11031. // There is nothing to do since scheduled job might have been executed by another succeeding call
  11032. this.setLocalDescription();
  11033. if(successCallback){
  11034. successCallback();
  11035. }
  11036. return;
  11037. }
  11038. // FIXME: this is a big hack
  11039. // https://code.google.com/p/webrtc/issues/detail?id=2688
  11040. // ^ has been fixed.
  11041. if (!(this.peerconnection.signalingState == 'stable' && this.peerconnection.iceConnectionState == 'connected')) {
  11042. console.warn('modifySources not yet', this.peerconnection.signalingState, this.peerconnection.iceConnectionState);
  11043. this.wait = true;
  11044. window.setTimeout(function() { self.modifySources(successCallback); }, 250);
  11045. return;
  11046. }
  11047. if (this.wait) {
  11048. window.setTimeout(function() { self.modifySources(successCallback); }, 2500);
  11049. this.wait = false;
  11050. return;
  11051. }
  11052. // Reset switch streams flag
  11053. this.switchstreams = false;
  11054. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11055. // add sources
  11056. this.addssrc.forEach(function(lines, idx) {
  11057. sdp.media[idx] += lines;
  11058. });
  11059. this.addssrc = [];
  11060. // remove sources
  11061. this.removessrc.forEach(function(lines, idx) {
  11062. lines = lines.split('\r\n');
  11063. lines.pop(); // remove empty last element;
  11064. lines.forEach(function(line) {
  11065. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  11066. });
  11067. });
  11068. this.removessrc = [];
  11069. // FIXME:
  11070. // this was a hack for the situation when only one peer exists
  11071. // in the conference.
  11072. // check if still required and remove
  11073. if (sdp.media[0])
  11074. sdp.media[0] = sdp.media[0].replace('a=recvonly', 'a=sendrecv');
  11075. if (sdp.media[1])
  11076. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11077. sdp.raw = sdp.session + sdp.media.join('');
  11078. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  11079. function() {
  11080. if(self.signalingState == 'closed') {
  11081. console.error("createAnswer attempt on closed state");
  11082. return;
  11083. }
  11084. self.peerconnection.createAnswer(
  11085. function(modifiedAnswer) {
  11086. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  11087. if (self.pendingop !== null) {
  11088. var sdp = new SDP(modifiedAnswer.sdp);
  11089. if (sdp.media.length > 1) {
  11090. switch(self.pendingop) {
  11091. case 'mute':
  11092. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  11093. break;
  11094. case 'unmute':
  11095. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11096. break;
  11097. }
  11098. sdp.raw = sdp.session + sdp.media.join('');
  11099. modifiedAnswer.sdp = sdp.raw;
  11100. }
  11101. self.pendingop = null;
  11102. }
  11103. // FIXME: pushing down an answer while ice connection state
  11104. // is still checking is bad...
  11105. //console.log(self.peerconnection.iceConnectionState);
  11106. // trying to work around another chrome bug
  11107. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  11108. self.peerconnection.setLocalDescription(modifiedAnswer,
  11109. function() {
  11110. //console.log('modified setLocalDescription ok');
  11111. self.setLocalDescription();
  11112. if(successCallback){
  11113. successCallback();
  11114. }
  11115. },
  11116. function(error) {
  11117. console.error('modified setLocalDescription failed', error);
  11118. }
  11119. );
  11120. },
  11121. function(error) {
  11122. console.error('modified answer failed', error);
  11123. }
  11124. );
  11125. },
  11126. function(error) {
  11127. console.error('modify failed', error);
  11128. }
  11129. );
  11130. };
  11131. /**
  11132. * Switches video streams.
  11133. * @param new_stream new stream that will be used as video of this session.
  11134. * @param oldStream old video stream of this session.
  11135. * @param success_callback callback executed after successful stream switch.
  11136. */
  11137. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback) {
  11138. var self = this;
  11139. // Remember SDP to figure out added/removed SSRCs
  11140. var oldSdp = null;
  11141. if(self.peerconnection) {
  11142. if(self.peerconnection.localDescription) {
  11143. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  11144. }
  11145. self.peerconnection.removeStream(oldStream, true);
  11146. self.peerconnection.addStream(new_stream);
  11147. }
  11148. APP.RTC.switchVideoStreams(new_stream, oldStream);
  11149. // Conference is not active
  11150. if(!oldSdp || !self.peerconnection) {
  11151. success_callback();
  11152. return;
  11153. }
  11154. self.switchstreams = true;
  11155. self.modifySources(function() {
  11156. console.log('modify sources done');
  11157. success_callback();
  11158. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  11159. console.log("SDPs", oldSdp, newSdp);
  11160. self.notifyMySSRCUpdate(oldSdp, newSdp);
  11161. });
  11162. };
  11163. /**
  11164. * Figures out added/removed ssrcs and send update IQs.
  11165. * @param old_sdp SDP object for old description.
  11166. * @param new_sdp SDP object for new description.
  11167. */
  11168. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  11169. if (!(this.peerconnection.signalingState == 'stable' &&
  11170. this.peerconnection.iceConnectionState == 'connected')){
  11171. console.log("Too early to send updates");
  11172. return;
  11173. }
  11174. // send source-remove IQ.
  11175. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  11176. var remove = $iq({to: this.peerjid, type: 'set'})
  11177. .c('jingle', {
  11178. xmlns: 'urn:xmpp:jingle:1',
  11179. action: 'source-remove',
  11180. initiator: this.initiator,
  11181. sid: this.sid
  11182. }
  11183. );
  11184. var removed = sdpDiffer.toJingle(remove);
  11185. if (removed) {
  11186. this.connection.sendIQ(remove,
  11187. function (res) {
  11188. console.info('got remove result', res);
  11189. },
  11190. function (err) {
  11191. console.error('got remove error', err);
  11192. }
  11193. );
  11194. } else {
  11195. console.log('removal not necessary');
  11196. }
  11197. // send source-add IQ.
  11198. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  11199. var add = $iq({to: this.peerjid, type: 'set'})
  11200. .c('jingle', {
  11201. xmlns: 'urn:xmpp:jingle:1',
  11202. action: 'source-add',
  11203. initiator: this.initiator,
  11204. sid: this.sid
  11205. }
  11206. );
  11207. var added = sdpDiffer.toJingle(add);
  11208. if (added) {
  11209. this.connection.sendIQ(add,
  11210. function (res) {
  11211. console.info('got add result', res);
  11212. },
  11213. function (err) {
  11214. console.error('got add error', err);
  11215. }
  11216. );
  11217. } else {
  11218. console.log('addition not necessary');
  11219. }
  11220. };
  11221. /**
  11222. * Determines whether the (local) video is mute i.e. all video tracks are
  11223. * disabled.
  11224. *
  11225. * @return <tt>true</tt> if the (local) video is mute i.e. all video tracks are
  11226. * disabled; otherwise, <tt>false</tt>
  11227. */
  11228. JingleSession.prototype.isVideoMute = function () {
  11229. var tracks = APP.RTC.localVideo.getVideoTracks();
  11230. var mute = true;
  11231. for (var i = 0; i < tracks.length; ++i) {
  11232. if (tracks[i].enabled) {
  11233. mute = false;
  11234. break;
  11235. }
  11236. }
  11237. return mute;
  11238. };
  11239. /**
  11240. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  11241. *
  11242. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  11243. * tracks; otherwise, <tt>false</tt>
  11244. * @param callback a function to be invoked with <tt>mute</tt> after all video
  11245. * tracks have been enabled/disabled. The function may, optionally, return
  11246. * another function which is to be invoked after the whole mute/unmute operation
  11247. * has completed successfully.
  11248. * @param options an object which specifies optional arguments such as the
  11249. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  11250. * specifies whether the method was initiated in response to a user command (in
  11251. * contrast to an automatic decision made by the application logic)
  11252. */
  11253. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  11254. var byUser;
  11255. if (options) {
  11256. byUser = options.byUser;
  11257. if (typeof byUser === 'undefined') {
  11258. byUser = true;
  11259. }
  11260. } else {
  11261. byUser = true;
  11262. }
  11263. // The user's command to mute the (local) video takes precedence over any
  11264. // automatic decision made by the application logic.
  11265. if (byUser) {
  11266. this.videoMuteByUser = mute;
  11267. } else if (this.videoMuteByUser) {
  11268. return;
  11269. }
  11270. var self = this;
  11271. var localCallback = function (mute) {
  11272. self.connection.emuc.addVideoInfoToPresence(mute);
  11273. self.connection.emuc.sendPresence();
  11274. return callback(mute)
  11275. };
  11276. if (mute == APP.RTC.localVideo.isMuted())
  11277. {
  11278. // Even if no change occurs, the specified callback is to be executed.
  11279. // The specified callback may, optionally, return a successCallback
  11280. // which is to be executed as well.
  11281. var successCallback = localCallback(mute);
  11282. if (successCallback) {
  11283. successCallback();
  11284. }
  11285. } else {
  11286. APP.RTC.localVideo.setMute(!mute);
  11287. this.hardMuteVideo(mute);
  11288. this.modifySources(localCallback(mute));
  11289. }
  11290. };
  11291. // SDP-based mute by going recvonly/sendrecv
  11292. // FIXME: should probably black out the screen as well
  11293. JingleSession.prototype.toggleVideoMute = function (callback) {
  11294. this.service.setVideoMute(APP.RTC.localVideo.isMuted(), callback);
  11295. };
  11296. JingleSession.prototype.hardMuteVideo = function (muted) {
  11297. this.pendingop = muted ? 'mute' : 'unmute';
  11298. };
  11299. JingleSession.prototype.sendMute = function (muted, content) {
  11300. var info = $iq({to: this.peerjid,
  11301. type: 'set'})
  11302. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11303. action: 'session-info',
  11304. initiator: this.initiator,
  11305. sid: this.sid });
  11306. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11307. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  11308. if (content) {
  11309. info.attrs({'name': content});
  11310. }
  11311. this.connection.send(info);
  11312. };
  11313. JingleSession.prototype.sendRinging = function () {
  11314. var info = $iq({to: this.peerjid,
  11315. type: 'set'})
  11316. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11317. action: 'session-info',
  11318. initiator: this.initiator,
  11319. sid: this.sid });
  11320. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11321. this.connection.send(info);
  11322. };
  11323. JingleSession.prototype.getStats = function (interval) {
  11324. var self = this;
  11325. var recv = {audio: 0, video: 0};
  11326. var lost = {audio: 0, video: 0};
  11327. var lastrecv = {audio: 0, video: 0};
  11328. var lastlost = {audio: 0, video: 0};
  11329. var loss = {audio: 0, video: 0};
  11330. var delta = {audio: 0, video: 0};
  11331. this.statsinterval = window.setInterval(function () {
  11332. if (self && self.peerconnection && self.peerconnection.getStats) {
  11333. self.peerconnection.getStats(function (stats) {
  11334. var results = stats.result();
  11335. // TODO: there are so much statistics you can get from this..
  11336. for (var i = 0; i < results.length; ++i) {
  11337. if (results[i].type == 'ssrc') {
  11338. var packetsrecv = results[i].stat('packetsReceived');
  11339. var packetslost = results[i].stat('packetsLost');
  11340. if (packetsrecv && packetslost) {
  11341. packetsrecv = parseInt(packetsrecv, 10);
  11342. packetslost = parseInt(packetslost, 10);
  11343. if (results[i].stat('googFrameRateReceived')) {
  11344. lastlost.video = lost.video;
  11345. lastrecv.video = recv.video;
  11346. recv.video = packetsrecv;
  11347. lost.video = packetslost;
  11348. } else {
  11349. lastlost.audio = lost.audio;
  11350. lastrecv.audio = recv.audio;
  11351. recv.audio = packetsrecv;
  11352. lost.audio = packetslost;
  11353. }
  11354. }
  11355. }
  11356. }
  11357. delta.audio = recv.audio - lastrecv.audio;
  11358. delta.video = recv.video - lastrecv.video;
  11359. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  11360. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  11361. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  11362. });
  11363. }
  11364. }, interval || 3000);
  11365. return this.statsinterval;
  11366. };
  11367. JingleSession.onJingleError = function (session, error)
  11368. {
  11369. console.error("Jingle error", error);
  11370. }
  11371. JingleSession.onJingleFatalError = function (session, error)
  11372. {
  11373. this.service.sessionTerminated = true;
  11374. this.connection.emuc.doLeave();
  11375. APP.UI.messageHandler.showError( "Sorry",
  11376. "Internal application error[setRemoteDescription]");
  11377. }
  11378. JingleSession.prototype.setLocalDescription = function () {
  11379. // put our ssrcs into presence so other clients can identify our stream
  11380. var newssrcs = [];
  11381. var media = APP.simulcast.parseMedia(this.peerconnection.localDescription);
  11382. media.forEach(function (media) {
  11383. if(Object.keys(media.sources).length > 0) {
  11384. // TODO(gp) maybe exclude FID streams?
  11385. Object.keys(media.sources).forEach(function (ssrc) {
  11386. newssrcs.push({
  11387. 'ssrc': ssrc,
  11388. 'type': media.type,
  11389. 'direction': media.direction
  11390. });
  11391. });
  11392. }
  11393. else if(this.localStreamsSSRC && this.localStreamsSSRC[media.type])
  11394. {
  11395. newssrcs.push({
  11396. 'ssrc': this.localStreamsSSRC[media.type],
  11397. 'type': media.type,
  11398. 'direction': media.direction
  11399. });
  11400. }
  11401. });
  11402. console.log('new ssrcs', newssrcs);
  11403. // Have to clear presence map to get rid of removed streams
  11404. this.connection.emuc.clearPresenceMedia();
  11405. if (newssrcs.length > 0) {
  11406. for (var i = 1; i <= newssrcs.length; i ++) {
  11407. // Change video type to screen
  11408. if (newssrcs[i-1].type === 'video' && APP.desktopsharing.isUsingScreenStream()) {
  11409. newssrcs[i-1].type = 'screen';
  11410. }
  11411. this.connection.emuc.addMediaToPresence(i,
  11412. newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
  11413. }
  11414. this.connection.emuc.sendPresence();
  11415. }
  11416. }
  11417. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11418. function sendKeyframe(pc) {
  11419. console.log('sendkeyframe', pc.iceConnectionState);
  11420. if (pc.iceConnectionState !== 'connected') return; // safe...
  11421. pc.setRemoteDescription(
  11422. pc.remoteDescription,
  11423. function () {
  11424. pc.createAnswer(
  11425. function (modifiedAnswer) {
  11426. pc.setLocalDescription(
  11427. modifiedAnswer,
  11428. function () {
  11429. // noop
  11430. },
  11431. function (error) {
  11432. console.log('triggerKeyframe setLocalDescription failed', error);
  11433. APP.UI.messageHandler.showError();
  11434. }
  11435. );
  11436. },
  11437. function (error) {
  11438. console.log('triggerKeyframe createAnswer failed', error);
  11439. APP.UI.messageHandler.showError();
  11440. }
  11441. );
  11442. },
  11443. function (error) {
  11444. console.log('triggerKeyframe setRemoteDescription failed', error);
  11445. APP.UI.messageHandler.showError();
  11446. }
  11447. );
  11448. }
  11449. JingleSession.prototype.remoteStreamAdded = function (data) {
  11450. var self = this;
  11451. var thessrc;
  11452. var ssrc2jid = this.connection.emuc.ssrc2jid;
  11453. // look up an associated JID for a stream id
  11454. if (data.stream.id && data.stream.id.indexOf('mixedmslabel') === -1) {
  11455. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  11456. var ssrclines
  11457. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  11458. ssrclines = ssrclines.filter(function (line) {
  11459. // NOTE(gp) previously we filtered on the mslabel, but that property
  11460. // is not always present.
  11461. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  11462. return ((line.indexOf('msid:' + data.stream.id) !== -1));
  11463. });
  11464. if (ssrclines.length) {
  11465. thessrc = ssrclines[0].substring(7).split(' ')[0];
  11466. // We signal our streams (through Jingle to the focus) before we set
  11467. // our presence (through which peers associate remote streams to
  11468. // jids). So, it might arrive that a remote stream is added but
  11469. // ssrc2jid is not yet updated and thus data.peerjid cannot be
  11470. // successfully set. Here we wait for up to a second for the
  11471. // presence to arrive.
  11472. if (!ssrc2jid[thessrc]) {
  11473. // TODO(gp) limit wait duration to 1 sec.
  11474. setTimeout(function(d) {
  11475. return function() {
  11476. self.remoteStreamAdded(d);
  11477. }
  11478. }(data), 250);
  11479. return;
  11480. }
  11481. // ok to overwrite the one from focus? might save work in colibri.js
  11482. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  11483. if (ssrc2jid[thessrc]) {
  11484. data.peerjid = ssrc2jid[thessrc];
  11485. }
  11486. }
  11487. }
  11488. //TODO: this code should be removed when firefox implement multistream support
  11489. if(APP.RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_FIREFOX)
  11490. {
  11491. if((JingleSession.notReceivedSSRCs.length == 0) ||
  11492. !ssrc2jid[JingleSession.notReceivedSSRCs[JingleSession.notReceivedSSRCs.length - 1]])
  11493. {
  11494. // TODO(gp) limit wait duration to 1 sec.
  11495. setTimeout(function(d) {
  11496. return function() {
  11497. self.remoteStreamAdded(d);
  11498. }
  11499. }(data), 250);
  11500. return;
  11501. }
  11502. thessrc = JingleSession.notReceivedSSRCs.pop();
  11503. if (ssrc2jid[thessrc]) {
  11504. data.peerjid = ssrc2jid[thessrc];
  11505. }
  11506. }
  11507. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  11508. var isVideo = data.stream.getVideoTracks().length > 0;
  11509. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11510. if (isVideo &&
  11511. data.peerjid && this.peerjid === data.peerjid &&
  11512. data.stream.getVideoTracks().length === 0 &&
  11513. APP.RTC.localVideo.getTracks().length > 0) {
  11514. window.setTimeout(function () {
  11515. sendKeyframe(self.peerconnection);
  11516. }, 3000);
  11517. }
  11518. }
  11519. module.exports = JingleSession;
  11520. },{"../../service/RTC/RTCBrowserType":80,"./SDP":49,"./SDPDiffer":50,"./SDPUtil":51,"./TraceablePeerConnection":52}],49:[function(require,module,exports){
  11521. /* jshint -W117 */
  11522. var SDPUtil = require("./SDPUtil");
  11523. // SDP STUFF
  11524. function SDP(sdp) {
  11525. this.media = sdp.split('\r\nm=');
  11526. for (var i = 1; i < this.media.length; i++) {
  11527. this.media[i] = 'm=' + this.media[i];
  11528. if (i != this.media.length - 1) {
  11529. this.media[i] += '\r\n';
  11530. }
  11531. }
  11532. this.session = this.media.shift() + '\r\n';
  11533. this.raw = this.session + this.media.join('');
  11534. }
  11535. /**
  11536. * Returns map of MediaChannel mapped per channel idx.
  11537. */
  11538. SDP.prototype.getMediaSsrcMap = function() {
  11539. var self = this;
  11540. var media_ssrcs = {};
  11541. var tmp;
  11542. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  11543. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  11544. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  11545. var media = {
  11546. mediaindex: mediaindex,
  11547. mid: mid,
  11548. ssrcs: {},
  11549. ssrcGroups: []
  11550. };
  11551. media_ssrcs[mediaindex] = media;
  11552. tmp.forEach(function (line) {
  11553. var linessrc = line.substring(7).split(' ')[0];
  11554. // allocate new ChannelSsrc
  11555. if(!media.ssrcs[linessrc]) {
  11556. media.ssrcs[linessrc] = {
  11557. ssrc: linessrc,
  11558. lines: []
  11559. };
  11560. }
  11561. media.ssrcs[linessrc].lines.push(line);
  11562. });
  11563. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  11564. tmp.forEach(function(line){
  11565. var semantics = line.substr(0, idx).substr(13);
  11566. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11567. if (ssrcs.length != 0) {
  11568. media.ssrcGroups.push({
  11569. semantics: semantics,
  11570. ssrcs: ssrcs
  11571. });
  11572. }
  11573. });
  11574. }
  11575. return media_ssrcs;
  11576. };
  11577. /**
  11578. * Returns <tt>true</tt> if this SDP contains given SSRC.
  11579. * @param ssrc the ssrc to check.
  11580. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  11581. */
  11582. SDP.prototype.containsSSRC = function(ssrc) {
  11583. var medias = this.getMediaSsrcMap();
  11584. var contains = false;
  11585. Object.keys(medias).forEach(function(mediaindex){
  11586. var media = medias[mediaindex];
  11587. //console.log("Check", channel, ssrc);
  11588. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  11589. contains = true;
  11590. }
  11591. });
  11592. return contains;
  11593. };
  11594. // remove iSAC and CN from SDP
  11595. SDP.prototype.mangle = function () {
  11596. var i, j, mline, lines, rtpmap, newdesc;
  11597. for (i = 0; i < this.media.length; i++) {
  11598. lines = this.media[i].split('\r\n');
  11599. lines.pop(); // remove empty last element
  11600. mline = SDPUtil.parse_mline(lines.shift());
  11601. if (mline.media != 'audio')
  11602. continue;
  11603. newdesc = '';
  11604. mline.fmt.length = 0;
  11605. for (j = 0; j < lines.length; j++) {
  11606. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  11607. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  11608. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  11609. continue;
  11610. mline.fmt.push(rtpmap.id);
  11611. newdesc += lines[j] + '\r\n';
  11612. } else {
  11613. newdesc += lines[j] + '\r\n';
  11614. }
  11615. }
  11616. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  11617. this.media[i] += newdesc;
  11618. }
  11619. this.raw = this.session + this.media.join('');
  11620. };
  11621. // remove lines matching prefix from session section
  11622. SDP.prototype.removeSessionLines = function(prefix) {
  11623. var self = this;
  11624. var lines = SDPUtil.find_lines(this.session, prefix);
  11625. lines.forEach(function(line) {
  11626. self.session = self.session.replace(line + '\r\n', '');
  11627. });
  11628. this.raw = this.session + this.media.join('');
  11629. return lines;
  11630. }
  11631. // remove lines matching prefix from a media section specified by mediaindex
  11632. // TODO: non-numeric mediaindex could match mid
  11633. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  11634. var self = this;
  11635. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  11636. lines.forEach(function(line) {
  11637. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  11638. });
  11639. this.raw = this.session + this.media.join('');
  11640. return lines;
  11641. }
  11642. // add content's to a jingle element
  11643. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  11644. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  11645. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  11646. var self = this;
  11647. // new bundle plan
  11648. if (SDPUtil.find_line(this.session, 'a=group:')) {
  11649. lines = SDPUtil.find_lines(this.session, 'a=group:');
  11650. for (i = 0; i < lines.length; i++) {
  11651. tmp = lines[i].split(' ');
  11652. var semantics = tmp.shift().substr(8);
  11653. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  11654. for (j = 0; j < tmp.length; j++) {
  11655. elem.c('content', {name: tmp[j]}).up();
  11656. }
  11657. elem.up();
  11658. }
  11659. }
  11660. for (i = 0; i < this.media.length; i++) {
  11661. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  11662. if (!(mline.media === 'audio' ||
  11663. mline.media === 'video' ||
  11664. mline.media === 'application'))
  11665. {
  11666. continue;
  11667. }
  11668. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  11669. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  11670. } else {
  11671. if(ssrcs && ssrcs[mline.media])
  11672. {
  11673. ssrc = ssrcs[mline.media];
  11674. }
  11675. else
  11676. ssrc = false;
  11677. }
  11678. elem.c('content', {creator: thecreator, name: mline.media});
  11679. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  11680. // prefer identifier from a=mid if present
  11681. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  11682. elem.attrs({ name: mid });
  11683. }
  11684. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  11685. {
  11686. elem.c('description',
  11687. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  11688. media: mline.media });
  11689. if (ssrc) {
  11690. elem.attrs({ssrc: ssrc});
  11691. }
  11692. for (j = 0; j < mline.fmt.length; j++) {
  11693. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  11694. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  11695. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  11696. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  11697. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  11698. for (k = 0; k < tmp.length; k++) {
  11699. elem.c('parameter', tmp[k]).up();
  11700. }
  11701. }
  11702. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  11703. elem.up();
  11704. }
  11705. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  11706. elem.c('encryption', {required: 1});
  11707. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  11708. crypto.forEach(function(line) {
  11709. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  11710. });
  11711. elem.up(); // end of encryption
  11712. }
  11713. if (ssrc) {
  11714. // new style mapping
  11715. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11716. // FIXME: group by ssrc and support multiple different ssrcs
  11717. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  11718. if(ssrclines.length > 0) {
  11719. ssrclines.forEach(function (line) {
  11720. idx = line.indexOf(' ');
  11721. var linessrc = line.substr(0, idx).substr(7);
  11722. if (linessrc != ssrc) {
  11723. elem.up();
  11724. ssrc = linessrc;
  11725. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11726. }
  11727. var kv = line.substr(idx + 1);
  11728. elem.c('parameter');
  11729. if (kv.indexOf(':') == -1) {
  11730. elem.attrs({ name: kv });
  11731. } else {
  11732. elem.attrs({ name: kv.split(':', 2)[0] });
  11733. elem.attrs({ value: kv.split(':', 2)[1] });
  11734. }
  11735. elem.up();
  11736. });
  11737. elem.up();
  11738. }
  11739. else
  11740. {
  11741. elem.up();
  11742. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11743. elem.c('parameter');
  11744. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  11745. elem.up();
  11746. var msid = null;
  11747. if(mline.media == "audio")
  11748. {
  11749. msid = APP.RTC.localAudio.getId();
  11750. }
  11751. else
  11752. {
  11753. msid = APP.RTC.localVideo.getId();
  11754. }
  11755. if(msid != null)
  11756. {
  11757. msid = msid.replace(/[\{,\}]/g,"");
  11758. elem.c('parameter');
  11759. elem.attrs({name: "msid", value:msid});
  11760. elem.up();
  11761. elem.c('parameter');
  11762. elem.attrs({name: "mslabel", value:msid});
  11763. elem.up();
  11764. elem.c('parameter');
  11765. elem.attrs({name: "label", value:msid});
  11766. elem.up();
  11767. elem.up();
  11768. }
  11769. }
  11770. // XEP-0339 handle ssrc-group attributes
  11771. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  11772. ssrc_group_lines.forEach(function(line) {
  11773. idx = line.indexOf(' ');
  11774. var semantics = line.substr(0, idx).substr(13);
  11775. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11776. if (ssrcs.length != 0) {
  11777. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11778. ssrcs.forEach(function(ssrc) {
  11779. elem.c('source', { ssrc: ssrc })
  11780. .up();
  11781. });
  11782. elem.up();
  11783. }
  11784. });
  11785. }
  11786. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  11787. elem.c('rtcp-mux').up();
  11788. }
  11789. // XEP-0293 -- map a=rtcp-fb:*
  11790. this.RtcpFbToJingle(i, elem, '*');
  11791. // XEP-0294
  11792. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  11793. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  11794. for (j = 0; j < lines.length; j++) {
  11795. tmp = SDPUtil.parse_extmap(lines[j]);
  11796. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  11797. uri: tmp.uri,
  11798. id: tmp.value });
  11799. if (tmp.hasOwnProperty('direction')) {
  11800. switch (tmp.direction) {
  11801. case 'sendonly':
  11802. elem.attrs({senders: 'responder'});
  11803. break;
  11804. case 'recvonly':
  11805. elem.attrs({senders: 'initiator'});
  11806. break;
  11807. case 'sendrecv':
  11808. elem.attrs({senders: 'both'});
  11809. break;
  11810. case 'inactive':
  11811. elem.attrs({senders: 'none'});
  11812. break;
  11813. }
  11814. }
  11815. // TODO: handle params
  11816. elem.up();
  11817. }
  11818. }
  11819. elem.up(); // end of description
  11820. }
  11821. // map ice-ufrag/pwd, dtls fingerprint, candidates
  11822. this.TransportToJingle(i, elem);
  11823. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  11824. elem.attrs({senders: 'both'});
  11825. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  11826. elem.attrs({senders: 'initiator'});
  11827. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  11828. elem.attrs({senders: 'responder'});
  11829. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  11830. elem.attrs({senders: 'none'});
  11831. }
  11832. if (mline.port == '0') {
  11833. // estos hack to reject an m-line
  11834. elem.attrs({senders: 'rejected'});
  11835. }
  11836. elem.up(); // end of content
  11837. }
  11838. elem.up();
  11839. return elem;
  11840. };
  11841. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  11842. var i = mediaindex;
  11843. var tmp;
  11844. var self = this;
  11845. elem.c('transport');
  11846. // XEP-0343 DTLS/SCTP
  11847. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  11848. {
  11849. var sctpmap = SDPUtil.find_line(
  11850. this.media[i], 'a=sctpmap:', self.session);
  11851. if (sctpmap)
  11852. {
  11853. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  11854. elem.c('sctpmap',
  11855. {
  11856. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  11857. number: sctpAttrs[0], /* SCTP port */
  11858. protocol: sctpAttrs[1], /* protocol */
  11859. });
  11860. // Optional stream count attribute
  11861. if (sctpAttrs.length > 2)
  11862. elem.attrs({ streams: sctpAttrs[2]});
  11863. elem.up();
  11864. }
  11865. }
  11866. // XEP-0320
  11867. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  11868. fingerprints.forEach(function(line) {
  11869. tmp = SDPUtil.parse_fingerprint(line);
  11870. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  11871. elem.c('fingerprint').t(tmp.fingerprint);
  11872. delete tmp.fingerprint;
  11873. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  11874. if (line) {
  11875. tmp.setup = line.substr(8);
  11876. }
  11877. elem.attrs(tmp);
  11878. elem.up(); // end of fingerprint
  11879. });
  11880. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  11881. if (tmp) {
  11882. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11883. elem.attrs(tmp);
  11884. // XEP-0176
  11885. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  11886. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  11887. lines.forEach(function (line) {
  11888. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  11889. });
  11890. }
  11891. }
  11892. elem.up(); // end of transport
  11893. }
  11894. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  11895. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  11896. lines.forEach(function (line) {
  11897. var tmp = SDPUtil.parse_rtcpfb(line);
  11898. if (tmp.type == 'trr-int') {
  11899. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  11900. elem.up();
  11901. } else {
  11902. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  11903. if (tmp.params.length > 0) {
  11904. elem.attrs({'subtype': tmp.params[0]});
  11905. }
  11906. elem.up();
  11907. }
  11908. });
  11909. };
  11910. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  11911. var media = '';
  11912. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  11913. if (tmp.length) {
  11914. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  11915. if (tmp.attr('value')) {
  11916. media += tmp.attr('value');
  11917. } else {
  11918. media += '0';
  11919. }
  11920. media += '\r\n';
  11921. }
  11922. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  11923. tmp.each(function () {
  11924. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  11925. if ($(this).attr('subtype')) {
  11926. media += ' ' + $(this).attr('subtype');
  11927. }
  11928. media += '\r\n';
  11929. });
  11930. return media;
  11931. };
  11932. // construct an SDP from a jingle stanza
  11933. SDP.prototype.fromJingle = function (jingle) {
  11934. var self = this;
  11935. this.raw = 'v=0\r\n' +
  11936. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  11937. 's=-\r\n' +
  11938. 't=0 0\r\n';
  11939. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  11940. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  11941. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  11942. var contents = $(group).find('>content').map(function (idx, content) {
  11943. return content.getAttribute('name');
  11944. }).get();
  11945. if (contents.length > 0) {
  11946. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  11947. }
  11948. });
  11949. }
  11950. this.session = this.raw;
  11951. jingle.find('>content').each(function () {
  11952. var m = self.jingle2media($(this));
  11953. self.media.push(m);
  11954. });
  11955. // reconstruct msid-semantic -- apparently not necessary
  11956. /*
  11957. var msid = SDPUtil.parse_ssrc(this.raw);
  11958. if (msid.hasOwnProperty('mslabel')) {
  11959. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  11960. }
  11961. */
  11962. this.raw = this.session + this.media.join('');
  11963. };
  11964. // translate a jingle content element into an an SDP media part
  11965. SDP.prototype.jingle2media = function (content) {
  11966. var media = '',
  11967. desc = content.find('description'),
  11968. ssrc = desc.attr('ssrc'),
  11969. self = this,
  11970. tmp;
  11971. var sctp = content.find(
  11972. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  11973. tmp = { media: desc.attr('media') };
  11974. tmp.port = '1';
  11975. if (content.attr('senders') == 'rejected') {
  11976. // estos hack to reject an m-line.
  11977. tmp.port = '0';
  11978. }
  11979. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  11980. if (sctp.length)
  11981. tmp.proto = 'DTLS/SCTP';
  11982. else
  11983. tmp.proto = 'RTP/SAVPF';
  11984. } else {
  11985. tmp.proto = 'RTP/AVPF';
  11986. }
  11987. if (!sctp.length)
  11988. {
  11989. tmp.fmt = desc.find('payload-type').map(
  11990. function () { return this.getAttribute('id'); }).get();
  11991. media += SDPUtil.build_mline(tmp) + '\r\n';
  11992. }
  11993. else
  11994. {
  11995. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  11996. media += 'a=sctpmap:' + sctp.attr('number') +
  11997. ' ' + sctp.attr('protocol');
  11998. var streamCount = sctp.attr('streams');
  11999. if (streamCount)
  12000. media += ' ' + streamCount + '\r\n';
  12001. else
  12002. media += '\r\n';
  12003. }
  12004. media += 'c=IN IP4 0.0.0.0\r\n';
  12005. if (!sctp.length)
  12006. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  12007. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  12008. if (tmp.length) {
  12009. if (tmp.attr('ufrag')) {
  12010. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  12011. }
  12012. if (tmp.attr('pwd')) {
  12013. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  12014. }
  12015. tmp.find('>fingerprint').each(function () {
  12016. // FIXME: check namespace at some point
  12017. media += 'a=fingerprint:' + this.getAttribute('hash');
  12018. media += ' ' + $(this).text();
  12019. media += '\r\n';
  12020. if (this.getAttribute('setup')) {
  12021. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  12022. }
  12023. });
  12024. }
  12025. switch (content.attr('senders')) {
  12026. case 'initiator':
  12027. media += 'a=sendonly\r\n';
  12028. break;
  12029. case 'responder':
  12030. media += 'a=recvonly\r\n';
  12031. break;
  12032. case 'none':
  12033. media += 'a=inactive\r\n';
  12034. break;
  12035. case 'both':
  12036. media += 'a=sendrecv\r\n';
  12037. break;
  12038. }
  12039. media += 'a=mid:' + content.attr('name') + '\r\n';
  12040. // <description><rtcp-mux/></description>
  12041. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  12042. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  12043. if (desc.find('rtcp-mux').length) {
  12044. media += 'a=rtcp-mux\r\n';
  12045. }
  12046. if (desc.find('encryption').length) {
  12047. desc.find('encryption>crypto').each(function () {
  12048. media += 'a=crypto:' + this.getAttribute('tag');
  12049. media += ' ' + this.getAttribute('crypto-suite');
  12050. media += ' ' + this.getAttribute('key-params');
  12051. if (this.getAttribute('session-params')) {
  12052. media += ' ' + this.getAttribute('session-params');
  12053. }
  12054. media += '\r\n';
  12055. });
  12056. }
  12057. desc.find('payload-type').each(function () {
  12058. media += SDPUtil.build_rtpmap(this) + '\r\n';
  12059. if ($(this).find('>parameter').length) {
  12060. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  12061. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  12062. media += '\r\n';
  12063. }
  12064. // xep-0293
  12065. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  12066. });
  12067. // xep-0293
  12068. media += self.RtcpFbFromJingle(desc, '*');
  12069. // xep-0294
  12070. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  12071. tmp.each(function () {
  12072. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  12073. });
  12074. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  12075. media += SDPUtil.candidateFromJingle(this);
  12076. });
  12077. // XEP-0339 handle ssrc-group attributes
  12078. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12079. var semantics = this.getAttribute('semantics');
  12080. var ssrcs = $(this).find('>source').map(function() {
  12081. return this.getAttribute('ssrc');
  12082. }).get();
  12083. if (ssrcs.length != 0) {
  12084. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12085. }
  12086. });
  12087. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  12088. tmp.each(function () {
  12089. var ssrc = this.getAttribute('ssrc');
  12090. $(this).find('>parameter').each(function () {
  12091. media += 'a=ssrc:' + ssrc + ' ' + this.getAttribute('name');
  12092. if (this.getAttribute('value') && this.getAttribute('value').length)
  12093. media += ':' + this.getAttribute('value');
  12094. media += '\r\n';
  12095. });
  12096. });
  12097. return media;
  12098. };
  12099. module.exports = SDP;
  12100. },{"./SDPUtil":51}],50:[function(require,module,exports){
  12101. function SDPDiffer(mySDP, otherSDP) {
  12102. this.mySDP = mySDP;
  12103. this.otherSDP = otherSDP;
  12104. }
  12105. /**
  12106. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  12107. * @param otherSdp the other SDP to check ssrc with.
  12108. */
  12109. SDPDiffer.prototype.getNewMedia = function() {
  12110. // this could be useful in Array.prototype.
  12111. function arrayEquals(array) {
  12112. // if the other array is a falsy value, return
  12113. if (!array)
  12114. return false;
  12115. // compare lengths - can save a lot of time
  12116. if (this.length != array.length)
  12117. return false;
  12118. for (var i = 0, l=this.length; i < l; i++) {
  12119. // Check if we have nested arrays
  12120. if (this[i] instanceof Array && array[i] instanceof Array) {
  12121. // recurse into the nested arrays
  12122. if (!this[i].equals(array[i]))
  12123. return false;
  12124. }
  12125. else if (this[i] != array[i]) {
  12126. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  12127. return false;
  12128. }
  12129. }
  12130. return true;
  12131. }
  12132. var myMedias = this.mySDP.getMediaSsrcMap();
  12133. var othersMedias = this.otherSDP.getMediaSsrcMap();
  12134. var newMedia = {};
  12135. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  12136. var myMedia = myMedias[othersMediaIdx];
  12137. var othersMedia = othersMedias[othersMediaIdx];
  12138. if(!myMedia && othersMedia) {
  12139. // Add whole channel
  12140. newMedia[othersMediaIdx] = othersMedia;
  12141. return;
  12142. }
  12143. // Look for new ssrcs accross the channel
  12144. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  12145. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  12146. // Allocate channel if we've found ssrc that doesn't exist in our channel
  12147. if(!newMedia[othersMediaIdx]){
  12148. newMedia[othersMediaIdx] = {
  12149. mediaindex: othersMedia.mediaindex,
  12150. mid: othersMedia.mid,
  12151. ssrcs: {},
  12152. ssrcGroups: []
  12153. };
  12154. }
  12155. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  12156. }
  12157. });
  12158. // Look for new ssrc groups across the channels
  12159. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  12160. // try to match the other ssrc-group with an ssrc-group of ours
  12161. var matched = false;
  12162. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  12163. var mySsrcGroup = myMedia.ssrcGroups[i];
  12164. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  12165. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  12166. matched = true;
  12167. break;
  12168. }
  12169. }
  12170. if (!matched) {
  12171. // Allocate channel if we've found an ssrc-group that doesn't
  12172. // exist in our channel
  12173. if(!newMedia[othersMediaIdx]){
  12174. newMedia[othersMediaIdx] = {
  12175. mediaindex: othersMedia.mediaindex,
  12176. mid: othersMedia.mid,
  12177. ssrcs: {},
  12178. ssrcGroups: []
  12179. };
  12180. }
  12181. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  12182. }
  12183. });
  12184. });
  12185. return newMedia;
  12186. };
  12187. /**
  12188. * Sends SSRC update IQ.
  12189. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  12190. * @param sid session identifier that will be put into the IQ.
  12191. * @param initiator initiator identifier.
  12192. * @param toJid destination Jid
  12193. * @param isAdd indicates if this is remove or add operation.
  12194. */
  12195. SDPDiffer.prototype.toJingle = function(modify) {
  12196. var sdpMediaSsrcs = this.getNewMedia();
  12197. var self = this;
  12198. // FIXME: only announce video ssrcs since we mix audio and dont need
  12199. // the audio ssrcs therefore
  12200. var modified = false;
  12201. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  12202. modified = true;
  12203. var media = sdpMediaSsrcs[mediaindex];
  12204. modify.c('content', {name: media.mid});
  12205. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  12206. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  12207. // generate sources from lines
  12208. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  12209. var mediaSsrc = media.ssrcs[ssrcNum];
  12210. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12211. modify.attrs({ssrc: mediaSsrc.ssrc});
  12212. // iterate over ssrc lines
  12213. mediaSsrc.lines.forEach(function (line) {
  12214. var idx = line.indexOf(' ');
  12215. var kv = line.substr(idx + 1);
  12216. modify.c('parameter');
  12217. if (kv.indexOf(':') == -1) {
  12218. modify.attrs({ name: kv });
  12219. } else {
  12220. modify.attrs({ name: kv.split(':', 2)[0] });
  12221. modify.attrs({ value: kv.split(':', 2)[1] });
  12222. }
  12223. modify.up(); // end of parameter
  12224. });
  12225. modify.up(); // end of source
  12226. });
  12227. // generate source groups from lines
  12228. media.ssrcGroups.forEach(function(ssrcGroup) {
  12229. if (ssrcGroup.ssrcs.length != 0) {
  12230. modify.c('ssrc-group', {
  12231. semantics: ssrcGroup.semantics,
  12232. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  12233. });
  12234. ssrcGroup.ssrcs.forEach(function (ssrc) {
  12235. modify.c('source', { ssrc: ssrc })
  12236. .up(); // end of source
  12237. });
  12238. modify.up(); // end of ssrc-group
  12239. }
  12240. });
  12241. modify.up(); // end of description
  12242. modify.up(); // end of content
  12243. });
  12244. return modified;
  12245. };
  12246. module.exports = SDPDiffer;
  12247. },{}],51:[function(require,module,exports){
  12248. SDPUtil = {
  12249. iceparams: function (mediadesc, sessiondesc) {
  12250. var data = null;
  12251. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  12252. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  12253. data = {
  12254. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  12255. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  12256. };
  12257. }
  12258. return data;
  12259. },
  12260. parse_iceufrag: function (line) {
  12261. return line.substring(12);
  12262. },
  12263. build_iceufrag: function (frag) {
  12264. return 'a=ice-ufrag:' + frag;
  12265. },
  12266. parse_icepwd: function (line) {
  12267. return line.substring(10);
  12268. },
  12269. build_icepwd: function (pwd) {
  12270. return 'a=ice-pwd:' + pwd;
  12271. },
  12272. parse_mid: function (line) {
  12273. return line.substring(6);
  12274. },
  12275. parse_mline: function (line) {
  12276. var parts = line.substring(2).split(' '),
  12277. data = {};
  12278. data.media = parts.shift();
  12279. data.port = parts.shift();
  12280. data.proto = parts.shift();
  12281. if (parts[parts.length - 1] === '') { // trailing whitespace
  12282. parts.pop();
  12283. }
  12284. data.fmt = parts;
  12285. return data;
  12286. },
  12287. build_mline: function (mline) {
  12288. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  12289. },
  12290. parse_rtpmap: function (line) {
  12291. var parts = line.substring(9).split(' '),
  12292. data = {};
  12293. data.id = parts.shift();
  12294. parts = parts[0].split('/');
  12295. data.name = parts.shift();
  12296. data.clockrate = parts.shift();
  12297. data.channels = parts.length ? parts.shift() : '1';
  12298. return data;
  12299. },
  12300. /**
  12301. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  12302. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  12303. * @returns [SCTP port number, protocol, streams]
  12304. */
  12305. parse_sctpmap: function (line)
  12306. {
  12307. var parts = line.substring(10).split(' ');
  12308. var sctpPort = parts[0];
  12309. var protocol = parts[1];
  12310. // Stream count is optional
  12311. var streamCount = parts.length > 2 ? parts[2] : null;
  12312. return [sctpPort, protocol, streamCount];// SCTP port
  12313. },
  12314. build_rtpmap: function (el) {
  12315. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  12316. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  12317. line += '/' + el.getAttribute('channels');
  12318. }
  12319. return line;
  12320. },
  12321. parse_crypto: function (line) {
  12322. var parts = line.substring(9).split(' '),
  12323. data = {};
  12324. data.tag = parts.shift();
  12325. data['crypto-suite'] = parts.shift();
  12326. data['key-params'] = parts.shift();
  12327. if (parts.length) {
  12328. data['session-params'] = parts.join(' ');
  12329. }
  12330. return data;
  12331. },
  12332. parse_fingerprint: function (line) { // RFC 4572
  12333. var parts = line.substring(14).split(' '),
  12334. data = {};
  12335. data.hash = parts.shift();
  12336. data.fingerprint = parts.shift();
  12337. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  12338. return data;
  12339. },
  12340. parse_fmtp: function (line) {
  12341. var parts = line.split(' '),
  12342. i, key, value,
  12343. data = [];
  12344. parts.shift();
  12345. parts = parts.join(' ').split(';');
  12346. for (i = 0; i < parts.length; i++) {
  12347. key = parts[i].split('=')[0];
  12348. while (key.length && key[0] == ' ') {
  12349. key = key.substring(1);
  12350. }
  12351. value = parts[i].split('=')[1];
  12352. if (key && value) {
  12353. data.push({name: key, value: value});
  12354. } else if (key) {
  12355. // rfc 4733 (DTMF) style stuff
  12356. data.push({name: '', value: key});
  12357. }
  12358. }
  12359. return data;
  12360. },
  12361. parse_icecandidate: function (line) {
  12362. var candidate = {},
  12363. elems = line.split(' ');
  12364. candidate.foundation = elems[0].substring(12);
  12365. candidate.component = elems[1];
  12366. candidate.protocol = elems[2].toLowerCase();
  12367. candidate.priority = elems[3];
  12368. candidate.ip = elems[4];
  12369. candidate.port = elems[5];
  12370. // elems[6] => "typ"
  12371. candidate.type = elems[7];
  12372. candidate.generation = 0; // default value, may be overwritten below
  12373. for (var i = 8; i < elems.length; i += 2) {
  12374. switch (elems[i]) {
  12375. case 'raddr':
  12376. candidate['rel-addr'] = elems[i + 1];
  12377. break;
  12378. case 'rport':
  12379. candidate['rel-port'] = elems[i + 1];
  12380. break;
  12381. case 'generation':
  12382. candidate.generation = elems[i + 1];
  12383. break;
  12384. case 'tcptype':
  12385. candidate.tcptype = elems[i + 1];
  12386. break;
  12387. default: // TODO
  12388. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12389. }
  12390. }
  12391. candidate.network = '1';
  12392. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12393. return candidate;
  12394. },
  12395. build_icecandidate: function (cand) {
  12396. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  12397. line += ' ';
  12398. switch (cand.type) {
  12399. case 'srflx':
  12400. case 'prflx':
  12401. case 'relay':
  12402. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  12403. line += 'raddr';
  12404. line += ' ';
  12405. line += cand['rel-addr'];
  12406. line += ' ';
  12407. line += 'rport';
  12408. line += ' ';
  12409. line += cand['rel-port'];
  12410. line += ' ';
  12411. }
  12412. break;
  12413. }
  12414. if (cand.hasOwnAttribute('tcptype')) {
  12415. line += 'tcptype';
  12416. line += ' ';
  12417. line += cand.tcptype;
  12418. line += ' ';
  12419. }
  12420. line += 'generation';
  12421. line += ' ';
  12422. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  12423. return line;
  12424. },
  12425. parse_ssrc: function (desc) {
  12426. // proprietary mapping of a=ssrc lines
  12427. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  12428. // and parse according to that
  12429. var lines = desc.split('\r\n'),
  12430. data = {};
  12431. for (var i = 0; i < lines.length; i++) {
  12432. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  12433. var idx = lines[i].indexOf(' ');
  12434. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  12435. }
  12436. }
  12437. return data;
  12438. },
  12439. parse_rtcpfb: function (line) {
  12440. var parts = line.substr(10).split(' ');
  12441. var data = {};
  12442. data.pt = parts.shift();
  12443. data.type = parts.shift();
  12444. data.params = parts;
  12445. return data;
  12446. },
  12447. parse_extmap: function (line) {
  12448. var parts = line.substr(9).split(' ');
  12449. var data = {};
  12450. data.value = parts.shift();
  12451. if (data.value.indexOf('/') != -1) {
  12452. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  12453. data.value = data.value.substr(0, data.value.indexOf('/'));
  12454. } else {
  12455. data.direction = 'both';
  12456. }
  12457. data.uri = parts.shift();
  12458. data.params = parts;
  12459. return data;
  12460. },
  12461. find_line: function (haystack, needle, sessionpart) {
  12462. var lines = haystack.split('\r\n');
  12463. for (var i = 0; i < lines.length; i++) {
  12464. if (lines[i].substring(0, needle.length) == needle) {
  12465. return lines[i];
  12466. }
  12467. }
  12468. if (!sessionpart) {
  12469. return false;
  12470. }
  12471. // search session part
  12472. lines = sessionpart.split('\r\n');
  12473. for (var j = 0; j < lines.length; j++) {
  12474. if (lines[j].substring(0, needle.length) == needle) {
  12475. return lines[j];
  12476. }
  12477. }
  12478. return false;
  12479. },
  12480. find_lines: function (haystack, needle, sessionpart) {
  12481. var lines = haystack.split('\r\n'),
  12482. needles = [];
  12483. for (var i = 0; i < lines.length; i++) {
  12484. if (lines[i].substring(0, needle.length) == needle)
  12485. needles.push(lines[i]);
  12486. }
  12487. if (needles.length || !sessionpart) {
  12488. return needles;
  12489. }
  12490. // search session part
  12491. lines = sessionpart.split('\r\n');
  12492. for (var j = 0; j < lines.length; j++) {
  12493. if (lines[j].substring(0, needle.length) == needle) {
  12494. needles.push(lines[j]);
  12495. }
  12496. }
  12497. return needles;
  12498. },
  12499. candidateToJingle: function (line) {
  12500. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  12501. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  12502. if (line.indexOf('candidate:') === 0) {
  12503. line = 'a=' + line;
  12504. } else if (line.substring(0, 12) != 'a=candidate:') {
  12505. console.log('parseCandidate called with a line that is not a candidate line');
  12506. console.log(line);
  12507. return null;
  12508. }
  12509. if (line.substring(line.length - 2) == '\r\n') // chomp it
  12510. line = line.substring(0, line.length - 2);
  12511. var candidate = {},
  12512. elems = line.split(' '),
  12513. i;
  12514. if (elems[6] != 'typ') {
  12515. console.log('did not find typ in the right place');
  12516. console.log(line);
  12517. return null;
  12518. }
  12519. candidate.foundation = elems[0].substring(12);
  12520. candidate.component = elems[1];
  12521. candidate.protocol = elems[2].toLowerCase();
  12522. candidate.priority = elems[3];
  12523. candidate.ip = elems[4];
  12524. candidate.port = elems[5];
  12525. // elems[6] => "typ"
  12526. candidate.type = elems[7];
  12527. candidate.generation = '0'; // default, may be overwritten below
  12528. for (i = 8; i < elems.length; i += 2) {
  12529. switch (elems[i]) {
  12530. case 'raddr':
  12531. candidate['rel-addr'] = elems[i + 1];
  12532. break;
  12533. case 'rport':
  12534. candidate['rel-port'] = elems[i + 1];
  12535. break;
  12536. case 'generation':
  12537. candidate.generation = elems[i + 1];
  12538. break;
  12539. case 'tcptype':
  12540. candidate.tcptype = elems[i + 1];
  12541. break;
  12542. default: // TODO
  12543. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12544. }
  12545. }
  12546. candidate.network = '1';
  12547. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12548. return candidate;
  12549. },
  12550. candidateFromJingle: function (cand) {
  12551. var line = 'a=candidate:';
  12552. line += cand.getAttribute('foundation');
  12553. line += ' ';
  12554. line += cand.getAttribute('component');
  12555. line += ' ';
  12556. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  12557. line += ' ';
  12558. line += cand.getAttribute('priority');
  12559. line += ' ';
  12560. line += cand.getAttribute('ip');
  12561. line += ' ';
  12562. line += cand.getAttribute('port');
  12563. line += ' ';
  12564. line += 'typ';
  12565. line += ' ' + cand.getAttribute('type');
  12566. line += ' ';
  12567. switch (cand.getAttribute('type')) {
  12568. case 'srflx':
  12569. case 'prflx':
  12570. case 'relay':
  12571. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  12572. line += 'raddr';
  12573. line += ' ';
  12574. line += cand.getAttribute('rel-addr');
  12575. line += ' ';
  12576. line += 'rport';
  12577. line += ' ';
  12578. line += cand.getAttribute('rel-port');
  12579. line += ' ';
  12580. }
  12581. break;
  12582. }
  12583. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  12584. line += 'tcptype';
  12585. line += ' ';
  12586. line += cand.getAttribute('tcptype');
  12587. line += ' ';
  12588. }
  12589. line += 'generation';
  12590. line += ' ';
  12591. line += cand.getAttribute('generation') || '0';
  12592. return line + '\r\n';
  12593. }
  12594. };
  12595. module.exports = SDPUtil;
  12596. },{}],52:[function(require,module,exports){
  12597. function TraceablePeerConnection(ice_config, constraints) {
  12598. var self = this;
  12599. var RTCPeerconnection = navigator.mozGetUserMedia ? mozRTCPeerConnection : webkitRTCPeerConnection;
  12600. this.peerconnection = new RTCPeerconnection(ice_config, constraints);
  12601. this.updateLog = [];
  12602. this.stats = {};
  12603. this.statsinterval = null;
  12604. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  12605. // override as desired
  12606. this.trace = function (what, info) {
  12607. //console.warn('WTRACE', what, info);
  12608. self.updateLog.push({
  12609. time: new Date(),
  12610. type: what,
  12611. value: info || ""
  12612. });
  12613. };
  12614. this.onicecandidate = null;
  12615. this.peerconnection.onicecandidate = function (event) {
  12616. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  12617. if (self.onicecandidate !== null) {
  12618. self.onicecandidate(event);
  12619. }
  12620. };
  12621. this.onaddstream = null;
  12622. this.peerconnection.onaddstream = function (event) {
  12623. self.trace('onaddstream', event.stream.id);
  12624. if (self.onaddstream !== null) {
  12625. self.onaddstream(event);
  12626. }
  12627. };
  12628. this.onremovestream = null;
  12629. this.peerconnection.onremovestream = function (event) {
  12630. self.trace('onremovestream', event.stream.id);
  12631. if (self.onremovestream !== null) {
  12632. self.onremovestream(event);
  12633. }
  12634. };
  12635. this.onsignalingstatechange = null;
  12636. this.peerconnection.onsignalingstatechange = function (event) {
  12637. self.trace('onsignalingstatechange', self.signalingState);
  12638. if (self.onsignalingstatechange !== null) {
  12639. self.onsignalingstatechange(event);
  12640. }
  12641. };
  12642. this.oniceconnectionstatechange = null;
  12643. this.peerconnection.oniceconnectionstatechange = function (event) {
  12644. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  12645. if (self.oniceconnectionstatechange !== null) {
  12646. self.oniceconnectionstatechange(event);
  12647. }
  12648. };
  12649. this.onnegotiationneeded = null;
  12650. this.peerconnection.onnegotiationneeded = function (event) {
  12651. self.trace('onnegotiationneeded');
  12652. if (self.onnegotiationneeded !== null) {
  12653. self.onnegotiationneeded(event);
  12654. }
  12655. };
  12656. self.ondatachannel = null;
  12657. this.peerconnection.ondatachannel = function (event) {
  12658. self.trace('ondatachannel', event);
  12659. if (self.ondatachannel !== null) {
  12660. self.ondatachannel(event);
  12661. }
  12662. };
  12663. if (!navigator.mozGetUserMedia && this.maxstats) {
  12664. this.statsinterval = window.setInterval(function() {
  12665. self.peerconnection.getStats(function(stats) {
  12666. var results = stats.result();
  12667. for (var i = 0; i < results.length; ++i) {
  12668. //console.log(results[i].type, results[i].id, results[i].names())
  12669. var now = new Date();
  12670. results[i].names().forEach(function (name) {
  12671. var id = results[i].id + '-' + name;
  12672. if (!self.stats[id]) {
  12673. self.stats[id] = {
  12674. startTime: now,
  12675. endTime: now,
  12676. values: [],
  12677. times: []
  12678. };
  12679. }
  12680. self.stats[id].values.push(results[i].stat(name));
  12681. self.stats[id].times.push(now.getTime());
  12682. if (self.stats[id].values.length > self.maxstats) {
  12683. self.stats[id].values.shift();
  12684. self.stats[id].times.shift();
  12685. }
  12686. self.stats[id].endTime = now;
  12687. });
  12688. }
  12689. });
  12690. }, 1000);
  12691. }
  12692. };
  12693. dumpSDP = function(description) {
  12694. return 'type: ' + description.type + '\r\n' + description.sdp;
  12695. }
  12696. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  12697. TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
  12698. TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
  12699. TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() {
  12700. var publicLocalDescription = APP.simulcast.reverseTransformLocalDescription(this.peerconnection.localDescription);
  12701. return publicLocalDescription;
  12702. });
  12703. TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() {
  12704. var publicRemoteDescription = APP.simulcast.reverseTransformRemoteDescription(this.peerconnection.remoteDescription);
  12705. return publicRemoteDescription;
  12706. });
  12707. }
  12708. TraceablePeerConnection.prototype.addStream = function (stream) {
  12709. this.trace('addStream', stream.id);
  12710. APP.simulcast.resetSender();
  12711. try
  12712. {
  12713. this.peerconnection.addStream(stream);
  12714. }
  12715. catch (e)
  12716. {
  12717. console.error(e);
  12718. return;
  12719. }
  12720. };
  12721. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  12722. this.trace('removeStream', stream.id);
  12723. APP.simulcast.resetSender();
  12724. if(stopStreams) {
  12725. stream.getAudioTracks().forEach(function (track) {
  12726. track.stop();
  12727. });
  12728. stream.getVideoTracks().forEach(function (track) {
  12729. track.stop();
  12730. });
  12731. }
  12732. this.peerconnection.removeStream(stream);
  12733. };
  12734. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  12735. this.trace('createDataChannel', label, opts);
  12736. return this.peerconnection.createDataChannel(label, opts);
  12737. };
  12738. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  12739. var self = this;
  12740. description = APP.simulcast.transformLocalDescription(description);
  12741. this.trace('setLocalDescription', dumpSDP(description));
  12742. this.peerconnection.setLocalDescription(description,
  12743. function () {
  12744. self.trace('setLocalDescriptionOnSuccess');
  12745. successCallback();
  12746. },
  12747. function (err) {
  12748. self.trace('setLocalDescriptionOnFailure', err);
  12749. failureCallback(err);
  12750. }
  12751. );
  12752. /*
  12753. if (this.statsinterval === null && this.maxstats > 0) {
  12754. // start gathering stats
  12755. }
  12756. */
  12757. };
  12758. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  12759. var self = this;
  12760. description = APP.simulcast.transformRemoteDescription(description);
  12761. this.trace('setRemoteDescription', dumpSDP(description));
  12762. this.peerconnection.setRemoteDescription(description,
  12763. function () {
  12764. self.trace('setRemoteDescriptionOnSuccess');
  12765. successCallback();
  12766. },
  12767. function (err) {
  12768. self.trace('setRemoteDescriptionOnFailure', err);
  12769. failureCallback(err);
  12770. }
  12771. );
  12772. /*
  12773. if (this.statsinterval === null && this.maxstats > 0) {
  12774. // start gathering stats
  12775. }
  12776. */
  12777. };
  12778. TraceablePeerConnection.prototype.close = function () {
  12779. this.trace('stop');
  12780. if (this.statsinterval !== null) {
  12781. window.clearInterval(this.statsinterval);
  12782. this.statsinterval = null;
  12783. }
  12784. this.peerconnection.close();
  12785. };
  12786. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  12787. var self = this;
  12788. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  12789. this.peerconnection.createOffer(
  12790. function (offer) {
  12791. self.trace('createOfferOnSuccess', dumpSDP(offer));
  12792. successCallback(offer);
  12793. },
  12794. function(err) {
  12795. self.trace('createOfferOnFailure', err);
  12796. failureCallback(err);
  12797. },
  12798. constraints
  12799. );
  12800. };
  12801. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  12802. var self = this;
  12803. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  12804. this.peerconnection.createAnswer(
  12805. function (answer) {
  12806. answer = APP.simulcast.transformAnswer(answer);
  12807. self.trace('createAnswerOnSuccess', dumpSDP(answer));
  12808. successCallback(answer);
  12809. },
  12810. function(err) {
  12811. self.trace('createAnswerOnFailure', err);
  12812. failureCallback(err);
  12813. },
  12814. constraints
  12815. );
  12816. };
  12817. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  12818. var self = this;
  12819. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  12820. this.peerconnection.addIceCandidate(candidate);
  12821. /* maybe later
  12822. this.peerconnection.addIceCandidate(candidate,
  12823. function () {
  12824. self.trace('addIceCandidateOnSuccess');
  12825. successCallback();
  12826. },
  12827. function (err) {
  12828. self.trace('addIceCandidateOnFailure', err);
  12829. failureCallback(err);
  12830. }
  12831. );
  12832. */
  12833. };
  12834. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  12835. if (navigator.mozGetUserMedia) {
  12836. // ignore for now...
  12837. if(!errback)
  12838. errback = function () {
  12839. }
  12840. this.peerconnection.getStats(null,callback,errback);
  12841. } else {
  12842. this.peerconnection.getStats(callback);
  12843. }
  12844. };
  12845. module.exports = TraceablePeerConnection;
  12846. },{}],53:[function(require,module,exports){
  12847. /* global $, $iq, config, connection, UI, messageHandler,
  12848. roomName, sessionTerminated, Strophe, Util */
  12849. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  12850. var Settings = require("../settings/Settings");
  12851. var AuthenticationEvents
  12852. = require("../../service/authentication/AuthenticationEvents");
  12853. /**
  12854. * Contains logic responsible for enabling/disabling functionality available
  12855. * only to moderator users.
  12856. */
  12857. var connection = null;
  12858. var focusUserJid;
  12859. function createExpBackoffTimer(step) {
  12860. var count = 1;
  12861. return function (reset) {
  12862. // Reset call
  12863. if (reset) {
  12864. count = 1;
  12865. return;
  12866. }
  12867. // Calculate next timeout
  12868. var timeout = Math.pow(2, count - 1);
  12869. count += 1;
  12870. return timeout * step;
  12871. };
  12872. }
  12873. var getNextTimeout = createExpBackoffTimer(1000);
  12874. var getNextErrorTimeout = createExpBackoffTimer(1000);
  12875. // External authentication stuff
  12876. var externalAuthEnabled = false;
  12877. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  12878. // it will be enabled automatically if focus detects the component through
  12879. // service discovery.
  12880. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  12881. var eventEmitter = null;
  12882. var Moderator = {
  12883. isModerator: function () {
  12884. return connection && connection.emuc.isModerator();
  12885. },
  12886. isPeerModerator: function (peerJid) {
  12887. return connection &&
  12888. connection.emuc.getMemberRole(peerJid) === 'moderator';
  12889. },
  12890. isExternalAuthEnabled: function () {
  12891. return externalAuthEnabled;
  12892. },
  12893. isSipGatewayEnabled: function () {
  12894. return sipGatewayEnabled;
  12895. },
  12896. setConnection: function (con) {
  12897. connection = con;
  12898. },
  12899. init: function (xmpp, emitter) {
  12900. this.xmppService = xmpp;
  12901. eventEmitter = emitter;
  12902. // Message listener that talks to POPUP window
  12903. function listener(event) {
  12904. if (event.data && event.data.sessionId) {
  12905. if (event.origin !== window.location.origin) {
  12906. console.warn(
  12907. "Ignoring sessionId from different origin: " + event.origin);
  12908. return;
  12909. }
  12910. localStorage.setItem('sessionId', event.data.sessionId);
  12911. // After popup is closed we will authenticate
  12912. }
  12913. }
  12914. // Register
  12915. if (window.addEventListener) {
  12916. window.addEventListener("message", listener, false);
  12917. } else {
  12918. window.attachEvent("onmessage", listener);
  12919. }
  12920. },
  12921. onMucLeft: function (jid) {
  12922. console.info("Someone left is it focus ? " + jid);
  12923. var resource = Strophe.getResourceFromJid(jid);
  12924. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  12925. console.info(
  12926. "Focus has left the room - leaving conference");
  12927. //hangUp();
  12928. // We'd rather reload to have everything re-initialized
  12929. // FIXME: show some message before reload
  12930. location.reload();
  12931. }
  12932. },
  12933. setFocusUserJid: function (focusJid) {
  12934. if (!focusUserJid) {
  12935. focusUserJid = focusJid;
  12936. console.info("Focus jid set to: " + focusUserJid);
  12937. }
  12938. },
  12939. getFocusUserJid: function () {
  12940. return focusUserJid;
  12941. },
  12942. getFocusComponent: function () {
  12943. // Get focus component address
  12944. var focusComponent = config.hosts.focus;
  12945. // If not specified use default: 'focus.domain'
  12946. if (!focusComponent) {
  12947. focusComponent = 'focus.' + config.hosts.domain;
  12948. }
  12949. return focusComponent;
  12950. },
  12951. createConferenceIq: function (roomName) {
  12952. // Generate create conference IQ
  12953. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  12954. // Session Id used for authentication
  12955. var sessionId = localStorage.getItem('sessionId');
  12956. var machineUID = Settings.getSettings().uid;
  12957. console.info(
  12958. "Session ID: " + sessionId + " machine UID: " + machineUID);
  12959. elem.c('conference', {
  12960. xmlns: 'http://jitsi.org/protocol/focus',
  12961. room: roomName,
  12962. 'machine-uid': machineUID
  12963. });
  12964. if (sessionId) {
  12965. elem.attrs({ 'session-id': sessionId});
  12966. }
  12967. if (config.hosts.bridge !== undefined) {
  12968. elem.c(
  12969. 'property',
  12970. { name: 'bridge', value: config.hosts.bridge})
  12971. .up();
  12972. }
  12973. // Tell the focus we have Jigasi configured
  12974. if (config.hosts.call_control !== undefined) {
  12975. elem.c(
  12976. 'property',
  12977. { name: 'call_control', value: config.hosts.call_control})
  12978. .up();
  12979. }
  12980. if (config.channelLastN !== undefined) {
  12981. elem.c(
  12982. 'property',
  12983. { name: 'channelLastN', value: config.channelLastN})
  12984. .up();
  12985. }
  12986. if (config.adaptiveLastN !== undefined) {
  12987. elem.c(
  12988. 'property',
  12989. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  12990. .up();
  12991. }
  12992. if (config.adaptiveSimulcast !== undefined) {
  12993. elem.c(
  12994. 'property',
  12995. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  12996. .up();
  12997. }
  12998. if (config.openSctp !== undefined) {
  12999. elem.c(
  13000. 'property',
  13001. { name: 'openSctp', value: config.openSctp})
  13002. .up();
  13003. }
  13004. if (config.enableFirefoxSupport !== undefined) {
  13005. elem.c(
  13006. 'property',
  13007. { name: 'enableFirefoxHacks',
  13008. value: config.enableFirefoxSupport})
  13009. .up();
  13010. }
  13011. elem.up();
  13012. return elem;
  13013. },
  13014. parseConfigOptions: function (resultIq) {
  13015. Moderator.setFocusUserJid(
  13016. $(resultIq).find('conference').attr('focusjid'));
  13017. var authenticationEnabled
  13018. = $(resultIq).find(
  13019. '>conference>property' +
  13020. '[name=\'authentication\'][value=\'true\']').length > 0;
  13021. console.info("Authentication enabled: " + authenticationEnabled);
  13022. externalAuthEnabled
  13023. = $(resultIq).find(
  13024. '>conference>property' +
  13025. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  13026. console.info('External authentication enabled: ' + externalAuthEnabled);
  13027. if (!externalAuthEnabled) {
  13028. // We expect to receive sessionId in 'internal' authentication mode
  13029. var sessionId
  13030. = $(resultIq).find('conference').attr('session-id');
  13031. if (sessionId) {
  13032. console.info('Received sessionId: ' + sessionId);
  13033. localStorage.setItem('sessionId', sessionId);
  13034. }
  13035. }
  13036. var authIdentity = $(resultIq).find('>conference').attr('identity');
  13037. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  13038. authenticationEnabled, authIdentity);
  13039. // Check if focus has auto-detected Jigasi component(this will be also
  13040. // included if we have passed our host from the config)
  13041. if ($(resultIq).find(
  13042. '>conference>property' +
  13043. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  13044. sipGatewayEnabled = true;
  13045. }
  13046. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  13047. },
  13048. // FIXME: we need to show the fact that we're waiting for the focus
  13049. // to the user(or that focus is not available)
  13050. allocateConferenceFocus: function (roomName, callback) {
  13051. // Try to use focus user JID from the config
  13052. Moderator.setFocusUserJid(config.focusUserJid);
  13053. // Send create conference IQ
  13054. var iq = Moderator.createConferenceIq(roomName);
  13055. var self = this;
  13056. connection.sendIQ(
  13057. iq,
  13058. function (result) {
  13059. // Setup config options
  13060. Moderator.parseConfigOptions(result);
  13061. if ('true' === $(result).find('conference').attr('ready')) {
  13062. // Reset both timers
  13063. getNextTimeout(true);
  13064. getNextErrorTimeout(true);
  13065. // Exec callback
  13066. callback();
  13067. } else {
  13068. var waitMs = getNextTimeout();
  13069. console.info("Waiting for the focus... " + waitMs);
  13070. // Reset error timeout
  13071. getNextErrorTimeout(true);
  13072. window.setTimeout(
  13073. function () {
  13074. Moderator.allocateConferenceFocus(
  13075. roomName, callback);
  13076. }, waitMs);
  13077. }
  13078. },
  13079. function (error) {
  13080. // Not authorized to create new room
  13081. if ($(error).find('>error>not-authorized').length) {
  13082. console.warn("Unauthorized to start the conference", error);
  13083. if ($(error).find('>error>session-invalid').length) {
  13084. // FIXME: just retry
  13085. console.info("Session expired! - removing");
  13086. localStorage.removeItem("sessionId");
  13087. }
  13088. var toDomain
  13089. = Strophe.getDomainFromJid(error.getAttribute('to'));
  13090. if (toDomain === config.hosts.anonymousdomain) {
  13091. // we are connected with anonymous domain and
  13092. // only non anonymous users can create rooms
  13093. // we must authorize the user
  13094. self.xmppService.promptLogin();
  13095. } else {
  13096. eventEmitter.emit(XMPPEvents.AUTHENTICATION_REQUIRED, // External authentication mode
  13097. function () {
  13098. Moderator.allocateConferenceFocus(
  13099. roomName, callback);
  13100. });
  13101. }
  13102. return;
  13103. }
  13104. var waitMs = getNextErrorTimeout();
  13105. console.error("Focus error, retry after " + waitMs, error);
  13106. // Show message
  13107. APP.UI.messageHandler.notify( null, "notify.focus",
  13108. 'Conference focus', 'disconnected',"notify.focusFail",
  13109. Moderator.getFocusComponent() +
  13110. ' not available - retry in ' +
  13111. (waitMs / 1000) + ' sec',
  13112. {component: Moderator.getFocusComponent(),
  13113. ms: (waitMs / 1000)});
  13114. // Reset response timeout
  13115. getNextTimeout(true);
  13116. window.setTimeout(
  13117. function () {
  13118. Moderator.allocateConferenceFocus(roomName, callback);
  13119. }, waitMs);
  13120. }
  13121. );
  13122. },
  13123. getLoginUrl: function (roomName, urlCallback) {
  13124. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13125. iq.c('login-url', {
  13126. xmlns: 'http://jitsi.org/protocol/focus',
  13127. room: roomName,
  13128. 'machine-uid': Settings.getSettings().uid
  13129. });
  13130. connection.sendIQ(
  13131. iq,
  13132. function (result) {
  13133. var url = $(result).find('login-url').attr('url');
  13134. url = url = decodeURIComponent(url);
  13135. if (url) {
  13136. console.info("Got auth url: " + url);
  13137. urlCallback(url);
  13138. } else {
  13139. console.error(
  13140. "Failed to get auth url from the focus", result);
  13141. }
  13142. },
  13143. function (error) {
  13144. console.error("Get auth url error", error);
  13145. }
  13146. );
  13147. },
  13148. getPopupLoginUrl: function (roomName, urlCallback) {
  13149. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13150. iq.c('login-url', {
  13151. xmlns: 'http://jitsi.org/protocol/focus',
  13152. room: roomName,
  13153. 'machine-uid': Settings.getSettings().uid,
  13154. popup: true
  13155. });
  13156. connection.sendIQ(
  13157. iq,
  13158. function (result) {
  13159. var url = $(result).find('login-url').attr('url');
  13160. url = url = decodeURIComponent(url);
  13161. if (url) {
  13162. console.info("Got POPUP auth url: " + url);
  13163. urlCallback(url);
  13164. } else {
  13165. console.error(
  13166. "Failed to get POPUP auth url from the focus", result);
  13167. }
  13168. },
  13169. function (error) {
  13170. console.error('Get POPUP auth url error', error);
  13171. }
  13172. );
  13173. },
  13174. logout: function (callback) {
  13175. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  13176. var sessionId = localStorage.getItem('sessionId');
  13177. if (!sessionId) {
  13178. callback();
  13179. return;
  13180. }
  13181. iq.c('logout', {
  13182. xmlns: 'http://jitsi.org/protocol/focus',
  13183. 'session-id': sessionId
  13184. });
  13185. connection.sendIQ(
  13186. iq,
  13187. function (result) {
  13188. var logoutUrl = $(result).find('logout').attr('logout-url');
  13189. if (logoutUrl) {
  13190. logoutUrl = decodeURIComponent(logoutUrl);
  13191. }
  13192. console.info("Log out OK, url: " + logoutUrl, result);
  13193. localStorage.removeItem('sessionId');
  13194. callback(logoutUrl);
  13195. },
  13196. function (error) {
  13197. console.error("Logout error", error);
  13198. }
  13199. );
  13200. }
  13201. };
  13202. module.exports = Moderator;
  13203. },{"../../service/authentication/AuthenticationEvents":85,"../../service/xmpp/XMPPEvents":89,"../settings/Settings":38}],54:[function(require,module,exports){
  13204. /* global $, $iq, config, connection, focusMucJid, messageHandler, Moderator,
  13205. Toolbar, Util */
  13206. var Moderator = require("./moderator");
  13207. var recordingToken = null;
  13208. var recordingEnabled;
  13209. /**
  13210. * Whether to use a jirecon component for recording, or use the videobridge
  13211. * through COLIBRI.
  13212. */
  13213. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  13214. /**
  13215. * The ID of the jirecon recording session. Jirecon generates it when we
  13216. * initially start recording, and it needs to be used in subsequent requests
  13217. * to jirecon.
  13218. */
  13219. var jireconRid = null;
  13220. function setRecordingToken(token) {
  13221. recordingToken = token;
  13222. }
  13223. function setRecording(state, token, callback, connection) {
  13224. if (useJirecon){
  13225. setRecordingJirecon(state, token, callback, connection);
  13226. } else {
  13227. setRecordingColibri(state, token, callback, connection);
  13228. }
  13229. }
  13230. function setRecordingJirecon(state, token, callback, connection) {
  13231. if (state == recordingEnabled){
  13232. return;
  13233. }
  13234. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  13235. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  13236. action: state ? 'start' : 'stop',
  13237. mucjid: connection.emuc.roomjid});
  13238. if (!state){
  13239. iq.attrs({rid: jireconRid});
  13240. }
  13241. console.log('Start recording');
  13242. connection.sendIQ(
  13243. iq,
  13244. function (result) {
  13245. // TODO wait for an IQ with the real status, since this is
  13246. // provisional?
  13247. jireconRid = $(result).find('recording').attr('rid');
  13248. console.log('Recording ' + (state ? 'started' : 'stopped') +
  13249. '(jirecon)' + result);
  13250. recordingEnabled = state;
  13251. if (!state){
  13252. jireconRid = null;
  13253. }
  13254. callback(state);
  13255. },
  13256. function (error) {
  13257. console.log('Failed to start recording, error: ', error);
  13258. callback(recordingEnabled);
  13259. });
  13260. }
  13261. // Sends a COLIBRI message which enables or disables (according to 'state')
  13262. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  13263. // with the new recording state, according to the IQ.
  13264. function setRecordingColibri(state, token, callback, connection) {
  13265. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  13266. elem.c('conference', {
  13267. xmlns: 'http://jitsi.org/protocol/colibri'
  13268. });
  13269. elem.c('recording', {state: state, token: token});
  13270. connection.sendIQ(elem,
  13271. function (result) {
  13272. console.log('Set recording "', state, '". Result:', result);
  13273. var recordingElem = $(result).find('>conference>recording');
  13274. var newState = ('true' === recordingElem.attr('state'));
  13275. recordingEnabled = newState;
  13276. callback(newState);
  13277. },
  13278. function (error) {
  13279. console.warn(error);
  13280. callback(recordingEnabled);
  13281. }
  13282. );
  13283. }
  13284. var Recording = {
  13285. toggleRecording: function (tokenEmptyCallback,
  13286. startingCallback, startedCallback, connection) {
  13287. if (!Moderator.isModerator()) {
  13288. console.log(
  13289. 'non-focus, or conference not yet organized:' +
  13290. ' not enabling recording');
  13291. return;
  13292. }
  13293. var self = this;
  13294. // Jirecon does not (currently) support a token.
  13295. if (!recordingToken && !useJirecon) {
  13296. tokenEmptyCallback(function (value) {
  13297. setRecordingToken(value);
  13298. self.toggleRecording();
  13299. });
  13300. return;
  13301. }
  13302. var oldState = recordingEnabled;
  13303. startingCallback(!oldState);
  13304. setRecording(!oldState,
  13305. recordingToken,
  13306. function (state) {
  13307. console.log("New recording state: ", state);
  13308. if (state === oldState) {
  13309. // FIXME: new focus:
  13310. // this will not work when moderator changes
  13311. // during active session. Then it will assume that
  13312. // recording status has changed to true, but it might have
  13313. // been already true(and we only received actual status from
  13314. // the focus).
  13315. //
  13316. // SO we start with status null, so that it is initialized
  13317. // here and will fail only after second click, so if invalid
  13318. // token was used we have to press the button twice before
  13319. // current status will be fetched and token will be reset.
  13320. //
  13321. // Reliable way would be to return authentication error.
  13322. // Or status update when moderator connects.
  13323. // Or we have to stop recording session when current
  13324. // moderator leaves the room.
  13325. // Failed to change, reset the token because it might
  13326. // have been wrong
  13327. setRecordingToken(null);
  13328. }
  13329. startedCallback(state);
  13330. },
  13331. connection
  13332. );
  13333. }
  13334. }
  13335. module.exports = Recording;
  13336. },{"./moderator":53}],55:[function(require,module,exports){
  13337. /* jshint -W117 */
  13338. /* a simple MUC connection plugin
  13339. * can only handle a single MUC room
  13340. */
  13341. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13342. var Moderator = require("./moderator");
  13343. var JingleSession = require("./JingleSession");
  13344. var bridgeIsDown = false;
  13345. module.exports = function(XMPP, eventEmitter) {
  13346. Strophe.addConnectionPlugin('emuc', {
  13347. connection: null,
  13348. roomjid: null,
  13349. myroomjid: null,
  13350. members: {},
  13351. list_members: [], // so we can elect a new focus
  13352. presMap: {},
  13353. preziMap: {},
  13354. joined: false,
  13355. isOwner: false,
  13356. role: null,
  13357. focusMucJid: null,
  13358. ssrc2jid: {},
  13359. init: function (conn) {
  13360. this.connection = conn;
  13361. },
  13362. initPresenceMap: function (myroomjid) {
  13363. this.presMap['to'] = myroomjid;
  13364. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  13365. },
  13366. doJoin: function (jid, password) {
  13367. this.myroomjid = jid;
  13368. console.info("Joined MUC as " + this.myroomjid);
  13369. this.initPresenceMap(this.myroomjid);
  13370. if (!this.roomjid) {
  13371. this.roomjid = Strophe.getBareJidFromJid(jid);
  13372. // add handlers (just once)
  13373. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  13374. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  13375. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  13376. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  13377. }
  13378. if (password !== undefined) {
  13379. this.presMap['password'] = password;
  13380. }
  13381. this.sendPresence();
  13382. },
  13383. doLeave: function () {
  13384. console.log("do leave", this.myroomjid);
  13385. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  13386. this.presMap.length = 0;
  13387. this.connection.send(pres);
  13388. },
  13389. createNonAnonymousRoom: function () {
  13390. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  13391. var getForm = $iq({type: 'get', to: this.roomjid})
  13392. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  13393. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13394. var self = this;
  13395. this.connection.sendIQ(getForm, function (form) {
  13396. if (!$(form).find(
  13397. '>query>x[xmlns="jabber:x:data"]' +
  13398. '>field[var="muc#roomconfig_whois"]').length) {
  13399. console.error('non-anonymous rooms not supported');
  13400. return;
  13401. }
  13402. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  13403. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  13404. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13405. formSubmit.c('field', {'var': 'FORM_TYPE'})
  13406. .c('value')
  13407. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  13408. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  13409. .c('value').t('anyone').up().up();
  13410. self.connection.sendIQ(formSubmit);
  13411. }, function (error) {
  13412. console.error("Error getting room configuration form");
  13413. });
  13414. },
  13415. onPresence: function (pres) {
  13416. var from = pres.getAttribute('from');
  13417. // What is this for? A workaround for something?
  13418. if (pres.getAttribute('type')) {
  13419. return true;
  13420. }
  13421. // Parse etherpad tag.
  13422. var etherpad = $(pres).find('>etherpad');
  13423. if (etherpad.length) {
  13424. if (config.etherpad_base && !Moderator.isModerator()) {
  13425. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  13426. }
  13427. }
  13428. // Parse prezi tag.
  13429. var presentation = $(pres).find('>prezi');
  13430. if (presentation.length) {
  13431. var url = presentation.attr('url');
  13432. var current = presentation.find('>current').text();
  13433. console.log('presentation info received from', from, url);
  13434. if (this.preziMap[from] == null) {
  13435. this.preziMap[from] = url;
  13436. $(document).trigger('presentationadded.muc', [from, url, current]);
  13437. }
  13438. else {
  13439. $(document).trigger('gotoslide.muc', [from, url, current]);
  13440. }
  13441. }
  13442. else if (this.preziMap[from] != null) {
  13443. var url = this.preziMap[from];
  13444. delete this.preziMap[from];
  13445. $(document).trigger('presentationremoved.muc', [from, url]);
  13446. }
  13447. // Parse audio info tag.
  13448. var audioMuted = $(pres).find('>audiomuted');
  13449. if (audioMuted.length) {
  13450. $(document).trigger('audiomuted.muc', [from, audioMuted.text()]);
  13451. }
  13452. // Parse video info tag.
  13453. var videoMuted = $(pres).find('>videomuted');
  13454. if (videoMuted.length) {
  13455. $(document).trigger('videomuted.muc', [from, videoMuted.text()]);
  13456. }
  13457. var stats = $(pres).find('>stats');
  13458. if (stats.length) {
  13459. var statsObj = {};
  13460. Strophe.forEachChild(stats[0], "stat", function (el) {
  13461. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  13462. });
  13463. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  13464. }
  13465. // Parse status.
  13466. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  13467. this.isOwner = true;
  13468. this.createNonAnonymousRoom();
  13469. }
  13470. // Parse roles.
  13471. var member = {};
  13472. member.show = $(pres).find('>show').text();
  13473. member.status = $(pres).find('>status').text();
  13474. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  13475. member.affiliation = tmp.attr('affiliation');
  13476. member.role = tmp.attr('role');
  13477. // Focus recognition
  13478. member.jid = tmp.attr('jid');
  13479. member.isFocus = false;
  13480. if (member.jid
  13481. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  13482. member.isFocus = true;
  13483. }
  13484. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  13485. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  13486. if (from == this.myroomjid) {
  13487. if (member.affiliation == 'owner') this.isOwner = true;
  13488. if (this.role !== member.role) {
  13489. this.role = member.role;
  13490. eventEmitter.emit(XMPPEvents.LOCALROLE_CHANGED,
  13491. from, member, pres, Moderator.isModerator());
  13492. }
  13493. if (!this.joined) {
  13494. this.joined = true;
  13495. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  13496. this.list_members.push(from);
  13497. }
  13498. } else if (this.members[from] === undefined) {
  13499. // new participant
  13500. this.members[from] = member;
  13501. this.list_members.push(from);
  13502. console.log('entered', from, member);
  13503. if (member.isFocus) {
  13504. this.focusMucJid = from;
  13505. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  13506. }
  13507. else {
  13508. var id = $(pres).find('>userID').text();
  13509. var email = $(pres).find('>email');
  13510. if (email.length > 0) {
  13511. id = email.text();
  13512. }
  13513. eventEmitter.emit(XMPPEvents.MUC_ENTER, from, id, member.displayName);
  13514. }
  13515. } else {
  13516. // Presence update for existing participant
  13517. // Watch role change:
  13518. if (this.members[from].role != member.role) {
  13519. this.members[from].role = member.role;
  13520. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  13521. member.role, member.displayName);
  13522. }
  13523. }
  13524. // Always trigger presence to update bindings
  13525. this.parsePresence(from, member, pres);
  13526. // Trigger status message update
  13527. if (member.status) {
  13528. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  13529. }
  13530. return true;
  13531. },
  13532. onPresenceUnavailable: function (pres) {
  13533. var from = pres.getAttribute('from');
  13534. // Status code 110 indicates that this notification is "self-presence".
  13535. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  13536. delete this.members[from];
  13537. this.list_members.splice(this.list_members.indexOf(from), 1);
  13538. this.onParticipantLeft(from);
  13539. }
  13540. // If the status code is 110 this means we're leaving and we would like
  13541. // to remove everyone else from our view, so we trigger the event.
  13542. else if (this.list_members.length > 1) {
  13543. for (var i = 0; i < this.list_members.length; i++) {
  13544. var member = this.list_members[i];
  13545. delete this.members[i];
  13546. this.list_members.splice(i, 1);
  13547. this.onParticipantLeft(member);
  13548. }
  13549. }
  13550. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  13551. $(document).trigger('kicked.muc', [from]);
  13552. if (this.myroomjid === from) {
  13553. XMPP.disposeConference(false);
  13554. eventEmitter.emit(XMPPEvents.KICKED);
  13555. }
  13556. }
  13557. return true;
  13558. },
  13559. onPresenceError: function (pres) {
  13560. var from = pres.getAttribute('from');
  13561. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13562. console.log('on password required', from);
  13563. var self = this;
  13564. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  13565. self.doJoin(from, value);
  13566. });
  13567. } else if ($(pres).find(
  13568. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13569. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  13570. if (toDomain === config.hosts.anonymousdomain) {
  13571. // enter the room by replying with 'not-authorized'. This would
  13572. // result in reconnection from authorized domain.
  13573. // We're either missing Jicofo/Prosody config for anonymous
  13574. // domains or something is wrong.
  13575. // XMPP.promptLogin();
  13576. APP.UI.messageHandler.openReportDialog(null,
  13577. 'Oops ! We couldn`t join the conference.' +
  13578. ' There might be some problem with security' +
  13579. ' configuration. Please contact service' +
  13580. ' administrator.', pres);
  13581. } else {
  13582. console.warn('onPresError ', pres);
  13583. APP.UI.messageHandler.openReportDialog(null,
  13584. 'Oops! Something went wrong and we couldn`t connect to the conference.',
  13585. pres);
  13586. }
  13587. } else {
  13588. console.warn('onPresError ', pres);
  13589. APP.UI.messageHandler.openReportDialog(null,
  13590. 'Oops! Something went wrong and we couldn`t connect to the conference.',
  13591. pres);
  13592. }
  13593. return true;
  13594. },
  13595. sendMessage: function (body, nickname) {
  13596. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  13597. msg.c('body', body).up();
  13598. if (nickname) {
  13599. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  13600. }
  13601. this.connection.send(msg);
  13602. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  13603. },
  13604. setSubject: function (subject) {
  13605. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  13606. msg.c('subject', subject);
  13607. this.connection.send(msg);
  13608. console.log("topic changed to " + subject);
  13609. },
  13610. onMessage: function (msg) {
  13611. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  13612. var from = msg.getAttribute('from');
  13613. var nick =
  13614. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  13615. .text() ||
  13616. Strophe.getResourceFromJid(from);
  13617. var txt = $(msg).find('>body').text();
  13618. var type = msg.getAttribute("type");
  13619. if (type == "error") {
  13620. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  13621. $(msg).find('>text').text(), txt);
  13622. return true;
  13623. }
  13624. var subject = $(msg).find('>subject');
  13625. if (subject.length) {
  13626. var subjectText = subject.text();
  13627. if (subjectText || subjectText == "") {
  13628. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  13629. console.log("Subject is changed to " + subjectText);
  13630. }
  13631. }
  13632. if (txt) {
  13633. console.log('chat', nick, txt);
  13634. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  13635. from, nick, txt, this.myroomjid);
  13636. }
  13637. return true;
  13638. },
  13639. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  13640. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  13641. var ob = this;
  13642. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  13643. function (res) {
  13644. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  13645. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  13646. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13647. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  13648. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  13649. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  13650. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  13651. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  13652. ob.connection.sendIQ(formsubmit,
  13653. onSuccess,
  13654. onError);
  13655. } else {
  13656. onNotSupported();
  13657. }
  13658. }, onError);
  13659. },
  13660. kick: function (jid) {
  13661. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  13662. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  13663. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  13664. .c('reason').t('You have been kicked.').up().up().up();
  13665. this.connection.sendIQ(
  13666. kickIQ,
  13667. function (result) {
  13668. console.log('Kick participant with jid: ', jid, result);
  13669. },
  13670. function (error) {
  13671. console.log('Kick participant error: ', error);
  13672. });
  13673. },
  13674. sendPresence: function () {
  13675. var pres = $pres({to: this.presMap['to'] });
  13676. pres.c('x', {xmlns: this.presMap['xns']});
  13677. if (this.presMap['password']) {
  13678. pres.c('password').t(this.presMap['password']).up();
  13679. }
  13680. pres.up();
  13681. // Send XEP-0115 'c' stanza that contains our capabilities info
  13682. if (this.connection.caps) {
  13683. this.connection.caps.node = config.clientNode;
  13684. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  13685. }
  13686. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  13687. .t(navigator.userAgent).up();
  13688. if (this.presMap['bridgeIsDown']) {
  13689. pres.c('bridgeIsDown').up();
  13690. }
  13691. if (this.presMap['email']) {
  13692. pres.c('email').t(this.presMap['email']).up();
  13693. }
  13694. if (this.presMap['userId']) {
  13695. pres.c('userId').t(this.presMap['userId']).up();
  13696. }
  13697. if (this.presMap['displayName']) {
  13698. // XEP-0172
  13699. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  13700. .t(this.presMap['displayName']).up();
  13701. }
  13702. if (this.presMap['audions']) {
  13703. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  13704. .t(this.presMap['audiomuted']).up();
  13705. }
  13706. if (this.presMap['videons']) {
  13707. pres.c('videomuted', {xmlns: this.presMap['videons']})
  13708. .t(this.presMap['videomuted']).up();
  13709. }
  13710. if (this.presMap['statsns']) {
  13711. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  13712. for (var stat in this.presMap["stats"])
  13713. if (this.presMap["stats"][stat] != null)
  13714. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  13715. pres.up();
  13716. }
  13717. if (this.presMap['prezins']) {
  13718. pres.c('prezi',
  13719. {xmlns: this.presMap['prezins'],
  13720. 'url': this.presMap['preziurl']})
  13721. .c('current').t(this.presMap['prezicurrent']).up().up();
  13722. }
  13723. if (this.presMap['etherpadns']) {
  13724. pres.c('etherpad', {xmlns: this.presMap['etherpadns']})
  13725. .t(this.presMap['etherpadname']).up();
  13726. }
  13727. if (this.presMap['medians']) {
  13728. pres.c('media', {xmlns: this.presMap['medians']});
  13729. var sourceNumber = 0;
  13730. Object.keys(this.presMap).forEach(function (key) {
  13731. if (key.indexOf('source') >= 0) {
  13732. sourceNumber++;
  13733. }
  13734. });
  13735. if (sourceNumber > 0)
  13736. for (var i = 1; i <= sourceNumber / 3; i++) {
  13737. pres.c('source',
  13738. {type: this.presMap['source' + i + '_type'],
  13739. ssrc: this.presMap['source' + i + '_ssrc'],
  13740. direction: this.presMap['source' + i + '_direction']
  13741. || 'sendrecv' }
  13742. ).up();
  13743. }
  13744. }
  13745. pres.up();
  13746. this.connection.send(pres);
  13747. },
  13748. addDisplayNameToPresence: function (displayName) {
  13749. this.presMap['displayName'] = displayName;
  13750. },
  13751. addMediaToPresence: function (sourceNumber, mtype, ssrcs, direction) {
  13752. if (!this.presMap['medians'])
  13753. this.presMap['medians'] = 'http://estos.de/ns/mjs';
  13754. this.presMap['source' + sourceNumber + '_type'] = mtype;
  13755. this.presMap['source' + sourceNumber + '_ssrc'] = ssrcs;
  13756. this.presMap['source' + sourceNumber + '_direction'] = direction;
  13757. },
  13758. clearPresenceMedia: function () {
  13759. var self = this;
  13760. Object.keys(this.presMap).forEach(function (key) {
  13761. if (key.indexOf('source') != -1) {
  13762. delete self.presMap[key];
  13763. }
  13764. });
  13765. },
  13766. addPreziToPresence: function (url, currentSlide) {
  13767. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  13768. this.presMap['preziurl'] = url;
  13769. this.presMap['prezicurrent'] = currentSlide;
  13770. },
  13771. removePreziFromPresence: function () {
  13772. delete this.presMap['prezins'];
  13773. delete this.presMap['preziurl'];
  13774. delete this.presMap['prezicurrent'];
  13775. },
  13776. addCurrentSlideToPresence: function (currentSlide) {
  13777. this.presMap['prezicurrent'] = currentSlide;
  13778. },
  13779. getPrezi: function (roomjid) {
  13780. return this.preziMap[roomjid];
  13781. },
  13782. addEtherpadToPresence: function (etherpadName) {
  13783. this.presMap['etherpadns'] = 'http://jitsi.org/jitmeet/etherpad';
  13784. this.presMap['etherpadname'] = etherpadName;
  13785. },
  13786. addAudioInfoToPresence: function (isMuted) {
  13787. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  13788. this.presMap['audiomuted'] = isMuted.toString();
  13789. },
  13790. addVideoInfoToPresence: function (isMuted) {
  13791. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  13792. this.presMap['videomuted'] = isMuted.toString();
  13793. },
  13794. addConnectionInfoToPresence: function (stats) {
  13795. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  13796. this.presMap['stats'] = stats;
  13797. },
  13798. findJidFromResource: function (resourceJid) {
  13799. if (resourceJid &&
  13800. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  13801. return this.myroomjid;
  13802. }
  13803. var peerJid = null;
  13804. Object.keys(this.members).some(function (jid) {
  13805. peerJid = jid;
  13806. return Strophe.getResourceFromJid(jid) === resourceJid;
  13807. });
  13808. return peerJid;
  13809. },
  13810. addBridgeIsDownToPresence: function () {
  13811. this.presMap['bridgeIsDown'] = true;
  13812. },
  13813. addEmailToPresence: function (email) {
  13814. this.presMap['email'] = email;
  13815. },
  13816. addUserIdToPresence: function (userId) {
  13817. this.presMap['userId'] = userId;
  13818. },
  13819. isModerator: function () {
  13820. return this.role === 'moderator';
  13821. },
  13822. getMemberRole: function (peerJid) {
  13823. if (this.members[peerJid]) {
  13824. return this.members[peerJid].role;
  13825. }
  13826. return null;
  13827. },
  13828. onParticipantLeft: function (jid) {
  13829. eventEmitter.emit(XMPPEvents.MUC_LEFT, jid);
  13830. this.connection.jingle.terminateByJid(jid);
  13831. if (this.getPrezi(jid)) {
  13832. $(document).trigger('presentationremoved.muc',
  13833. [jid, this.getPrezi(jid)]);
  13834. }
  13835. Moderator.onMucLeft(jid);
  13836. },
  13837. parsePresence: function (from, memeber, pres) {
  13838. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  13839. bridgeIsDown = true;
  13840. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  13841. }
  13842. if(memeber.isFocus)
  13843. return;
  13844. var self = this;
  13845. // Remove old ssrcs coming from the jid
  13846. Object.keys(this.ssrc2jid).forEach(function (ssrc) {
  13847. if (self.ssrc2jid[ssrc] == from) {
  13848. delete self.ssrc2jid[ssrc];
  13849. }
  13850. });
  13851. var changedStreams = [];
  13852. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  13853. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  13854. var ssrcV = ssrc.getAttribute('ssrc');
  13855. self.ssrc2jid[ssrcV] = from;
  13856. JingleSession.notReceivedSSRCs.push(ssrcV);
  13857. var type = ssrc.getAttribute('type');
  13858. var direction = ssrc.getAttribute('direction');
  13859. changedStreams.push({type: type, direction: direction});
  13860. });
  13861. eventEmitter.emit(XMPPEvents.CHANGED_STREAMS, from, changedStreams);
  13862. var displayName = !config.displayJids
  13863. ? memeber.displayName : Strophe.getResourceFromJid(from);
  13864. if (displayName && displayName.length > 0)
  13865. {
  13866. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  13867. }
  13868. var id = $(pres).find('>userID').text();
  13869. var email = $(pres).find('>email');
  13870. if(email.length > 0) {
  13871. id = email.text();
  13872. }
  13873. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  13874. }
  13875. });
  13876. };
  13877. },{"../../service/xmpp/XMPPEvents":89,"./JingleSession":48,"./moderator":53}],56:[function(require,module,exports){
  13878. /* jshint -W117 */
  13879. var JingleSession = require("./JingleSession");
  13880. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13881. module.exports = function(XMPP, eventEmitter)
  13882. {
  13883. function CallIncomingJingle(sid, connection) {
  13884. var sess = connection.jingle.sessions[sid];
  13885. // TODO: do we check activecall == null?
  13886. connection.jingle.activecall = sess;
  13887. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  13888. // TODO: check affiliation and/or role
  13889. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  13890. sess.usedrip = true; // not-so-naive trickle ice
  13891. sess.sendAnswer();
  13892. sess.accept();
  13893. };
  13894. Strophe.addConnectionPlugin('jingle', {
  13895. connection: null,
  13896. sessions: {},
  13897. jid2session: {},
  13898. ice_config: {iceServers: []},
  13899. pc_constraints: {},
  13900. activecall: null,
  13901. media_constraints: {
  13902. mandatory: {
  13903. 'OfferToReceiveAudio': true,
  13904. 'OfferToReceiveVideo': true
  13905. }
  13906. // MozDontOfferDataChannel: true when this is firefox
  13907. },
  13908. init: function (conn) {
  13909. this.connection = conn;
  13910. if (this.connection.disco) {
  13911. // http://xmpp.org/extensions/xep-0167.html#support
  13912. // http://xmpp.org/extensions/xep-0176.html#support
  13913. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  13914. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  13915. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  13916. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  13917. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  13918. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  13919. // this is dealt with by SDP O/A so we don't need to annouce this
  13920. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  13921. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  13922. if (config.useRtcpMux) {
  13923. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  13924. }
  13925. if (config.useBundle) {
  13926. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  13927. }
  13928. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  13929. }
  13930. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  13931. },
  13932. onJingle: function (iq) {
  13933. var sid = $(iq).find('jingle').attr('sid');
  13934. var action = $(iq).find('jingle').attr('action');
  13935. var fromJid = iq.getAttribute('from');
  13936. // send ack first
  13937. var ack = $iq({type: 'result',
  13938. to: fromJid,
  13939. id: iq.getAttribute('id')
  13940. });
  13941. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  13942. var sess = this.sessions[sid];
  13943. if ('session-initiate' != action) {
  13944. if (sess === null) {
  13945. ack.type = 'error';
  13946. ack.c('error', {type: 'cancel'})
  13947. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  13948. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  13949. this.connection.send(ack);
  13950. return true;
  13951. }
  13952. // compare from to sess.peerjid (bare jid comparison for later compat with message-mode)
  13953. // local jid is not checked
  13954. if (Strophe.getBareJidFromJid(fromJid) != Strophe.getBareJidFromJid(sess.peerjid)) {
  13955. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  13956. ack.type = 'error';
  13957. ack.c('error', {type: 'cancel'})
  13958. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  13959. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  13960. this.connection.send(ack);
  13961. return true;
  13962. }
  13963. } else if (sess !== undefined) {
  13964. // existing session with same session id
  13965. // this might be out-of-order if the sess.peerjid is the same as from
  13966. ack.type = 'error';
  13967. ack.c('error', {type: 'cancel'})
  13968. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  13969. console.warn('duplicate session id', sid);
  13970. this.connection.send(ack);
  13971. return true;
  13972. }
  13973. // FIXME: check for a defined action
  13974. this.connection.send(ack);
  13975. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  13976. switch (action) {
  13977. case 'session-initiate':
  13978. sess = new JingleSession(
  13979. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  13980. this.connection, XMPP);
  13981. // configure session
  13982. sess.media_constraints = this.media_constraints;
  13983. sess.pc_constraints = this.pc_constraints;
  13984. sess.ice_config = this.ice_config;
  13985. sess.initiate(fromJid, false);
  13986. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  13987. sess.setRemoteDescription($(iq).find('>jingle'), 'offer');
  13988. this.sessions[sess.sid] = sess;
  13989. this.jid2session[sess.peerjid] = sess;
  13990. // the callback should either
  13991. // .sendAnswer and .accept
  13992. // or .sendTerminate -- not necessarily synchronus
  13993. CallIncomingJingle(sess.sid, this.connection);
  13994. break;
  13995. case 'session-accept':
  13996. sess.setRemoteDescription($(iq).find('>jingle'), 'answer');
  13997. sess.accept();
  13998. $(document).trigger('callaccepted.jingle', [sess.sid]);
  13999. break;
  14000. case 'session-terminate':
  14001. // If this is not the focus sending the terminate, we have
  14002. // nothing more to do here.
  14003. if (Object.keys(this.sessions).length < 1
  14004. || !(this.sessions[Object.keys(this.sessions)[0]]
  14005. instanceof JingleSession))
  14006. {
  14007. break;
  14008. }
  14009. console.log('terminating...', sess.sid);
  14010. sess.terminate();
  14011. this.terminate(sess.sid);
  14012. if ($(iq).find('>jingle>reason').length) {
  14013. $(document).trigger('callterminated.jingle', [
  14014. sess.sid,
  14015. sess.peerjid,
  14016. $(iq).find('>jingle>reason>:first')[0].tagName,
  14017. $(iq).find('>jingle>reason>text').text()
  14018. ]);
  14019. } else {
  14020. $(document).trigger('callterminated.jingle',
  14021. [sess.sid, sess.peerjid]);
  14022. }
  14023. break;
  14024. case 'transport-info':
  14025. sess.addIceCandidate($(iq).find('>jingle>content'));
  14026. break;
  14027. case 'session-info':
  14028. var affected;
  14029. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14030. $(document).trigger('ringing.jingle', [sess.sid]);
  14031. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14032. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14033. $(document).trigger('mute.jingle', [sess.sid, affected]);
  14034. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14035. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14036. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  14037. }
  14038. break;
  14039. case 'addsource': // FIXME: proprietary, un-jingleish
  14040. case 'source-add': // FIXME: proprietary
  14041. sess.addSource($(iq).find('>jingle>content'), fromJid);
  14042. break;
  14043. case 'removesource': // FIXME: proprietary, un-jingleish
  14044. case 'source-remove': // FIXME: proprietary
  14045. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  14046. break;
  14047. default:
  14048. console.warn('jingle action not implemented', action);
  14049. break;
  14050. }
  14051. return true;
  14052. },
  14053. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  14054. var sess = new JingleSession(myjid || this.connection.jid,
  14055. Math.random().toString(36).substr(2, 12), // random string
  14056. this.connection, XMPP);
  14057. // configure session
  14058. sess.media_constraints = this.media_constraints;
  14059. sess.pc_constraints = this.pc_constraints;
  14060. sess.ice_config = this.ice_config;
  14061. sess.initiate(peerjid, true);
  14062. this.sessions[sess.sid] = sess;
  14063. this.jid2session[sess.peerjid] = sess;
  14064. sess.sendOffer();
  14065. return sess;
  14066. },
  14067. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  14068. if (sid === null || sid === undefined) {
  14069. for (sid in this.sessions) {
  14070. if (this.sessions[sid].state != 'ended') {
  14071. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14072. this.sessions[sid].terminate();
  14073. }
  14074. delete this.jid2session[this.sessions[sid].peerjid];
  14075. delete this.sessions[sid];
  14076. }
  14077. } else if (this.sessions.hasOwnProperty(sid)) {
  14078. if (this.sessions[sid].state != 'ended') {
  14079. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14080. this.sessions[sid].terminate();
  14081. }
  14082. delete this.jid2session[this.sessions[sid].peerjid];
  14083. delete this.sessions[sid];
  14084. }
  14085. },
  14086. // Used to terminate a session when an unavailable presence is received.
  14087. terminateByJid: function (jid) {
  14088. if (this.jid2session.hasOwnProperty(jid)) {
  14089. var sess = this.jid2session[jid];
  14090. if (sess) {
  14091. sess.terminate();
  14092. console.log('peer went away silently', jid);
  14093. delete this.sessions[sess.sid];
  14094. delete this.jid2session[jid];
  14095. $(document).trigger('callterminated.jingle',
  14096. [sess.sid, jid], 'gone');
  14097. }
  14098. }
  14099. },
  14100. terminateRemoteByJid: function (jid, reason) {
  14101. if (this.jid2session.hasOwnProperty(jid)) {
  14102. var sess = this.jid2session[jid];
  14103. if (sess) {
  14104. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  14105. sess.terminate();
  14106. console.log('terminate peer with jid', sess.sid, jid);
  14107. delete this.sessions[sess.sid];
  14108. delete this.jid2session[jid];
  14109. $(document).trigger('callterminated.jingle',
  14110. [sess.sid, jid, 'kicked']);
  14111. }
  14112. }
  14113. },
  14114. getStunAndTurnCredentials: function () {
  14115. // get stun and turn configuration from server via xep-0215
  14116. // uses time-limited credentials as described in
  14117. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  14118. //
  14119. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  14120. // for a prosody module which implements this
  14121. //
  14122. // currently, this doesn't work with updateIce and therefore credentials with a long
  14123. // validity have to be fetched before creating the peerconnection
  14124. // TODO: implement refresh via updateIce as described in
  14125. // https://code.google.com/p/webrtc/issues/detail?id=1650
  14126. var self = this;
  14127. this.connection.sendIQ(
  14128. $iq({type: 'get', to: this.connection.domain})
  14129. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  14130. function (res) {
  14131. var iceservers = [];
  14132. $(res).find('>services>service').each(function (idx, el) {
  14133. el = $(el);
  14134. var dict = {};
  14135. var type = el.attr('type');
  14136. switch (type) {
  14137. case 'stun':
  14138. dict.url = 'stun:' + el.attr('host');
  14139. if (el.attr('port')) {
  14140. dict.url += ':' + el.attr('port');
  14141. }
  14142. iceservers.push(dict);
  14143. break;
  14144. case 'turn':
  14145. case 'turns':
  14146. dict.url = type + ':';
  14147. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  14148. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  14149. dict.url += el.attr('username') + '@';
  14150. } else {
  14151. dict.username = el.attr('username'); // only works in M28
  14152. }
  14153. }
  14154. dict.url += el.attr('host');
  14155. if (el.attr('port') && el.attr('port') != '3478') {
  14156. dict.url += ':' + el.attr('port');
  14157. }
  14158. if (el.attr('transport') && el.attr('transport') != 'udp') {
  14159. dict.url += '?transport=' + el.attr('transport');
  14160. }
  14161. if (el.attr('password')) {
  14162. dict.credential = el.attr('password');
  14163. }
  14164. iceservers.push(dict);
  14165. break;
  14166. }
  14167. });
  14168. self.ice_config.iceServers = iceservers;
  14169. },
  14170. function (err) {
  14171. console.warn('getting turn credentials failed', err);
  14172. console.warn('is mod_turncredentials or similar installed?');
  14173. }
  14174. );
  14175. // implement push?
  14176. },
  14177. /**
  14178. * Populates the log data
  14179. */
  14180. populateData: function () {
  14181. var data = {};
  14182. Object.keys(this.sessions).forEach(function (sid) {
  14183. var session = this.sessions[sid];
  14184. if (session.peerconnection && session.peerconnection.updateLog) {
  14185. // FIXME: should probably be a .dump call
  14186. data["jingle_" + session.sid] = {
  14187. updateLog: session.peerconnection.updateLog,
  14188. stats: session.peerconnection.stats,
  14189. url: window.location.href
  14190. };
  14191. }
  14192. });
  14193. return data;
  14194. }
  14195. });
  14196. };
  14197. },{"../../service/xmpp/XMPPEvents":89,"./JingleSession":48}],57:[function(require,module,exports){
  14198. /* global Strophe */
  14199. module.exports = function () {
  14200. Strophe.addConnectionPlugin('logger', {
  14201. // logs raw stanzas and makes them available for download as JSON
  14202. connection: null,
  14203. log: [],
  14204. init: function (conn) {
  14205. this.connection = conn;
  14206. this.connection.rawInput = this.log_incoming.bind(this);
  14207. this.connection.rawOutput = this.log_outgoing.bind(this);
  14208. },
  14209. log_incoming: function (stanza) {
  14210. this.log.push([new Date().getTime(), 'incoming', stanza]);
  14211. },
  14212. log_outgoing: function (stanza) {
  14213. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  14214. }
  14215. });
  14216. };
  14217. },{}],58:[function(require,module,exports){
  14218. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  14219. setAudioMuted, Strophe */
  14220. /**
  14221. * Moderate connection plugin.
  14222. */
  14223. module.exports = function (XMPP) {
  14224. Strophe.addConnectionPlugin('moderate', {
  14225. connection: null,
  14226. init: function (conn) {
  14227. this.connection = conn;
  14228. this.connection.addHandler(this.onMute.bind(this),
  14229. 'http://jitsi.org/jitmeet/audio',
  14230. 'iq',
  14231. 'set',
  14232. null,
  14233. null);
  14234. },
  14235. setMute: function (jid, mute) {
  14236. console.info("set mute", mute);
  14237. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  14238. .c('mute', {
  14239. xmlns: 'http://jitsi.org/jitmeet/audio',
  14240. jid: jid
  14241. })
  14242. .t(mute.toString())
  14243. .up();
  14244. this.connection.sendIQ(
  14245. iqToFocus,
  14246. function (result) {
  14247. console.log('set mute', result);
  14248. },
  14249. function (error) {
  14250. console.log('set mute error', error);
  14251. });
  14252. },
  14253. onMute: function (iq) {
  14254. var from = iq.getAttribute('from');
  14255. if (from !== this.connection.emuc.focusMucJid) {
  14256. console.warn("Ignored mute from non focus peer");
  14257. return false;
  14258. }
  14259. var mute = $(iq).find('mute');
  14260. if (mute.length) {
  14261. var doMuteAudio = mute.text() === "true";
  14262. APP.UI.setAudioMuted(doMuteAudio);
  14263. XMPP.forceMuted = doMuteAudio;
  14264. }
  14265. return true;
  14266. },
  14267. eject: function (jid) {
  14268. // We're not the focus, so can't terminate
  14269. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  14270. this.connection.emuc.kick(jid);
  14271. }
  14272. });
  14273. }
  14274. },{}],59:[function(require,module,exports){
  14275. /* jshint -W117 */
  14276. module.exports = function() {
  14277. Strophe.addConnectionPlugin('rayo',
  14278. {
  14279. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  14280. connection: null,
  14281. init: function (conn) {
  14282. this.connection = conn;
  14283. if (this.connection.disco) {
  14284. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  14285. }
  14286. this.connection.addHandler(
  14287. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  14288. },
  14289. onRayo: function (iq) {
  14290. console.info("Rayo IQ", iq);
  14291. },
  14292. dial: function (to, from, roomName, roomPass) {
  14293. var self = this;
  14294. var req = $iq(
  14295. {
  14296. type: 'set',
  14297. to: this.connection.emuc.focusMucJid
  14298. }
  14299. );
  14300. req.c('dial',
  14301. {
  14302. xmlns: this.RAYO_XMLNS,
  14303. to: to,
  14304. from: from
  14305. });
  14306. req.c('header',
  14307. {
  14308. name: 'JvbRoomName',
  14309. value: roomName
  14310. }).up();
  14311. if (roomPass !== null && roomPass.length) {
  14312. req.c('header',
  14313. {
  14314. name: 'JvbRoomPassword',
  14315. value: roomPass
  14316. }).up();
  14317. }
  14318. this.connection.sendIQ(
  14319. req,
  14320. function (result) {
  14321. console.info('Dial result ', result);
  14322. var resource = $(result).find('ref').attr('uri');
  14323. this.call_resource = resource.substr('xmpp:'.length);
  14324. console.info(
  14325. "Received call resource: " + this.call_resource);
  14326. },
  14327. function (error) {
  14328. console.info('Dial error ', error);
  14329. }
  14330. );
  14331. },
  14332. hang_up: function () {
  14333. if (!this.call_resource) {
  14334. console.warn("No call in progress");
  14335. return;
  14336. }
  14337. var self = this;
  14338. var req = $iq(
  14339. {
  14340. type: 'set',
  14341. to: this.call_resource
  14342. }
  14343. );
  14344. req.c('hangup',
  14345. {
  14346. xmlns: this.RAYO_XMLNS
  14347. });
  14348. this.connection.sendIQ(
  14349. req,
  14350. function (result) {
  14351. console.info('Hangup result ', result);
  14352. self.call_resource = null;
  14353. },
  14354. function (error) {
  14355. console.info('Hangup error ', error);
  14356. self.call_resource = null;
  14357. }
  14358. );
  14359. }
  14360. }
  14361. );
  14362. };
  14363. },{}],60:[function(require,module,exports){
  14364. /**
  14365. * Strophe logger implementation. Logs from level WARN and above.
  14366. */
  14367. module.exports = function () {
  14368. Strophe.log = function (level, msg) {
  14369. switch (level) {
  14370. case Strophe.LogLevel.WARN:
  14371. console.warn("Strophe: " + msg);
  14372. break;
  14373. case Strophe.LogLevel.ERROR:
  14374. case Strophe.LogLevel.FATAL:
  14375. console.error("Strophe: " + msg);
  14376. break;
  14377. }
  14378. };
  14379. Strophe.getStatusString = function (status) {
  14380. switch (status) {
  14381. case Strophe.Status.ERROR:
  14382. return "ERROR";
  14383. case Strophe.Status.CONNECTING:
  14384. return "CONNECTING";
  14385. case Strophe.Status.CONNFAIL:
  14386. return "CONNFAIL";
  14387. case Strophe.Status.AUTHENTICATING:
  14388. return "AUTHENTICATING";
  14389. case Strophe.Status.AUTHFAIL:
  14390. return "AUTHFAIL";
  14391. case Strophe.Status.CONNECTED:
  14392. return "CONNECTED";
  14393. case Strophe.Status.DISCONNECTED:
  14394. return "DISCONNECTED";
  14395. case Strophe.Status.DISCONNECTING:
  14396. return "DISCONNECTING";
  14397. case Strophe.Status.ATTACHED:
  14398. return "ATTACHED";
  14399. default:
  14400. return "unknown";
  14401. }
  14402. };
  14403. };
  14404. },{}],61:[function(require,module,exports){
  14405. var Moderator = require("./moderator");
  14406. var EventEmitter = require("events");
  14407. var Recording = require("./recording");
  14408. var SDP = require("./SDP");
  14409. var Pako = require("pako");
  14410. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  14411. var UIEvents = require("../../service/UI/UIEvents");
  14412. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14413. var eventEmitter = new EventEmitter();
  14414. var connection = null;
  14415. var authenticatedUser = false;
  14416. function connect(jid, password, uiCredentials) {
  14417. var bosh
  14418. = (uiCredentials && uiCredentials.bosh? uiCredentials.bosh : null)
  14419. || config.bosh || '/http-bind';
  14420. connection = new Strophe.Connection(bosh);
  14421. Moderator.setConnection(connection);
  14422. if(uiCredentials) {
  14423. var email = uiCredentials.email;
  14424. var displayName = uiCredentials.displayName;
  14425. if (email) {
  14426. connection.emuc.addEmailToPresence(email);
  14427. } else {
  14428. connection.emuc.addUserIdToPresence(uiCredentials.uid);
  14429. }
  14430. if (displayName) {
  14431. connection.emuc.addDisplayNameToPresence(displayName);
  14432. }
  14433. }
  14434. if (connection.disco) {
  14435. // for chrome, add multistream cap
  14436. }
  14437. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  14438. if (config.useIPv6) {
  14439. // https://code.google.com/p/webrtc/issues/detail?id=2828
  14440. if (!connection.jingle.pc_constraints.optional)
  14441. connection.jingle.pc_constraints.optional = [];
  14442. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  14443. }
  14444. if(!password)
  14445. password = uiCredentials.password;
  14446. var anonymousConnectionFailed = false;
  14447. connection.connect(jid, password, function (status, msg) {
  14448. console.log('Strophe status changed to',
  14449. Strophe.getStatusString(status));
  14450. if (status === Strophe.Status.CONNECTED) {
  14451. if (config.useStunTurn) {
  14452. connection.jingle.getStunAndTurnCredentials();
  14453. }
  14454. APP.UI.disableConnect();
  14455. console.info("My Jabber ID: " + connection.jid);
  14456. if(password)
  14457. authenticatedUser = true;
  14458. maybeDoJoin();
  14459. } else if (status === Strophe.Status.CONNFAIL) {
  14460. if(msg === 'x-strophe-bad-non-anon-jid') {
  14461. anonymousConnectionFailed = true;
  14462. }
  14463. } else if (status === Strophe.Status.DISCONNECTED) {
  14464. if(anonymousConnectionFailed) {
  14465. // prompt user for username and password
  14466. XMPP.promptLogin();
  14467. }
  14468. } else if (status === Strophe.Status.AUTHFAIL) {
  14469. // wrong password or username, prompt user
  14470. XMPP.promptLogin();
  14471. }
  14472. });
  14473. }
  14474. function maybeDoJoin() {
  14475. if (connection && connection.connected &&
  14476. Strophe.getResourceFromJid(connection.jid)
  14477. && (APP.RTC.localAudio || APP.RTC.localVideo)) {
  14478. // .connected is true while connecting?
  14479. doJoin();
  14480. }
  14481. }
  14482. function doJoin() {
  14483. var roomName = APP.UI.generateRoomName();
  14484. Moderator.allocateConferenceFocus(
  14485. roomName, APP.UI.checkForNicknameAndJoin);
  14486. }
  14487. function initStrophePlugins()
  14488. {
  14489. require("./strophe.emuc")(XMPP, eventEmitter);
  14490. require("./strophe.jingle")(XMPP, eventEmitter);
  14491. require("./strophe.moderate")(XMPP);
  14492. require("./strophe.util")();
  14493. require("./strophe.rayo")();
  14494. require("./strophe.logger")();
  14495. }
  14496. function registerListeners() {
  14497. APP.RTC.addStreamListener(maybeDoJoin,
  14498. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  14499. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  14500. XMPP.addToPresence("displayName", nickname);
  14501. });
  14502. }
  14503. function setupEvents() {
  14504. $(window).bind('beforeunload', function () {
  14505. if (connection && connection.connected) {
  14506. // ensure signout
  14507. $.ajax({
  14508. type: 'POST',
  14509. url: config.bosh,
  14510. async: false,
  14511. cache: false,
  14512. contentType: 'application/xml',
  14513. data: "<body rid='" + (connection.rid || connection._proto.rid)
  14514. + "' xmlns='http://jabber.org/protocol/httpbind' sid='"
  14515. + (connection.sid || connection._proto.sid)
  14516. + "' type='terminate'>" +
  14517. "<presence xmlns='jabber:client' type='unavailable'/>" +
  14518. "</body>",
  14519. success: function (data) {
  14520. console.log('signed out');
  14521. console.log(data);
  14522. },
  14523. error: function (XMLHttpRequest, textStatus, errorThrown) {
  14524. console.log('signout error',
  14525. textStatus + ' (' + errorThrown + ')');
  14526. }
  14527. });
  14528. }
  14529. XMPP.disposeConference(true);
  14530. });
  14531. }
  14532. var XMPP = {
  14533. sessionTerminated: false,
  14534. /**
  14535. * Remembers if we were muted by the focus.
  14536. * @type {boolean}
  14537. */
  14538. forceMuted: false,
  14539. start: function (uiCredentials) {
  14540. setupEvents();
  14541. initStrophePlugins();
  14542. registerListeners();
  14543. Moderator.init(this, eventEmitter);
  14544. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  14545. // Force authenticated domain if room is appended with '?login=true'
  14546. if (config.hosts.anonymousdomain &&
  14547. window.location.search.indexOf("login=true") !== -1) {
  14548. configDomain = config.hosts.domain;
  14549. }
  14550. var jid = uiCredentials.jid || configDomain || window.location.hostname;
  14551. connect(jid, null, uiCredentials);
  14552. },
  14553. promptLogin: function () {
  14554. APP.UI.showLoginPopup(connect);
  14555. },
  14556. joinRoom: function(roomName, useNicks, nick)
  14557. {
  14558. var roomjid;
  14559. roomjid = roomName;
  14560. if (useNicks) {
  14561. if (nick) {
  14562. roomjid += '/' + nick;
  14563. } else {
  14564. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  14565. }
  14566. } else {
  14567. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  14568. if(!authenticatedUser)
  14569. tmpJid = tmpJid.substr(0, 8);
  14570. roomjid += '/' + tmpJid;
  14571. }
  14572. connection.emuc.doJoin(roomjid);
  14573. },
  14574. myJid: function () {
  14575. if(!connection)
  14576. return null;
  14577. return connection.emuc.myroomjid;
  14578. },
  14579. myResource: function () {
  14580. if(!connection || ! connection.emuc.myroomjid)
  14581. return null;
  14582. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  14583. },
  14584. disposeConference: function (onUnload) {
  14585. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  14586. var handler = connection.jingle.activecall;
  14587. if (handler && handler.peerconnection) {
  14588. // FIXME: probably removing streams is not required and close() should
  14589. // be enough
  14590. if (APP.RTC.localAudio) {
  14591. handler.peerconnection.removeStream(APP.RTC.localAudio.getOriginalStream(), onUnload);
  14592. }
  14593. if (APP.RTC.localVideo) {
  14594. handler.peerconnection.removeStream(APP.RTC.localVideo.getOriginalStream(), onUnload);
  14595. }
  14596. handler.peerconnection.close();
  14597. }
  14598. connection.jingle.activecall = null;
  14599. if(!onUnload)
  14600. {
  14601. this.sessionTerminated = true;
  14602. connection.emuc.doLeave();
  14603. }
  14604. },
  14605. addListener: function(type, listener)
  14606. {
  14607. eventEmitter.on(type, listener);
  14608. },
  14609. removeListener: function (type, listener) {
  14610. eventEmitter.removeListener(type, listener);
  14611. },
  14612. allocateConferenceFocus: function(roomName, callback) {
  14613. Moderator.allocateConferenceFocus(roomName, callback);
  14614. },
  14615. getLoginUrl: function (roomName, callback) {
  14616. Moderator.getLoginUrl(roomName, callback);
  14617. },
  14618. getPopupLoginUrl: function (roomName, callback) {
  14619. Moderator.getPopupLoginUrl(roomName, callback);
  14620. },
  14621. isModerator: function () {
  14622. return Moderator.isModerator();
  14623. },
  14624. isSipGatewayEnabled: function () {
  14625. return Moderator.isSipGatewayEnabled();
  14626. },
  14627. isExternalAuthEnabled: function () {
  14628. return Moderator.isExternalAuthEnabled();
  14629. },
  14630. switchStreams: function (stream, oldStream, callback) {
  14631. if (connection && connection.jingle.activecall) {
  14632. // FIXME: will block switchInProgress on true value in case of exception
  14633. connection.jingle.activecall.switchStreams(stream, oldStream, callback);
  14634. } else {
  14635. // We are done immediately
  14636. console.error("No conference handler");
  14637. APP.UI.messageHandler.showError('Error',
  14638. 'Unable to switch video stream.');
  14639. callback();
  14640. }
  14641. },
  14642. setVideoMute: function (mute, callback, options) {
  14643. if(connection && APP.RTC.localVideo && connection.jingle.activecall)
  14644. {
  14645. connection.jingle.activecall.setVideoMute(mute, callback, options);
  14646. }
  14647. },
  14648. setAudioMute: function (mute, callback) {
  14649. if (!(connection && APP.RTC.localAudio)) {
  14650. return false;
  14651. }
  14652. if (this.forceMuted && !mute) {
  14653. console.info("Asking focus for unmute");
  14654. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  14655. // FIXME: wait for result before resetting muted status
  14656. this.forceMuted = false;
  14657. }
  14658. if (mute == APP.RTC.localAudio.isMuted()) {
  14659. // Nothing to do
  14660. return true;
  14661. }
  14662. // It is not clear what is the right way to handle multiple tracks.
  14663. // So at least make sure that they are all muted or all unmuted and
  14664. // that we send presence just once.
  14665. APP.RTC.localAudio.mute();
  14666. // isMuted is the opposite of audioEnabled
  14667. connection.emuc.addAudioInfoToPresence(mute);
  14668. connection.emuc.sendPresence();
  14669. callback();
  14670. return true;
  14671. },
  14672. // Really mute video, i.e. dont even send black frames
  14673. muteVideo: function (pc, unmute) {
  14674. // FIXME: this probably needs another of those lovely state safeguards...
  14675. // which checks for iceconn == connected and sigstate == stable
  14676. pc.setRemoteDescription(pc.remoteDescription,
  14677. function () {
  14678. pc.createAnswer(
  14679. function (answer) {
  14680. var sdp = new SDP(answer.sdp);
  14681. if (sdp.media.length > 1) {
  14682. if (unmute)
  14683. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  14684. else
  14685. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  14686. sdp.raw = sdp.session + sdp.media.join('');
  14687. answer.sdp = sdp.raw;
  14688. }
  14689. pc.setLocalDescription(answer,
  14690. function () {
  14691. console.log('mute SLD ok');
  14692. },
  14693. function (error) {
  14694. console.log('mute SLD error');
  14695. APP.UI.messageHandler.showError('Error',
  14696. 'Oops! Something went wrong and we failed to ' +
  14697. 'mute! (SLD Failure)');
  14698. }
  14699. );
  14700. },
  14701. function (error) {
  14702. console.log(error);
  14703. APP.UI.messageHandler.showError();
  14704. }
  14705. );
  14706. },
  14707. function (error) {
  14708. console.log('muteVideo SRD error');
  14709. APP.UI.messageHandler.showError('Error',
  14710. 'Oops! Something went wrong and we failed to stop video!' +
  14711. '(SRD Failure)');
  14712. }
  14713. );
  14714. },
  14715. toggleRecording: function (tokenEmptyCallback,
  14716. startingCallback, startedCallback) {
  14717. Recording.toggleRecording(tokenEmptyCallback,
  14718. startingCallback, startedCallback, connection);
  14719. },
  14720. addToPresence: function (name, value, dontSend) {
  14721. switch (name)
  14722. {
  14723. case "displayName":
  14724. connection.emuc.addDisplayNameToPresence(value);
  14725. break;
  14726. case "etherpad":
  14727. connection.emuc.addEtherpadToPresence(value);
  14728. break;
  14729. case "prezi":
  14730. connection.emuc.addPreziToPresence(value, 0);
  14731. break;
  14732. case "preziSlide":
  14733. connection.emuc.addCurrentSlideToPresence(value);
  14734. break;
  14735. case "connectionQuality":
  14736. connection.emuc.addConnectionInfoToPresence(value);
  14737. break;
  14738. case "email":
  14739. connection.emuc.addEmailToPresence(value);
  14740. default :
  14741. console.log("Unknown tag for presence.");
  14742. return;
  14743. }
  14744. if(!dontSend)
  14745. connection.emuc.sendPresence();
  14746. },
  14747. sendLogs: function (data) {
  14748. if(!connection.emuc.focusMucJid)
  14749. return;
  14750. var deflate = true;
  14751. var content = JSON.stringify(data);
  14752. if (deflate) {
  14753. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  14754. }
  14755. content = Base64.encode(content);
  14756. // XEP-0337-ish
  14757. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  14758. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  14759. id: 'PeerConnectionStats'});
  14760. message.c('message').t(content).up();
  14761. if (deflate) {
  14762. message.c('tag', {name: "deflated", value: "true"}).up();
  14763. }
  14764. message.up();
  14765. connection.send(message);
  14766. },
  14767. populateData: function () {
  14768. var data = {};
  14769. if (connection.jingle) {
  14770. data = connection.jingle.populateData();
  14771. }
  14772. return data;
  14773. },
  14774. getLogger: function () {
  14775. if(connection.logger)
  14776. return connection.logger.log;
  14777. return null;
  14778. },
  14779. getPrezi: function () {
  14780. return connection.emuc.getPrezi(this.myJid());
  14781. },
  14782. removePreziFromPresence: function () {
  14783. connection.emuc.removePreziFromPresence();
  14784. connection.emuc.sendPresence();
  14785. },
  14786. sendChatMessage: function (message, nickname) {
  14787. connection.emuc.sendMessage(message, nickname);
  14788. },
  14789. setSubject: function (topic) {
  14790. connection.emuc.setSubject(topic);
  14791. },
  14792. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  14793. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  14794. },
  14795. dial: function (to, from, roomName,roomPass) {
  14796. connection.rayo.dial(to, from, roomName,roomPass);
  14797. },
  14798. setMute: function (jid, mute) {
  14799. connection.moderate.setMute(jid, mute);
  14800. },
  14801. eject: function (jid) {
  14802. connection.moderate.eject(jid);
  14803. },
  14804. logout: function (callback) {
  14805. Moderator.logout(callback);
  14806. },
  14807. findJidFromResource: function (resource) {
  14808. return connection.emuc.findJidFromResource(resource);
  14809. },
  14810. getMembers: function () {
  14811. return connection.emuc.members;
  14812. },
  14813. getJidFromSSRC: function (ssrc) {
  14814. if(!connection)
  14815. return null;
  14816. return connection.emuc.ssrc2jid[ssrc];
  14817. },
  14818. getMUCJoined: function () {
  14819. return connection.emuc.joined;
  14820. },
  14821. getSessions: function () {
  14822. return connection.jingle.sessions;
  14823. }
  14824. };
  14825. module.exports = XMPP;
  14826. },{"../../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){
  14827. // i18next, v1.7.7
  14828. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  14829. // Distributed under MIT license
  14830. // http://i18next.com
  14831. (function() {
  14832. // add indexOf to non ECMA-262 standard compliant browsers
  14833. if (!Array.prototype.indexOf) {
  14834. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  14835. "use strict";
  14836. if (this == null) {
  14837. throw new TypeError();
  14838. }
  14839. var t = Object(this);
  14840. var len = t.length >>> 0;
  14841. if (len === 0) {
  14842. return -1;
  14843. }
  14844. var n = 0;
  14845. if (arguments.length > 0) {
  14846. n = Number(arguments[1]);
  14847. if (n != n) { // shortcut for verifying if it's NaN
  14848. n = 0;
  14849. } else if (n != 0 && n != Infinity && n != -Infinity) {
  14850. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  14851. }
  14852. }
  14853. if (n >= len) {
  14854. return -1;
  14855. }
  14856. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  14857. for (; k < len; k++) {
  14858. if (k in t && t[k] === searchElement) {
  14859. return k;
  14860. }
  14861. }
  14862. return -1;
  14863. }
  14864. }
  14865. // add lastIndexOf to non ECMA-262 standard compliant browsers
  14866. if (!Array.prototype.lastIndexOf) {
  14867. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  14868. "use strict";
  14869. if (this == null) {
  14870. throw new TypeError();
  14871. }
  14872. var t = Object(this);
  14873. var len = t.length >>> 0;
  14874. if (len === 0) {
  14875. return -1;
  14876. }
  14877. var n = len;
  14878. if (arguments.length > 1) {
  14879. n = Number(arguments[1]);
  14880. if (n != n) {
  14881. n = 0;
  14882. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  14883. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  14884. }
  14885. }
  14886. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  14887. for (; k >= 0; k--) {
  14888. if (k in t && t[k] === searchElement) {
  14889. return k;
  14890. }
  14891. }
  14892. return -1;
  14893. };
  14894. }
  14895. // Add string trim for IE8.
  14896. if (typeof String.prototype.trim !== 'function') {
  14897. String.prototype.trim = function() {
  14898. return this.replace(/^\s+|\s+$/g, '');
  14899. }
  14900. }
  14901. var root = this
  14902. , $ = root.jQuery || root.Zepto
  14903. , i18n = {}
  14904. , resStore = {}
  14905. , currentLng
  14906. , replacementCounter = 0
  14907. , languages = []
  14908. , initialized = false
  14909. , sync = {};
  14910. // Export the i18next object for **CommonJS**.
  14911. // If we're not in CommonJS, add `i18n` to the
  14912. // global object or to jquery.
  14913. if (typeof module !== 'undefined' && module.exports) {
  14914. if (!$) {
  14915. try {
  14916. $ = require('jquery');
  14917. } catch(e) {
  14918. // just ignore
  14919. }
  14920. }
  14921. if ($) {
  14922. $.i18n = $.i18n || i18n;
  14923. }
  14924. module.exports = i18n;
  14925. } else {
  14926. if ($) {
  14927. $.i18n = $.i18n || i18n;
  14928. }
  14929. root.i18n = root.i18n || i18n;
  14930. }
  14931. sync = {
  14932. load: function(lngs, options, cb) {
  14933. if (options.useLocalStorage) {
  14934. sync._loadLocal(lngs, options, function(err, store) {
  14935. var missingLngs = [];
  14936. for (var i = 0, len = lngs.length; i < len; i++) {
  14937. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  14938. }
  14939. if (missingLngs.length > 0) {
  14940. sync._fetch(missingLngs, options, function(err, fetched) {
  14941. f.extend(store, fetched);
  14942. sync._storeLocal(fetched);
  14943. cb(null, store);
  14944. });
  14945. } else {
  14946. cb(null, store);
  14947. }
  14948. });
  14949. } else {
  14950. sync._fetch(lngs, options, function(err, store){
  14951. cb(null, store);
  14952. });
  14953. }
  14954. },
  14955. _loadLocal: function(lngs, options, cb) {
  14956. var store = {}
  14957. , nowMS = new Date().getTime();
  14958. if(window.localStorage) {
  14959. var todo = lngs.length;
  14960. f.each(lngs, function(key, lng) {
  14961. var local = window.localStorage.getItem('res_' + lng);
  14962. if (local) {
  14963. local = JSON.parse(local);
  14964. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  14965. store[lng] = local;
  14966. }
  14967. }
  14968. todo--; // wait for all done befor callback
  14969. if (todo === 0) cb(null, store);
  14970. });
  14971. }
  14972. },
  14973. _storeLocal: function(store) {
  14974. if(window.localStorage) {
  14975. for (var m in store) {
  14976. store[m].i18nStamp = new Date().getTime();
  14977. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  14978. }
  14979. }
  14980. return;
  14981. },
  14982. _fetch: function(lngs, options, cb) {
  14983. var ns = options.ns
  14984. , store = {};
  14985. if (!options.dynamicLoad) {
  14986. var todo = ns.namespaces.length * lngs.length
  14987. , errors;
  14988. // load each file individual
  14989. f.each(ns.namespaces, function(nsIndex, nsValue) {
  14990. f.each(lngs, function(lngIndex, lngValue) {
  14991. // Call this once our translation has returned.
  14992. var loadComplete = function(err, data) {
  14993. if (err) {
  14994. errors = errors || [];
  14995. errors.push(err);
  14996. }
  14997. store[lngValue] = store[lngValue] || {};
  14998. store[lngValue][nsValue] = data;
  14999. todo--; // wait for all done befor callback
  15000. if (todo === 0) cb(errors, store);
  15001. };
  15002. if(typeof options.customLoad == 'function'){
  15003. // Use the specified custom callback.
  15004. options.customLoad(lngValue, nsValue, options, loadComplete);
  15005. } else {
  15006. //~ // Use our inbuilt sync.
  15007. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  15008. }
  15009. });
  15010. });
  15011. } else {
  15012. // Call this once our translation has returned.
  15013. var loadComplete = function(err, data) {
  15014. cb(null, data);
  15015. };
  15016. if(typeof options.customLoad == 'function'){
  15017. // Use the specified custom callback.
  15018. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  15019. } else {
  15020. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  15021. // load all needed stuff once
  15022. f.ajax({
  15023. url: url,
  15024. success: function(data, status, xhr) {
  15025. f.log('loaded: ' + url);
  15026. loadComplete(null, data);
  15027. },
  15028. error : function(xhr, status, error) {
  15029. f.log('failed loading: ' + url);
  15030. loadComplete('failed loading resource.json error: ' + error);
  15031. },
  15032. dataType: "json",
  15033. async : options.getAsync
  15034. });
  15035. }
  15036. }
  15037. },
  15038. _fetchOne: function(lng, ns, options, done) {
  15039. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  15040. f.ajax({
  15041. url: url,
  15042. success: function(data, status, xhr) {
  15043. f.log('loaded: ' + url);
  15044. done(null, data);
  15045. },
  15046. error : function(xhr, status, error) {
  15047. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  15048. // file loaded but invalid json, stop waste time !
  15049. f.error('There is a typo in: ' + url);
  15050. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  15051. f.log('Does not exist: ' + url);
  15052. } else {
  15053. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  15054. f.log(theStatus + ' when loading ' + url);
  15055. }
  15056. done(error, {});
  15057. },
  15058. dataType: "json",
  15059. async : options.getAsync
  15060. });
  15061. },
  15062. postMissing: function(lng, ns, key, defaultValue, lngs) {
  15063. var payload = {};
  15064. payload[key] = defaultValue;
  15065. var urls = [];
  15066. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  15067. for (var i = 0; i < o.fallbackLng.length; i++) {
  15068. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  15069. }
  15070. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  15071. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  15072. } else if (o.sendMissingTo === 'all') {
  15073. for (var i = 0, l = lngs.length; i < l; i++) {
  15074. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  15075. }
  15076. }
  15077. for (var y = 0, len = urls.length; y < len; y++) {
  15078. var item = urls[y];
  15079. f.ajax({
  15080. url: item.url,
  15081. type: o.sendType,
  15082. data: payload,
  15083. success: function(data, status, xhr) {
  15084. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  15085. // add key to resStore
  15086. var keys = key.split('.');
  15087. var x = 0;
  15088. var value = resStore[item.lng][ns];
  15089. while (keys[x]) {
  15090. if (x === keys.length - 1) {
  15091. value = value[keys[x]] = defaultValue;
  15092. } else {
  15093. value = value[keys[x]] = value[keys[x]] || {};
  15094. }
  15095. x++;
  15096. }
  15097. },
  15098. error : function(xhr, status, error) {
  15099. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  15100. },
  15101. dataType: "json",
  15102. async : o.postAsync
  15103. });
  15104. }
  15105. },
  15106. reload: reload
  15107. };
  15108. // defaults
  15109. var o = {
  15110. lng: undefined,
  15111. load: 'all',
  15112. preload: [],
  15113. lowerCaseLng: false,
  15114. returnObjectTrees: false,
  15115. fallbackLng: ['dev'],
  15116. fallbackNS: [],
  15117. detectLngQS: 'setLng',
  15118. detectLngFromLocalStorage: false,
  15119. ns: 'translation',
  15120. fallbackOnNull: true,
  15121. fallbackOnEmpty: false,
  15122. fallbackToDefaultNS: false,
  15123. nsseparator: ':',
  15124. keyseparator: '.',
  15125. selectorAttr: 'data-i18n',
  15126. debug: false,
  15127. resGetPath: 'locales/__lng__/__ns__.json',
  15128. resPostPath: 'locales/add/__lng__/__ns__',
  15129. getAsync: true,
  15130. postAsync: true,
  15131. resStore: undefined,
  15132. useLocalStorage: false,
  15133. localStorageExpirationTime: 7*24*60*60*1000,
  15134. dynamicLoad: false,
  15135. sendMissing: false,
  15136. sendMissingTo: 'fallback', // current | all
  15137. sendType: 'POST',
  15138. interpolationPrefix: '__',
  15139. interpolationSuffix: '__',
  15140. defaultVariables: false,
  15141. reusePrefix: '$t(',
  15142. reuseSuffix: ')',
  15143. pluralSuffix: '_plural',
  15144. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  15145. contextNotFound: ['context_not_found', Math.random()].join(''),
  15146. escapeInterpolation: false,
  15147. indefiniteSuffix: '_indefinite',
  15148. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  15149. setJqueryExt: true,
  15150. defaultValueFromContent: true,
  15151. useDataAttrOptions: false,
  15152. cookieExpirationTime: undefined,
  15153. useCookie: true,
  15154. cookieName: 'i18next',
  15155. cookieDomain: undefined,
  15156. objectTreeKeyHandler: undefined,
  15157. postProcess: undefined,
  15158. parseMissingKey: undefined,
  15159. missingKeyHandler: sync.postMissing,
  15160. shortcutFunction: 'sprintf' // or: defaultValue
  15161. };
  15162. function _extend(target, source) {
  15163. if (!source || typeof source === 'function') {
  15164. return target;
  15165. }
  15166. for (var attr in source) { target[attr] = source[attr]; }
  15167. return target;
  15168. }
  15169. function _deepExtend(target, source) {
  15170. for (var prop in source)
  15171. if (prop in target)
  15172. _deepExtend(target[prop], source[prop]);
  15173. else
  15174. target[prop] = source[prop];
  15175. return target;
  15176. }
  15177. function _each(object, callback, args) {
  15178. var name, i = 0,
  15179. length = object.length,
  15180. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  15181. if (args) {
  15182. if (isObj) {
  15183. for (name in object) {
  15184. if (callback.apply(object[name], args) === false) {
  15185. break;
  15186. }
  15187. }
  15188. } else {
  15189. for ( ; i < length; ) {
  15190. if (callback.apply(object[i++], args) === false) {
  15191. break;
  15192. }
  15193. }
  15194. }
  15195. // A special, fast, case for the most common use of each
  15196. } else {
  15197. if (isObj) {
  15198. for (name in object) {
  15199. if (callback.call(object[name], name, object[name]) === false) {
  15200. break;
  15201. }
  15202. }
  15203. } else {
  15204. for ( ; i < length; ) {
  15205. if (callback.call(object[i], i, object[i++]) === false) {
  15206. break;
  15207. }
  15208. }
  15209. }
  15210. }
  15211. return object;
  15212. }
  15213. var _entityMap = {
  15214. "&": "&amp;",
  15215. "<": "&lt;",
  15216. ">": "&gt;",
  15217. '"': '&quot;',
  15218. "'": '&#39;',
  15219. "/": '&#x2F;'
  15220. };
  15221. function _escape(data) {
  15222. if (typeof data === 'string') {
  15223. return data.replace(/[&<>"'\/]/g, function (s) {
  15224. return _entityMap[s];
  15225. });
  15226. }else{
  15227. return data;
  15228. }
  15229. }
  15230. function _ajax(options) {
  15231. // v0.5.0 of https://github.com/goloroden/http.js
  15232. var getXhr = function (callback) {
  15233. // Use the native XHR object if the browser supports it.
  15234. if (window.XMLHttpRequest) {
  15235. return callback(null, new XMLHttpRequest());
  15236. } else if (window.ActiveXObject) {
  15237. // In Internet Explorer check for ActiveX versions of the XHR object.
  15238. try {
  15239. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  15240. } catch (e) {
  15241. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  15242. }
  15243. }
  15244. // If no XHR support was found, throw an error.
  15245. return callback(new Error());
  15246. };
  15247. var encodeUsingUrlEncoding = function (data) {
  15248. if(typeof data === 'string') {
  15249. return data;
  15250. }
  15251. var result = [];
  15252. for(var dataItem in data) {
  15253. if(data.hasOwnProperty(dataItem)) {
  15254. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  15255. }
  15256. }
  15257. return result.join('&');
  15258. };
  15259. var utf8 = function (text) {
  15260. text = text.replace(/\r\n/g, '\n');
  15261. var result = '';
  15262. for(var i = 0; i < text.length; i++) {
  15263. var c = text.charCodeAt(i);
  15264. if(c < 128) {
  15265. result += String.fromCharCode(c);
  15266. } else if((c > 127) && (c < 2048)) {
  15267. result += String.fromCharCode((c >> 6) | 192);
  15268. result += String.fromCharCode((c & 63) | 128);
  15269. } else {
  15270. result += String.fromCharCode((c >> 12) | 224);
  15271. result += String.fromCharCode(((c >> 6) & 63) | 128);
  15272. result += String.fromCharCode((c & 63) | 128);
  15273. }
  15274. }
  15275. return result;
  15276. };
  15277. var base64 = function (text) {
  15278. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  15279. text = utf8(text);
  15280. var result = '',
  15281. chr1, chr2, chr3,
  15282. enc1, enc2, enc3, enc4,
  15283. i = 0;
  15284. do {
  15285. chr1 = text.charCodeAt(i++);
  15286. chr2 = text.charCodeAt(i++);
  15287. chr3 = text.charCodeAt(i++);
  15288. enc1 = chr1 >> 2;
  15289. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  15290. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  15291. enc4 = chr3 & 63;
  15292. if(isNaN(chr2)) {
  15293. enc3 = enc4 = 64;
  15294. } else if(isNaN(chr3)) {
  15295. enc4 = 64;
  15296. }
  15297. result +=
  15298. keyStr.charAt(enc1) +
  15299. keyStr.charAt(enc2) +
  15300. keyStr.charAt(enc3) +
  15301. keyStr.charAt(enc4);
  15302. chr1 = chr2 = chr3 = '';
  15303. enc1 = enc2 = enc3 = enc4 = '';
  15304. } while(i < text.length);
  15305. return result;
  15306. };
  15307. var mergeHeaders = function () {
  15308. // Use the first header object as base.
  15309. var result = arguments[0];
  15310. // Iterate through the remaining header objects and add them.
  15311. for(var i = 1; i < arguments.length; i++) {
  15312. var currentHeaders = arguments[i];
  15313. for(var header in currentHeaders) {
  15314. if(currentHeaders.hasOwnProperty(header)) {
  15315. result[header] = currentHeaders[header];
  15316. }
  15317. }
  15318. }
  15319. // Return the merged headers.
  15320. return result;
  15321. };
  15322. var ajax = function (method, url, options, callback) {
  15323. // Adjust parameters.
  15324. if(typeof options === 'function') {
  15325. callback = options;
  15326. options = {};
  15327. }
  15328. // Set default parameter values.
  15329. options.cache = options.cache || false;
  15330. options.data = options.data || {};
  15331. options.headers = options.headers || {};
  15332. options.jsonp = options.jsonp || false;
  15333. options.async = options.async === undefined ? true : options.async;
  15334. // Merge the various header objects.
  15335. var headers = mergeHeaders({
  15336. 'accept': '*/*',
  15337. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  15338. }, ajax.headers, options.headers);
  15339. // Encode the data according to the content-type.
  15340. var payload;
  15341. if (headers['content-type'] === 'application/json') {
  15342. payload = JSON.stringify(options.data);
  15343. } else {
  15344. payload = encodeUsingUrlEncoding(options.data);
  15345. }
  15346. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  15347. // if neccessary.
  15348. if(method === 'GET') {
  15349. // Setup the query string.
  15350. var queryString = [];
  15351. if(payload) {
  15352. queryString.push(payload);
  15353. payload = null;
  15354. }
  15355. // Handle caching.
  15356. if(!options.cache) {
  15357. queryString.push('_=' + (new Date()).getTime());
  15358. }
  15359. // If neccessary prepare the query string for a JSONP call.
  15360. if(options.jsonp) {
  15361. queryString.push('callback=' + options.jsonp);
  15362. queryString.push('jsonp=' + options.jsonp);
  15363. }
  15364. // Merge the query string and attach it to the url.
  15365. queryString = queryString.join('&');
  15366. if (queryString.length > 1) {
  15367. if (url.indexOf('?') > -1) {
  15368. url += '&' + queryString;
  15369. } else {
  15370. url += '?' + queryString;
  15371. }
  15372. }
  15373. // Make a JSONP call if neccessary.
  15374. if(options.jsonp) {
  15375. var head = document.getElementsByTagName('head')[0];
  15376. var script = document.createElement('script');
  15377. script.type = 'text/javascript';
  15378. script.src = url;
  15379. head.appendChild(script);
  15380. return;
  15381. }
  15382. }
  15383. // Since we got here, it is no JSONP request, so make a normal XHR request.
  15384. getXhr(function (err, xhr) {
  15385. if(err) return callback(err);
  15386. // Open the request.
  15387. xhr.open(method, url, options.async);
  15388. // Set the request headers.
  15389. for(var header in headers) {
  15390. if(headers.hasOwnProperty(header)) {
  15391. xhr.setRequestHeader(header, headers[header]);
  15392. }
  15393. }
  15394. // Handle the request events.
  15395. xhr.onreadystatechange = function () {
  15396. if(xhr.readyState === 4) {
  15397. var data = xhr.responseText || '';
  15398. // If no callback is given, return.
  15399. if(!callback) {
  15400. return;
  15401. }
  15402. // Return an object that provides access to the data as text and JSON.
  15403. callback(xhr.status, {
  15404. text: function () {
  15405. return data;
  15406. },
  15407. json: function () {
  15408. try {
  15409. return JSON.parse(data)
  15410. } catch (e) {
  15411. f.error('Can not parse JSON. URL: ' + url);
  15412. return {};
  15413. }
  15414. }
  15415. });
  15416. }
  15417. };
  15418. // Actually send the XHR request.
  15419. xhr.send(payload);
  15420. });
  15421. };
  15422. // Define the external interface.
  15423. var http = {
  15424. authBasic: function (username, password) {
  15425. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  15426. },
  15427. connect: function (url, options, callback) {
  15428. return ajax('CONNECT', url, options, callback);
  15429. },
  15430. del: function (url, options, callback) {
  15431. return ajax('DELETE', url, options, callback);
  15432. },
  15433. get: function (url, options, callback) {
  15434. return ajax('GET', url, options, callback);
  15435. },
  15436. head: function (url, options, callback) {
  15437. return ajax('HEAD', url, options, callback);
  15438. },
  15439. headers: function (headers) {
  15440. ajax.headers = headers || {};
  15441. },
  15442. isAllowed: function (url, verb, callback) {
  15443. this.options(url, function (status, data) {
  15444. callback(data.text().indexOf(verb) !== -1);
  15445. });
  15446. },
  15447. options: function (url, options, callback) {
  15448. return ajax('OPTIONS', url, options, callback);
  15449. },
  15450. patch: function (url, options, callback) {
  15451. return ajax('PATCH', url, options, callback);
  15452. },
  15453. post: function (url, options, callback) {
  15454. return ajax('POST', url, options, callback);
  15455. },
  15456. put: function (url, options, callback) {
  15457. return ajax('PUT', url, options, callback);
  15458. },
  15459. trace: function (url, options, callback) {
  15460. return ajax('TRACE', url, options, callback);
  15461. }
  15462. };
  15463. var methode = options.type ? options.type.toLowerCase() : 'get';
  15464. http[methode](options.url, options, function (status, data) {
  15465. // file: protocol always gives status code 0, so check for data
  15466. if (status === 200 || (status === 0 && data.text())) {
  15467. options.success(data.json(), status, null);
  15468. } else {
  15469. options.error(data.text(), status, null);
  15470. }
  15471. });
  15472. }
  15473. var _cookie = {
  15474. create: function(name,value,minutes,domain) {
  15475. var expires;
  15476. if (minutes) {
  15477. var date = new Date();
  15478. date.setTime(date.getTime()+(minutes*60*1000));
  15479. expires = "; expires="+date.toGMTString();
  15480. }
  15481. else expires = "";
  15482. domain = (domain)? "domain="+domain+";" : "";
  15483. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  15484. },
  15485. read: function(name) {
  15486. var nameEQ = name + "=";
  15487. var ca = document.cookie.split(';');
  15488. for(var i=0;i < ca.length;i++) {
  15489. var c = ca[i];
  15490. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  15491. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  15492. }
  15493. return null;
  15494. },
  15495. remove: function(name) {
  15496. this.create(name,"",-1);
  15497. }
  15498. };
  15499. var cookie_noop = {
  15500. create: function(name,value,minutes,domain) {},
  15501. read: function(name) { return null; },
  15502. remove: function(name) {}
  15503. };
  15504. // move dependent functions to a container so that
  15505. // they can be overriden easier in no jquery environment (node.js)
  15506. var f = {
  15507. extend: $ ? $.extend : _extend,
  15508. deepExtend: _deepExtend,
  15509. each: $ ? $.each : _each,
  15510. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  15511. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  15512. detectLanguage: detectLanguage,
  15513. escape: _escape,
  15514. log: function(str) {
  15515. if (o.debug && typeof console !== "undefined") console.log(str);
  15516. },
  15517. error: function(str) {
  15518. if (typeof console !== "undefined") console.error(str);
  15519. },
  15520. getCountyIndexOfLng: function(lng) {
  15521. var lng_index = 0;
  15522. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  15523. return lng_index;
  15524. },
  15525. toLanguages: function(lng) {
  15526. var log = this.log;
  15527. function applyCase(l) {
  15528. var ret = l;
  15529. if (typeof l === 'string' && l.indexOf('-') > -1) {
  15530. var parts = l.split('-');
  15531. ret = o.lowerCaseLng ?
  15532. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  15533. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  15534. } else {
  15535. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  15536. }
  15537. return ret;
  15538. }
  15539. var languages = [];
  15540. var whitelist = o.lngWhitelist || false;
  15541. var addLanguage = function(language){
  15542. //reject langs not whitelisted
  15543. if(!whitelist || whitelist.indexOf(language) > -1){
  15544. languages.push(language);
  15545. }else{
  15546. log('rejecting non-whitelisted language: ' + language);
  15547. }
  15548. };
  15549. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  15550. var parts = lng.split('-');
  15551. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  15552. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  15553. } else {
  15554. addLanguage(applyCase(lng));
  15555. }
  15556. for (var i = 0; i < o.fallbackLng.length; i++) {
  15557. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  15558. }
  15559. return languages;
  15560. },
  15561. regexEscape: function(str) {
  15562. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  15563. },
  15564. regexReplacementEscape: function(strOrFn) {
  15565. if (typeof strOrFn === 'string') {
  15566. return strOrFn.replace(/\$/g, "$$$$");
  15567. } else {
  15568. return strOrFn;
  15569. }
  15570. },
  15571. localStorage: {
  15572. setItem: function(key, value) {
  15573. if (window.localStorage) {
  15574. try {
  15575. window.localStorage.setItem(key, value);
  15576. } catch (e) {
  15577. f.log('failed to set value for key "' + key + '" to localStorage.');
  15578. }
  15579. }
  15580. }
  15581. }
  15582. };
  15583. function init(options, cb) {
  15584. if (typeof options === 'function') {
  15585. cb = options;
  15586. options = {};
  15587. }
  15588. options = options || {};
  15589. // override defaults with passed in options
  15590. f.extend(o, options);
  15591. delete o.fixLng; /* passed in each time */
  15592. // override functions: .log(), .detectLanguage(), etc
  15593. if (o.functions) {
  15594. delete o.functions;
  15595. f.extend(f, options.functions);
  15596. }
  15597. // create namespace object if namespace is passed in as string
  15598. if (typeof o.ns == 'string') {
  15599. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  15600. }
  15601. // fallback namespaces
  15602. if (typeof o.fallbackNS == 'string') {
  15603. o.fallbackNS = [o.fallbackNS];
  15604. }
  15605. // fallback languages
  15606. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  15607. o.fallbackLng = [o.fallbackLng];
  15608. }
  15609. // escape prefix/suffix
  15610. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  15611. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  15612. if (!o.lng) o.lng = f.detectLanguage();
  15613. languages = f.toLanguages(o.lng);
  15614. currentLng = languages[0];
  15615. f.log('currentLng set to: ' + currentLng);
  15616. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  15617. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  15618. }
  15619. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  15620. f.localStorage.setItem('i18next_lng', currentLng);
  15621. }
  15622. var lngTranslate = translate;
  15623. if (options.fixLng) {
  15624. lngTranslate = function(key, options) {
  15625. options = options || {};
  15626. options.lng = options.lng || lngTranslate.lng;
  15627. return translate(key, options);
  15628. };
  15629. lngTranslate.lng = currentLng;
  15630. }
  15631. pluralExtensions.setCurrentLng(currentLng);
  15632. // add JQuery extensions
  15633. if ($ && o.setJqueryExt) addJqueryFunct();
  15634. // jQuery deferred
  15635. var deferred;
  15636. if ($ && $.Deferred) {
  15637. deferred = $.Deferred();
  15638. }
  15639. // return immidiatly if res are passed in
  15640. if (o.resStore) {
  15641. resStore = o.resStore;
  15642. initialized = true;
  15643. if (cb) cb(lngTranslate);
  15644. if (deferred) deferred.resolve(lngTranslate);
  15645. if (deferred) return deferred.promise();
  15646. return;
  15647. }
  15648. // languages to load
  15649. var lngsToLoad = f.toLanguages(o.lng);
  15650. if (typeof o.preload === 'string') o.preload = [o.preload];
  15651. for (var i = 0, l = o.preload.length; i < l; i++) {
  15652. var pres = f.toLanguages(o.preload[i]);
  15653. for (var y = 0, len = pres.length; y < len; y++) {
  15654. if (lngsToLoad.indexOf(pres[y]) < 0) {
  15655. lngsToLoad.push(pres[y]);
  15656. }
  15657. }
  15658. }
  15659. // else load them
  15660. i18n.sync.load(lngsToLoad, o, function(err, store) {
  15661. resStore = store;
  15662. initialized = true;
  15663. if (cb) cb(lngTranslate);
  15664. if (deferred) deferred.resolve(lngTranslate);
  15665. });
  15666. if (deferred) return deferred.promise();
  15667. }
  15668. function preload(lngs, cb) {
  15669. if (typeof lngs === 'string') lngs = [lngs];
  15670. for (var i = 0, l = lngs.length; i < l; i++) {
  15671. if (o.preload.indexOf(lngs[i]) < 0) {
  15672. o.preload.push(lngs[i]);
  15673. }
  15674. }
  15675. return init(cb);
  15676. }
  15677. function addResourceBundle(lng, ns, resources, deep) {
  15678. if (typeof ns !== 'string') {
  15679. resources = ns;
  15680. ns = o.ns.defaultNs;
  15681. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  15682. o.ns.namespaces.push(ns);
  15683. }
  15684. resStore[lng] = resStore[lng] || {};
  15685. resStore[lng][ns] = resStore[lng][ns] || {};
  15686. if (deep) {
  15687. f.deepExtend(resStore[lng][ns], resources);
  15688. } else {
  15689. f.extend(resStore[lng][ns], resources);
  15690. }
  15691. }
  15692. function hasResourceBundle(lng, ns) {
  15693. if (typeof ns !== 'string') {
  15694. ns = o.ns.defaultNs;
  15695. }
  15696. resStore[lng] = resStore[lng] || {};
  15697. var res = resStore[lng][ns] || {};
  15698. var hasValues = false;
  15699. for(var prop in res) {
  15700. if (res.hasOwnProperty(prop)) {
  15701. hasValues = true;
  15702. }
  15703. }
  15704. return hasValues;
  15705. }
  15706. function removeResourceBundle(lng, ns) {
  15707. if (typeof ns !== 'string') {
  15708. ns = o.ns.defaultNs;
  15709. }
  15710. resStore[lng] = resStore[lng] || {};
  15711. resStore[lng][ns] = {};
  15712. }
  15713. function addResource(lng, ns, key, value) {
  15714. if (typeof ns !== 'string') {
  15715. resource = ns;
  15716. ns = o.ns.defaultNs;
  15717. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  15718. o.ns.namespaces.push(ns);
  15719. }
  15720. resStore[lng] = resStore[lng] || {};
  15721. resStore[lng][ns] = resStore[lng][ns] || {};
  15722. var keys = key.split(o.keyseparator);
  15723. var x = 0;
  15724. var node = resStore[lng][ns];
  15725. var origRef = node;
  15726. while (keys[x]) {
  15727. if (x == keys.length - 1)
  15728. node[keys[x]] = value;
  15729. else {
  15730. if (node[keys[x]] == null)
  15731. node[keys[x]] = {};
  15732. node = node[keys[x]];
  15733. }
  15734. x++;
  15735. }
  15736. }
  15737. function addResources(lng, ns, resources) {
  15738. if (typeof ns !== 'string') {
  15739. resource = ns;
  15740. ns = o.ns.defaultNs;
  15741. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  15742. o.ns.namespaces.push(ns);
  15743. }
  15744. for (var m in resources) {
  15745. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  15746. }
  15747. }
  15748. function setDefaultNamespace(ns) {
  15749. o.ns.defaultNs = ns;
  15750. }
  15751. function loadNamespace(namespace, cb) {
  15752. loadNamespaces([namespace], cb);
  15753. }
  15754. function loadNamespaces(namespaces, cb) {
  15755. var opts = {
  15756. dynamicLoad: o.dynamicLoad,
  15757. resGetPath: o.resGetPath,
  15758. getAsync: o.getAsync,
  15759. customLoad: o.customLoad,
  15760. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  15761. };
  15762. // languages to load
  15763. var lngsToLoad = f.toLanguages(o.lng);
  15764. if (typeof o.preload === 'string') o.preload = [o.preload];
  15765. for (var i = 0, l = o.preload.length; i < l; i++) {
  15766. var pres = f.toLanguages(o.preload[i]);
  15767. for (var y = 0, len = pres.length; y < len; y++) {
  15768. if (lngsToLoad.indexOf(pres[y]) < 0) {
  15769. lngsToLoad.push(pres[y]);
  15770. }
  15771. }
  15772. }
  15773. // check if we have to load
  15774. var lngNeedLoad = [];
  15775. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  15776. var needLoad = false;
  15777. var resSet = resStore[lngsToLoad[a]];
  15778. if (resSet) {
  15779. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  15780. if (!resSet[namespaces[b]]) needLoad = true;
  15781. }
  15782. } else {
  15783. needLoad = true;
  15784. }
  15785. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  15786. }
  15787. if (lngNeedLoad.length) {
  15788. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  15789. var todo = namespaces.length * lngNeedLoad.length;
  15790. // load each file individual
  15791. f.each(namespaces, function(nsIndex, nsValue) {
  15792. // append namespace to namespace array
  15793. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  15794. o.ns.namespaces.push(nsValue);
  15795. }
  15796. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  15797. resStore[lngValue] = resStore[lngValue] || {};
  15798. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  15799. todo--; // wait for all done befor callback
  15800. if (todo === 0 && cb) {
  15801. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  15802. cb();
  15803. }
  15804. });
  15805. });
  15806. });
  15807. } else {
  15808. if (cb) cb();
  15809. }
  15810. }
  15811. function setLng(lng, options, cb) {
  15812. if (typeof options === 'function') {
  15813. cb = options;
  15814. options = {};
  15815. } else if (!options) {
  15816. options = {};
  15817. }
  15818. options.lng = lng;
  15819. return init(options, cb);
  15820. }
  15821. function lng() {
  15822. return currentLng;
  15823. }
  15824. function reload(cb) {
  15825. resStore = {};
  15826. setLng(currentLng, cb);
  15827. }
  15828. function addJqueryFunct() {
  15829. // $.t shortcut
  15830. $.t = $.t || translate;
  15831. function parse(ele, key, options) {
  15832. if (key.length === 0) return;
  15833. var attr = 'text';
  15834. if (key.indexOf('[') === 0) {
  15835. var parts = key.split(']');
  15836. key = parts[1];
  15837. attr = parts[0].substr(1, parts[0].length-1);
  15838. }
  15839. if (key.indexOf(';') === key.length-1) {
  15840. key = key.substr(0, key.length-2);
  15841. }
  15842. var optionsToUse;
  15843. if (attr === 'html') {
  15844. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  15845. ele.html($.t(key, optionsToUse));
  15846. } else if (attr === 'text') {
  15847. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  15848. ele.text($.t(key, optionsToUse));
  15849. } else if (attr === 'prepend') {
  15850. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  15851. ele.prepend($.t(key, optionsToUse));
  15852. } else if (attr === 'append') {
  15853. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  15854. ele.append($.t(key, optionsToUse));
  15855. } else if (attr.indexOf("data-") === 0) {
  15856. var dataAttr = attr.substr(("data-").length);
  15857. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  15858. var translated = $.t(key, optionsToUse);
  15859. //we change into the data cache
  15860. ele.data(dataAttr, translated);
  15861. //we change into the dom
  15862. ele.attr(attr, translated);
  15863. } else {
  15864. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  15865. ele.attr(attr, $.t(key, optionsToUse));
  15866. }
  15867. }
  15868. function localize(ele, options) {
  15869. var key = ele.attr(o.selectorAttr);
  15870. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  15871. if (!key) return;
  15872. var target = ele
  15873. , targetSelector = ele.data("i18n-target");
  15874. if (targetSelector) {
  15875. target = ele.find(targetSelector) || ele;
  15876. }
  15877. if (!options && o.useDataAttrOptions === true) {
  15878. options = ele.data("i18n-options");
  15879. }
  15880. options = options || {};
  15881. if (key.indexOf(';') >= 0) {
  15882. var keys = key.split(';');
  15883. $.each(keys, function(m, k) {
  15884. if (k !== '') parse(target, k, options);
  15885. });
  15886. } else {
  15887. parse(target, key, options);
  15888. }
  15889. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  15890. }
  15891. // fn
  15892. $.fn.i18n = function (options) {
  15893. return this.each(function() {
  15894. // localize element itself
  15895. localize($(this), options);
  15896. // localize childs
  15897. var elements = $(this).find('[' + o.selectorAttr + ']');
  15898. elements.each(function() {
  15899. localize($(this), options);
  15900. });
  15901. });
  15902. };
  15903. }
  15904. function applyReplacement(str, replacementHash, nestedKey, options) {
  15905. if (!str) return str;
  15906. options = options || replacementHash; // first call uses replacement hash combined with options
  15907. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  15908. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  15909. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  15910. , unEscapingSuffix = 'HTML'+suffix;
  15911. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  15912. f.each(hash, function(key, value) {
  15913. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  15914. if (typeof value === 'object' && value !== null) {
  15915. str = applyReplacement(str, value, nextKey, options);
  15916. } else {
  15917. if (options.escapeInterpolation || o.escapeInterpolation) {
  15918. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  15919. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  15920. } else {
  15921. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  15922. }
  15923. // str = options.escapeInterpolation;
  15924. }
  15925. });
  15926. return str;
  15927. }
  15928. // append it to functions
  15929. f.applyReplacement = applyReplacement;
  15930. function applyReuse(translated, options) {
  15931. var comma = ',';
  15932. var options_open = '{';
  15933. var options_close = '}';
  15934. var opts = f.extend({}, options);
  15935. delete opts.postProcess;
  15936. while (translated.indexOf(o.reusePrefix) != -1) {
  15937. replacementCounter++;
  15938. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  15939. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  15940. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  15941. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  15942. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  15943. if (index_of_end_of_closing <= index_of_opening) {
  15944. f.error('there is an missing closing in following translation value', translated);
  15945. return '';
  15946. }
  15947. if (token_without_symbols.indexOf(comma) != -1) {
  15948. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  15949. 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) {
  15950. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  15951. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  15952. try {
  15953. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  15954. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  15955. } catch (e) {
  15956. }
  15957. }
  15958. }
  15959. var translated_token = _translate(token_without_symbols, opts);
  15960. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  15961. }
  15962. return translated;
  15963. }
  15964. function hasContext(options) {
  15965. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  15966. }
  15967. function needsPlural(options, lng) {
  15968. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  15969. }
  15970. function needsIndefiniteArticle(options) {
  15971. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  15972. }
  15973. function exists(key, options) {
  15974. options = options || {};
  15975. var notFound = _getDefaultValue(key, options)
  15976. , found = _find(key, options);
  15977. return found !== undefined || found === notFound;
  15978. }
  15979. function translate(key, options) {
  15980. options = options || {};
  15981. if (!initialized) {
  15982. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  15983. return options.defaultValue || '';
  15984. };
  15985. replacementCounter = 0;
  15986. return _translate.apply(null, arguments);
  15987. }
  15988. function _getDefaultValue(key, options) {
  15989. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  15990. }
  15991. function _injectSprintfProcessor() {
  15992. var values = [];
  15993. // mh: build array from second argument onwards
  15994. for (var i = 1; i < arguments.length; i++) {
  15995. values.push(arguments[i]);
  15996. }
  15997. return {
  15998. postProcess: 'sprintf',
  15999. sprintf: values
  16000. };
  16001. }
  16002. function _translate(potentialKeys, options) {
  16003. if (options && typeof options !== 'object') {
  16004. if (o.shortcutFunction === 'sprintf') {
  16005. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  16006. options = _injectSprintfProcessor.apply(null, arguments);
  16007. } else if (o.shortcutFunction === 'defaultValue') {
  16008. options = {
  16009. defaultValue: options
  16010. }
  16011. }
  16012. } else {
  16013. options = options || {};
  16014. }
  16015. if (typeof o.defaultVariables === 'object') {
  16016. options = f.extend({}, o.defaultVariables, options);
  16017. }
  16018. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  16019. if (typeof potentialKeys === 'string') {
  16020. potentialKeys = [potentialKeys];
  16021. }
  16022. var key = potentialKeys[0];
  16023. if (potentialKeys.length > 1) {
  16024. for (var i = 0; i < potentialKeys.length; i++) {
  16025. key = potentialKeys[i];
  16026. if (exists(key, options)) {
  16027. break;
  16028. }
  16029. }
  16030. }
  16031. var notFound = _getDefaultValue(key, options)
  16032. , found = _find(key, options)
  16033. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  16034. , ns = options.ns || o.ns.defaultNs
  16035. , parts;
  16036. // split ns and key
  16037. if (key.indexOf(o.nsseparator) > -1) {
  16038. parts = key.split(o.nsseparator);
  16039. ns = parts[0];
  16040. key = parts[1];
  16041. }
  16042. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  16043. if (options.lng) {
  16044. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  16045. } else {
  16046. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  16047. }
  16048. }
  16049. var postProcessor = options.postProcess || o.postProcess;
  16050. if (found !== undefined && postProcessor) {
  16051. if (postProcessors[postProcessor]) {
  16052. found = postProcessors[postProcessor](found, key, options);
  16053. }
  16054. }
  16055. // process notFound if function exists
  16056. var splitNotFound = notFound;
  16057. if (notFound.indexOf(o.nsseparator) > -1) {
  16058. parts = notFound.split(o.nsseparator);
  16059. splitNotFound = parts[1];
  16060. }
  16061. if (splitNotFound === key && o.parseMissingKey) {
  16062. notFound = o.parseMissingKey(notFound);
  16063. }
  16064. if (found === undefined) {
  16065. notFound = applyReplacement(notFound, options);
  16066. notFound = applyReuse(notFound, options);
  16067. if (postProcessor && postProcessors[postProcessor]) {
  16068. var val = _getDefaultValue(key, options);
  16069. found = postProcessors[postProcessor](val, key, options);
  16070. }
  16071. }
  16072. return (found !== undefined) ? found : notFound;
  16073. }
  16074. function _find(key, options) {
  16075. options = options || {};
  16076. var optionWithoutCount, translated
  16077. , notFound = _getDefaultValue(key, options)
  16078. , lngs = languages;
  16079. if (!resStore) { return notFound; } // no resStore to translate from
  16080. // CI mode
  16081. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  16082. // passed in lng
  16083. if (options.lngs) lngs = options.lngs;
  16084. if (options.lng) {
  16085. lngs = f.toLanguages(options.lng, options.fallbackLng);
  16086. if (!resStore[lngs[0]]) {
  16087. var oldAsync = o.getAsync;
  16088. o.getAsync = false;
  16089. i18n.sync.load(lngs, o, function(err, store) {
  16090. f.extend(resStore, store);
  16091. o.getAsync = oldAsync;
  16092. });
  16093. }
  16094. }
  16095. var ns = options.ns || o.ns.defaultNs;
  16096. if (key.indexOf(o.nsseparator) > -1) {
  16097. var parts = key.split(o.nsseparator);
  16098. ns = parts[0];
  16099. key = parts[1];
  16100. }
  16101. if (hasContext(options)) {
  16102. optionWithoutCount = f.extend({}, options);
  16103. delete optionWithoutCount.context;
  16104. optionWithoutCount.defaultValue = o.contextNotFound;
  16105. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  16106. translated = translate(contextKey, optionWithoutCount);
  16107. if (translated != o.contextNotFound) {
  16108. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  16109. } // else continue translation with original/nonContext key
  16110. }
  16111. if (needsPlural(options, lngs[0])) {
  16112. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  16113. delete optionWithoutCount.count;
  16114. delete optionWithoutCount.lng;
  16115. optionWithoutCount.defaultValue = o.pluralNotFound;
  16116. var pluralKey;
  16117. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  16118. pluralKey = ns + o.nsseparator + key;
  16119. } else {
  16120. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  16121. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  16122. if (pluralExtension >= 0) {
  16123. pluralKey = pluralKey + '_' + pluralExtension;
  16124. } else if (pluralExtension === 1) {
  16125. pluralKey = ns + o.nsseparator + key; // singular
  16126. }
  16127. }
  16128. translated = translate(pluralKey, optionWithoutCount);
  16129. if (translated != o.pluralNotFound) {
  16130. return applyReplacement(translated, {
  16131. count: options.count,
  16132. interpolationPrefix: options.interpolationPrefix,
  16133. interpolationSuffix: options.interpolationSuffix
  16134. }); // apply replacement for count only
  16135. } else if (lngs.length > 1) {
  16136. // remove failed lng
  16137. var clone = lngs.slice();
  16138. clone.shift();
  16139. options = f.extend(options, { lngs: clone });
  16140. delete options.lng;
  16141. // retry with fallbacks
  16142. translated = translate(ns + o.nsseparator + key, options);
  16143. if (translated != o.pluralNotFound) return translated;
  16144. } else {
  16145. return translated;
  16146. }
  16147. }
  16148. if (needsIndefiniteArticle(options)) {
  16149. var optionsWithoutIndef = f.extend({}, options);
  16150. delete optionsWithoutIndef.indefinite_article;
  16151. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  16152. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  16153. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  16154. translated = translate(indefiniteKey, optionsWithoutIndef);
  16155. if (translated != o.indefiniteNotFound) {
  16156. return translated;
  16157. }
  16158. }
  16159. var found;
  16160. var keys = key.split(o.keyseparator);
  16161. for (var i = 0, len = lngs.length; i < len; i++ ) {
  16162. if (found !== undefined) break;
  16163. var l = lngs[i];
  16164. var x = 0;
  16165. var value = resStore[l] && resStore[l][ns];
  16166. while (keys[x]) {
  16167. value = value && value[keys[x]];
  16168. x++;
  16169. }
  16170. if (value !== undefined) {
  16171. var valueType = Object.prototype.toString.apply(value);
  16172. if (typeof value === 'string') {
  16173. value = applyReplacement(value, options);
  16174. value = applyReuse(value, options);
  16175. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  16176. value = value.join('\n');
  16177. value = applyReplacement(value, options);
  16178. value = applyReuse(value, options);
  16179. } else if (value === null && o.fallbackOnNull === true) {
  16180. value = undefined;
  16181. } else if (value !== null) {
  16182. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  16183. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  16184. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  16185. } else {
  16186. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  16187. 'returned an object instead of string.';
  16188. f.log(value);
  16189. }
  16190. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  16191. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  16192. f.each(value, function(m) {
  16193. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  16194. });
  16195. value = copy;
  16196. }
  16197. }
  16198. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  16199. value = undefined;
  16200. found = value;
  16201. }
  16202. }
  16203. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  16204. // set flag for fallback lookup - avoid recursion
  16205. options.isFallbackLookup = true;
  16206. if (o.fallbackNS.length) {
  16207. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  16208. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  16209. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  16210. /* compare value without namespace */
  16211. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  16212. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  16213. if (foundValue !== notFoundValue) break;
  16214. }
  16215. }
  16216. } else {
  16217. found = _find(key, options); // fallback to default NS
  16218. }
  16219. options.isFallbackLookup = false;
  16220. }
  16221. return found;
  16222. }
  16223. function detectLanguage() {
  16224. var detectedLng;
  16225. var whitelist = o.lngWhitelist || [];
  16226. var userLngChoices = [];
  16227. // get from qs
  16228. var qsParm = [];
  16229. if (typeof window !== 'undefined') {
  16230. (function() {
  16231. var query = window.location.search.substring(1);
  16232. var params = query.split('&');
  16233. for (var i=0; i<params.length; i++) {
  16234. var pos = params[i].indexOf('=');
  16235. if (pos > 0) {
  16236. var key = params[i].substring(0,pos);
  16237. if (key == o.detectLngQS) {
  16238. userLngChoices.push(params[i].substring(pos+1));
  16239. }
  16240. }
  16241. }
  16242. })();
  16243. }
  16244. // get from cookie
  16245. if (o.useCookie && typeof document !== 'undefined') {
  16246. var c = f.cookie.read(o.cookieName);
  16247. if (c) userLngChoices.push(c);
  16248. }
  16249. // get from localStorage
  16250. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  16251. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  16252. }
  16253. // get from navigator
  16254. if (typeof navigator !== 'undefined') {
  16255. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  16256. for (var i=0;i<navigator.languages.length;i++) {
  16257. userLngChoices.push(navigator.languages[i]);
  16258. }
  16259. }
  16260. if (navigator.userLanguage) {
  16261. userLngChoices.push(navigator.userLanguage);
  16262. }
  16263. if (navigator.language) {
  16264. userLngChoices.push(navigator.language);
  16265. }
  16266. }
  16267. (function() {
  16268. for (var i=0;i<userLngChoices.length;i++) {
  16269. var lng = userLngChoices[i];
  16270. if (lng.indexOf('-') > -1) {
  16271. var parts = lng.split('-');
  16272. lng = o.lowerCaseLng ?
  16273. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  16274. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  16275. }
  16276. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  16277. detectedLng = lng;
  16278. break;
  16279. }
  16280. }
  16281. })();
  16282. //fallback
  16283. if (!detectedLng){
  16284. detectedLng = o.fallbackLng[0];
  16285. }
  16286. return detectedLng;
  16287. }
  16288. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  16289. /* [code, name, numbers, pluralsType] */
  16290. var _rules = [
  16291. ["ach", "Acholi", [1,2], 1],
  16292. ["af", "Afrikaans",[1,2], 2],
  16293. ["ak", "Akan", [1,2], 1],
  16294. ["am", "Amharic", [1,2], 1],
  16295. ["an", "Aragonese",[1,2], 2],
  16296. ["ar", "Arabic", [0,1,2,3,11,100],5],
  16297. ["arn", "Mapudungun",[1,2], 1],
  16298. ["ast", "Asturian", [1,2], 2],
  16299. ["ay", "Aymará", [1], 3],
  16300. ["az", "Azerbaijani",[1,2],2],
  16301. ["be", "Belarusian",[1,2,5],4],
  16302. ["bg", "Bulgarian",[1,2], 2],
  16303. ["bn", "Bengali", [1,2], 2],
  16304. ["bo", "Tibetan", [1], 3],
  16305. ["br", "Breton", [1,2], 1],
  16306. ["bs", "Bosnian", [1,2,5],4],
  16307. ["ca", "Catalan", [1,2], 2],
  16308. ["cgg", "Chiga", [1], 3],
  16309. ["cs", "Czech", [1,2,5],6],
  16310. ["csb", "Kashubian",[1,2,5],7],
  16311. ["cy", "Welsh", [1,2,3,8],8],
  16312. ["da", "Danish", [1,2], 2],
  16313. ["de", "German", [1,2], 2],
  16314. ["dev", "Development Fallback", [1,2], 2],
  16315. ["dz", "Dzongkha", [1], 3],
  16316. ["el", "Greek", [1,2], 2],
  16317. ["en", "English", [1,2], 2],
  16318. ["eo", "Esperanto",[1,2], 2],
  16319. ["es", "Spanish", [1,2], 2],
  16320. ["es_ar","Argentinean Spanish", [1,2], 2],
  16321. ["et", "Estonian", [1,2], 2],
  16322. ["eu", "Basque", [1,2], 2],
  16323. ["fa", "Persian", [1], 3],
  16324. ["fi", "Finnish", [1,2], 2],
  16325. ["fil", "Filipino", [1,2], 1],
  16326. ["fo", "Faroese", [1,2], 2],
  16327. ["fr", "French", [1,2], 9],
  16328. ["fur", "Friulian", [1,2], 2],
  16329. ["fy", "Frisian", [1,2], 2],
  16330. ["ga", "Irish", [1,2,3,7,11],10],
  16331. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  16332. ["gl", "Galician", [1,2], 2],
  16333. ["gu", "Gujarati", [1,2], 2],
  16334. ["gun", "Gun", [1,2], 1],
  16335. ["ha", "Hausa", [1,2], 2],
  16336. ["he", "Hebrew", [1,2], 2],
  16337. ["hi", "Hindi", [1,2], 2],
  16338. ["hr", "Croatian", [1,2,5],4],
  16339. ["hu", "Hungarian",[1,2], 2],
  16340. ["hy", "Armenian", [1,2], 2],
  16341. ["ia", "Interlingua",[1,2],2],
  16342. ["id", "Indonesian",[1], 3],
  16343. ["is", "Icelandic",[1,2], 12],
  16344. ["it", "Italian", [1,2], 2],
  16345. ["ja", "Japanese", [1], 3],
  16346. ["jbo", "Lojban", [1], 3],
  16347. ["jv", "Javanese", [0,1], 13],
  16348. ["ka", "Georgian", [1], 3],
  16349. ["kk", "Kazakh", [1], 3],
  16350. ["km", "Khmer", [1], 3],
  16351. ["kn", "Kannada", [1,2], 2],
  16352. ["ko", "Korean", [1], 3],
  16353. ["ku", "Kurdish", [1,2], 2],
  16354. ["kw", "Cornish", [1,2,3,4],14],
  16355. ["ky", "Kyrgyz", [1], 3],
  16356. ["lb", "Letzeburgesch",[1,2],2],
  16357. ["ln", "Lingala", [1,2], 1],
  16358. ["lo", "Lao", [1], 3],
  16359. ["lt", "Lithuanian",[1,2,10],15],
  16360. ["lv", "Latvian", [1,2,0],16],
  16361. ["mai", "Maithili", [1,2], 2],
  16362. ["mfe", "Mauritian Creole",[1,2],1],
  16363. ["mg", "Malagasy", [1,2], 1],
  16364. ["mi", "Maori", [1,2], 1],
  16365. ["mk", "Macedonian",[1,2],17],
  16366. ["ml", "Malayalam",[1,2], 2],
  16367. ["mn", "Mongolian",[1,2], 2],
  16368. ["mnk", "Mandinka", [0,1,2],18],
  16369. ["mr", "Marathi", [1,2], 2],
  16370. ["ms", "Malay", [1], 3],
  16371. ["mt", "Maltese", [1,2,11,20],19],
  16372. ["nah", "Nahuatl", [1,2], 2],
  16373. ["nap", "Neapolitan",[1,2], 2],
  16374. ["nb", "Norwegian Bokmal",[1,2],2],
  16375. ["ne", "Nepali", [1,2], 2],
  16376. ["nl", "Dutch", [1,2], 2],
  16377. ["nn", "Norwegian Nynorsk",[1,2],2],
  16378. ["no", "Norwegian",[1,2], 2],
  16379. ["nso", "Northern Sotho",[1,2],2],
  16380. ["oc", "Occitan", [1,2], 1],
  16381. ["or", "Oriya", [2,1], 2],
  16382. ["pa", "Punjabi", [1,2], 2],
  16383. ["pap", "Papiamento",[1,2], 2],
  16384. ["pl", "Polish", [1,2,5],7],
  16385. ["pms", "Piemontese",[1,2], 2],
  16386. ["ps", "Pashto", [1,2], 2],
  16387. ["pt", "Portuguese",[1,2], 2],
  16388. ["pt_br","Brazilian Portuguese",[1,2], 2],
  16389. ["rm", "Romansh", [1,2], 2],
  16390. ["ro", "Romanian", [1,2,20],20],
  16391. ["ru", "Russian", [1,2,5],4],
  16392. ["sah", "Yakut", [1], 3],
  16393. ["sco", "Scots", [1,2], 2],
  16394. ["se", "Northern Sami",[1,2], 2],
  16395. ["si", "Sinhala", [1,2], 2],
  16396. ["sk", "Slovak", [1,2,5],6],
  16397. ["sl", "Slovenian",[5,1,2,3],21],
  16398. ["so", "Somali", [1,2], 2],
  16399. ["son", "Songhay", [1,2], 2],
  16400. ["sq", "Albanian", [1,2], 2],
  16401. ["sr", "Serbian", [1,2,5],4],
  16402. ["su", "Sundanese",[1], 3],
  16403. ["sv", "Swedish", [1,2], 2],
  16404. ["sw", "Swahili", [1,2], 2],
  16405. ["ta", "Tamil", [1,2], 2],
  16406. ["te", "Telugu", [1,2], 2],
  16407. ["tg", "Tajik", [1,2], 1],
  16408. ["th", "Thai", [1], 3],
  16409. ["ti", "Tigrinya", [1,2], 1],
  16410. ["tk", "Turkmen", [1,2], 2],
  16411. ["tr", "Turkish", [1,2], 1],
  16412. ["tt", "Tatar", [1], 3],
  16413. ["ug", "Uyghur", [1], 3],
  16414. ["uk", "Ukrainian",[1,2,5],4],
  16415. ["ur", "Urdu", [1,2], 2],
  16416. ["uz", "Uzbek", [1,2], 1],
  16417. ["vi", "Vietnamese",[1], 3],
  16418. ["wa", "Walloon", [1,2], 1],
  16419. ["wo", "Wolof", [1], 3],
  16420. ["yo", "Yoruba", [1,2], 2],
  16421. ["zh", "Chinese", [1], 3]
  16422. ];
  16423. var _rulesPluralsTypes = {
  16424. 1: function(n) {return Number(n > 1);},
  16425. 2: function(n) {return Number(n != 1);},
  16426. 3: function(n) {return 0;},
  16427. 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);},
  16428. 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);},
  16429. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  16430. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  16431. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  16432. 9: function(n) {return Number(n >= 2);},
  16433. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  16434. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  16435. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  16436. 13: function(n) {return Number(n !== 0);},
  16437. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  16438. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  16439. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  16440. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  16441. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  16442. 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);},
  16443. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  16444. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  16445. };
  16446. var pluralExtensions = {
  16447. rules: (function () {
  16448. var l, rules = {};
  16449. for (l=_rules.length; l-- ;) {
  16450. rules[_rules[l][0]] = {
  16451. name: _rules[l][1],
  16452. numbers: _rules[l][2],
  16453. plurals: _rulesPluralsTypes[_rules[l][3]]
  16454. }
  16455. }
  16456. return rules;
  16457. }()),
  16458. // you can add your own pluralExtensions
  16459. addRule: function(lng, obj) {
  16460. pluralExtensions.rules[lng] = obj;
  16461. },
  16462. setCurrentLng: function(lng) {
  16463. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  16464. var parts = lng.split('-');
  16465. pluralExtensions.currentRule = {
  16466. lng: lng,
  16467. rule: pluralExtensions.rules[parts[0]]
  16468. };
  16469. }
  16470. },
  16471. needsPlural: function(lng, count) {
  16472. var parts = lng.split('-');
  16473. var ext;
  16474. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  16475. ext = pluralExtensions.currentRule.rule;
  16476. } else {
  16477. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  16478. }
  16479. if (ext && ext.numbers.length <= 1) {
  16480. return false;
  16481. } else {
  16482. return this.get(lng, count) !== 1;
  16483. }
  16484. },
  16485. get: function(lng, count) {
  16486. var parts = lng.split('-');
  16487. function getResult(l, c) {
  16488. var ext;
  16489. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  16490. ext = pluralExtensions.currentRule.rule;
  16491. } else {
  16492. ext = pluralExtensions.rules[l];
  16493. }
  16494. if (ext) {
  16495. var i;
  16496. if (ext.noAbs) {
  16497. i = ext.plurals(c);
  16498. } else {
  16499. i = ext.plurals(Math.abs(c));
  16500. }
  16501. var number = ext.numbers[i];
  16502. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  16503. if (number === 2) {
  16504. number = -1; // regular plural
  16505. } else if (number === 1) {
  16506. number = 1; // singular
  16507. }
  16508. }//console.log(count + '-' + number);
  16509. return number;
  16510. } else {
  16511. return c === 1 ? '1' : '-1';
  16512. }
  16513. }
  16514. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  16515. }
  16516. };
  16517. var postProcessors = {};
  16518. var addPostProcessor = function(name, fc) {
  16519. postProcessors[name] = fc;
  16520. };
  16521. // sprintf support
  16522. var sprintf = (function() {
  16523. function get_type(variable) {
  16524. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  16525. }
  16526. function str_repeat(input, multiplier) {
  16527. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  16528. return output.join('');
  16529. }
  16530. var str_format = function() {
  16531. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  16532. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  16533. }
  16534. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  16535. };
  16536. str_format.format = function(parse_tree, argv) {
  16537. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  16538. for (i = 0; i < tree_length; i++) {
  16539. node_type = get_type(parse_tree[i]);
  16540. if (node_type === 'string') {
  16541. output.push(parse_tree[i]);
  16542. }
  16543. else if (node_type === 'array') {
  16544. match = parse_tree[i]; // convenience purposes only
  16545. if (match[2]) { // keyword argument
  16546. arg = argv[cursor];
  16547. for (k = 0; k < match[2].length; k++) {
  16548. if (!arg.hasOwnProperty(match[2][k])) {
  16549. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  16550. }
  16551. arg = arg[match[2][k]];
  16552. }
  16553. }
  16554. else if (match[1]) { // positional argument (explicit)
  16555. arg = argv[match[1]];
  16556. }
  16557. else { // positional argument (implicit)
  16558. arg = argv[cursor++];
  16559. }
  16560. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  16561. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  16562. }
  16563. switch (match[8]) {
  16564. case 'b': arg = arg.toString(2); break;
  16565. case 'c': arg = String.fromCharCode(arg); break;
  16566. case 'd': arg = parseInt(arg, 10); break;
  16567. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  16568. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  16569. case 'o': arg = arg.toString(8); break;
  16570. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  16571. case 'u': arg = Math.abs(arg); break;
  16572. case 'x': arg = arg.toString(16); break;
  16573. case 'X': arg = arg.toString(16).toUpperCase(); break;
  16574. }
  16575. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  16576. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  16577. pad_length = match[6] - String(arg).length;
  16578. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  16579. output.push(match[5] ? arg + pad : pad + arg);
  16580. }
  16581. }
  16582. return output.join('');
  16583. };
  16584. str_format.cache = {};
  16585. str_format.parse = function(fmt) {
  16586. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  16587. while (_fmt) {
  16588. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  16589. parse_tree.push(match[0]);
  16590. }
  16591. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  16592. parse_tree.push('%');
  16593. }
  16594. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  16595. if (match[2]) {
  16596. arg_names |= 1;
  16597. var field_list = [], replacement_field = match[2], field_match = [];
  16598. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  16599. field_list.push(field_match[1]);
  16600. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  16601. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  16602. field_list.push(field_match[1]);
  16603. }
  16604. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  16605. field_list.push(field_match[1]);
  16606. }
  16607. else {
  16608. throw('[sprintf] huh?');
  16609. }
  16610. }
  16611. }
  16612. else {
  16613. throw('[sprintf] huh?');
  16614. }
  16615. match[2] = field_list;
  16616. }
  16617. else {
  16618. arg_names |= 2;
  16619. }
  16620. if (arg_names === 3) {
  16621. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  16622. }
  16623. parse_tree.push(match);
  16624. }
  16625. else {
  16626. throw('[sprintf] huh?');
  16627. }
  16628. _fmt = _fmt.substring(match[0].length);
  16629. }
  16630. return parse_tree;
  16631. };
  16632. return str_format;
  16633. })();
  16634. var vsprintf = function(fmt, argv) {
  16635. argv.unshift(fmt);
  16636. return sprintf.apply(null, argv);
  16637. };
  16638. addPostProcessor("sprintf", function(val, key, opts) {
  16639. if (!opts.sprintf) return val;
  16640. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  16641. return vsprintf(val, opts.sprintf);
  16642. } else if (typeof opts.sprintf === 'object') {
  16643. return sprintf(val, opts.sprintf);
  16644. }
  16645. return val;
  16646. });
  16647. // public api interface
  16648. i18n.init = init;
  16649. i18n.setLng = setLng;
  16650. i18n.preload = preload;
  16651. i18n.addResourceBundle = addResourceBundle;
  16652. i18n.hasResourceBundle = hasResourceBundle;
  16653. i18n.addResource = addResource;
  16654. i18n.addResources = addResources;
  16655. i18n.removeResourceBundle = removeResourceBundle;
  16656. i18n.loadNamespace = loadNamespace;
  16657. i18n.loadNamespaces = loadNamespaces;
  16658. i18n.setDefaultNamespace = setDefaultNamespace;
  16659. i18n.t = translate;
  16660. i18n.translate = translate;
  16661. i18n.exists = exists;
  16662. i18n.detectLanguage = f.detectLanguage;
  16663. i18n.pluralExtensions = pluralExtensions;
  16664. i18n.sync = sync;
  16665. i18n.functions = f;
  16666. i18n.lng = lng;
  16667. i18n.addPostProcessor = addPostProcessor;
  16668. i18n.options = o;
  16669. })();
  16670. },{"jquery":"jquery"}],63:[function(require,module,exports){
  16671. // Top level file is just a mixin of submodules & constants
  16672. 'use strict';
  16673. var assign = require('./lib/utils/common').assign;
  16674. var deflate = require('./lib/deflate');
  16675. var inflate = require('./lib/inflate');
  16676. var constants = require('./lib/zlib/constants');
  16677. var pako = {};
  16678. assign(pako, deflate, inflate, constants);
  16679. module.exports = pako;
  16680. },{"./lib/deflate":64,"./lib/inflate":65,"./lib/utils/common":66,"./lib/zlib/constants":69}],64:[function(require,module,exports){
  16681. 'use strict';
  16682. var zlib_deflate = require('./zlib/deflate.js');
  16683. var utils = require('./utils/common');
  16684. var strings = require('./utils/strings');
  16685. var msg = require('./zlib/messages');
  16686. var zstream = require('./zlib/zstream');
  16687. /* Public constants ==========================================================*/
  16688. /* ===========================================================================*/
  16689. var Z_NO_FLUSH = 0;
  16690. var Z_FINISH = 4;
  16691. var Z_OK = 0;
  16692. var Z_STREAM_END = 1;
  16693. var Z_DEFAULT_COMPRESSION = -1;
  16694. var Z_DEFAULT_STRATEGY = 0;
  16695. var Z_DEFLATED = 8;
  16696. /* ===========================================================================*/
  16697. /**
  16698. * class Deflate
  16699. *
  16700. * Generic JS-style wrapper for zlib calls. If you don't need
  16701. * streaming behaviour - use more simple functions: [[deflate]],
  16702. * [[deflateRaw]] and [[gzip]].
  16703. **/
  16704. /* internal
  16705. * Deflate.chunks -> Array
  16706. *
  16707. * Chunks of output data, if [[Deflate#onData]] not overriden.
  16708. **/
  16709. /**
  16710. * Deflate.result -> Uint8Array|Array
  16711. *
  16712. * Compressed result, generated by default [[Deflate#onData]]
  16713. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  16714. * (call [[Deflate#push]] with `Z_FINISH` / `true` param).
  16715. **/
  16716. /**
  16717. * Deflate.err -> Number
  16718. *
  16719. * Error code after deflate finished. 0 (Z_OK) on success.
  16720. * You will not need it in real life, because deflate errors
  16721. * are possible only on wrong options or bad `onData` / `onEnd`
  16722. * custom handlers.
  16723. **/
  16724. /**
  16725. * Deflate.msg -> String
  16726. *
  16727. * Error message, if [[Deflate.err]] != 0
  16728. **/
  16729. /**
  16730. * new Deflate(options)
  16731. * - options (Object): zlib deflate options.
  16732. *
  16733. * Creates new deflator instance with specified params. Throws exception
  16734. * on bad params. Supported options:
  16735. *
  16736. * - `level`
  16737. * - `windowBits`
  16738. * - `memLevel`
  16739. * - `strategy`
  16740. *
  16741. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  16742. * for more information on these.
  16743. *
  16744. * Additional options, for internal needs:
  16745. *
  16746. * - `chunkSize` - size of generated data chunks (16K by default)
  16747. * - `raw` (Boolean) - do raw deflate
  16748. * - `gzip` (Boolean) - create gzip wrapper
  16749. * - `to` (String) - if equal to 'string', then result will be "binary string"
  16750. * (each char code [0..255])
  16751. * - `header` (Object) - custom header for gzip
  16752. * - `text` (Boolean) - true if compressed data believed to be text
  16753. * - `time` (Number) - modification time, unix timestamp
  16754. * - `os` (Number) - operation system code
  16755. * - `extra` (Array) - array of bytes with extra data (max 65536)
  16756. * - `name` (String) - file name (binary string)
  16757. * - `comment` (String) - comment (binary string)
  16758. * - `hcrc` (Boolean) - true if header crc should be added
  16759. *
  16760. * ##### Example:
  16761. *
  16762. * ```javascript
  16763. * var pako = require('pako')
  16764. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  16765. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  16766. *
  16767. * var deflate = new pako.Deflate({ level: 3});
  16768. *
  16769. * deflate.push(chunk1, false);
  16770. * deflate.push(chunk2, true); // true -> last chunk
  16771. *
  16772. * if (deflate.err) { throw new Error(deflate.err); }
  16773. *
  16774. * console.log(deflate.result);
  16775. * ```
  16776. **/
  16777. var Deflate = function(options) {
  16778. this.options = utils.assign({
  16779. level: Z_DEFAULT_COMPRESSION,
  16780. method: Z_DEFLATED,
  16781. chunkSize: 16384,
  16782. windowBits: 15,
  16783. memLevel: 8,
  16784. strategy: Z_DEFAULT_STRATEGY,
  16785. to: ''
  16786. }, options || {});
  16787. var opt = this.options;
  16788. if (opt.raw && (opt.windowBits > 0)) {
  16789. opt.windowBits = -opt.windowBits;
  16790. }
  16791. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  16792. opt.windowBits += 16;
  16793. }
  16794. this.err = 0; // error code, if happens (0 = Z_OK)
  16795. this.msg = ''; // error message
  16796. this.ended = false; // used to avoid multiple onEnd() calls
  16797. this.chunks = []; // chunks of compressed data
  16798. this.strm = new zstream();
  16799. this.strm.avail_out = 0;
  16800. var status = zlib_deflate.deflateInit2(
  16801. this.strm,
  16802. opt.level,
  16803. opt.method,
  16804. opt.windowBits,
  16805. opt.memLevel,
  16806. opt.strategy
  16807. );
  16808. if (status !== Z_OK) {
  16809. throw new Error(msg[status]);
  16810. }
  16811. if (opt.header) {
  16812. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  16813. }
  16814. };
  16815. /**
  16816. * Deflate#push(data[, mode]) -> Boolean
  16817. * - data (Uint8Array|Array|String): input data. Strings will be converted to
  16818. * utf8 byte sequence.
  16819. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  16820. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  16821. *
  16822. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  16823. * new compressed chunks. Returns `true` on success. The last data block must have
  16824. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  16825. * [[Deflate#onEnd]].
  16826. *
  16827. * On fail call [[Deflate#onEnd]] with error code and return false.
  16828. *
  16829. * We strongly recommend to use `Uint8Array` on input for best speed (output
  16830. * array format is detected automatically). Also, don't skip last param and always
  16831. * use the same type in your code (boolean or number). That will improve JS speed.
  16832. *
  16833. * For regular `Array`-s make sure all elements are [0..255].
  16834. *
  16835. * ##### Example
  16836. *
  16837. * ```javascript
  16838. * push(chunk, false); // push one of data chunks
  16839. * ...
  16840. * push(chunk, true); // push last chunk
  16841. * ```
  16842. **/
  16843. Deflate.prototype.push = function(data, mode) {
  16844. var strm = this.strm;
  16845. var chunkSize = this.options.chunkSize;
  16846. var status, _mode;
  16847. if (this.ended) { return false; }
  16848. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  16849. // Convert data if needed
  16850. if (typeof data === 'string') {
  16851. // If we need to compress text, change encoding to utf8.
  16852. strm.input = strings.string2buf(data);
  16853. } else {
  16854. strm.input = data;
  16855. }
  16856. strm.next_in = 0;
  16857. strm.avail_in = strm.input.length;
  16858. do {
  16859. if (strm.avail_out === 0) {
  16860. strm.output = new utils.Buf8(chunkSize);
  16861. strm.next_out = 0;
  16862. strm.avail_out = chunkSize;
  16863. }
  16864. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  16865. if (status !== Z_STREAM_END && status !== Z_OK) {
  16866. this.onEnd(status);
  16867. this.ended = true;
  16868. return false;
  16869. }
  16870. if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) {
  16871. if (this.options.to === 'string') {
  16872. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  16873. } else {
  16874. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  16875. }
  16876. }
  16877. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  16878. // Finalize on the last chunk.
  16879. if (_mode === Z_FINISH) {
  16880. status = zlib_deflate.deflateEnd(this.strm);
  16881. this.onEnd(status);
  16882. this.ended = true;
  16883. return status === Z_OK;
  16884. }
  16885. return true;
  16886. };
  16887. /**
  16888. * Deflate#onData(chunk) -> Void
  16889. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  16890. * on js engine support. When string output requested, each chunk
  16891. * will be string.
  16892. *
  16893. * By default, stores data blocks in `chunks[]` property and glue
  16894. * those in `onEnd`. Override this handler, if you need another behaviour.
  16895. **/
  16896. Deflate.prototype.onData = function(chunk) {
  16897. this.chunks.push(chunk);
  16898. };
  16899. /**
  16900. * Deflate#onEnd(status) -> Void
  16901. * - status (Number): deflate status. 0 (Z_OK) on success,
  16902. * other if not.
  16903. *
  16904. * Called once after you tell deflate that input stream complete
  16905. * or error happenned. By default - join collected chunks,
  16906. * free memory and fill `results` / `err` properties.
  16907. **/
  16908. Deflate.prototype.onEnd = function(status) {
  16909. // On success - join
  16910. if (status === Z_OK) {
  16911. if (this.options.to === 'string') {
  16912. this.result = this.chunks.join('');
  16913. } else {
  16914. this.result = utils.flattenChunks(this.chunks);
  16915. }
  16916. }
  16917. this.chunks = [];
  16918. this.err = status;
  16919. this.msg = this.strm.msg;
  16920. };
  16921. /**
  16922. * deflate(data[, options]) -> Uint8Array|Array|String
  16923. * - data (Uint8Array|Array|String): input data to compress.
  16924. * - options (Object): zlib deflate options.
  16925. *
  16926. * Compress `data` with deflate alrorythm and `options`.
  16927. *
  16928. * Supported options are:
  16929. *
  16930. * - level
  16931. * - windowBits
  16932. * - memLevel
  16933. * - strategy
  16934. *
  16935. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  16936. * for more information on these.
  16937. *
  16938. * Sugar (options):
  16939. *
  16940. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  16941. * negative windowBits implicitly.
  16942. * - `to` (String) - if equal to 'string', then result will be "binary string"
  16943. * (each char code [0..255])
  16944. *
  16945. * ##### Example:
  16946. *
  16947. * ```javascript
  16948. * var pako = require('pako')
  16949. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  16950. *
  16951. * console.log(pako.deflate(data));
  16952. * ```
  16953. **/
  16954. function deflate(input, options) {
  16955. var deflator = new Deflate(options);
  16956. deflator.push(input, true);
  16957. // That will never happens, if you don't cheat with options :)
  16958. if (deflator.err) { throw deflator.msg; }
  16959. return deflator.result;
  16960. }
  16961. /**
  16962. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  16963. * - data (Uint8Array|Array|String): input data to compress.
  16964. * - options (Object): zlib deflate options.
  16965. *
  16966. * The same as [[deflate]], but creates raw data, without wrapper
  16967. * (header and adler32 crc).
  16968. **/
  16969. function deflateRaw(input, options) {
  16970. options = options || {};
  16971. options.raw = true;
  16972. return deflate(input, options);
  16973. }
  16974. /**
  16975. * gzip(data[, options]) -> Uint8Array|Array|String
  16976. * - data (Uint8Array|Array|String): input data to compress.
  16977. * - options (Object): zlib deflate options.
  16978. *
  16979. * The same as [[deflate]], but create gzip wrapper instead of
  16980. * deflate one.
  16981. **/
  16982. function gzip(input, options) {
  16983. options = options || {};
  16984. options.gzip = true;
  16985. return deflate(input, options);
  16986. }
  16987. exports.Deflate = Deflate;
  16988. exports.deflate = deflate;
  16989. exports.deflateRaw = deflateRaw;
  16990. exports.gzip = gzip;
  16991. },{"./utils/common":66,"./utils/strings":67,"./zlib/deflate.js":71,"./zlib/messages":76,"./zlib/zstream":78}],65:[function(require,module,exports){
  16992. 'use strict';
  16993. var zlib_inflate = require('./zlib/inflate.js');
  16994. var utils = require('./utils/common');
  16995. var strings = require('./utils/strings');
  16996. var c = require('./zlib/constants');
  16997. var msg = require('./zlib/messages');
  16998. var zstream = require('./zlib/zstream');
  16999. var gzheader = require('./zlib/gzheader');
  17000. /**
  17001. * class Inflate
  17002. *
  17003. * Generic JS-style wrapper for zlib calls. If you don't need
  17004. * streaming behaviour - use more simple functions: [[inflate]]
  17005. * and [[inflateRaw]].
  17006. **/
  17007. /* internal
  17008. * inflate.chunks -> Array
  17009. *
  17010. * Chunks of output data, if [[Inflate#onData]] not overriden.
  17011. **/
  17012. /**
  17013. * Inflate.result -> Uint8Array|Array|String
  17014. *
  17015. * Uncompressed result, generated by default [[Inflate#onData]]
  17016. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  17017. * (call [[Inflate#push]] with `Z_FINISH` / `true` param).
  17018. **/
  17019. /**
  17020. * Inflate.err -> Number
  17021. *
  17022. * Error code after inflate finished. 0 (Z_OK) on success.
  17023. * Should be checked if broken data possible.
  17024. **/
  17025. /**
  17026. * Inflate.msg -> String
  17027. *
  17028. * Error message, if [[Inflate.err]] != 0
  17029. **/
  17030. /**
  17031. * new Inflate(options)
  17032. * - options (Object): zlib inflate options.
  17033. *
  17034. * Creates new inflator instance with specified params. Throws exception
  17035. * on bad params. Supported options:
  17036. *
  17037. * - `windowBits`
  17038. *
  17039. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17040. * for more information on these.
  17041. *
  17042. * Additional options, for internal needs:
  17043. *
  17044. * - `chunkSize` - size of generated data chunks (16K by default)
  17045. * - `raw` (Boolean) - do raw inflate
  17046. * - `to` (String) - if equal to 'string', then result will be converted
  17047. * from utf8 to utf16 (javascript) string. When string output requested,
  17048. * chunk length can differ from `chunkSize`, depending on content.
  17049. *
  17050. * By default, when no options set, autodetect deflate/gzip data format via
  17051. * wrapper header.
  17052. *
  17053. * ##### Example:
  17054. *
  17055. * ```javascript
  17056. * var pako = require('pako')
  17057. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  17058. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  17059. *
  17060. * var inflate = new pako.Inflate({ level: 3});
  17061. *
  17062. * inflate.push(chunk1, false);
  17063. * inflate.push(chunk2, true); // true -> last chunk
  17064. *
  17065. * if (inflate.err) { throw new Error(inflate.err); }
  17066. *
  17067. * console.log(inflate.result);
  17068. * ```
  17069. **/
  17070. var Inflate = function(options) {
  17071. this.options = utils.assign({
  17072. chunkSize: 16384,
  17073. windowBits: 0,
  17074. to: ''
  17075. }, options || {});
  17076. var opt = this.options;
  17077. // Force window size for `raw` data, if not set directly,
  17078. // because we have no header for autodetect.
  17079. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  17080. opt.windowBits = -opt.windowBits;
  17081. if (opt.windowBits === 0) { opt.windowBits = -15; }
  17082. }
  17083. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  17084. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  17085. !(options && options.windowBits)) {
  17086. opt.windowBits += 32;
  17087. }
  17088. // Gzip header has no info about windows size, we can do autodetect only
  17089. // for deflate. So, if window size not set, force it to max when gzip possible
  17090. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  17091. // bit 3 (16) -> gzipped data
  17092. // bit 4 (32) -> autodetect gzip/deflate
  17093. if ((opt.windowBits & 15) === 0) {
  17094. opt.windowBits |= 15;
  17095. }
  17096. }
  17097. this.err = 0; // error code, if happens (0 = Z_OK)
  17098. this.msg = ''; // error message
  17099. this.ended = false; // used to avoid multiple onEnd() calls
  17100. this.chunks = []; // chunks of compressed data
  17101. this.strm = new zstream();
  17102. this.strm.avail_out = 0;
  17103. var status = zlib_inflate.inflateInit2(
  17104. this.strm,
  17105. opt.windowBits
  17106. );
  17107. if (status !== c.Z_OK) {
  17108. throw new Error(msg[status]);
  17109. }
  17110. this.header = new gzheader();
  17111. zlib_inflate.inflateGetHeader(this.strm, this.header);
  17112. };
  17113. /**
  17114. * Inflate#push(data[, mode]) -> Boolean
  17115. * - data (Uint8Array|Array|String): input data
  17116. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  17117. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  17118. *
  17119. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  17120. * new output chunks. Returns `true` on success. The last data block must have
  17121. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  17122. * [[Inflate#onEnd]].
  17123. *
  17124. * On fail call [[Inflate#onEnd]] with error code and return false.
  17125. *
  17126. * We strongly recommend to use `Uint8Array` on input for best speed (output
  17127. * format is detected automatically). Also, don't skip last param and always
  17128. * use the same type in your code (boolean or number). That will improve JS speed.
  17129. *
  17130. * For regular `Array`-s make sure all elements are [0..255].
  17131. *
  17132. * ##### Example
  17133. *
  17134. * ```javascript
  17135. * push(chunk, false); // push one of data chunks
  17136. * ...
  17137. * push(chunk, true); // push last chunk
  17138. * ```
  17139. **/
  17140. Inflate.prototype.push = function(data, mode) {
  17141. var strm = this.strm;
  17142. var chunkSize = this.options.chunkSize;
  17143. var status, _mode;
  17144. var next_out_utf8, tail, utf8str;
  17145. if (this.ended) { return false; }
  17146. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  17147. // Convert data if needed
  17148. if (typeof data === 'string') {
  17149. // Only binary strings can be decompressed on practice
  17150. strm.input = strings.binstring2buf(data);
  17151. } else {
  17152. strm.input = data;
  17153. }
  17154. strm.next_in = 0;
  17155. strm.avail_in = strm.input.length;
  17156. do {
  17157. if (strm.avail_out === 0) {
  17158. strm.output = new utils.Buf8(chunkSize);
  17159. strm.next_out = 0;
  17160. strm.avail_out = chunkSize;
  17161. }
  17162. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  17163. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  17164. this.onEnd(status);
  17165. this.ended = true;
  17166. return false;
  17167. }
  17168. if (strm.next_out) {
  17169. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) {
  17170. if (this.options.to === 'string') {
  17171. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  17172. tail = strm.next_out - next_out_utf8;
  17173. utf8str = strings.buf2string(strm.output, next_out_utf8);
  17174. // move tail
  17175. strm.next_out = tail;
  17176. strm.avail_out = chunkSize - tail;
  17177. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  17178. this.onData(utf8str);
  17179. } else {
  17180. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  17181. }
  17182. }
  17183. }
  17184. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  17185. if (status === c.Z_STREAM_END) {
  17186. _mode = c.Z_FINISH;
  17187. }
  17188. // Finalize on the last chunk.
  17189. if (_mode === c.Z_FINISH) {
  17190. status = zlib_inflate.inflateEnd(this.strm);
  17191. this.onEnd(status);
  17192. this.ended = true;
  17193. return status === c.Z_OK;
  17194. }
  17195. return true;
  17196. };
  17197. /**
  17198. * Inflate#onData(chunk) -> Void
  17199. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  17200. * on js engine support. When string output requested, each chunk
  17201. * will be string.
  17202. *
  17203. * By default, stores data blocks in `chunks[]` property and glue
  17204. * those in `onEnd`. Override this handler, if you need another behaviour.
  17205. **/
  17206. Inflate.prototype.onData = function(chunk) {
  17207. this.chunks.push(chunk);
  17208. };
  17209. /**
  17210. * Inflate#onEnd(status) -> Void
  17211. * - status (Number): inflate status. 0 (Z_OK) on success,
  17212. * other if not.
  17213. *
  17214. * Called once after you tell inflate that input stream complete
  17215. * or error happenned. By default - join collected chunks,
  17216. * free memory and fill `results` / `err` properties.
  17217. **/
  17218. Inflate.prototype.onEnd = function(status) {
  17219. // On success - join
  17220. if (status === c.Z_OK) {
  17221. if (this.options.to === 'string') {
  17222. // Glue & convert here, until we teach pako to send
  17223. // utf8 alligned strings to onData
  17224. this.result = this.chunks.join('');
  17225. } else {
  17226. this.result = utils.flattenChunks(this.chunks);
  17227. }
  17228. }
  17229. this.chunks = [];
  17230. this.err = status;
  17231. this.msg = this.strm.msg;
  17232. };
  17233. /**
  17234. * inflate(data[, options]) -> Uint8Array|Array|String
  17235. * - data (Uint8Array|Array|String): input data to decompress.
  17236. * - options (Object): zlib inflate options.
  17237. *
  17238. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  17239. * format via wrapper header by default. That's why we don't provide
  17240. * separate `ungzip` method.
  17241. *
  17242. * Supported options are:
  17243. *
  17244. * - windowBits
  17245. *
  17246. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17247. * for more information.
  17248. *
  17249. * Sugar (options):
  17250. *
  17251. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  17252. * negative windowBits implicitly.
  17253. * - `to` (String) - if equal to 'string', then result will be converted
  17254. * from utf8 to utf16 (javascript) string. When string output requested,
  17255. * chunk length can differ from `chunkSize`, depending on content.
  17256. *
  17257. *
  17258. * ##### Example:
  17259. *
  17260. * ```javascript
  17261. * var pako = require('pako')
  17262. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  17263. * , output;
  17264. *
  17265. * try {
  17266. * output = pako.inflate(input);
  17267. * } catch (err)
  17268. * console.log(err);
  17269. * }
  17270. * ```
  17271. **/
  17272. function inflate(input, options) {
  17273. var inflator = new Inflate(options);
  17274. inflator.push(input, true);
  17275. // That will never happens, if you don't cheat with options :)
  17276. if (inflator.err) { throw inflator.msg; }
  17277. return inflator.result;
  17278. }
  17279. /**
  17280. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  17281. * - data (Uint8Array|Array|String): input data to decompress.
  17282. * - options (Object): zlib inflate options.
  17283. *
  17284. * The same as [[inflate]], but creates raw data, without wrapper
  17285. * (header and adler32 crc).
  17286. **/
  17287. function inflateRaw(input, options) {
  17288. options = options || {};
  17289. options.raw = true;
  17290. return inflate(input, options);
  17291. }
  17292. /**
  17293. * ungzip(data[, options]) -> Uint8Array|Array|String
  17294. * - data (Uint8Array|Array|String): input data to decompress.
  17295. * - options (Object): zlib inflate options.
  17296. *
  17297. * Just shortcut to [[inflate]], because it autodetects format
  17298. * by header.content. Done for convenience.
  17299. **/
  17300. exports.Inflate = Inflate;
  17301. exports.inflate = inflate;
  17302. exports.inflateRaw = inflateRaw;
  17303. exports.ungzip = inflate;
  17304. },{"./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){
  17305. 'use strict';
  17306. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  17307. (typeof Uint16Array !== 'undefined') &&
  17308. (typeof Int32Array !== 'undefined');
  17309. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  17310. var sources = Array.prototype.slice.call(arguments, 1);
  17311. while (sources.length) {
  17312. var source = sources.shift();
  17313. if (!source) { continue; }
  17314. if (typeof(source) !== 'object') {
  17315. throw new TypeError(source + 'must be non-object');
  17316. }
  17317. for (var p in source) {
  17318. if (source.hasOwnProperty(p)) {
  17319. obj[p] = source[p];
  17320. }
  17321. }
  17322. }
  17323. return obj;
  17324. };
  17325. // reduce buffer size, avoiding mem copy
  17326. exports.shrinkBuf = function (buf, size) {
  17327. if (buf.length === size) { return buf; }
  17328. if (buf.subarray) { return buf.subarray(0, size); }
  17329. buf.length = size;
  17330. return buf;
  17331. };
  17332. var fnTyped = {
  17333. arraySet: function (dest, src, src_offs, len, dest_offs) {
  17334. if (src.subarray && dest.subarray) {
  17335. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  17336. return;
  17337. }
  17338. // Fallback to ordinary array
  17339. for(var i=0; i<len; i++) {
  17340. dest[dest_offs + i] = src[src_offs + i];
  17341. }
  17342. },
  17343. // Join array of chunks to single array.
  17344. flattenChunks: function(chunks) {
  17345. var i, l, len, pos, chunk, result;
  17346. // calculate data length
  17347. len = 0;
  17348. for (i=0, l=chunks.length; i<l; i++) {
  17349. len += chunks[i].length;
  17350. }
  17351. // join chunks
  17352. result = new Uint8Array(len);
  17353. pos = 0;
  17354. for (i=0, l=chunks.length; i<l; i++) {
  17355. chunk = chunks[i];
  17356. result.set(chunk, pos);
  17357. pos += chunk.length;
  17358. }
  17359. return result;
  17360. }
  17361. };
  17362. var fnUntyped = {
  17363. arraySet: function (dest, src, src_offs, len, dest_offs) {
  17364. for(var i=0; i<len; i++) {
  17365. dest[dest_offs + i] = src[src_offs + i];
  17366. }
  17367. },
  17368. // Join array of chunks to single array.
  17369. flattenChunks: function(chunks) {
  17370. return [].concat.apply([], chunks);
  17371. }
  17372. };
  17373. // Enable/Disable typed arrays use, for testing
  17374. //
  17375. exports.setTyped = function (on) {
  17376. if (on) {
  17377. exports.Buf8 = Uint8Array;
  17378. exports.Buf16 = Uint16Array;
  17379. exports.Buf32 = Int32Array;
  17380. exports.assign(exports, fnTyped);
  17381. } else {
  17382. exports.Buf8 = Array;
  17383. exports.Buf16 = Array;
  17384. exports.Buf32 = Array;
  17385. exports.assign(exports, fnUntyped);
  17386. }
  17387. };
  17388. exports.setTyped(TYPED_OK);
  17389. },{}],67:[function(require,module,exports){
  17390. // String encode/decode helpers
  17391. 'use strict';
  17392. var utils = require('./common');
  17393. // Quick check if we can use fast array to bin string conversion
  17394. //
  17395. // - apply(Array) can fail on Android 2.2
  17396. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  17397. //
  17398. var STR_APPLY_OK = true;
  17399. var STR_APPLY_UIA_OK = true;
  17400. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  17401. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  17402. // Table with utf8 lengths (calculated by first byte of sequence)
  17403. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  17404. // because max possible codepoint is 0x10ffff
  17405. var _utf8len = new utils.Buf8(256);
  17406. for (var i=0; i<256; i++) {
  17407. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  17408. }
  17409. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  17410. // convert string to array (typed, when possible)
  17411. exports.string2buf = function (str) {
  17412. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  17413. // count binary size
  17414. for (m_pos = 0; m_pos < str_len; m_pos++) {
  17415. c = str.charCodeAt(m_pos);
  17416. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  17417. c2 = str.charCodeAt(m_pos+1);
  17418. if ((c2 & 0xfc00) === 0xdc00) {
  17419. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  17420. m_pos++;
  17421. }
  17422. }
  17423. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  17424. }
  17425. // allocate buffer
  17426. buf = new utils.Buf8(buf_len);
  17427. // convert
  17428. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  17429. c = str.charCodeAt(m_pos);
  17430. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  17431. c2 = str.charCodeAt(m_pos+1);
  17432. if ((c2 & 0xfc00) === 0xdc00) {
  17433. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  17434. m_pos++;
  17435. }
  17436. }
  17437. if (c < 0x80) {
  17438. /* one byte */
  17439. buf[i++] = c;
  17440. } else if (c < 0x800) {
  17441. /* two bytes */
  17442. buf[i++] = 0xC0 | (c >>> 6);
  17443. buf[i++] = 0x80 | (c & 0x3f);
  17444. } else if (c < 0x10000) {
  17445. /* three bytes */
  17446. buf[i++] = 0xE0 | (c >>> 12);
  17447. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  17448. buf[i++] = 0x80 | (c & 0x3f);
  17449. } else {
  17450. /* four bytes */
  17451. buf[i++] = 0xf0 | (c >>> 18);
  17452. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  17453. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  17454. buf[i++] = 0x80 | (c & 0x3f);
  17455. }
  17456. }
  17457. return buf;
  17458. };
  17459. // Helper (used in 2 places)
  17460. function buf2binstring(buf, len) {
  17461. // use fallback for big arrays to avoid stack overflow
  17462. if (len < 65537) {
  17463. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  17464. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  17465. }
  17466. }
  17467. var result = '';
  17468. for(var i=0; i < len; i++) {
  17469. result += String.fromCharCode(buf[i]);
  17470. }
  17471. return result;
  17472. }
  17473. // Convert byte array to binary string
  17474. exports.buf2binstring = function(buf) {
  17475. return buf2binstring(buf, buf.length);
  17476. };
  17477. // Convert binary string (typed, when possible)
  17478. exports.binstring2buf = function(str) {
  17479. var buf = new utils.Buf8(str.length);
  17480. for(var i=0, len=buf.length; i < len; i++) {
  17481. buf[i] = str.charCodeAt(i);
  17482. }
  17483. return buf;
  17484. };
  17485. // convert array to string
  17486. exports.buf2string = function (buf, max) {
  17487. var i, out, c, c_len;
  17488. var len = max || buf.length;
  17489. // Reserve max possible length (2 words per char)
  17490. // NB: by unknown reasons, Array is significantly faster for
  17491. // String.fromCharCode.apply than Uint16Array.
  17492. var utf16buf = new Array(len*2);
  17493. for (out=0, i=0; i<len;) {
  17494. c = buf[i++];
  17495. // quick process ascii
  17496. if (c < 0x80) { utf16buf[out++] = c; continue; }
  17497. c_len = _utf8len[c];
  17498. // skip 5 & 6 byte codes
  17499. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  17500. // apply mask on first byte
  17501. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  17502. // join the rest
  17503. while (c_len > 1 && i < len) {
  17504. c = (c << 6) | (buf[i++] & 0x3f);
  17505. c_len--;
  17506. }
  17507. // terminated by end of string?
  17508. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  17509. if (c < 0x10000) {
  17510. utf16buf[out++] = c;
  17511. } else {
  17512. c -= 0x10000;
  17513. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  17514. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  17515. }
  17516. }
  17517. return buf2binstring(utf16buf, out);
  17518. };
  17519. // Calculate max possible position in utf8 buffer,
  17520. // that will not break sequence. If that's not possible
  17521. // - (very small limits) return max size as is.
  17522. //
  17523. // buf[] - utf8 bytes array
  17524. // max - length limit (mandatory);
  17525. exports.utf8border = function(buf, max) {
  17526. var pos;
  17527. max = max || buf.length;
  17528. if (max > buf.length) { max = buf.length; }
  17529. // go back from last position, until start of sequence found
  17530. pos = max-1;
  17531. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  17532. // Fuckup - very small and broken sequence,
  17533. // return max, because we should return something anyway.
  17534. if (pos < 0) { return max; }
  17535. // If we came to start of buffer - that means vuffer is too small,
  17536. // return max too.
  17537. if (pos === 0) { return max; }
  17538. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  17539. };
  17540. },{"./common":66}],68:[function(require,module,exports){
  17541. 'use strict';
  17542. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  17543. // It doesn't worth to make additional optimizationa as in original.
  17544. // Small size is preferable.
  17545. function adler32(adler, buf, len, pos) {
  17546. var s1 = (adler & 0xffff) |0
  17547. , s2 = ((adler >>> 16) & 0xffff) |0
  17548. , n = 0;
  17549. while (len !== 0) {
  17550. // Set limit ~ twice less than 5552, to keep
  17551. // s2 in 31-bits, because we force signed ints.
  17552. // in other case %= will fail.
  17553. n = len > 2000 ? 2000 : len;
  17554. len -= n;
  17555. do {
  17556. s1 = (s1 + buf[pos++]) |0;
  17557. s2 = (s2 + s1) |0;
  17558. } while (--n);
  17559. s1 %= 65521;
  17560. s2 %= 65521;
  17561. }
  17562. return (s1 | (s2 << 16)) |0;
  17563. }
  17564. module.exports = adler32;
  17565. },{}],69:[function(require,module,exports){
  17566. module.exports = {
  17567. /* Allowed flush values; see deflate() and inflate() below for details */
  17568. Z_NO_FLUSH: 0,
  17569. Z_PARTIAL_FLUSH: 1,
  17570. Z_SYNC_FLUSH: 2,
  17571. Z_FULL_FLUSH: 3,
  17572. Z_FINISH: 4,
  17573. Z_BLOCK: 5,
  17574. Z_TREES: 6,
  17575. /* Return codes for the compression/decompression functions. Negative values
  17576. * are errors, positive values are used for special but normal events.
  17577. */
  17578. Z_OK: 0,
  17579. Z_STREAM_END: 1,
  17580. Z_NEED_DICT: 2,
  17581. Z_ERRNO: -1,
  17582. Z_STREAM_ERROR: -2,
  17583. Z_DATA_ERROR: -3,
  17584. //Z_MEM_ERROR: -4,
  17585. Z_BUF_ERROR: -5,
  17586. //Z_VERSION_ERROR: -6,
  17587. /* compression levels */
  17588. Z_NO_COMPRESSION: 0,
  17589. Z_BEST_SPEED: 1,
  17590. Z_BEST_COMPRESSION: 9,
  17591. Z_DEFAULT_COMPRESSION: -1,
  17592. Z_FILTERED: 1,
  17593. Z_HUFFMAN_ONLY: 2,
  17594. Z_RLE: 3,
  17595. Z_FIXED: 4,
  17596. Z_DEFAULT_STRATEGY: 0,
  17597. /* Possible values of the data_type field (though see inflate()) */
  17598. Z_BINARY: 0,
  17599. Z_TEXT: 1,
  17600. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  17601. Z_UNKNOWN: 2,
  17602. /* The deflate compression method */
  17603. Z_DEFLATED: 8
  17604. //Z_NULL: null // Use -1 or null inline, depending on var type
  17605. };
  17606. },{}],70:[function(require,module,exports){
  17607. 'use strict';
  17608. // Note: we can't get significant speed boost here.
  17609. // So write code to minimize size - no pregenerated tables
  17610. // and array tools dependencies.
  17611. // Use ordinary array, since untyped makes no boost here
  17612. function makeTable() {
  17613. var c, table = [];
  17614. for(var n =0; n < 256; n++){
  17615. c = n;
  17616. for(var k =0; k < 8; k++){
  17617. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  17618. }
  17619. table[n] = c;
  17620. }
  17621. return table;
  17622. }
  17623. // Create table on load. Just 255 signed longs. Not a problem.
  17624. var crcTable = makeTable();
  17625. function crc32(crc, buf, len, pos) {
  17626. var t = crcTable
  17627. , end = pos + len;
  17628. crc = crc ^ (-1);
  17629. for (var i = pos; i < end; i++ ) {
  17630. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  17631. }
  17632. return (crc ^ (-1)); // >>> 0;
  17633. }
  17634. module.exports = crc32;
  17635. },{}],71:[function(require,module,exports){
  17636. 'use strict';
  17637. var utils = require('../utils/common');
  17638. var trees = require('./trees');
  17639. var adler32 = require('./adler32');
  17640. var crc32 = require('./crc32');
  17641. var msg = require('./messages');
  17642. /* Public constants ==========================================================*/
  17643. /* ===========================================================================*/
  17644. /* Allowed flush values; see deflate() and inflate() below for details */
  17645. var Z_NO_FLUSH = 0;
  17646. var Z_PARTIAL_FLUSH = 1;
  17647. //var Z_SYNC_FLUSH = 2;
  17648. var Z_FULL_FLUSH = 3;
  17649. var Z_FINISH = 4;
  17650. var Z_BLOCK = 5;
  17651. //var Z_TREES = 6;
  17652. /* Return codes for the compression/decompression functions. Negative values
  17653. * are errors, positive values are used for special but normal events.
  17654. */
  17655. var Z_OK = 0;
  17656. var Z_STREAM_END = 1;
  17657. //var Z_NEED_DICT = 2;
  17658. //var Z_ERRNO = -1;
  17659. var Z_STREAM_ERROR = -2;
  17660. var Z_DATA_ERROR = -3;
  17661. //var Z_MEM_ERROR = -4;
  17662. var Z_BUF_ERROR = -5;
  17663. //var Z_VERSION_ERROR = -6;
  17664. /* compression levels */
  17665. //var Z_NO_COMPRESSION = 0;
  17666. //var Z_BEST_SPEED = 1;
  17667. //var Z_BEST_COMPRESSION = 9;
  17668. var Z_DEFAULT_COMPRESSION = -1;
  17669. var Z_FILTERED = 1;
  17670. var Z_HUFFMAN_ONLY = 2;
  17671. var Z_RLE = 3;
  17672. var Z_FIXED = 4;
  17673. var Z_DEFAULT_STRATEGY = 0;
  17674. /* Possible values of the data_type field (though see inflate()) */
  17675. //var Z_BINARY = 0;
  17676. //var Z_TEXT = 1;
  17677. //var Z_ASCII = 1; // = Z_TEXT
  17678. var Z_UNKNOWN = 2;
  17679. /* The deflate compression method */
  17680. var Z_DEFLATED = 8;
  17681. /*============================================================================*/
  17682. var MAX_MEM_LEVEL = 9;
  17683. /* Maximum value for memLevel in deflateInit2 */
  17684. var MAX_WBITS = 15;
  17685. /* 32K LZ77 window */
  17686. var DEF_MEM_LEVEL = 8;
  17687. var LENGTH_CODES = 29;
  17688. /* number of length codes, not counting the special END_BLOCK code */
  17689. var LITERALS = 256;
  17690. /* number of literal bytes 0..255 */
  17691. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  17692. /* number of Literal or Length codes, including the END_BLOCK code */
  17693. var D_CODES = 30;
  17694. /* number of distance codes */
  17695. var BL_CODES = 19;
  17696. /* number of codes used to transfer the bit lengths */
  17697. var HEAP_SIZE = 2*L_CODES + 1;
  17698. /* maximum heap size */
  17699. var MAX_BITS = 15;
  17700. /* All codes must not exceed MAX_BITS bits */
  17701. var MIN_MATCH = 3;
  17702. var MAX_MATCH = 258;
  17703. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  17704. var PRESET_DICT = 0x20;
  17705. var INIT_STATE = 42;
  17706. var EXTRA_STATE = 69;
  17707. var NAME_STATE = 73;
  17708. var COMMENT_STATE = 91;
  17709. var HCRC_STATE = 103;
  17710. var BUSY_STATE = 113;
  17711. var FINISH_STATE = 666;
  17712. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  17713. var BS_BLOCK_DONE = 2; /* block flush performed */
  17714. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  17715. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  17716. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  17717. function err(strm, errorCode) {
  17718. strm.msg = msg[errorCode];
  17719. return errorCode;
  17720. }
  17721. function rank(f) {
  17722. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  17723. }
  17724. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  17725. /* =========================================================================
  17726. * Flush as much pending output as possible. All deflate() output goes
  17727. * through this function so some applications may wish to modify it
  17728. * to avoid allocating a large strm->output buffer and copying into it.
  17729. * (See also read_buf()).
  17730. */
  17731. function flush_pending(strm) {
  17732. var s = strm.state;
  17733. //_tr_flush_bits(s);
  17734. var len = s.pending;
  17735. if (len > strm.avail_out) {
  17736. len = strm.avail_out;
  17737. }
  17738. if (len === 0) { return; }
  17739. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  17740. strm.next_out += len;
  17741. s.pending_out += len;
  17742. strm.total_out += len;
  17743. strm.avail_out -= len;
  17744. s.pending -= len;
  17745. if (s.pending === 0) {
  17746. s.pending_out = 0;
  17747. }
  17748. }
  17749. function flush_block_only (s, last) {
  17750. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  17751. s.block_start = s.strstart;
  17752. flush_pending(s.strm);
  17753. }
  17754. function put_byte(s, b) {
  17755. s.pending_buf[s.pending++] = b;
  17756. }
  17757. /* =========================================================================
  17758. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  17759. * IN assertion: the stream state is correct and there is enough room in
  17760. * pending_buf.
  17761. */
  17762. function putShortMSB(s, b) {
  17763. // put_byte(s, (Byte)(b >> 8));
  17764. // put_byte(s, (Byte)(b & 0xff));
  17765. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  17766. s.pending_buf[s.pending++] = b & 0xff;
  17767. }
  17768. /* ===========================================================================
  17769. * Read a new buffer from the current input stream, update the adler32
  17770. * and total number of bytes read. All deflate() input goes through
  17771. * this function so some applications may wish to modify it to avoid
  17772. * allocating a large strm->input buffer and copying from it.
  17773. * (See also flush_pending()).
  17774. */
  17775. function read_buf(strm, buf, start, size) {
  17776. var len = strm.avail_in;
  17777. if (len > size) { len = size; }
  17778. if (len === 0) { return 0; }
  17779. strm.avail_in -= len;
  17780. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  17781. if (strm.state.wrap === 1) {
  17782. strm.adler = adler32(strm.adler, buf, len, start);
  17783. }
  17784. else if (strm.state.wrap === 2) {
  17785. strm.adler = crc32(strm.adler, buf, len, start);
  17786. }
  17787. strm.next_in += len;
  17788. strm.total_in += len;
  17789. return len;
  17790. }
  17791. /* ===========================================================================
  17792. * Set match_start to the longest match starting at the given string and
  17793. * return its length. Matches shorter or equal to prev_length are discarded,
  17794. * in which case the result is equal to prev_length and match_start is
  17795. * garbage.
  17796. * IN assertions: cur_match is the head of the hash chain for the current
  17797. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  17798. * OUT assertion: the match length is not greater than s->lookahead.
  17799. */
  17800. function longest_match(s, cur_match) {
  17801. var chain_length = s.max_chain_length; /* max hash chain length */
  17802. var scan = s.strstart; /* current string */
  17803. var match; /* matched string */
  17804. var len; /* length of current match */
  17805. var best_len = s.prev_length; /* best match length so far */
  17806. var nice_match = s.nice_match; /* stop if match long enough */
  17807. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  17808. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  17809. var _win = s.window; // shortcut
  17810. var wmask = s.w_mask;
  17811. var prev = s.prev;
  17812. /* Stop when cur_match becomes <= limit. To simplify the code,
  17813. * we prevent matches with the string of window index 0.
  17814. */
  17815. var strend = s.strstart + MAX_MATCH;
  17816. var scan_end1 = _win[scan + best_len - 1];
  17817. var scan_end = _win[scan + best_len];
  17818. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  17819. * It is easy to get rid of this optimization if necessary.
  17820. */
  17821. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  17822. /* Do not waste too much time if we already have a good match: */
  17823. if (s.prev_length >= s.good_match) {
  17824. chain_length >>= 2;
  17825. }
  17826. /* Do not look for matches beyond the end of the input. This is necessary
  17827. * to make deflate deterministic.
  17828. */
  17829. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  17830. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  17831. do {
  17832. // Assert(cur_match < s->strstart, "no future");
  17833. match = cur_match;
  17834. /* Skip to next match if the match length cannot increase
  17835. * or if the match length is less than 2. Note that the checks below
  17836. * for insufficient lookahead only occur occasionally for performance
  17837. * reasons. Therefore uninitialized memory will be accessed, and
  17838. * conditional jumps will be made that depend on those values.
  17839. * However the length of the match is limited to the lookahead, so
  17840. * the output of deflate is not affected by the uninitialized values.
  17841. */
  17842. if (_win[match + best_len] !== scan_end ||
  17843. _win[match + best_len - 1] !== scan_end1 ||
  17844. _win[match] !== _win[scan] ||
  17845. _win[++match] !== _win[scan + 1]) {
  17846. continue;
  17847. }
  17848. /* The check at best_len-1 can be removed because it will be made
  17849. * again later. (This heuristic is not always a win.)
  17850. * It is not necessary to compare scan[2] and match[2] since they
  17851. * are always equal when the other bytes match, given that
  17852. * the hash keys are equal and that HASH_BITS >= 8.
  17853. */
  17854. scan += 2;
  17855. match++;
  17856. // Assert(*scan == *match, "match[2]?");
  17857. /* We check for insufficient lookahead only every 8th comparison;
  17858. * the 256th check will be made at strstart+258.
  17859. */
  17860. do {
  17861. /*jshint noempty:false*/
  17862. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  17863. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  17864. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  17865. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  17866. scan < strend);
  17867. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  17868. len = MAX_MATCH - (strend - scan);
  17869. scan = strend - MAX_MATCH;
  17870. if (len > best_len) {
  17871. s.match_start = cur_match;
  17872. best_len = len;
  17873. if (len >= nice_match) {
  17874. break;
  17875. }
  17876. scan_end1 = _win[scan + best_len - 1];
  17877. scan_end = _win[scan + best_len];
  17878. }
  17879. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  17880. if (best_len <= s.lookahead) {
  17881. return best_len;
  17882. }
  17883. return s.lookahead;
  17884. }
  17885. /* ===========================================================================
  17886. * Fill the window when the lookahead becomes insufficient.
  17887. * Updates strstart and lookahead.
  17888. *
  17889. * IN assertion: lookahead < MIN_LOOKAHEAD
  17890. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  17891. * At least one byte has been read, or avail_in == 0; reads are
  17892. * performed for at least two bytes (required for the zip translate_eol
  17893. * option -- not supported here).
  17894. */
  17895. function fill_window(s) {
  17896. var _w_size = s.w_size;
  17897. var p, n, m, more, str;
  17898. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  17899. do {
  17900. more = s.window_size - s.lookahead - s.strstart;
  17901. // JS ints have 32 bit, block below not needed
  17902. /* Deal with !@#$% 64K limit: */
  17903. //if (sizeof(int) <= 2) {
  17904. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  17905. // more = wsize;
  17906. //
  17907. // } else if (more == (unsigned)(-1)) {
  17908. // /* Very unlikely, but possible on 16 bit machine if
  17909. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  17910. // */
  17911. // more--;
  17912. // }
  17913. //}
  17914. /* If the window is almost full and there is insufficient lookahead,
  17915. * move the upper half to the lower one to make room in the upper half.
  17916. */
  17917. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  17918. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  17919. s.match_start -= _w_size;
  17920. s.strstart -= _w_size;
  17921. /* we now have strstart >= MAX_DIST */
  17922. s.block_start -= _w_size;
  17923. /* Slide the hash table (could be avoided with 32 bit values
  17924. at the expense of memory usage). We slide even when level == 0
  17925. to keep the hash table consistent if we switch back to level > 0
  17926. later. (Using level 0 permanently is not an optimal usage of
  17927. zlib, so we don't care about this pathological case.)
  17928. */
  17929. n = s.hash_size;
  17930. p = n;
  17931. do {
  17932. m = s.head[--p];
  17933. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  17934. } while (--n);
  17935. n = _w_size;
  17936. p = n;
  17937. do {
  17938. m = s.prev[--p];
  17939. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  17940. /* If n is not on any hash chain, prev[n] is garbage but
  17941. * its value will never be used.
  17942. */
  17943. } while (--n);
  17944. more += _w_size;
  17945. }
  17946. if (s.strm.avail_in === 0) {
  17947. break;
  17948. }
  17949. /* If there was no sliding:
  17950. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  17951. * more == window_size - lookahead - strstart
  17952. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  17953. * => more >= window_size - 2*WSIZE + 2
  17954. * In the BIG_MEM or MMAP case (not yet supported),
  17955. * window_size == input_size + MIN_LOOKAHEAD &&
  17956. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  17957. * Otherwise, window_size == 2*WSIZE so more >= 2.
  17958. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  17959. */
  17960. //Assert(more >= 2, "more < 2");
  17961. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  17962. s.lookahead += n;
  17963. /* Initialize the hash value now that we have some input: */
  17964. if (s.lookahead + s.insert >= MIN_MATCH) {
  17965. str = s.strstart - s.insert;
  17966. s.ins_h = s.window[str];
  17967. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  17968. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  17969. //#if MIN_MATCH != 3
  17970. // Call update_hash() MIN_MATCH-3 more times
  17971. //#endif
  17972. while (s.insert) {
  17973. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  17974. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  17975. s.prev[str & s.w_mask] = s.head[s.ins_h];
  17976. s.head[s.ins_h] = str;
  17977. str++;
  17978. s.insert--;
  17979. if (s.lookahead + s.insert < MIN_MATCH) {
  17980. break;
  17981. }
  17982. }
  17983. }
  17984. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  17985. * but this is not important since only literal bytes will be emitted.
  17986. */
  17987. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  17988. /* If the WIN_INIT bytes after the end of the current data have never been
  17989. * written, then zero those bytes in order to avoid memory check reports of
  17990. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  17991. * the longest match routines. Update the high water mark for the next
  17992. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  17993. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  17994. */
  17995. // if (s.high_water < s.window_size) {
  17996. // var curr = s.strstart + s.lookahead;
  17997. // var init = 0;
  17998. //
  17999. // if (s.high_water < curr) {
  18000. // /* Previous high water mark below current data -- zero WIN_INIT
  18001. // * bytes or up to end of window, whichever is less.
  18002. // */
  18003. // init = s.window_size - curr;
  18004. // if (init > WIN_INIT)
  18005. // init = WIN_INIT;
  18006. // zmemzero(s->window + curr, (unsigned)init);
  18007. // s->high_water = curr + init;
  18008. // }
  18009. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  18010. // /* High water mark at or above current data, but below current data
  18011. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  18012. // * to end of window, whichever is less.
  18013. // */
  18014. // init = (ulg)curr + WIN_INIT - s->high_water;
  18015. // if (init > s->window_size - s->high_water)
  18016. // init = s->window_size - s->high_water;
  18017. // zmemzero(s->window + s->high_water, (unsigned)init);
  18018. // s->high_water += init;
  18019. // }
  18020. // }
  18021. //
  18022. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  18023. // "not enough room for search");
  18024. }
  18025. /* ===========================================================================
  18026. * Copy without compression as much as possible from the input stream, return
  18027. * the current block state.
  18028. * This function does not insert new strings in the dictionary since
  18029. * uncompressible data is probably not useful. This function is used
  18030. * only for the level=0 compression option.
  18031. * NOTE: this function should be optimized to avoid extra copying from
  18032. * window to pending_buf.
  18033. */
  18034. function deflate_stored(s, flush) {
  18035. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  18036. * to pending_buf_size, and each stored block has a 5 byte header:
  18037. */
  18038. var max_block_size = 0xffff;
  18039. if (max_block_size > s.pending_buf_size - 5) {
  18040. max_block_size = s.pending_buf_size - 5;
  18041. }
  18042. /* Copy as much as possible from input to output: */
  18043. for (;;) {
  18044. /* Fill the window as much as possible: */
  18045. if (s.lookahead <= 1) {
  18046. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  18047. // s->block_start >= (long)s->w_size, "slide too late");
  18048. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  18049. // s.block_start >= s.w_size)) {
  18050. // throw new Error("slide too late");
  18051. // }
  18052. fill_window(s);
  18053. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  18054. return BS_NEED_MORE;
  18055. }
  18056. if (s.lookahead === 0) {
  18057. break;
  18058. }
  18059. /* flush the current block */
  18060. }
  18061. //Assert(s->block_start >= 0L, "block gone");
  18062. // if (s.block_start < 0) throw new Error("block gone");
  18063. s.strstart += s.lookahead;
  18064. s.lookahead = 0;
  18065. /* Emit a stored block if pending_buf will be full: */
  18066. var max_start = s.block_start + max_block_size;
  18067. if (s.strstart === 0 || s.strstart >= max_start) {
  18068. /* strstart == 0 is possible when wraparound on 16-bit machine */
  18069. s.lookahead = s.strstart - max_start;
  18070. s.strstart = max_start;
  18071. /*** FLUSH_BLOCK(s, 0); ***/
  18072. flush_block_only(s, false);
  18073. if (s.strm.avail_out === 0) {
  18074. return BS_NEED_MORE;
  18075. }
  18076. /***/
  18077. }
  18078. /* Flush if we may have to slide, otherwise block_start may become
  18079. * negative and the data will be gone:
  18080. */
  18081. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  18082. /*** FLUSH_BLOCK(s, 0); ***/
  18083. flush_block_only(s, false);
  18084. if (s.strm.avail_out === 0) {
  18085. return BS_NEED_MORE;
  18086. }
  18087. /***/
  18088. }
  18089. }
  18090. s.insert = 0;
  18091. if (flush === Z_FINISH) {
  18092. /*** FLUSH_BLOCK(s, 1); ***/
  18093. flush_block_only(s, true);
  18094. if (s.strm.avail_out === 0) {
  18095. return BS_FINISH_STARTED;
  18096. }
  18097. /***/
  18098. return BS_FINISH_DONE;
  18099. }
  18100. if (s.strstart > s.block_start) {
  18101. /*** FLUSH_BLOCK(s, 0); ***/
  18102. flush_block_only(s, false);
  18103. if (s.strm.avail_out === 0) {
  18104. return BS_NEED_MORE;
  18105. }
  18106. /***/
  18107. }
  18108. return BS_NEED_MORE;
  18109. }
  18110. /* ===========================================================================
  18111. * Compress as much as possible from the input stream, return the current
  18112. * block state.
  18113. * This function does not perform lazy evaluation of matches and inserts
  18114. * new strings in the dictionary only for unmatched strings or for short
  18115. * matches. It is used only for the fast compression options.
  18116. */
  18117. function deflate_fast(s, flush) {
  18118. var hash_head; /* head of the hash chain */
  18119. var bflush; /* set if current block must be flushed */
  18120. for (;;) {
  18121. /* Make sure that we always have enough lookahead, except
  18122. * at the end of the input file. We need MAX_MATCH bytes
  18123. * for the next match, plus MIN_MATCH bytes to insert the
  18124. * string following the next match.
  18125. */
  18126. if (s.lookahead < MIN_LOOKAHEAD) {
  18127. fill_window(s);
  18128. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  18129. return BS_NEED_MORE;
  18130. }
  18131. if (s.lookahead === 0) {
  18132. break; /* flush the current block */
  18133. }
  18134. }
  18135. /* Insert the string window[strstart .. strstart+2] in the
  18136. * dictionary, and set hash_head to the head of the hash chain:
  18137. */
  18138. hash_head = 0/*NIL*/;
  18139. if (s.lookahead >= MIN_MATCH) {
  18140. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18141. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18142. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18143. s.head[s.ins_h] = s.strstart;
  18144. /***/
  18145. }
  18146. /* Find the longest match, discarding those <= prev_length.
  18147. * At this point we have always match_length < MIN_MATCH
  18148. */
  18149. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  18150. /* To simplify the code, we prevent matches with the string
  18151. * of window index 0 (in particular we have to avoid a match
  18152. * of the string with itself at the start of the input file).
  18153. */
  18154. s.match_length = longest_match(s, hash_head);
  18155. /* longest_match() sets match_start */
  18156. }
  18157. if (s.match_length >= MIN_MATCH) {
  18158. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  18159. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  18160. s.match_length - MIN_MATCH, bflush); ***/
  18161. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  18162. s.lookahead -= s.match_length;
  18163. /* Insert new strings in the hash table only if the match length
  18164. * is not too large. This saves time but degrades compression.
  18165. */
  18166. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  18167. s.match_length--; /* string at strstart already in table */
  18168. do {
  18169. s.strstart++;
  18170. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18171. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18172. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18173. s.head[s.ins_h] = s.strstart;
  18174. /***/
  18175. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  18176. * always MIN_MATCH bytes ahead.
  18177. */
  18178. } while (--s.match_length !== 0);
  18179. s.strstart++;
  18180. } else
  18181. {
  18182. s.strstart += s.match_length;
  18183. s.match_length = 0;
  18184. s.ins_h = s.window[s.strstart];
  18185. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  18186. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  18187. //#if MIN_MATCH != 3
  18188. // Call UPDATE_HASH() MIN_MATCH-3 more times
  18189. //#endif
  18190. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  18191. * matter since it will be recomputed at next deflate call.
  18192. */
  18193. }
  18194. } else {
  18195. /* No match, output a literal byte */
  18196. //Tracevv((stderr,"%c", s.window[s.strstart]));
  18197. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18198. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18199. s.lookahead--;
  18200. s.strstart++;
  18201. }
  18202. if (bflush) {
  18203. /*** FLUSH_BLOCK(s, 0); ***/
  18204. flush_block_only(s, false);
  18205. if (s.strm.avail_out === 0) {
  18206. return BS_NEED_MORE;
  18207. }
  18208. /***/
  18209. }
  18210. }
  18211. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  18212. if (flush === Z_FINISH) {
  18213. /*** FLUSH_BLOCK(s, 1); ***/
  18214. flush_block_only(s, true);
  18215. if (s.strm.avail_out === 0) {
  18216. return BS_FINISH_STARTED;
  18217. }
  18218. /***/
  18219. return BS_FINISH_DONE;
  18220. }
  18221. if (s.last_lit) {
  18222. /*** FLUSH_BLOCK(s, 0); ***/
  18223. flush_block_only(s, false);
  18224. if (s.strm.avail_out === 0) {
  18225. return BS_NEED_MORE;
  18226. }
  18227. /***/
  18228. }
  18229. return BS_BLOCK_DONE;
  18230. }
  18231. /* ===========================================================================
  18232. * Same as above, but achieves better compression. We use a lazy
  18233. * evaluation for matches: a match is finally adopted only if there is
  18234. * no better match at the next window position.
  18235. */
  18236. function deflate_slow(s, flush) {
  18237. var hash_head; /* head of hash chain */
  18238. var bflush; /* set if current block must be flushed */
  18239. var max_insert;
  18240. /* Process the input block. */
  18241. for (;;) {
  18242. /* Make sure that we always have enough lookahead, except
  18243. * at the end of the input file. We need MAX_MATCH bytes
  18244. * for the next match, plus MIN_MATCH bytes to insert the
  18245. * string following the next match.
  18246. */
  18247. if (s.lookahead < MIN_LOOKAHEAD) {
  18248. fill_window(s);
  18249. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  18250. return BS_NEED_MORE;
  18251. }
  18252. if (s.lookahead === 0) { break; } /* flush the current block */
  18253. }
  18254. /* Insert the string window[strstart .. strstart+2] in the
  18255. * dictionary, and set hash_head to the head of the hash chain:
  18256. */
  18257. hash_head = 0/*NIL*/;
  18258. if (s.lookahead >= MIN_MATCH) {
  18259. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18260. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18261. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18262. s.head[s.ins_h] = s.strstart;
  18263. /***/
  18264. }
  18265. /* Find the longest match, discarding those <= prev_length.
  18266. */
  18267. s.prev_length = s.match_length;
  18268. s.prev_match = s.match_start;
  18269. s.match_length = MIN_MATCH-1;
  18270. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  18271. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  18272. /* To simplify the code, we prevent matches with the string
  18273. * of window index 0 (in particular we have to avoid a match
  18274. * of the string with itself at the start of the input file).
  18275. */
  18276. s.match_length = longest_match(s, hash_head);
  18277. /* longest_match() sets match_start */
  18278. if (s.match_length <= 5 &&
  18279. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  18280. /* If prev_match is also MIN_MATCH, match_start is garbage
  18281. * but we will ignore the current match anyway.
  18282. */
  18283. s.match_length = MIN_MATCH-1;
  18284. }
  18285. }
  18286. /* If there was a match at the previous step and the current
  18287. * match is not better, output the previous match:
  18288. */
  18289. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  18290. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  18291. /* Do not insert strings in hash table beyond this. */
  18292. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  18293. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  18294. s.prev_length - MIN_MATCH, bflush);***/
  18295. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  18296. /* Insert in hash table all strings up to the end of the match.
  18297. * strstart-1 and strstart are already inserted. If there is not
  18298. * enough lookahead, the last two strings are not inserted in
  18299. * the hash table.
  18300. */
  18301. s.lookahead -= s.prev_length-1;
  18302. s.prev_length -= 2;
  18303. do {
  18304. if (++s.strstart <= max_insert) {
  18305. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18306. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18307. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18308. s.head[s.ins_h] = s.strstart;
  18309. /***/
  18310. }
  18311. } while (--s.prev_length !== 0);
  18312. s.match_available = 0;
  18313. s.match_length = MIN_MATCH-1;
  18314. s.strstart++;
  18315. if (bflush) {
  18316. /*** FLUSH_BLOCK(s, 0); ***/
  18317. flush_block_only(s, false);
  18318. if (s.strm.avail_out === 0) {
  18319. return BS_NEED_MORE;
  18320. }
  18321. /***/
  18322. }
  18323. } else if (s.match_available) {
  18324. /* If there was no match at the previous position, output a
  18325. * single literal. If there was a match but the current match
  18326. * is longer, truncate the previous match to a single literal.
  18327. */
  18328. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  18329. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  18330. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  18331. if (bflush) {
  18332. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  18333. flush_block_only(s, false);
  18334. /***/
  18335. }
  18336. s.strstart++;
  18337. s.lookahead--;
  18338. if (s.strm.avail_out === 0) {
  18339. return BS_NEED_MORE;
  18340. }
  18341. } else {
  18342. /* There is no previous match to compare with, wait for
  18343. * the next step to decide.
  18344. */
  18345. s.match_available = 1;
  18346. s.strstart++;
  18347. s.lookahead--;
  18348. }
  18349. }
  18350. //Assert (flush != Z_NO_FLUSH, "no flush?");
  18351. if (s.match_available) {
  18352. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  18353. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  18354. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  18355. s.match_available = 0;
  18356. }
  18357. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  18358. if (flush === Z_FINISH) {
  18359. /*** FLUSH_BLOCK(s, 1); ***/
  18360. flush_block_only(s, true);
  18361. if (s.strm.avail_out === 0) {
  18362. return BS_FINISH_STARTED;
  18363. }
  18364. /***/
  18365. return BS_FINISH_DONE;
  18366. }
  18367. if (s.last_lit) {
  18368. /*** FLUSH_BLOCK(s, 0); ***/
  18369. flush_block_only(s, false);
  18370. if (s.strm.avail_out === 0) {
  18371. return BS_NEED_MORE;
  18372. }
  18373. /***/
  18374. }
  18375. return BS_BLOCK_DONE;
  18376. }
  18377. /* ===========================================================================
  18378. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  18379. * one. Do not maintain a hash table. (It will be regenerated if this run of
  18380. * deflate switches away from Z_RLE.)
  18381. */
  18382. function deflate_rle(s, flush) {
  18383. var bflush; /* set if current block must be flushed */
  18384. var prev; /* byte at distance one to match */
  18385. var scan, strend; /* scan goes up to strend for length of run */
  18386. var _win = s.window;
  18387. for (;;) {
  18388. /* Make sure that we always have enough lookahead, except
  18389. * at the end of the input file. We need MAX_MATCH bytes
  18390. * for the longest run, plus one for the unrolled loop.
  18391. */
  18392. if (s.lookahead <= MAX_MATCH) {
  18393. fill_window(s);
  18394. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  18395. return BS_NEED_MORE;
  18396. }
  18397. if (s.lookahead === 0) { break; } /* flush the current block */
  18398. }
  18399. /* See how many times the previous byte repeats */
  18400. s.match_length = 0;
  18401. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  18402. scan = s.strstart - 1;
  18403. prev = _win[scan];
  18404. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  18405. strend = s.strstart + MAX_MATCH;
  18406. do {
  18407. /*jshint noempty:false*/
  18408. } while (prev === _win[++scan] && prev === _win[++scan] &&
  18409. prev === _win[++scan] && prev === _win[++scan] &&
  18410. prev === _win[++scan] && prev === _win[++scan] &&
  18411. prev === _win[++scan] && prev === _win[++scan] &&
  18412. scan < strend);
  18413. s.match_length = MAX_MATCH - (strend - scan);
  18414. if (s.match_length > s.lookahead) {
  18415. s.match_length = s.lookahead;
  18416. }
  18417. }
  18418. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  18419. }
  18420. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  18421. if (s.match_length >= MIN_MATCH) {
  18422. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  18423. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  18424. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  18425. s.lookahead -= s.match_length;
  18426. s.strstart += s.match_length;
  18427. s.match_length = 0;
  18428. } else {
  18429. /* No match, output a literal byte */
  18430. //Tracevv((stderr,"%c", s->window[s->strstart]));
  18431. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18432. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18433. s.lookahead--;
  18434. s.strstart++;
  18435. }
  18436. if (bflush) {
  18437. /*** FLUSH_BLOCK(s, 0); ***/
  18438. flush_block_only(s, false);
  18439. if (s.strm.avail_out === 0) {
  18440. return BS_NEED_MORE;
  18441. }
  18442. /***/
  18443. }
  18444. }
  18445. s.insert = 0;
  18446. if (flush === Z_FINISH) {
  18447. /*** FLUSH_BLOCK(s, 1); ***/
  18448. flush_block_only(s, true);
  18449. if (s.strm.avail_out === 0) {
  18450. return BS_FINISH_STARTED;
  18451. }
  18452. /***/
  18453. return BS_FINISH_DONE;
  18454. }
  18455. if (s.last_lit) {
  18456. /*** FLUSH_BLOCK(s, 0); ***/
  18457. flush_block_only(s, false);
  18458. if (s.strm.avail_out === 0) {
  18459. return BS_NEED_MORE;
  18460. }
  18461. /***/
  18462. }
  18463. return BS_BLOCK_DONE;
  18464. }
  18465. /* ===========================================================================
  18466. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  18467. * (It will be regenerated if this run of deflate switches away from Huffman.)
  18468. */
  18469. function deflate_huff(s, flush) {
  18470. var bflush; /* set if current block must be flushed */
  18471. for (;;) {
  18472. /* Make sure that we have a literal to write. */
  18473. if (s.lookahead === 0) {
  18474. fill_window(s);
  18475. if (s.lookahead === 0) {
  18476. if (flush === Z_NO_FLUSH) {
  18477. return BS_NEED_MORE;
  18478. }
  18479. break; /* flush the current block */
  18480. }
  18481. }
  18482. /* Output a literal byte */
  18483. s.match_length = 0;
  18484. //Tracevv((stderr,"%c", s->window[s->strstart]));
  18485. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18486. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18487. s.lookahead--;
  18488. s.strstart++;
  18489. if (bflush) {
  18490. /*** FLUSH_BLOCK(s, 0); ***/
  18491. flush_block_only(s, false);
  18492. if (s.strm.avail_out === 0) {
  18493. return BS_NEED_MORE;
  18494. }
  18495. /***/
  18496. }
  18497. }
  18498. s.insert = 0;
  18499. if (flush === Z_FINISH) {
  18500. /*** FLUSH_BLOCK(s, 1); ***/
  18501. flush_block_only(s, true);
  18502. if (s.strm.avail_out === 0) {
  18503. return BS_FINISH_STARTED;
  18504. }
  18505. /***/
  18506. return BS_FINISH_DONE;
  18507. }
  18508. if (s.last_lit) {
  18509. /*** FLUSH_BLOCK(s, 0); ***/
  18510. flush_block_only(s, false);
  18511. if (s.strm.avail_out === 0) {
  18512. return BS_NEED_MORE;
  18513. }
  18514. /***/
  18515. }
  18516. return BS_BLOCK_DONE;
  18517. }
  18518. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  18519. * the desired pack level (0..9). The values given below have been tuned to
  18520. * exclude worst case performance for pathological files. Better values may be
  18521. * found for specific files.
  18522. */
  18523. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  18524. this.good_length = good_length;
  18525. this.max_lazy = max_lazy;
  18526. this.nice_length = nice_length;
  18527. this.max_chain = max_chain;
  18528. this.func = func;
  18529. };
  18530. var configuration_table;
  18531. configuration_table = [
  18532. /* good lazy nice chain */
  18533. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  18534. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  18535. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  18536. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  18537. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  18538. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  18539. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  18540. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  18541. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  18542. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  18543. ];
  18544. /* ===========================================================================
  18545. * Initialize the "longest match" routines for a new zlib stream
  18546. */
  18547. function lm_init(s) {
  18548. s.window_size = 2 * s.w_size;
  18549. /*** CLEAR_HASH(s); ***/
  18550. zero(s.head); // Fill with NIL (= 0);
  18551. /* Set the default configuration parameters:
  18552. */
  18553. s.max_lazy_match = configuration_table[s.level].max_lazy;
  18554. s.good_match = configuration_table[s.level].good_length;
  18555. s.nice_match = configuration_table[s.level].nice_length;
  18556. s.max_chain_length = configuration_table[s.level].max_chain;
  18557. s.strstart = 0;
  18558. s.block_start = 0;
  18559. s.lookahead = 0;
  18560. s.insert = 0;
  18561. s.match_length = s.prev_length = MIN_MATCH - 1;
  18562. s.match_available = 0;
  18563. s.ins_h = 0;
  18564. }
  18565. function DeflateState() {
  18566. this.strm = null; /* pointer back to this zlib stream */
  18567. this.status = 0; /* as the name implies */
  18568. this.pending_buf = null; /* output still pending */
  18569. this.pending_buf_size = 0; /* size of pending_buf */
  18570. this.pending_out = 0; /* next pending byte to output to the stream */
  18571. this.pending = 0; /* nb of bytes in the pending buffer */
  18572. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  18573. this.gzhead = null; /* gzip header information to write */
  18574. this.gzindex = 0; /* where in extra, name, or comment */
  18575. this.method = Z_DEFLATED; /* can only be DEFLATED */
  18576. this.last_flush = -1; /* value of flush param for previous deflate call */
  18577. this.w_size = 0; /* LZ77 window size (32K by default) */
  18578. this.w_bits = 0; /* log2(w_size) (8..16) */
  18579. this.w_mask = 0; /* w_size - 1 */
  18580. this.window = null;
  18581. /* Sliding window. Input bytes are read into the second half of the window,
  18582. * and move to the first half later to keep a dictionary of at least wSize
  18583. * bytes. With this organization, matches are limited to a distance of
  18584. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  18585. * performed with a length multiple of the block size.
  18586. */
  18587. this.window_size = 0;
  18588. /* Actual size of window: 2*wSize, except when the user input buffer
  18589. * is directly used as sliding window.
  18590. */
  18591. this.prev = null;
  18592. /* Link to older string with same hash index. To limit the size of this
  18593. * array to 64K, this link is maintained only for the last 32K strings.
  18594. * An index in this array is thus a window index modulo 32K.
  18595. */
  18596. this.head = null; /* Heads of the hash chains or NIL. */
  18597. this.ins_h = 0; /* hash index of string to be inserted */
  18598. this.hash_size = 0; /* number of elements in hash table */
  18599. this.hash_bits = 0; /* log2(hash_size) */
  18600. this.hash_mask = 0; /* hash_size-1 */
  18601. this.hash_shift = 0;
  18602. /* Number of bits by which ins_h must be shifted at each input
  18603. * step. It must be such that after MIN_MATCH steps, the oldest
  18604. * byte no longer takes part in the hash key, that is:
  18605. * hash_shift * MIN_MATCH >= hash_bits
  18606. */
  18607. this.block_start = 0;
  18608. /* Window position at the beginning of the current output block. Gets
  18609. * negative when the window is moved backwards.
  18610. */
  18611. this.match_length = 0; /* length of best match */
  18612. this.prev_match = 0; /* previous match */
  18613. this.match_available = 0; /* set if previous match exists */
  18614. this.strstart = 0; /* start of string to insert */
  18615. this.match_start = 0; /* start of matching string */
  18616. this.lookahead = 0; /* number of valid bytes ahead in window */
  18617. this.prev_length = 0;
  18618. /* Length of the best match at previous step. Matches not greater than this
  18619. * are discarded. This is used in the lazy match evaluation.
  18620. */
  18621. this.max_chain_length = 0;
  18622. /* To speed up deflation, hash chains are never searched beyond this
  18623. * length. A higher limit improves compression ratio but degrades the
  18624. * speed.
  18625. */
  18626. this.max_lazy_match = 0;
  18627. /* Attempt to find a better match only when the current match is strictly
  18628. * smaller than this value. This mechanism is used only for compression
  18629. * levels >= 4.
  18630. */
  18631. // That's alias to max_lazy_match, don't use directly
  18632. //this.max_insert_length = 0;
  18633. /* Insert new strings in the hash table only if the match length is not
  18634. * greater than this length. This saves time but degrades compression.
  18635. * max_insert_length is used only for compression levels <= 3.
  18636. */
  18637. this.level = 0; /* compression level (1..9) */
  18638. this.strategy = 0; /* favor or force Huffman coding*/
  18639. this.good_match = 0;
  18640. /* Use a faster search when the previous match is longer than this */
  18641. this.nice_match = 0; /* Stop searching when current match exceeds this */
  18642. /* used by trees.c: */
  18643. /* Didn't use ct_data typedef below to suppress compiler warning */
  18644. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  18645. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  18646. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  18647. // Use flat array of DOUBLE size, with interleaved fata,
  18648. // because JS does not support effective
  18649. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  18650. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  18651. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  18652. zero(this.dyn_ltree);
  18653. zero(this.dyn_dtree);
  18654. zero(this.bl_tree);
  18655. this.l_desc = null; /* desc. for literal tree */
  18656. this.d_desc = null; /* desc. for distance tree */
  18657. this.bl_desc = null; /* desc. for bit length tree */
  18658. //ush bl_count[MAX_BITS+1];
  18659. this.bl_count = new utils.Buf16(MAX_BITS+1);
  18660. /* number of codes at each bit length for an optimal tree */
  18661. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  18662. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  18663. zero(this.heap);
  18664. this.heap_len = 0; /* number of elements in the heap */
  18665. this.heap_max = 0; /* element of largest frequency */
  18666. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  18667. * The same heap array is used to build all trees.
  18668. */
  18669. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  18670. zero(this.depth);
  18671. /* Depth of each subtree used as tie breaker for trees of equal frequency
  18672. */
  18673. this.l_buf = 0; /* buffer index for literals or lengths */
  18674. this.lit_bufsize = 0;
  18675. /* Size of match buffer for literals/lengths. There are 4 reasons for
  18676. * limiting lit_bufsize to 64K:
  18677. * - frequencies can be kept in 16 bit counters
  18678. * - if compression is not successful for the first block, all input
  18679. * data is still in the window so we can still emit a stored block even
  18680. * when input comes from standard input. (This can also be done for
  18681. * all blocks if lit_bufsize is not greater than 32K.)
  18682. * - if compression is not successful for a file smaller than 64K, we can
  18683. * even emit a stored file instead of a stored block (saving 5 bytes).
  18684. * This is applicable only for zip (not gzip or zlib).
  18685. * - creating new Huffman trees less frequently may not provide fast
  18686. * adaptation to changes in the input data statistics. (Take for
  18687. * example a binary file with poorly compressible code followed by
  18688. * a highly compressible string table.) Smaller buffer sizes give
  18689. * fast adaptation but have of course the overhead of transmitting
  18690. * trees more frequently.
  18691. * - I can't count above 4
  18692. */
  18693. this.last_lit = 0; /* running index in l_buf */
  18694. this.d_buf = 0;
  18695. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  18696. * the same number of elements. To use different lengths, an extra flag
  18697. * array would be necessary.
  18698. */
  18699. this.opt_len = 0; /* bit length of current block with optimal trees */
  18700. this.static_len = 0; /* bit length of current block with static trees */
  18701. this.matches = 0; /* number of string matches in current block */
  18702. this.insert = 0; /* bytes at end of window left to insert */
  18703. this.bi_buf = 0;
  18704. /* Output buffer. bits are inserted starting at the bottom (least
  18705. * significant bits).
  18706. */
  18707. this.bi_valid = 0;
  18708. /* Number of valid bits in bi_buf. All bits above the last valid bit
  18709. * are always zero.
  18710. */
  18711. // Used for window memory init. We safely ignore it for JS. That makes
  18712. // sense only for pointers and memory check tools.
  18713. //this.high_water = 0;
  18714. /* High water mark offset in window for initialized bytes -- bytes above
  18715. * this are set to zero in order to avoid memory check warnings when
  18716. * longest match routines access bytes past the input. This is then
  18717. * updated to the new high water mark.
  18718. */
  18719. }
  18720. function deflateResetKeep(strm) {
  18721. var s;
  18722. if (!strm || !strm.state) {
  18723. return err(strm, Z_STREAM_ERROR);
  18724. }
  18725. strm.total_in = strm.total_out = 0;
  18726. strm.data_type = Z_UNKNOWN;
  18727. s = strm.state;
  18728. s.pending = 0;
  18729. s.pending_out = 0;
  18730. if (s.wrap < 0) {
  18731. s.wrap = -s.wrap;
  18732. /* was made negative by deflate(..., Z_FINISH); */
  18733. }
  18734. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  18735. strm.adler = (s.wrap === 2) ?
  18736. 0 // crc32(0, Z_NULL, 0)
  18737. :
  18738. 1; // adler32(0, Z_NULL, 0)
  18739. s.last_flush = Z_NO_FLUSH;
  18740. trees._tr_init(s);
  18741. return Z_OK;
  18742. }
  18743. function deflateReset(strm) {
  18744. var ret = deflateResetKeep(strm);
  18745. if (ret === Z_OK) {
  18746. lm_init(strm.state);
  18747. }
  18748. return ret;
  18749. }
  18750. function deflateSetHeader(strm, head) {
  18751. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  18752. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  18753. strm.state.gzhead = head;
  18754. return Z_OK;
  18755. }
  18756. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  18757. if (!strm) { // === Z_NULL
  18758. return Z_STREAM_ERROR;
  18759. }
  18760. var wrap = 1;
  18761. if (level === Z_DEFAULT_COMPRESSION) {
  18762. level = 6;
  18763. }
  18764. if (windowBits < 0) { /* suppress zlib wrapper */
  18765. wrap = 0;
  18766. windowBits = -windowBits;
  18767. }
  18768. else if (windowBits > 15) {
  18769. wrap = 2; /* write gzip wrapper instead */
  18770. windowBits -= 16;
  18771. }
  18772. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  18773. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  18774. strategy < 0 || strategy > Z_FIXED) {
  18775. return err(strm, Z_STREAM_ERROR);
  18776. }
  18777. if (windowBits === 8) {
  18778. windowBits = 9;
  18779. }
  18780. /* until 256-byte window bug fixed */
  18781. var s = new DeflateState();
  18782. strm.state = s;
  18783. s.strm = strm;
  18784. s.wrap = wrap;
  18785. s.gzhead = null;
  18786. s.w_bits = windowBits;
  18787. s.w_size = 1 << s.w_bits;
  18788. s.w_mask = s.w_size - 1;
  18789. s.hash_bits = memLevel + 7;
  18790. s.hash_size = 1 << s.hash_bits;
  18791. s.hash_mask = s.hash_size - 1;
  18792. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  18793. s.window = new utils.Buf8(s.w_size * 2);
  18794. s.head = new utils.Buf16(s.hash_size);
  18795. s.prev = new utils.Buf16(s.w_size);
  18796. // Don't need mem init magic for JS.
  18797. //s.high_water = 0; /* nothing written to s->window yet */
  18798. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  18799. s.pending_buf_size = s.lit_bufsize * 4;
  18800. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  18801. s.d_buf = s.lit_bufsize >> 1;
  18802. s.l_buf = (1 + 2) * s.lit_bufsize;
  18803. s.level = level;
  18804. s.strategy = strategy;
  18805. s.method = method;
  18806. return deflateReset(strm);
  18807. }
  18808. function deflateInit(strm, level) {
  18809. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  18810. }
  18811. function deflate(strm, flush) {
  18812. var old_flush, s;
  18813. var beg, val; // for gzip header write only
  18814. if (!strm || !strm.state ||
  18815. flush > Z_BLOCK || flush < 0) {
  18816. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  18817. }
  18818. s = strm.state;
  18819. if (!strm.output ||
  18820. (!strm.input && strm.avail_in !== 0) ||
  18821. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  18822. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  18823. }
  18824. s.strm = strm; /* just in case */
  18825. old_flush = s.last_flush;
  18826. s.last_flush = flush;
  18827. /* Write the header */
  18828. if (s.status === INIT_STATE) {
  18829. if (s.wrap === 2) { // GZIP header
  18830. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  18831. put_byte(s, 31);
  18832. put_byte(s, 139);
  18833. put_byte(s, 8);
  18834. if (!s.gzhead) { // s->gzhead == Z_NULL
  18835. put_byte(s, 0);
  18836. put_byte(s, 0);
  18837. put_byte(s, 0);
  18838. put_byte(s, 0);
  18839. put_byte(s, 0);
  18840. put_byte(s, s.level === 9 ? 2 :
  18841. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  18842. 4 : 0));
  18843. put_byte(s, OS_CODE);
  18844. s.status = BUSY_STATE;
  18845. }
  18846. else {
  18847. put_byte(s, (s.gzhead.text ? 1 : 0) +
  18848. (s.gzhead.hcrc ? 2 : 0) +
  18849. (!s.gzhead.extra ? 0 : 4) +
  18850. (!s.gzhead.name ? 0 : 8) +
  18851. (!s.gzhead.comment ? 0 : 16)
  18852. );
  18853. put_byte(s, s.gzhead.time & 0xff);
  18854. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  18855. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  18856. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  18857. put_byte(s, s.level === 9 ? 2 :
  18858. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  18859. 4 : 0));
  18860. put_byte(s, s.gzhead.os & 0xff);
  18861. if (s.gzhead.extra && s.gzhead.extra.length) {
  18862. put_byte(s, s.gzhead.extra.length & 0xff);
  18863. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  18864. }
  18865. if (s.gzhead.hcrc) {
  18866. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  18867. }
  18868. s.gzindex = 0;
  18869. s.status = EXTRA_STATE;
  18870. }
  18871. }
  18872. else // DEFLATE header
  18873. {
  18874. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  18875. var level_flags = -1;
  18876. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  18877. level_flags = 0;
  18878. } else if (s.level < 6) {
  18879. level_flags = 1;
  18880. } else if (s.level === 6) {
  18881. level_flags = 2;
  18882. } else {
  18883. level_flags = 3;
  18884. }
  18885. header |= (level_flags << 6);
  18886. if (s.strstart !== 0) { header |= PRESET_DICT; }
  18887. header += 31 - (header % 31);
  18888. s.status = BUSY_STATE;
  18889. putShortMSB(s, header);
  18890. /* Save the adler32 of the preset dictionary: */
  18891. if (s.strstart !== 0) {
  18892. putShortMSB(s, strm.adler >>> 16);
  18893. putShortMSB(s, strm.adler & 0xffff);
  18894. }
  18895. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  18896. }
  18897. }
  18898. //#ifdef GZIP
  18899. if (s.status === EXTRA_STATE) {
  18900. if (s.gzhead.extra/* != Z_NULL*/) {
  18901. beg = s.pending; /* start of bytes to update crc */
  18902. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  18903. if (s.pending === s.pending_buf_size) {
  18904. if (s.gzhead.hcrc && s.pending > beg) {
  18905. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  18906. }
  18907. flush_pending(strm);
  18908. beg = s.pending;
  18909. if (s.pending === s.pending_buf_size) {
  18910. break;
  18911. }
  18912. }
  18913. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  18914. s.gzindex++;
  18915. }
  18916. if (s.gzhead.hcrc && s.pending > beg) {
  18917. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  18918. }
  18919. if (s.gzindex === s.gzhead.extra.length) {
  18920. s.gzindex = 0;
  18921. s.status = NAME_STATE;
  18922. }
  18923. }
  18924. else {
  18925. s.status = NAME_STATE;
  18926. }
  18927. }
  18928. if (s.status === NAME_STATE) {
  18929. if (s.gzhead.name/* != Z_NULL*/) {
  18930. beg = s.pending; /* start of bytes to update crc */
  18931. //int val;
  18932. do {
  18933. if (s.pending === s.pending_buf_size) {
  18934. if (s.gzhead.hcrc && s.pending > beg) {
  18935. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  18936. }
  18937. flush_pending(strm);
  18938. beg = s.pending;
  18939. if (s.pending === s.pending_buf_size) {
  18940. val = 1;
  18941. break;
  18942. }
  18943. }
  18944. // JS specific: little magic to add zero terminator to end of string
  18945. if (s.gzindex < s.gzhead.name.length) {
  18946. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  18947. } else {
  18948. val = 0;
  18949. }
  18950. put_byte(s, val);
  18951. } while (val !== 0);
  18952. if (s.gzhead.hcrc && s.pending > beg){
  18953. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  18954. }
  18955. if (val === 0) {
  18956. s.gzindex = 0;
  18957. s.status = COMMENT_STATE;
  18958. }
  18959. }
  18960. else {
  18961. s.status = COMMENT_STATE;
  18962. }
  18963. }
  18964. if (s.status === COMMENT_STATE) {
  18965. if (s.gzhead.comment/* != Z_NULL*/) {
  18966. beg = s.pending; /* start of bytes to update crc */
  18967. //int val;
  18968. do {
  18969. if (s.pending === s.pending_buf_size) {
  18970. if (s.gzhead.hcrc && s.pending > beg) {
  18971. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  18972. }
  18973. flush_pending(strm);
  18974. beg = s.pending;
  18975. if (s.pending === s.pending_buf_size) {
  18976. val = 1;
  18977. break;
  18978. }
  18979. }
  18980. // JS specific: little magic to add zero terminator to end of string
  18981. if (s.gzindex < s.gzhead.comment.length) {
  18982. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  18983. } else {
  18984. val = 0;
  18985. }
  18986. put_byte(s, val);
  18987. } while (val !== 0);
  18988. if (s.gzhead.hcrc && s.pending > beg) {
  18989. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  18990. }
  18991. if (val === 0) {
  18992. s.status = HCRC_STATE;
  18993. }
  18994. }
  18995. else {
  18996. s.status = HCRC_STATE;
  18997. }
  18998. }
  18999. if (s.status === HCRC_STATE) {
  19000. if (s.gzhead.hcrc) {
  19001. if (s.pending + 2 > s.pending_buf_size) {
  19002. flush_pending(strm);
  19003. }
  19004. if (s.pending + 2 <= s.pending_buf_size) {
  19005. put_byte(s, strm.adler & 0xff);
  19006. put_byte(s, (strm.adler >> 8) & 0xff);
  19007. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  19008. s.status = BUSY_STATE;
  19009. }
  19010. }
  19011. else {
  19012. s.status = BUSY_STATE;
  19013. }
  19014. }
  19015. //#endif
  19016. /* Flush as much pending output as possible */
  19017. if (s.pending !== 0) {
  19018. flush_pending(strm);
  19019. if (strm.avail_out === 0) {
  19020. /* Since avail_out is 0, deflate will be called again with
  19021. * more output space, but possibly with both pending and
  19022. * avail_in equal to zero. There won't be anything to do,
  19023. * but this is not an error situation so make sure we
  19024. * return OK instead of BUF_ERROR at next call of deflate:
  19025. */
  19026. s.last_flush = -1;
  19027. return Z_OK;
  19028. }
  19029. /* Make sure there is something to do and avoid duplicate consecutive
  19030. * flushes. For repeated and useless calls with Z_FINISH, we keep
  19031. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  19032. */
  19033. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  19034. flush !== Z_FINISH) {
  19035. return err(strm, Z_BUF_ERROR);
  19036. }
  19037. /* User must not provide more input after the first FINISH: */
  19038. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  19039. return err(strm, Z_BUF_ERROR);
  19040. }
  19041. /* Start a new block or continue the current one.
  19042. */
  19043. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  19044. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  19045. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  19046. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  19047. configuration_table[s.level].func(s, flush));
  19048. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  19049. s.status = FINISH_STATE;
  19050. }
  19051. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  19052. if (strm.avail_out === 0) {
  19053. s.last_flush = -1;
  19054. /* avoid BUF_ERROR next call, see above */
  19055. }
  19056. return Z_OK;
  19057. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  19058. * of deflate should use the same flush parameter to make sure
  19059. * that the flush is complete. So we don't have to output an
  19060. * empty block here, this will be done at next call. This also
  19061. * ensures that for a very small output buffer, we emit at most
  19062. * one empty block.
  19063. */
  19064. }
  19065. if (bstate === BS_BLOCK_DONE) {
  19066. if (flush === Z_PARTIAL_FLUSH) {
  19067. trees._tr_align(s);
  19068. }
  19069. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  19070. trees._tr_stored_block(s, 0, 0, false);
  19071. /* For a full flush, this empty block will be recognized
  19072. * as a special marker by inflate_sync().
  19073. */
  19074. if (flush === Z_FULL_FLUSH) {
  19075. /*** CLEAR_HASH(s); ***/ /* forget history */
  19076. zero(s.head); // Fill with NIL (= 0);
  19077. if (s.lookahead === 0) {
  19078. s.strstart = 0;
  19079. s.block_start = 0;
  19080. s.insert = 0;
  19081. }
  19082. }
  19083. }
  19084. flush_pending(strm);
  19085. if (strm.avail_out === 0) {
  19086. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  19087. return Z_OK;
  19088. }
  19089. }
  19090. }
  19091. //Assert(strm->avail_out > 0, "bug2");
  19092. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  19093. if (flush !== Z_FINISH) { return Z_OK; }
  19094. if (s.wrap <= 0) { return Z_STREAM_END; }
  19095. /* Write the trailer */
  19096. if (s.wrap === 2) {
  19097. put_byte(s, strm.adler & 0xff);
  19098. put_byte(s, (strm.adler >> 8) & 0xff);
  19099. put_byte(s, (strm.adler >> 16) & 0xff);
  19100. put_byte(s, (strm.adler >> 24) & 0xff);
  19101. put_byte(s, strm.total_in & 0xff);
  19102. put_byte(s, (strm.total_in >> 8) & 0xff);
  19103. put_byte(s, (strm.total_in >> 16) & 0xff);
  19104. put_byte(s, (strm.total_in >> 24) & 0xff);
  19105. }
  19106. else
  19107. {
  19108. putShortMSB(s, strm.adler >>> 16);
  19109. putShortMSB(s, strm.adler & 0xffff);
  19110. }
  19111. flush_pending(strm);
  19112. /* If avail_out is zero, the application will call deflate again
  19113. * to flush the rest.
  19114. */
  19115. if (s.wrap > 0) { s.wrap = -s.wrap; }
  19116. /* write the trailer only once! */
  19117. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  19118. }
  19119. function deflateEnd(strm) {
  19120. var status;
  19121. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  19122. return Z_STREAM_ERROR;
  19123. }
  19124. status = strm.state.status;
  19125. if (status !== INIT_STATE &&
  19126. status !== EXTRA_STATE &&
  19127. status !== NAME_STATE &&
  19128. status !== COMMENT_STATE &&
  19129. status !== HCRC_STATE &&
  19130. status !== BUSY_STATE &&
  19131. status !== FINISH_STATE
  19132. ) {
  19133. return err(strm, Z_STREAM_ERROR);
  19134. }
  19135. strm.state = null;
  19136. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  19137. }
  19138. /* =========================================================================
  19139. * Copy the source state to the destination state
  19140. */
  19141. //function deflateCopy(dest, source) {
  19142. //
  19143. //}
  19144. exports.deflateInit = deflateInit;
  19145. exports.deflateInit2 = deflateInit2;
  19146. exports.deflateReset = deflateReset;
  19147. exports.deflateResetKeep = deflateResetKeep;
  19148. exports.deflateSetHeader = deflateSetHeader;
  19149. exports.deflate = deflate;
  19150. exports.deflateEnd = deflateEnd;
  19151. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  19152. /* Not implemented
  19153. exports.deflateBound = deflateBound;
  19154. exports.deflateCopy = deflateCopy;
  19155. exports.deflateSetDictionary = deflateSetDictionary;
  19156. exports.deflateParams = deflateParams;
  19157. exports.deflatePending = deflatePending;
  19158. exports.deflatePrime = deflatePrime;
  19159. exports.deflateTune = deflateTune;
  19160. */
  19161. },{"../utils/common":66,"./adler32":68,"./crc32":70,"./messages":76,"./trees":77}],72:[function(require,module,exports){
  19162. 'use strict';
  19163. function GZheader() {
  19164. /* true if compressed data believed to be text */
  19165. this.text = 0;
  19166. /* modification time */
  19167. this.time = 0;
  19168. /* extra flags (not used when writing a gzip file) */
  19169. this.xflags = 0;
  19170. /* operating system */
  19171. this.os = 0;
  19172. /* pointer to extra field or Z_NULL if none */
  19173. this.extra = null;
  19174. /* extra field length (valid if extra != Z_NULL) */
  19175. this.extra_len = 0; // Actually, we don't need it in JS,
  19176. // but leave for few code modifications
  19177. //
  19178. // Setup limits is not necessary because in js we should not preallocate memory
  19179. // for inflate use constant limit in 65536 bytes
  19180. //
  19181. /* space at extra (only when reading header) */
  19182. // this.extra_max = 0;
  19183. /* pointer to zero-terminated file name or Z_NULL */
  19184. this.name = '';
  19185. /* space at name (only when reading header) */
  19186. // this.name_max = 0;
  19187. /* pointer to zero-terminated comment or Z_NULL */
  19188. this.comment = '';
  19189. /* space at comment (only when reading header) */
  19190. // this.comm_max = 0;
  19191. /* true if there was or will be a header crc */
  19192. this.hcrc = 0;
  19193. /* true when done reading gzip header (not used when writing a gzip file) */
  19194. this.done = false;
  19195. }
  19196. module.exports = GZheader;
  19197. },{}],73:[function(require,module,exports){
  19198. 'use strict';
  19199. // See state defs from inflate.js
  19200. var BAD = 30; /* got a data error -- remain here until reset */
  19201. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  19202. /*
  19203. Decode literal, length, and distance codes and write out the resulting
  19204. literal and match bytes until either not enough input or output is
  19205. available, an end-of-block is encountered, or a data error is encountered.
  19206. When large enough input and output buffers are supplied to inflate(), for
  19207. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  19208. inflate execution time is spent in this routine.
  19209. Entry assumptions:
  19210. state.mode === LEN
  19211. strm.avail_in >= 6
  19212. strm.avail_out >= 258
  19213. start >= strm.avail_out
  19214. state.bits < 8
  19215. On return, state.mode is one of:
  19216. LEN -- ran out of enough output space or enough available input
  19217. TYPE -- reached end of block code, inflate() to interpret next block
  19218. BAD -- error in block data
  19219. Notes:
  19220. - The maximum input bits used by a length/distance pair is 15 bits for the
  19221. length code, 5 bits for the length extra, 15 bits for the distance code,
  19222. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  19223. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  19224. checking for available input while decoding.
  19225. - The maximum bytes that a single length/distance pair can output is 258
  19226. bytes, which is the maximum length that can be coded. inflate_fast()
  19227. requires strm.avail_out >= 258 for each loop to avoid checking for
  19228. output space.
  19229. */
  19230. module.exports = function inflate_fast(strm, start) {
  19231. var state;
  19232. var _in; /* local strm.input */
  19233. var last; /* have enough input while in < last */
  19234. var _out; /* local strm.output */
  19235. var beg; /* inflate()'s initial strm.output */
  19236. var end; /* while out < end, enough space available */
  19237. //#ifdef INFLATE_STRICT
  19238. var dmax; /* maximum distance from zlib header */
  19239. //#endif
  19240. var wsize; /* window size or zero if not using window */
  19241. var whave; /* valid bytes in the window */
  19242. var wnext; /* window write index */
  19243. var window; /* allocated sliding window, if wsize != 0 */
  19244. var hold; /* local strm.hold */
  19245. var bits; /* local strm.bits */
  19246. var lcode; /* local strm.lencode */
  19247. var dcode; /* local strm.distcode */
  19248. var lmask; /* mask for first level of length codes */
  19249. var dmask; /* mask for first level of distance codes */
  19250. var here; /* retrieved table entry */
  19251. var op; /* code bits, operation, extra bits, or */
  19252. /* window position, window bytes to copy */
  19253. var len; /* match length, unused bytes */
  19254. var dist; /* match distance */
  19255. var from; /* where to copy match from */
  19256. var from_source;
  19257. var input, output; // JS specific, because we have no pointers
  19258. /* copy state to local variables */
  19259. state = strm.state;
  19260. //here = state.here;
  19261. _in = strm.next_in;
  19262. input = strm.input;
  19263. last = _in + (strm.avail_in - 5);
  19264. _out = strm.next_out;
  19265. output = strm.output;
  19266. beg = _out - (start - strm.avail_out);
  19267. end = _out + (strm.avail_out - 257);
  19268. //#ifdef INFLATE_STRICT
  19269. dmax = state.dmax;
  19270. //#endif
  19271. wsize = state.wsize;
  19272. whave = state.whave;
  19273. wnext = state.wnext;
  19274. window = state.window;
  19275. hold = state.hold;
  19276. bits = state.bits;
  19277. lcode = state.lencode;
  19278. dcode = state.distcode;
  19279. lmask = (1 << state.lenbits) - 1;
  19280. dmask = (1 << state.distbits) - 1;
  19281. /* decode literals and length/distances until end-of-block or not enough
  19282. input data or output space */
  19283. top:
  19284. do {
  19285. if (bits < 15) {
  19286. hold += input[_in++] << bits;
  19287. bits += 8;
  19288. hold += input[_in++] << bits;
  19289. bits += 8;
  19290. }
  19291. here = lcode[hold & lmask];
  19292. dolen:
  19293. for (;;) { // Goto emulation
  19294. op = here >>> 24/*here.bits*/;
  19295. hold >>>= op;
  19296. bits -= op;
  19297. op = (here >>> 16) & 0xff/*here.op*/;
  19298. if (op === 0) { /* literal */
  19299. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  19300. // "inflate: literal '%c'\n" :
  19301. // "inflate: literal 0x%02x\n", here.val));
  19302. output[_out++] = here & 0xffff/*here.val*/;
  19303. }
  19304. else if (op & 16) { /* length base */
  19305. len = here & 0xffff/*here.val*/;
  19306. op &= 15; /* number of extra bits */
  19307. if (op) {
  19308. if (bits < op) {
  19309. hold += input[_in++] << bits;
  19310. bits += 8;
  19311. }
  19312. len += hold & ((1 << op) - 1);
  19313. hold >>>= op;
  19314. bits -= op;
  19315. }
  19316. //Tracevv((stderr, "inflate: length %u\n", len));
  19317. if (bits < 15) {
  19318. hold += input[_in++] << bits;
  19319. bits += 8;
  19320. hold += input[_in++] << bits;
  19321. bits += 8;
  19322. }
  19323. here = dcode[hold & dmask];
  19324. dodist:
  19325. for (;;) { // goto emulation
  19326. op = here >>> 24/*here.bits*/;
  19327. hold >>>= op;
  19328. bits -= op;
  19329. op = (here >>> 16) & 0xff/*here.op*/;
  19330. if (op & 16) { /* distance base */
  19331. dist = here & 0xffff/*here.val*/;
  19332. op &= 15; /* number of extra bits */
  19333. if (bits < op) {
  19334. hold += input[_in++] << bits;
  19335. bits += 8;
  19336. if (bits < op) {
  19337. hold += input[_in++] << bits;
  19338. bits += 8;
  19339. }
  19340. }
  19341. dist += hold & ((1 << op) - 1);
  19342. //#ifdef INFLATE_STRICT
  19343. if (dist > dmax) {
  19344. strm.msg = 'invalid distance too far back';
  19345. state.mode = BAD;
  19346. break top;
  19347. }
  19348. //#endif
  19349. hold >>>= op;
  19350. bits -= op;
  19351. //Tracevv((stderr, "inflate: distance %u\n", dist));
  19352. op = _out - beg; /* max distance in output */
  19353. if (dist > op) { /* see if copy from window */
  19354. op = dist - op; /* distance back in window */
  19355. if (op > whave) {
  19356. if (state.sane) {
  19357. strm.msg = 'invalid distance too far back';
  19358. state.mode = BAD;
  19359. break top;
  19360. }
  19361. // (!) This block is disabled in zlib defailts,
  19362. // don't enable it for binary compatibility
  19363. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  19364. // if (len <= op - whave) {
  19365. // do {
  19366. // output[_out++] = 0;
  19367. // } while (--len);
  19368. // continue top;
  19369. // }
  19370. // len -= op - whave;
  19371. // do {
  19372. // output[_out++] = 0;
  19373. // } while (--op > whave);
  19374. // if (op === 0) {
  19375. // from = _out - dist;
  19376. // do {
  19377. // output[_out++] = output[from++];
  19378. // } while (--len);
  19379. // continue top;
  19380. // }
  19381. //#endif
  19382. }
  19383. from = 0; // window index
  19384. from_source = window;
  19385. if (wnext === 0) { /* very common case */
  19386. from += wsize - op;
  19387. if (op < len) { /* some from window */
  19388. len -= op;
  19389. do {
  19390. output[_out++] = window[from++];
  19391. } while (--op);
  19392. from = _out - dist; /* rest from output */
  19393. from_source = output;
  19394. }
  19395. }
  19396. else if (wnext < op) { /* wrap around window */
  19397. from += wsize + wnext - op;
  19398. op -= wnext;
  19399. if (op < len) { /* some from end of window */
  19400. len -= op;
  19401. do {
  19402. output[_out++] = window[from++];
  19403. } while (--op);
  19404. from = 0;
  19405. if (wnext < len) { /* some from start of window */
  19406. op = wnext;
  19407. len -= op;
  19408. do {
  19409. output[_out++] = window[from++];
  19410. } while (--op);
  19411. from = _out - dist; /* rest from output */
  19412. from_source = output;
  19413. }
  19414. }
  19415. }
  19416. else { /* contiguous in window */
  19417. from += wnext - op;
  19418. if (op < len) { /* some from window */
  19419. len -= op;
  19420. do {
  19421. output[_out++] = window[from++];
  19422. } while (--op);
  19423. from = _out - dist; /* rest from output */
  19424. from_source = output;
  19425. }
  19426. }
  19427. while (len > 2) {
  19428. output[_out++] = from_source[from++];
  19429. output[_out++] = from_source[from++];
  19430. output[_out++] = from_source[from++];
  19431. len -= 3;
  19432. }
  19433. if (len) {
  19434. output[_out++] = from_source[from++];
  19435. if (len > 1) {
  19436. output[_out++] = from_source[from++];
  19437. }
  19438. }
  19439. }
  19440. else {
  19441. from = _out - dist; /* copy direct from output */
  19442. do { /* minimum length is three */
  19443. output[_out++] = output[from++];
  19444. output[_out++] = output[from++];
  19445. output[_out++] = output[from++];
  19446. len -= 3;
  19447. } while (len > 2);
  19448. if (len) {
  19449. output[_out++] = output[from++];
  19450. if (len > 1) {
  19451. output[_out++] = output[from++];
  19452. }
  19453. }
  19454. }
  19455. }
  19456. else if ((op & 64) === 0) { /* 2nd level distance code */
  19457. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  19458. continue dodist;
  19459. }
  19460. else {
  19461. strm.msg = 'invalid distance code';
  19462. state.mode = BAD;
  19463. break top;
  19464. }
  19465. break; // need to emulate goto via "continue"
  19466. }
  19467. }
  19468. else if ((op & 64) === 0) { /* 2nd level length code */
  19469. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  19470. continue dolen;
  19471. }
  19472. else if (op & 32) { /* end-of-block */
  19473. //Tracevv((stderr, "inflate: end of block\n"));
  19474. state.mode = TYPE;
  19475. break top;
  19476. }
  19477. else {
  19478. strm.msg = 'invalid literal/length code';
  19479. state.mode = BAD;
  19480. break top;
  19481. }
  19482. break; // need to emulate goto via "continue"
  19483. }
  19484. } while (_in < last && _out < end);
  19485. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  19486. len = bits >> 3;
  19487. _in -= len;
  19488. bits -= len << 3;
  19489. hold &= (1 << bits) - 1;
  19490. /* update state and return */
  19491. strm.next_in = _in;
  19492. strm.next_out = _out;
  19493. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  19494. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  19495. state.hold = hold;
  19496. state.bits = bits;
  19497. return;
  19498. };
  19499. },{}],74:[function(require,module,exports){
  19500. 'use strict';
  19501. var utils = require('../utils/common');
  19502. var adler32 = require('./adler32');
  19503. var crc32 = require('./crc32');
  19504. var inflate_fast = require('./inffast');
  19505. var inflate_table = require('./inftrees');
  19506. var CODES = 0;
  19507. var LENS = 1;
  19508. var DISTS = 2;
  19509. /* Public constants ==========================================================*/
  19510. /* ===========================================================================*/
  19511. /* Allowed flush values; see deflate() and inflate() below for details */
  19512. //var Z_NO_FLUSH = 0;
  19513. //var Z_PARTIAL_FLUSH = 1;
  19514. //var Z_SYNC_FLUSH = 2;
  19515. //var Z_FULL_FLUSH = 3;
  19516. var Z_FINISH = 4;
  19517. var Z_BLOCK = 5;
  19518. var Z_TREES = 6;
  19519. /* Return codes for the compression/decompression functions. Negative values
  19520. * are errors, positive values are used for special but normal events.
  19521. */
  19522. var Z_OK = 0;
  19523. var Z_STREAM_END = 1;
  19524. var Z_NEED_DICT = 2;
  19525. //var Z_ERRNO = -1;
  19526. var Z_STREAM_ERROR = -2;
  19527. var Z_DATA_ERROR = -3;
  19528. var Z_MEM_ERROR = -4;
  19529. var Z_BUF_ERROR = -5;
  19530. //var Z_VERSION_ERROR = -6;
  19531. /* The deflate compression method */
  19532. var Z_DEFLATED = 8;
  19533. /* STATES ====================================================================*/
  19534. /* ===========================================================================*/
  19535. var HEAD = 1; /* i: waiting for magic header */
  19536. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  19537. var TIME = 3; /* i: waiting for modification time (gzip) */
  19538. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  19539. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  19540. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  19541. var NAME = 7; /* i: waiting for end of file name (gzip) */
  19542. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  19543. var HCRC = 9; /* i: waiting for header crc (gzip) */
  19544. var DICTID = 10; /* i: waiting for dictionary check value */
  19545. var DICT = 11; /* waiting for inflateSetDictionary() call */
  19546. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  19547. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  19548. var STORED = 14; /* i: waiting for stored size (length and complement) */
  19549. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  19550. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  19551. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  19552. var LENLENS = 18; /* i: waiting for code length code lengths */
  19553. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  19554. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  19555. var LEN = 21; /* i: waiting for length/lit/eob code */
  19556. var LENEXT = 22; /* i: waiting for length extra bits */
  19557. var DIST = 23; /* i: waiting for distance code */
  19558. var DISTEXT = 24; /* i: waiting for distance extra bits */
  19559. var MATCH = 25; /* o: waiting for output space to copy string */
  19560. var LIT = 26; /* o: waiting for output space to write literal */
  19561. var CHECK = 27; /* i: waiting for 32-bit check value */
  19562. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  19563. var DONE = 29; /* finished check, done -- remain here until reset */
  19564. var BAD = 30; /* got a data error -- remain here until reset */
  19565. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  19566. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  19567. /* ===========================================================================*/
  19568. var ENOUGH_LENS = 852;
  19569. var ENOUGH_DISTS = 592;
  19570. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  19571. var MAX_WBITS = 15;
  19572. /* 32K LZ77 window */
  19573. var DEF_WBITS = MAX_WBITS;
  19574. function ZSWAP32(q) {
  19575. return (((q >>> 24) & 0xff) +
  19576. ((q >>> 8) & 0xff00) +
  19577. ((q & 0xff00) << 8) +
  19578. ((q & 0xff) << 24));
  19579. }
  19580. function InflateState() {
  19581. this.mode = 0; /* current inflate mode */
  19582. this.last = false; /* true if processing last block */
  19583. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  19584. this.havedict = false; /* true if dictionary provided */
  19585. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  19586. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  19587. this.check = 0; /* protected copy of check value */
  19588. this.total = 0; /* protected copy of output count */
  19589. // TODO: may be {}
  19590. this.head = null; /* where to save gzip header information */
  19591. /* sliding window */
  19592. this.wbits = 0; /* log base 2 of requested window size */
  19593. this.wsize = 0; /* window size or zero if not using window */
  19594. this.whave = 0; /* valid bytes in the window */
  19595. this.wnext = 0; /* window write index */
  19596. this.window = null; /* allocated sliding window, if needed */
  19597. /* bit accumulator */
  19598. this.hold = 0; /* input bit accumulator */
  19599. this.bits = 0; /* number of bits in "in" */
  19600. /* for string and stored block copying */
  19601. this.length = 0; /* literal or length of data to copy */
  19602. this.offset = 0; /* distance back to copy string from */
  19603. /* for table and code decoding */
  19604. this.extra = 0; /* extra bits needed */
  19605. /* fixed and dynamic code tables */
  19606. this.lencode = null; /* starting table for length/literal codes */
  19607. this.distcode = null; /* starting table for distance codes */
  19608. this.lenbits = 0; /* index bits for lencode */
  19609. this.distbits = 0; /* index bits for distcode */
  19610. /* dynamic table building */
  19611. this.ncode = 0; /* number of code length code lengths */
  19612. this.nlen = 0; /* number of length code lengths */
  19613. this.ndist = 0; /* number of distance code lengths */
  19614. this.have = 0; /* number of code lengths in lens[] */
  19615. this.next = null; /* next available space in codes[] */
  19616. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  19617. this.work = new utils.Buf16(288); /* work area for code table building */
  19618. /*
  19619. because we don't have pointers in js, we use lencode and distcode directly
  19620. as buffers so we don't need codes
  19621. */
  19622. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  19623. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  19624. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  19625. this.sane = 0; /* if false, allow invalid distance too far */
  19626. this.back = 0; /* bits back of last unprocessed length/lit */
  19627. this.was = 0; /* initial length of match */
  19628. }
  19629. function inflateResetKeep(strm) {
  19630. var state;
  19631. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19632. state = strm.state;
  19633. strm.total_in = strm.total_out = state.total = 0;
  19634. strm.msg = ''; /*Z_NULL*/
  19635. if (state.wrap) { /* to support ill-conceived Java test suite */
  19636. strm.adler = state.wrap & 1;
  19637. }
  19638. state.mode = HEAD;
  19639. state.last = 0;
  19640. state.havedict = 0;
  19641. state.dmax = 32768;
  19642. state.head = null/*Z_NULL*/;
  19643. state.hold = 0;
  19644. state.bits = 0;
  19645. //state.lencode = state.distcode = state.next = state.codes;
  19646. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  19647. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  19648. state.sane = 1;
  19649. state.back = -1;
  19650. //Tracev((stderr, "inflate: reset\n"));
  19651. return Z_OK;
  19652. }
  19653. function inflateReset(strm) {
  19654. var state;
  19655. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19656. state = strm.state;
  19657. state.wsize = 0;
  19658. state.whave = 0;
  19659. state.wnext = 0;
  19660. return inflateResetKeep(strm);
  19661. }
  19662. function inflateReset2(strm, windowBits) {
  19663. var wrap;
  19664. var state;
  19665. /* get the state */
  19666. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19667. state = strm.state;
  19668. /* extract wrap request from windowBits parameter */
  19669. if (windowBits < 0) {
  19670. wrap = 0;
  19671. windowBits = -windowBits;
  19672. }
  19673. else {
  19674. wrap = (windowBits >> 4) + 1;
  19675. if (windowBits < 48) {
  19676. windowBits &= 15;
  19677. }
  19678. }
  19679. /* set number of window bits, free window if different */
  19680. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  19681. return Z_STREAM_ERROR;
  19682. }
  19683. if (state.window !== null && state.wbits !== windowBits) {
  19684. state.window = null;
  19685. }
  19686. /* update state and reset the rest of it */
  19687. state.wrap = wrap;
  19688. state.wbits = windowBits;
  19689. return inflateReset(strm);
  19690. }
  19691. function inflateInit2(strm, windowBits) {
  19692. var ret;
  19693. var state;
  19694. if (!strm) { return Z_STREAM_ERROR; }
  19695. //strm.msg = Z_NULL; /* in case we return an error */
  19696. state = new InflateState();
  19697. //if (state === Z_NULL) return Z_MEM_ERROR;
  19698. //Tracev((stderr, "inflate: allocated\n"));
  19699. strm.state = state;
  19700. state.window = null/*Z_NULL*/;
  19701. ret = inflateReset2(strm, windowBits);
  19702. if (ret !== Z_OK) {
  19703. strm.state = null/*Z_NULL*/;
  19704. }
  19705. return ret;
  19706. }
  19707. function inflateInit(strm) {
  19708. return inflateInit2(strm, DEF_WBITS);
  19709. }
  19710. /*
  19711. Return state with length and distance decoding tables and index sizes set to
  19712. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  19713. If BUILDFIXED is defined, then instead this routine builds the tables the
  19714. first time it's called, and returns those tables the first time and
  19715. thereafter. This reduces the size of the code by about 2K bytes, in
  19716. exchange for a little execution time. However, BUILDFIXED should not be
  19717. used for threaded applications, since the rewriting of the tables and virgin
  19718. may not be thread-safe.
  19719. */
  19720. var virgin = true;
  19721. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  19722. function fixedtables(state) {
  19723. /* build fixed huffman tables if first call (may not be thread safe) */
  19724. if (virgin) {
  19725. var sym;
  19726. lenfix = new utils.Buf32(512);
  19727. distfix = new utils.Buf32(32);
  19728. /* literal/length table */
  19729. sym = 0;
  19730. while (sym < 144) { state.lens[sym++] = 8; }
  19731. while (sym < 256) { state.lens[sym++] = 9; }
  19732. while (sym < 280) { state.lens[sym++] = 7; }
  19733. while (sym < 288) { state.lens[sym++] = 8; }
  19734. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  19735. /* distance table */
  19736. sym = 0;
  19737. while (sym < 32) { state.lens[sym++] = 5; }
  19738. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  19739. /* do this just once */
  19740. virgin = false;
  19741. }
  19742. state.lencode = lenfix;
  19743. state.lenbits = 9;
  19744. state.distcode = distfix;
  19745. state.distbits = 5;
  19746. }
  19747. /*
  19748. Update the window with the last wsize (normally 32K) bytes written before
  19749. returning. If window does not exist yet, create it. This is only called
  19750. when a window is already in use, or when output has been written during this
  19751. inflate call, but the end of the deflate stream has not been reached yet.
  19752. It is also called to create a window for dictionary data when a dictionary
  19753. is loaded.
  19754. Providing output buffers larger than 32K to inflate() should provide a speed
  19755. advantage, since only the last 32K of output is copied to the sliding window
  19756. upon return from inflate(), and since all distances after the first 32K of
  19757. output will fall in the output data, making match copies simpler and faster.
  19758. The advantage may be dependent on the size of the processor's data caches.
  19759. */
  19760. function updatewindow(strm, src, end, copy) {
  19761. var dist;
  19762. var state = strm.state;
  19763. /* if it hasn't been done already, allocate space for the window */
  19764. if (state.window === null) {
  19765. state.wsize = 1 << state.wbits;
  19766. state.wnext = 0;
  19767. state.whave = 0;
  19768. state.window = new utils.Buf8(state.wsize);
  19769. }
  19770. /* copy state->wsize or less output bytes into the circular window */
  19771. if (copy >= state.wsize) {
  19772. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  19773. state.wnext = 0;
  19774. state.whave = state.wsize;
  19775. }
  19776. else {
  19777. dist = state.wsize - state.wnext;
  19778. if (dist > copy) {
  19779. dist = copy;
  19780. }
  19781. //zmemcpy(state->window + state->wnext, end - copy, dist);
  19782. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  19783. copy -= dist;
  19784. if (copy) {
  19785. //zmemcpy(state->window, end - copy, copy);
  19786. utils.arraySet(state.window,src, end - copy, copy, 0);
  19787. state.wnext = copy;
  19788. state.whave = state.wsize;
  19789. }
  19790. else {
  19791. state.wnext += dist;
  19792. if (state.wnext === state.wsize) { state.wnext = 0; }
  19793. if (state.whave < state.wsize) { state.whave += dist; }
  19794. }
  19795. }
  19796. return 0;
  19797. }
  19798. function inflate(strm, flush) {
  19799. var state;
  19800. var input, output; // input/output buffers
  19801. var next; /* next input INDEX */
  19802. var put; /* next output INDEX */
  19803. var have, left; /* available input and output */
  19804. var hold; /* bit buffer */
  19805. var bits; /* bits in bit buffer */
  19806. var _in, _out; /* save starting available input and output */
  19807. var copy; /* number of stored or match bytes to copy */
  19808. var from; /* where to copy match bytes from */
  19809. var from_source;
  19810. var here = 0; /* current decoding table entry */
  19811. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  19812. //var last; /* parent table entry */
  19813. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  19814. var len; /* length to copy for repeats, bits to drop */
  19815. var ret; /* return code */
  19816. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  19817. var opts;
  19818. var n; // temporary var for NEED_BITS
  19819. var order = /* permutation of code lengths */
  19820. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  19821. if (!strm || !strm.state || !strm.output ||
  19822. (!strm.input && strm.avail_in !== 0)) {
  19823. return Z_STREAM_ERROR;
  19824. }
  19825. state = strm.state;
  19826. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  19827. //--- LOAD() ---
  19828. put = strm.next_out;
  19829. output = strm.output;
  19830. left = strm.avail_out;
  19831. next = strm.next_in;
  19832. input = strm.input;
  19833. have = strm.avail_in;
  19834. hold = state.hold;
  19835. bits = state.bits;
  19836. //---
  19837. _in = have;
  19838. _out = left;
  19839. ret = Z_OK;
  19840. inf_leave: // goto emulation
  19841. for (;;) {
  19842. switch (state.mode) {
  19843. case HEAD:
  19844. if (state.wrap === 0) {
  19845. state.mode = TYPEDO;
  19846. break;
  19847. }
  19848. //=== NEEDBITS(16);
  19849. while (bits < 16) {
  19850. if (have === 0) { break inf_leave; }
  19851. have--;
  19852. hold += input[next++] << bits;
  19853. bits += 8;
  19854. }
  19855. //===//
  19856. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  19857. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  19858. //=== CRC2(state.check, hold);
  19859. hbuf[0] = hold & 0xff;
  19860. hbuf[1] = (hold >>> 8) & 0xff;
  19861. state.check = crc32(state.check, hbuf, 2, 0);
  19862. //===//
  19863. //=== INITBITS();
  19864. hold = 0;
  19865. bits = 0;
  19866. //===//
  19867. state.mode = FLAGS;
  19868. break;
  19869. }
  19870. state.flags = 0; /* expect zlib header */
  19871. if (state.head) {
  19872. state.head.done = false;
  19873. }
  19874. if (!(state.wrap & 1) || /* check if zlib header allowed */
  19875. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  19876. strm.msg = 'incorrect header check';
  19877. state.mode = BAD;
  19878. break;
  19879. }
  19880. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  19881. strm.msg = 'unknown compression method';
  19882. state.mode = BAD;
  19883. break;
  19884. }
  19885. //--- DROPBITS(4) ---//
  19886. hold >>>= 4;
  19887. bits -= 4;
  19888. //---//
  19889. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  19890. if (state.wbits === 0) {
  19891. state.wbits = len;
  19892. }
  19893. else if (len > state.wbits) {
  19894. strm.msg = 'invalid window size';
  19895. state.mode = BAD;
  19896. break;
  19897. }
  19898. state.dmax = 1 << len;
  19899. //Tracev((stderr, "inflate: zlib header ok\n"));
  19900. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  19901. state.mode = hold & 0x200 ? DICTID : TYPE;
  19902. //=== INITBITS();
  19903. hold = 0;
  19904. bits = 0;
  19905. //===//
  19906. break;
  19907. case FLAGS:
  19908. //=== NEEDBITS(16); */
  19909. while (bits < 16) {
  19910. if (have === 0) { break inf_leave; }
  19911. have--;
  19912. hold += input[next++] << bits;
  19913. bits += 8;
  19914. }
  19915. //===//
  19916. state.flags = hold;
  19917. if ((state.flags & 0xff) !== Z_DEFLATED) {
  19918. strm.msg = 'unknown compression method';
  19919. state.mode = BAD;
  19920. break;
  19921. }
  19922. if (state.flags & 0xe000) {
  19923. strm.msg = 'unknown header flags set';
  19924. state.mode = BAD;
  19925. break;
  19926. }
  19927. if (state.head) {
  19928. state.head.text = ((hold >> 8) & 1);
  19929. }
  19930. if (state.flags & 0x0200) {
  19931. //=== CRC2(state.check, hold);
  19932. hbuf[0] = hold & 0xff;
  19933. hbuf[1] = (hold >>> 8) & 0xff;
  19934. state.check = crc32(state.check, hbuf, 2, 0);
  19935. //===//
  19936. }
  19937. //=== INITBITS();
  19938. hold = 0;
  19939. bits = 0;
  19940. //===//
  19941. state.mode = TIME;
  19942. /* falls through */
  19943. case TIME:
  19944. //=== NEEDBITS(32); */
  19945. while (bits < 32) {
  19946. if (have === 0) { break inf_leave; }
  19947. have--;
  19948. hold += input[next++] << bits;
  19949. bits += 8;
  19950. }
  19951. //===//
  19952. if (state.head) {
  19953. state.head.time = hold;
  19954. }
  19955. if (state.flags & 0x0200) {
  19956. //=== CRC4(state.check, hold)
  19957. hbuf[0] = hold & 0xff;
  19958. hbuf[1] = (hold >>> 8) & 0xff;
  19959. hbuf[2] = (hold >>> 16) & 0xff;
  19960. hbuf[3] = (hold >>> 24) & 0xff;
  19961. state.check = crc32(state.check, hbuf, 4, 0);
  19962. //===
  19963. }
  19964. //=== INITBITS();
  19965. hold = 0;
  19966. bits = 0;
  19967. //===//
  19968. state.mode = OS;
  19969. /* falls through */
  19970. case OS:
  19971. //=== NEEDBITS(16); */
  19972. while (bits < 16) {
  19973. if (have === 0) { break inf_leave; }
  19974. have--;
  19975. hold += input[next++] << bits;
  19976. bits += 8;
  19977. }
  19978. //===//
  19979. if (state.head) {
  19980. state.head.xflags = (hold & 0xff);
  19981. state.head.os = (hold >> 8);
  19982. }
  19983. if (state.flags & 0x0200) {
  19984. //=== CRC2(state.check, hold);
  19985. hbuf[0] = hold & 0xff;
  19986. hbuf[1] = (hold >>> 8) & 0xff;
  19987. state.check = crc32(state.check, hbuf, 2, 0);
  19988. //===//
  19989. }
  19990. //=== INITBITS();
  19991. hold = 0;
  19992. bits = 0;
  19993. //===//
  19994. state.mode = EXLEN;
  19995. /* falls through */
  19996. case EXLEN:
  19997. if (state.flags & 0x0400) {
  19998. //=== NEEDBITS(16); */
  19999. while (bits < 16) {
  20000. if (have === 0) { break inf_leave; }
  20001. have--;
  20002. hold += input[next++] << bits;
  20003. bits += 8;
  20004. }
  20005. //===//
  20006. state.length = hold;
  20007. if (state.head) {
  20008. state.head.extra_len = hold;
  20009. }
  20010. if (state.flags & 0x0200) {
  20011. //=== CRC2(state.check, hold);
  20012. hbuf[0] = hold & 0xff;
  20013. hbuf[1] = (hold >>> 8) & 0xff;
  20014. state.check = crc32(state.check, hbuf, 2, 0);
  20015. //===//
  20016. }
  20017. //=== INITBITS();
  20018. hold = 0;
  20019. bits = 0;
  20020. //===//
  20021. }
  20022. else if (state.head) {
  20023. state.head.extra = null/*Z_NULL*/;
  20024. }
  20025. state.mode = EXTRA;
  20026. /* falls through */
  20027. case EXTRA:
  20028. if (state.flags & 0x0400) {
  20029. copy = state.length;
  20030. if (copy > have) { copy = have; }
  20031. if (copy) {
  20032. if (state.head) {
  20033. len = state.head.extra_len - state.length;
  20034. if (!state.head.extra) {
  20035. // Use untyped array for more conveniend processing later
  20036. state.head.extra = new Array(state.head.extra_len);
  20037. }
  20038. utils.arraySet(
  20039. state.head.extra,
  20040. input,
  20041. next,
  20042. // extra field is limited to 65536 bytes
  20043. // - no need for additional size check
  20044. copy,
  20045. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  20046. len
  20047. );
  20048. //zmemcpy(state.head.extra + len, next,
  20049. // len + copy > state.head.extra_max ?
  20050. // state.head.extra_max - len : copy);
  20051. }
  20052. if (state.flags & 0x0200) {
  20053. state.check = crc32(state.check, input, copy, next);
  20054. }
  20055. have -= copy;
  20056. next += copy;
  20057. state.length -= copy;
  20058. }
  20059. if (state.length) { break inf_leave; }
  20060. }
  20061. state.length = 0;
  20062. state.mode = NAME;
  20063. /* falls through */
  20064. case NAME:
  20065. if (state.flags & 0x0800) {
  20066. if (have === 0) { break inf_leave; }
  20067. copy = 0;
  20068. do {
  20069. // TODO: 2 or 1 bytes?
  20070. len = input[next + copy++];
  20071. /* use constant limit because in js we should not preallocate memory */
  20072. if (state.head && len &&
  20073. (state.length < 65536 /*state.head.name_max*/)) {
  20074. state.head.name += String.fromCharCode(len);
  20075. }
  20076. } while (len && copy < have);
  20077. if (state.flags & 0x0200) {
  20078. state.check = crc32(state.check, input, copy, next);
  20079. }
  20080. have -= copy;
  20081. next += copy;
  20082. if (len) { break inf_leave; }
  20083. }
  20084. else if (state.head) {
  20085. state.head.name = null;
  20086. }
  20087. state.length = 0;
  20088. state.mode = COMMENT;
  20089. /* falls through */
  20090. case COMMENT:
  20091. if (state.flags & 0x1000) {
  20092. if (have === 0) { break inf_leave; }
  20093. copy = 0;
  20094. do {
  20095. len = input[next + copy++];
  20096. /* use constant limit because in js we should not preallocate memory */
  20097. if (state.head && len &&
  20098. (state.length < 65536 /*state.head.comm_max*/)) {
  20099. state.head.comment += String.fromCharCode(len);
  20100. }
  20101. } while (len && copy < have);
  20102. if (state.flags & 0x0200) {
  20103. state.check = crc32(state.check, input, copy, next);
  20104. }
  20105. have -= copy;
  20106. next += copy;
  20107. if (len) { break inf_leave; }
  20108. }
  20109. else if (state.head) {
  20110. state.head.comment = null;
  20111. }
  20112. state.mode = HCRC;
  20113. /* falls through */
  20114. case HCRC:
  20115. if (state.flags & 0x0200) {
  20116. //=== NEEDBITS(16); */
  20117. while (bits < 16) {
  20118. if (have === 0) { break inf_leave; }
  20119. have--;
  20120. hold += input[next++] << bits;
  20121. bits += 8;
  20122. }
  20123. //===//
  20124. if (hold !== (state.check & 0xffff)) {
  20125. strm.msg = 'header crc mismatch';
  20126. state.mode = BAD;
  20127. break;
  20128. }
  20129. //=== INITBITS();
  20130. hold = 0;
  20131. bits = 0;
  20132. //===//
  20133. }
  20134. if (state.head) {
  20135. state.head.hcrc = ((state.flags >> 9) & 1);
  20136. state.head.done = true;
  20137. }
  20138. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  20139. state.mode = TYPE;
  20140. break;
  20141. case DICTID:
  20142. //=== NEEDBITS(32); */
  20143. while (bits < 32) {
  20144. if (have === 0) { break inf_leave; }
  20145. have--;
  20146. hold += input[next++] << bits;
  20147. bits += 8;
  20148. }
  20149. //===//
  20150. strm.adler = state.check = ZSWAP32(hold);
  20151. //=== INITBITS();
  20152. hold = 0;
  20153. bits = 0;
  20154. //===//
  20155. state.mode = DICT;
  20156. /* falls through */
  20157. case DICT:
  20158. if (state.havedict === 0) {
  20159. //--- RESTORE() ---
  20160. strm.next_out = put;
  20161. strm.avail_out = left;
  20162. strm.next_in = next;
  20163. strm.avail_in = have;
  20164. state.hold = hold;
  20165. state.bits = bits;
  20166. //---
  20167. return Z_NEED_DICT;
  20168. }
  20169. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  20170. state.mode = TYPE;
  20171. /* falls through */
  20172. case TYPE:
  20173. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  20174. /* falls through */
  20175. case TYPEDO:
  20176. if (state.last) {
  20177. //--- BYTEBITS() ---//
  20178. hold >>>= bits & 7;
  20179. bits -= bits & 7;
  20180. //---//
  20181. state.mode = CHECK;
  20182. break;
  20183. }
  20184. //=== NEEDBITS(3); */
  20185. while (bits < 3) {
  20186. if (have === 0) { break inf_leave; }
  20187. have--;
  20188. hold += input[next++] << bits;
  20189. bits += 8;
  20190. }
  20191. //===//
  20192. state.last = (hold & 0x01)/*BITS(1)*/;
  20193. //--- DROPBITS(1) ---//
  20194. hold >>>= 1;
  20195. bits -= 1;
  20196. //---//
  20197. switch ((hold & 0x03)/*BITS(2)*/) {
  20198. case 0: /* stored block */
  20199. //Tracev((stderr, "inflate: stored block%s\n",
  20200. // state.last ? " (last)" : ""));
  20201. state.mode = STORED;
  20202. break;
  20203. case 1: /* fixed block */
  20204. fixedtables(state);
  20205. //Tracev((stderr, "inflate: fixed codes block%s\n",
  20206. // state.last ? " (last)" : ""));
  20207. state.mode = LEN_; /* decode codes */
  20208. if (flush === Z_TREES) {
  20209. //--- DROPBITS(2) ---//
  20210. hold >>>= 2;
  20211. bits -= 2;
  20212. //---//
  20213. break inf_leave;
  20214. }
  20215. break;
  20216. case 2: /* dynamic block */
  20217. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  20218. // state.last ? " (last)" : ""));
  20219. state.mode = TABLE;
  20220. break;
  20221. case 3:
  20222. strm.msg = 'invalid block type';
  20223. state.mode = BAD;
  20224. }
  20225. //--- DROPBITS(2) ---//
  20226. hold >>>= 2;
  20227. bits -= 2;
  20228. //---//
  20229. break;
  20230. case STORED:
  20231. //--- BYTEBITS() ---// /* go to byte boundary */
  20232. hold >>>= bits & 7;
  20233. bits -= bits & 7;
  20234. //---//
  20235. //=== NEEDBITS(32); */
  20236. while (bits < 32) {
  20237. if (have === 0) { break inf_leave; }
  20238. have--;
  20239. hold += input[next++] << bits;
  20240. bits += 8;
  20241. }
  20242. //===//
  20243. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  20244. strm.msg = 'invalid stored block lengths';
  20245. state.mode = BAD;
  20246. break;
  20247. }
  20248. state.length = hold & 0xffff;
  20249. //Tracev((stderr, "inflate: stored length %u\n",
  20250. // state.length));
  20251. //=== INITBITS();
  20252. hold = 0;
  20253. bits = 0;
  20254. //===//
  20255. state.mode = COPY_;
  20256. if (flush === Z_TREES) { break inf_leave; }
  20257. /* falls through */
  20258. case COPY_:
  20259. state.mode = COPY;
  20260. /* falls through */
  20261. case COPY:
  20262. copy = state.length;
  20263. if (copy) {
  20264. if (copy > have) { copy = have; }
  20265. if (copy > left) { copy = left; }
  20266. if (copy === 0) { break inf_leave; }
  20267. //--- zmemcpy(put, next, copy); ---
  20268. utils.arraySet(output, input, next, copy, put);
  20269. //---//
  20270. have -= copy;
  20271. next += copy;
  20272. left -= copy;
  20273. put += copy;
  20274. state.length -= copy;
  20275. break;
  20276. }
  20277. //Tracev((stderr, "inflate: stored end\n"));
  20278. state.mode = TYPE;
  20279. break;
  20280. case TABLE:
  20281. //=== NEEDBITS(14); */
  20282. while (bits < 14) {
  20283. if (have === 0) { break inf_leave; }
  20284. have--;
  20285. hold += input[next++] << bits;
  20286. bits += 8;
  20287. }
  20288. //===//
  20289. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  20290. //--- DROPBITS(5) ---//
  20291. hold >>>= 5;
  20292. bits -= 5;
  20293. //---//
  20294. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  20295. //--- DROPBITS(5) ---//
  20296. hold >>>= 5;
  20297. bits -= 5;
  20298. //---//
  20299. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  20300. //--- DROPBITS(4) ---//
  20301. hold >>>= 4;
  20302. bits -= 4;
  20303. //---//
  20304. //#ifndef PKZIP_BUG_WORKAROUND
  20305. if (state.nlen > 286 || state.ndist > 30) {
  20306. strm.msg = 'too many length or distance symbols';
  20307. state.mode = BAD;
  20308. break;
  20309. }
  20310. //#endif
  20311. //Tracev((stderr, "inflate: table sizes ok\n"));
  20312. state.have = 0;
  20313. state.mode = LENLENS;
  20314. /* falls through */
  20315. case LENLENS:
  20316. while (state.have < state.ncode) {
  20317. //=== NEEDBITS(3);
  20318. while (bits < 3) {
  20319. if (have === 0) { break inf_leave; }
  20320. have--;
  20321. hold += input[next++] << bits;
  20322. bits += 8;
  20323. }
  20324. //===//
  20325. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  20326. //--- DROPBITS(3) ---//
  20327. hold >>>= 3;
  20328. bits -= 3;
  20329. //---//
  20330. }
  20331. while (state.have < 19) {
  20332. state.lens[order[state.have++]] = 0;
  20333. }
  20334. // We have separate tables & no pointers. 2 commented lines below not needed.
  20335. //state.next = state.codes;
  20336. //state.lencode = state.next;
  20337. // Switch to use dynamic table
  20338. state.lencode = state.lendyn;
  20339. state.lenbits = 7;
  20340. opts = {bits: state.lenbits};
  20341. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  20342. state.lenbits = opts.bits;
  20343. if (ret) {
  20344. strm.msg = 'invalid code lengths set';
  20345. state.mode = BAD;
  20346. break;
  20347. }
  20348. //Tracev((stderr, "inflate: code lengths ok\n"));
  20349. state.have = 0;
  20350. state.mode = CODELENS;
  20351. /* falls through */
  20352. case CODELENS:
  20353. while (state.have < state.nlen + state.ndist) {
  20354. for (;;) {
  20355. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  20356. here_bits = here >>> 24;
  20357. here_op = (here >>> 16) & 0xff;
  20358. here_val = here & 0xffff;
  20359. if ((here_bits) <= bits) { break; }
  20360. //--- PULLBYTE() ---//
  20361. if (have === 0) { break inf_leave; }
  20362. have--;
  20363. hold += input[next++] << bits;
  20364. bits += 8;
  20365. //---//
  20366. }
  20367. if (here_val < 16) {
  20368. //--- DROPBITS(here.bits) ---//
  20369. hold >>>= here_bits;
  20370. bits -= here_bits;
  20371. //---//
  20372. state.lens[state.have++] = here_val;
  20373. }
  20374. else {
  20375. if (here_val === 16) {
  20376. //=== NEEDBITS(here.bits + 2);
  20377. n = here_bits + 2;
  20378. while (bits < n) {
  20379. if (have === 0) { break inf_leave; }
  20380. have--;
  20381. hold += input[next++] << bits;
  20382. bits += 8;
  20383. }
  20384. //===//
  20385. //--- DROPBITS(here.bits) ---//
  20386. hold >>>= here_bits;
  20387. bits -= here_bits;
  20388. //---//
  20389. if (state.have === 0) {
  20390. strm.msg = 'invalid bit length repeat';
  20391. state.mode = BAD;
  20392. break;
  20393. }
  20394. len = state.lens[state.have - 1];
  20395. copy = 3 + (hold & 0x03);//BITS(2);
  20396. //--- DROPBITS(2) ---//
  20397. hold >>>= 2;
  20398. bits -= 2;
  20399. //---//
  20400. }
  20401. else if (here_val === 17) {
  20402. //=== NEEDBITS(here.bits + 3);
  20403. n = here_bits + 3;
  20404. while (bits < n) {
  20405. if (have === 0) { break inf_leave; }
  20406. have--;
  20407. hold += input[next++] << bits;
  20408. bits += 8;
  20409. }
  20410. //===//
  20411. //--- DROPBITS(here.bits) ---//
  20412. hold >>>= here_bits;
  20413. bits -= here_bits;
  20414. //---//
  20415. len = 0;
  20416. copy = 3 + (hold & 0x07);//BITS(3);
  20417. //--- DROPBITS(3) ---//
  20418. hold >>>= 3;
  20419. bits -= 3;
  20420. //---//
  20421. }
  20422. else {
  20423. //=== NEEDBITS(here.bits + 7);
  20424. n = here_bits + 7;
  20425. while (bits < n) {
  20426. if (have === 0) { break inf_leave; }
  20427. have--;
  20428. hold += input[next++] << bits;
  20429. bits += 8;
  20430. }
  20431. //===//
  20432. //--- DROPBITS(here.bits) ---//
  20433. hold >>>= here_bits;
  20434. bits -= here_bits;
  20435. //---//
  20436. len = 0;
  20437. copy = 11 + (hold & 0x7f);//BITS(7);
  20438. //--- DROPBITS(7) ---//
  20439. hold >>>= 7;
  20440. bits -= 7;
  20441. //---//
  20442. }
  20443. if (state.have + copy > state.nlen + state.ndist) {
  20444. strm.msg = 'invalid bit length repeat';
  20445. state.mode = BAD;
  20446. break;
  20447. }
  20448. while (copy--) {
  20449. state.lens[state.have++] = len;
  20450. }
  20451. }
  20452. }
  20453. /* handle error breaks in while */
  20454. if (state.mode === BAD) { break; }
  20455. /* check for end-of-block code (better have one) */
  20456. if (state.lens[256] === 0) {
  20457. strm.msg = 'invalid code -- missing end-of-block';
  20458. state.mode = BAD;
  20459. break;
  20460. }
  20461. /* build code tables -- note: do not change the lenbits or distbits
  20462. values here (9 and 6) without reading the comments in inftrees.h
  20463. concerning the ENOUGH constants, which depend on those values */
  20464. state.lenbits = 9;
  20465. opts = {bits: state.lenbits};
  20466. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  20467. // We have separate tables & no pointers. 2 commented lines below not needed.
  20468. // state.next_index = opts.table_index;
  20469. state.lenbits = opts.bits;
  20470. // state.lencode = state.next;
  20471. if (ret) {
  20472. strm.msg = 'invalid literal/lengths set';
  20473. state.mode = BAD;
  20474. break;
  20475. }
  20476. state.distbits = 6;
  20477. //state.distcode.copy(state.codes);
  20478. // Switch to use dynamic table
  20479. state.distcode = state.distdyn;
  20480. opts = {bits: state.distbits};
  20481. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  20482. // We have separate tables & no pointers. 2 commented lines below not needed.
  20483. // state.next_index = opts.table_index;
  20484. state.distbits = opts.bits;
  20485. // state.distcode = state.next;
  20486. if (ret) {
  20487. strm.msg = 'invalid distances set';
  20488. state.mode = BAD;
  20489. break;
  20490. }
  20491. //Tracev((stderr, 'inflate: codes ok\n'));
  20492. state.mode = LEN_;
  20493. if (flush === Z_TREES) { break inf_leave; }
  20494. /* falls through */
  20495. case LEN_:
  20496. state.mode = LEN;
  20497. /* falls through */
  20498. case LEN:
  20499. if (have >= 6 && left >= 258) {
  20500. //--- RESTORE() ---
  20501. strm.next_out = put;
  20502. strm.avail_out = left;
  20503. strm.next_in = next;
  20504. strm.avail_in = have;
  20505. state.hold = hold;
  20506. state.bits = bits;
  20507. //---
  20508. inflate_fast(strm, _out);
  20509. //--- LOAD() ---
  20510. put = strm.next_out;
  20511. output = strm.output;
  20512. left = strm.avail_out;
  20513. next = strm.next_in;
  20514. input = strm.input;
  20515. have = strm.avail_in;
  20516. hold = state.hold;
  20517. bits = state.bits;
  20518. //---
  20519. if (state.mode === TYPE) {
  20520. state.back = -1;
  20521. }
  20522. break;
  20523. }
  20524. state.back = 0;
  20525. for (;;) {
  20526. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  20527. here_bits = here >>> 24;
  20528. here_op = (here >>> 16) & 0xff;
  20529. here_val = here & 0xffff;
  20530. if (here_bits <= bits) { break; }
  20531. //--- PULLBYTE() ---//
  20532. if (have === 0) { break inf_leave; }
  20533. have--;
  20534. hold += input[next++] << bits;
  20535. bits += 8;
  20536. //---//
  20537. }
  20538. if (here_op && (here_op & 0xf0) === 0) {
  20539. last_bits = here_bits;
  20540. last_op = here_op;
  20541. last_val = here_val;
  20542. for (;;) {
  20543. here = state.lencode[last_val +
  20544. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  20545. here_bits = here >>> 24;
  20546. here_op = (here >>> 16) & 0xff;
  20547. here_val = here & 0xffff;
  20548. if ((last_bits + here_bits) <= bits) { break; }
  20549. //--- PULLBYTE() ---//
  20550. if (have === 0) { break inf_leave; }
  20551. have--;
  20552. hold += input[next++] << bits;
  20553. bits += 8;
  20554. //---//
  20555. }
  20556. //--- DROPBITS(last.bits) ---//
  20557. hold >>>= last_bits;
  20558. bits -= last_bits;
  20559. //---//
  20560. state.back += last_bits;
  20561. }
  20562. //--- DROPBITS(here.bits) ---//
  20563. hold >>>= here_bits;
  20564. bits -= here_bits;
  20565. //---//
  20566. state.back += here_bits;
  20567. state.length = here_val;
  20568. if (here_op === 0) {
  20569. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  20570. // "inflate: literal '%c'\n" :
  20571. // "inflate: literal 0x%02x\n", here.val));
  20572. state.mode = LIT;
  20573. break;
  20574. }
  20575. if (here_op & 32) {
  20576. //Tracevv((stderr, "inflate: end of block\n"));
  20577. state.back = -1;
  20578. state.mode = TYPE;
  20579. break;
  20580. }
  20581. if (here_op & 64) {
  20582. strm.msg = 'invalid literal/length code';
  20583. state.mode = BAD;
  20584. break;
  20585. }
  20586. state.extra = here_op & 15;
  20587. state.mode = LENEXT;
  20588. /* falls through */
  20589. case LENEXT:
  20590. if (state.extra) {
  20591. //=== NEEDBITS(state.extra);
  20592. n = state.extra;
  20593. while (bits < n) {
  20594. if (have === 0) { break inf_leave; }
  20595. have--;
  20596. hold += input[next++] << bits;
  20597. bits += 8;
  20598. }
  20599. //===//
  20600. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  20601. //--- DROPBITS(state.extra) ---//
  20602. hold >>>= state.extra;
  20603. bits -= state.extra;
  20604. //---//
  20605. state.back += state.extra;
  20606. }
  20607. //Tracevv((stderr, "inflate: length %u\n", state.length));
  20608. state.was = state.length;
  20609. state.mode = DIST;
  20610. /* falls through */
  20611. case DIST:
  20612. for (;;) {
  20613. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  20614. here_bits = here >>> 24;
  20615. here_op = (here >>> 16) & 0xff;
  20616. here_val = here & 0xffff;
  20617. if ((here_bits) <= bits) { break; }
  20618. //--- PULLBYTE() ---//
  20619. if (have === 0) { break inf_leave; }
  20620. have--;
  20621. hold += input[next++] << bits;
  20622. bits += 8;
  20623. //---//
  20624. }
  20625. if ((here_op & 0xf0) === 0) {
  20626. last_bits = here_bits;
  20627. last_op = here_op;
  20628. last_val = here_val;
  20629. for (;;) {
  20630. here = state.distcode[last_val +
  20631. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  20632. here_bits = here >>> 24;
  20633. here_op = (here >>> 16) & 0xff;
  20634. here_val = here & 0xffff;
  20635. if ((last_bits + here_bits) <= bits) { break; }
  20636. //--- PULLBYTE() ---//
  20637. if (have === 0) { break inf_leave; }
  20638. have--;
  20639. hold += input[next++] << bits;
  20640. bits += 8;
  20641. //---//
  20642. }
  20643. //--- DROPBITS(last.bits) ---//
  20644. hold >>>= last_bits;
  20645. bits -= last_bits;
  20646. //---//
  20647. state.back += last_bits;
  20648. }
  20649. //--- DROPBITS(here.bits) ---//
  20650. hold >>>= here_bits;
  20651. bits -= here_bits;
  20652. //---//
  20653. state.back += here_bits;
  20654. if (here_op & 64) {
  20655. strm.msg = 'invalid distance code';
  20656. state.mode = BAD;
  20657. break;
  20658. }
  20659. state.offset = here_val;
  20660. state.extra = (here_op) & 15;
  20661. state.mode = DISTEXT;
  20662. /* falls through */
  20663. case DISTEXT:
  20664. if (state.extra) {
  20665. //=== NEEDBITS(state.extra);
  20666. n = state.extra;
  20667. while (bits < n) {
  20668. if (have === 0) { break inf_leave; }
  20669. have--;
  20670. hold += input[next++] << bits;
  20671. bits += 8;
  20672. }
  20673. //===//
  20674. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  20675. //--- DROPBITS(state.extra) ---//
  20676. hold >>>= state.extra;
  20677. bits -= state.extra;
  20678. //---//
  20679. state.back += state.extra;
  20680. }
  20681. //#ifdef INFLATE_STRICT
  20682. if (state.offset > state.dmax) {
  20683. strm.msg = 'invalid distance too far back';
  20684. state.mode = BAD;
  20685. break;
  20686. }
  20687. //#endif
  20688. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  20689. state.mode = MATCH;
  20690. /* falls through */
  20691. case MATCH:
  20692. if (left === 0) { break inf_leave; }
  20693. copy = _out - left;
  20694. if (state.offset > copy) { /* copy from window */
  20695. copy = state.offset - copy;
  20696. if (copy > state.whave) {
  20697. if (state.sane) {
  20698. strm.msg = 'invalid distance too far back';
  20699. state.mode = BAD;
  20700. break;
  20701. }
  20702. // (!) This block is disabled in zlib defailts,
  20703. // don't enable it for binary compatibility
  20704. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  20705. // Trace((stderr, "inflate.c too far\n"));
  20706. // copy -= state.whave;
  20707. // if (copy > state.length) { copy = state.length; }
  20708. // if (copy > left) { copy = left; }
  20709. // left -= copy;
  20710. // state.length -= copy;
  20711. // do {
  20712. // output[put++] = 0;
  20713. // } while (--copy);
  20714. // if (state.length === 0) { state.mode = LEN; }
  20715. // break;
  20716. //#endif
  20717. }
  20718. if (copy > state.wnext) {
  20719. copy -= state.wnext;
  20720. from = state.wsize - copy;
  20721. }
  20722. else {
  20723. from = state.wnext - copy;
  20724. }
  20725. if (copy > state.length) { copy = state.length; }
  20726. from_source = state.window;
  20727. }
  20728. else { /* copy from output */
  20729. from_source = output;
  20730. from = put - state.offset;
  20731. copy = state.length;
  20732. }
  20733. if (copy > left) { copy = left; }
  20734. left -= copy;
  20735. state.length -= copy;
  20736. do {
  20737. output[put++] = from_source[from++];
  20738. } while (--copy);
  20739. if (state.length === 0) { state.mode = LEN; }
  20740. break;
  20741. case LIT:
  20742. if (left === 0) { break inf_leave; }
  20743. output[put++] = state.length;
  20744. left--;
  20745. state.mode = LEN;
  20746. break;
  20747. case CHECK:
  20748. if (state.wrap) {
  20749. //=== NEEDBITS(32);
  20750. while (bits < 32) {
  20751. if (have === 0) { break inf_leave; }
  20752. have--;
  20753. // Use '|' insdead of '+' to make sure that result is signed
  20754. hold |= input[next++] << bits;
  20755. bits += 8;
  20756. }
  20757. //===//
  20758. _out -= left;
  20759. strm.total_out += _out;
  20760. state.total += _out;
  20761. if (_out) {
  20762. strm.adler = state.check =
  20763. /*UPDATE(state.check, put - _out, _out);*/
  20764. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  20765. }
  20766. _out = left;
  20767. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  20768. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  20769. strm.msg = 'incorrect data check';
  20770. state.mode = BAD;
  20771. break;
  20772. }
  20773. //=== INITBITS();
  20774. hold = 0;
  20775. bits = 0;
  20776. //===//
  20777. //Tracev((stderr, "inflate: check matches trailer\n"));
  20778. }
  20779. state.mode = LENGTH;
  20780. /* falls through */
  20781. case LENGTH:
  20782. if (state.wrap && state.flags) {
  20783. //=== NEEDBITS(32);
  20784. while (bits < 32) {
  20785. if (have === 0) { break inf_leave; }
  20786. have--;
  20787. hold += input[next++] << bits;
  20788. bits += 8;
  20789. }
  20790. //===//
  20791. if (hold !== (state.total & 0xffffffff)) {
  20792. strm.msg = 'incorrect length check';
  20793. state.mode = BAD;
  20794. break;
  20795. }
  20796. //=== INITBITS();
  20797. hold = 0;
  20798. bits = 0;
  20799. //===//
  20800. //Tracev((stderr, "inflate: length matches trailer\n"));
  20801. }
  20802. state.mode = DONE;
  20803. /* falls through */
  20804. case DONE:
  20805. ret = Z_STREAM_END;
  20806. break inf_leave;
  20807. case BAD:
  20808. ret = Z_DATA_ERROR;
  20809. break inf_leave;
  20810. case MEM:
  20811. return Z_MEM_ERROR;
  20812. case SYNC:
  20813. /* falls through */
  20814. default:
  20815. return Z_STREAM_ERROR;
  20816. }
  20817. }
  20818. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  20819. /*
  20820. Return from inflate(), updating the total counts and the check value.
  20821. If there was no progress during the inflate() call, return a buffer
  20822. error. Call updatewindow() to create and/or update the window state.
  20823. Note: a memory error from inflate() is non-recoverable.
  20824. */
  20825. //--- RESTORE() ---
  20826. strm.next_out = put;
  20827. strm.avail_out = left;
  20828. strm.next_in = next;
  20829. strm.avail_in = have;
  20830. state.hold = hold;
  20831. state.bits = bits;
  20832. //---
  20833. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  20834. (state.mode < CHECK || flush !== Z_FINISH))) {
  20835. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  20836. state.mode = MEM;
  20837. return Z_MEM_ERROR;
  20838. }
  20839. }
  20840. _in -= strm.avail_in;
  20841. _out -= strm.avail_out;
  20842. strm.total_in += _in;
  20843. strm.total_out += _out;
  20844. state.total += _out;
  20845. if (state.wrap && _out) {
  20846. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  20847. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  20848. }
  20849. strm.data_type = state.bits + (state.last ? 64 : 0) +
  20850. (state.mode === TYPE ? 128 : 0) +
  20851. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  20852. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  20853. ret = Z_BUF_ERROR;
  20854. }
  20855. return ret;
  20856. }
  20857. function inflateEnd(strm) {
  20858. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  20859. return Z_STREAM_ERROR;
  20860. }
  20861. var state = strm.state;
  20862. if (state.window) {
  20863. state.window = null;
  20864. }
  20865. strm.state = null;
  20866. return Z_OK;
  20867. }
  20868. function inflateGetHeader(strm, head) {
  20869. var state;
  20870. /* check state */
  20871. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  20872. state = strm.state;
  20873. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  20874. /* save header structure */
  20875. state.head = head;
  20876. head.done = false;
  20877. return Z_OK;
  20878. }
  20879. exports.inflateReset = inflateReset;
  20880. exports.inflateReset2 = inflateReset2;
  20881. exports.inflateResetKeep = inflateResetKeep;
  20882. exports.inflateInit = inflateInit;
  20883. exports.inflateInit2 = inflateInit2;
  20884. exports.inflate = inflate;
  20885. exports.inflateEnd = inflateEnd;
  20886. exports.inflateGetHeader = inflateGetHeader;
  20887. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  20888. /* Not implemented
  20889. exports.inflateCopy = inflateCopy;
  20890. exports.inflateGetDictionary = inflateGetDictionary;
  20891. exports.inflateMark = inflateMark;
  20892. exports.inflatePrime = inflatePrime;
  20893. exports.inflateSetDictionary = inflateSetDictionary;
  20894. exports.inflateSync = inflateSync;
  20895. exports.inflateSyncPoint = inflateSyncPoint;
  20896. exports.inflateUndermine = inflateUndermine;
  20897. */
  20898. },{"../utils/common":66,"./adler32":68,"./crc32":70,"./inffast":73,"./inftrees":75}],75:[function(require,module,exports){
  20899. 'use strict';
  20900. var utils = require('../utils/common');
  20901. var MAXBITS = 15;
  20902. var ENOUGH_LENS = 852;
  20903. var ENOUGH_DISTS = 592;
  20904. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  20905. var CODES = 0;
  20906. var LENS = 1;
  20907. var DISTS = 2;
  20908. var lbase = [ /* Length codes 257..285 base */
  20909. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  20910. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  20911. ];
  20912. var lext = [ /* Length codes 257..285 extra */
  20913. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  20914. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  20915. ];
  20916. var dbase = [ /* Distance codes 0..29 base */
  20917. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  20918. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  20919. 8193, 12289, 16385, 24577, 0, 0
  20920. ];
  20921. var dext = [ /* Distance codes 0..29 extra */
  20922. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  20923. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  20924. 28, 28, 29, 29, 64, 64
  20925. ];
  20926. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  20927. {
  20928. var bits = opts.bits;
  20929. //here = opts.here; /* table entry for duplication */
  20930. var len = 0; /* a code's length in bits */
  20931. var sym = 0; /* index of code symbols */
  20932. var min = 0, max = 0; /* minimum and maximum code lengths */
  20933. var root = 0; /* number of index bits for root table */
  20934. var curr = 0; /* number of index bits for current table */
  20935. var drop = 0; /* code bits to drop for sub-table */
  20936. var left = 0; /* number of prefix codes available */
  20937. var used = 0; /* code entries in table used */
  20938. var huff = 0; /* Huffman code */
  20939. var incr; /* for incrementing code, index */
  20940. var fill; /* index for replicating entries */
  20941. var low; /* low bits for current root entry */
  20942. var mask; /* mask for low root bits */
  20943. var next; /* next available space in table */
  20944. var base = null; /* base value table to use */
  20945. var base_index = 0;
  20946. // var shoextra; /* extra bits table to use */
  20947. var end; /* use base and extra for symbol > end */
  20948. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  20949. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  20950. var extra = null;
  20951. var extra_index = 0;
  20952. var here_bits, here_op, here_val;
  20953. /*
  20954. Process a set of code lengths to create a canonical Huffman code. The
  20955. code lengths are lens[0..codes-1]. Each length corresponds to the
  20956. symbols 0..codes-1. The Huffman code is generated by first sorting the
  20957. symbols by length from short to long, and retaining the symbol order
  20958. for codes with equal lengths. Then the code starts with all zero bits
  20959. for the first code of the shortest length, and the codes are integer
  20960. increments for the same length, and zeros are appended as the length
  20961. increases. For the deflate format, these bits are stored backwards
  20962. from their more natural integer increment ordering, and so when the
  20963. decoding tables are built in the large loop below, the integer codes
  20964. are incremented backwards.
  20965. This routine assumes, but does not check, that all of the entries in
  20966. lens[] are in the range 0..MAXBITS. The caller must assure this.
  20967. 1..MAXBITS is interpreted as that code length. zero means that that
  20968. symbol does not occur in this code.
  20969. The codes are sorted by computing a count of codes for each length,
  20970. creating from that a table of starting indices for each length in the
  20971. sorted table, and then entering the symbols in order in the sorted
  20972. table. The sorted table is work[], with that space being provided by
  20973. the caller.
  20974. The length counts are used for other purposes as well, i.e. finding
  20975. the minimum and maximum length codes, determining if there are any
  20976. codes at all, checking for a valid set of lengths, and looking ahead
  20977. at length counts to determine sub-table sizes when building the
  20978. decoding tables.
  20979. */
  20980. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  20981. for (len = 0; len <= MAXBITS; len++) {
  20982. count[len] = 0;
  20983. }
  20984. for (sym = 0; sym < codes; sym++) {
  20985. count[lens[lens_index + sym]]++;
  20986. }
  20987. /* bound code lengths, force root to be within code lengths */
  20988. root = bits;
  20989. for (max = MAXBITS; max >= 1; max--) {
  20990. if (count[max] !== 0) { break; }
  20991. }
  20992. if (root > max) {
  20993. root = max;
  20994. }
  20995. if (max === 0) { /* no symbols to code at all */
  20996. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  20997. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  20998. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  20999. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  21000. //table.op[opts.table_index] = 64;
  21001. //table.bits[opts.table_index] = 1;
  21002. //table.val[opts.table_index++] = 0;
  21003. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  21004. opts.bits = 1;
  21005. return 0; /* no symbols, but wait for decoding to report error */
  21006. }
  21007. for (min = 1; min < max; min++) {
  21008. if (count[min] !== 0) { break; }
  21009. }
  21010. if (root < min) {
  21011. root = min;
  21012. }
  21013. /* check for an over-subscribed or incomplete set of lengths */
  21014. left = 1;
  21015. for (len = 1; len <= MAXBITS; len++) {
  21016. left <<= 1;
  21017. left -= count[len];
  21018. if (left < 0) {
  21019. return -1;
  21020. } /* over-subscribed */
  21021. }
  21022. if (left > 0 && (type === CODES || max !== 1)) {
  21023. return -1; /* incomplete set */
  21024. }
  21025. /* generate offsets into symbol table for each length for sorting */
  21026. offs[1] = 0;
  21027. for (len = 1; len < MAXBITS; len++) {
  21028. offs[len + 1] = offs[len] + count[len];
  21029. }
  21030. /* sort symbols by length, by symbol order within each length */
  21031. for (sym = 0; sym < codes; sym++) {
  21032. if (lens[lens_index + sym] !== 0) {
  21033. work[offs[lens[lens_index + sym]]++] = sym;
  21034. }
  21035. }
  21036. /*
  21037. Create and fill in decoding tables. In this loop, the table being
  21038. filled is at next and has curr index bits. The code being used is huff
  21039. with length len. That code is converted to an index by dropping drop
  21040. bits off of the bottom. For codes where len is less than drop + curr,
  21041. those top drop + curr - len bits are incremented through all values to
  21042. fill the table with replicated entries.
  21043. root is the number of index bits for the root table. When len exceeds
  21044. root, sub-tables are created pointed to by the root entry with an index
  21045. of the low root bits of huff. This is saved in low to check for when a
  21046. new sub-table should be started. drop is zero when the root table is
  21047. being filled, and drop is root when sub-tables are being filled.
  21048. When a new sub-table is needed, it is necessary to look ahead in the
  21049. code lengths to determine what size sub-table is needed. The length
  21050. counts are used for this, and so count[] is decremented as codes are
  21051. entered in the tables.
  21052. used keeps track of how many table entries have been allocated from the
  21053. provided *table space. It is checked for LENS and DIST tables against
  21054. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  21055. the initial root table size constants. See the comments in inftrees.h
  21056. for more information.
  21057. sym increments through all symbols, and the loop terminates when
  21058. all codes of length max, i.e. all codes, have been processed. This
  21059. routine permits incomplete codes, so another loop after this one fills
  21060. in the rest of the decoding tables with invalid code markers.
  21061. */
  21062. /* set up for code type */
  21063. // poor man optimization - use if-else instead of switch,
  21064. // to avoid deopts in old v8
  21065. if (type === CODES) {
  21066. base = extra = work; /* dummy value--not used */
  21067. end = 19;
  21068. } else if (type === LENS) {
  21069. base = lbase;
  21070. base_index -= 257;
  21071. extra = lext;
  21072. extra_index -= 257;
  21073. end = 256;
  21074. } else { /* DISTS */
  21075. base = dbase;
  21076. extra = dext;
  21077. end = -1;
  21078. }
  21079. /* initialize opts for loop */
  21080. huff = 0; /* starting code */
  21081. sym = 0; /* starting code symbol */
  21082. len = min; /* starting code length */
  21083. next = table_index; /* current table to fill in */
  21084. curr = root; /* current table index bits */
  21085. drop = 0; /* current bits to drop from code for index */
  21086. low = -1; /* trigger new sub-table when len > root */
  21087. used = 1 << root; /* use root table entries */
  21088. mask = used - 1; /* mask for comparing low */
  21089. /* check available table space */
  21090. if ((type === LENS && used > ENOUGH_LENS) ||
  21091. (type === DISTS && used > ENOUGH_DISTS)) {
  21092. return 1;
  21093. }
  21094. var i=0;
  21095. /* process all codes and make table entries */
  21096. for (;;) {
  21097. i++;
  21098. /* create table entry */
  21099. here_bits = len - drop;
  21100. if (work[sym] < end) {
  21101. here_op = 0;
  21102. here_val = work[sym];
  21103. }
  21104. else if (work[sym] > end) {
  21105. here_op = extra[extra_index + work[sym]];
  21106. here_val = base[base_index + work[sym]];
  21107. }
  21108. else {
  21109. here_op = 32 + 64; /* end of block */
  21110. here_val = 0;
  21111. }
  21112. /* replicate for those indices with low len bits equal to huff */
  21113. incr = 1 << (len - drop);
  21114. fill = 1 << curr;
  21115. min = fill; /* save offset to next table */
  21116. do {
  21117. fill -= incr;
  21118. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  21119. } while (fill !== 0);
  21120. /* backwards increment the len-bit code huff */
  21121. incr = 1 << (len - 1);
  21122. while (huff & incr) {
  21123. incr >>= 1;
  21124. }
  21125. if (incr !== 0) {
  21126. huff &= incr - 1;
  21127. huff += incr;
  21128. } else {
  21129. huff = 0;
  21130. }
  21131. /* go to next symbol, update count, len */
  21132. sym++;
  21133. if (--count[len] === 0) {
  21134. if (len === max) { break; }
  21135. len = lens[lens_index + work[sym]];
  21136. }
  21137. /* create new sub-table if needed */
  21138. if (len > root && (huff & mask) !== low) {
  21139. /* if first time, transition to sub-tables */
  21140. if (drop === 0) {
  21141. drop = root;
  21142. }
  21143. /* increment past last table */
  21144. next += min; /* here min is 1 << curr */
  21145. /* determine length of next table */
  21146. curr = len - drop;
  21147. left = 1 << curr;
  21148. while (curr + drop < max) {
  21149. left -= count[curr + drop];
  21150. if (left <= 0) { break; }
  21151. curr++;
  21152. left <<= 1;
  21153. }
  21154. /* check for enough space */
  21155. used += 1 << curr;
  21156. if ((type === LENS && used > ENOUGH_LENS) ||
  21157. (type === DISTS && used > ENOUGH_DISTS)) {
  21158. return 1;
  21159. }
  21160. /* point entry in root table to sub-table */
  21161. low = huff & mask;
  21162. /*table.op[low] = curr;
  21163. table.bits[low] = root;
  21164. table.val[low] = next - opts.table_index;*/
  21165. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  21166. }
  21167. }
  21168. /* fill in remaining table entry if code is incomplete (guaranteed to have
  21169. at most one remaining entry, since if the code is incomplete, the
  21170. maximum code length that was allowed to get this far is one bit) */
  21171. if (huff !== 0) {
  21172. //table.op[next + huff] = 64; /* invalid code marker */
  21173. //table.bits[next + huff] = len - drop;
  21174. //table.val[next + huff] = 0;
  21175. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  21176. }
  21177. /* set return parameters */
  21178. //opts.table_index += used;
  21179. opts.bits = root;
  21180. return 0;
  21181. };
  21182. },{"../utils/common":66}],76:[function(require,module,exports){
  21183. 'use strict';
  21184. module.exports = {
  21185. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  21186. '1': 'stream end', /* Z_STREAM_END 1 */
  21187. '0': '', /* Z_OK 0 */
  21188. '-1': 'file error', /* Z_ERRNO (-1) */
  21189. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  21190. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  21191. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  21192. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  21193. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  21194. };
  21195. },{}],77:[function(require,module,exports){
  21196. 'use strict';
  21197. var utils = require('../utils/common');
  21198. /* Public constants ==========================================================*/
  21199. /* ===========================================================================*/
  21200. //var Z_FILTERED = 1;
  21201. //var Z_HUFFMAN_ONLY = 2;
  21202. //var Z_RLE = 3;
  21203. var Z_FIXED = 4;
  21204. //var Z_DEFAULT_STRATEGY = 0;
  21205. /* Possible values of the data_type field (though see inflate()) */
  21206. var Z_BINARY = 0;
  21207. var Z_TEXT = 1;
  21208. //var Z_ASCII = 1; // = Z_TEXT
  21209. var Z_UNKNOWN = 2;
  21210. /*============================================================================*/
  21211. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  21212. // From zutil.h
  21213. var STORED_BLOCK = 0;
  21214. var STATIC_TREES = 1;
  21215. var DYN_TREES = 2;
  21216. /* The three kinds of block type */
  21217. var MIN_MATCH = 3;
  21218. var MAX_MATCH = 258;
  21219. /* The minimum and maximum match lengths */
  21220. // From deflate.h
  21221. /* ===========================================================================
  21222. * Internal compression state.
  21223. */
  21224. var LENGTH_CODES = 29;
  21225. /* number of length codes, not counting the special END_BLOCK code */
  21226. var LITERALS = 256;
  21227. /* number of literal bytes 0..255 */
  21228. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  21229. /* number of Literal or Length codes, including the END_BLOCK code */
  21230. var D_CODES = 30;
  21231. /* number of distance codes */
  21232. var BL_CODES = 19;
  21233. /* number of codes used to transfer the bit lengths */
  21234. var HEAP_SIZE = 2*L_CODES + 1;
  21235. /* maximum heap size */
  21236. var MAX_BITS = 15;
  21237. /* All codes must not exceed MAX_BITS bits */
  21238. var Buf_size = 16;
  21239. /* size of bit buffer in bi_buf */
  21240. /* ===========================================================================
  21241. * Constants
  21242. */
  21243. var MAX_BL_BITS = 7;
  21244. /* Bit length codes must not exceed MAX_BL_BITS bits */
  21245. var END_BLOCK = 256;
  21246. /* end of block literal code */
  21247. var REP_3_6 = 16;
  21248. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  21249. var REPZ_3_10 = 17;
  21250. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  21251. var REPZ_11_138 = 18;
  21252. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  21253. var extra_lbits = /* extra bits for each length code */
  21254. [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];
  21255. var extra_dbits = /* extra bits for each distance code */
  21256. [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];
  21257. var extra_blbits = /* extra bits for each bit length code */
  21258. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  21259. var bl_order =
  21260. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  21261. /* The lengths of the bit length codes are sent in order of decreasing
  21262. * probability, to avoid transmitting the lengths for unused bit length codes.
  21263. */
  21264. /* ===========================================================================
  21265. * Local data. These are initialized only once.
  21266. */
  21267. // We pre-fill arrays with 0 to avoid uninitialized gaps
  21268. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  21269. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  21270. var static_ltree = new Array((L_CODES+2) * 2);
  21271. zero(static_ltree);
  21272. /* The static literal tree. Since the bit lengths are imposed, there is no
  21273. * need for the L_CODES extra codes used during heap construction. However
  21274. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  21275. * below).
  21276. */
  21277. var static_dtree = new Array(D_CODES * 2);
  21278. zero(static_dtree);
  21279. /* The static distance tree. (Actually a trivial tree since all codes use
  21280. * 5 bits.)
  21281. */
  21282. var _dist_code = new Array(DIST_CODE_LEN);
  21283. zero(_dist_code);
  21284. /* Distance codes. The first 256 values correspond to the distances
  21285. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  21286. * the 15 bit distances.
  21287. */
  21288. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  21289. zero(_length_code);
  21290. /* length code for each normalized match length (0 == MIN_MATCH) */
  21291. var base_length = new Array(LENGTH_CODES);
  21292. zero(base_length);
  21293. /* First normalized length for each code (0 = MIN_MATCH) */
  21294. var base_dist = new Array(D_CODES);
  21295. zero(base_dist);
  21296. /* First normalized distance for each code (0 = distance of 1) */
  21297. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  21298. this.static_tree = static_tree; /* static tree or NULL */
  21299. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  21300. this.extra_base = extra_base; /* base index for extra_bits */
  21301. this.elems = elems; /* max number of elements in the tree */
  21302. this.max_length = max_length; /* max bit length for the codes */
  21303. // show if `static_tree` has data or dummy - needed for monomorphic objects
  21304. this.has_stree = static_tree && static_tree.length;
  21305. };
  21306. var static_l_desc;
  21307. var static_d_desc;
  21308. var static_bl_desc;
  21309. var TreeDesc = function(dyn_tree, stat_desc) {
  21310. this.dyn_tree = dyn_tree; /* the dynamic tree */
  21311. this.max_code = 0; /* largest code with non zero frequency */
  21312. this.stat_desc = stat_desc; /* the corresponding static tree */
  21313. };
  21314. function d_code(dist) {
  21315. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  21316. }
  21317. /* ===========================================================================
  21318. * Output a short LSB first on the stream.
  21319. * IN assertion: there is enough room in pendingBuf.
  21320. */
  21321. function put_short (s, w) {
  21322. // put_byte(s, (uch)((w) & 0xff));
  21323. // put_byte(s, (uch)((ush)(w) >> 8));
  21324. s.pending_buf[s.pending++] = (w) & 0xff;
  21325. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  21326. }
  21327. /* ===========================================================================
  21328. * Send a value on a given number of bits.
  21329. * IN assertion: length <= 16 and value fits in length bits.
  21330. */
  21331. function send_bits(s, value, length) {
  21332. if (s.bi_valid > (Buf_size - length)) {
  21333. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  21334. put_short(s, s.bi_buf);
  21335. s.bi_buf = value >> (Buf_size - s.bi_valid);
  21336. s.bi_valid += length - Buf_size;
  21337. } else {
  21338. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  21339. s.bi_valid += length;
  21340. }
  21341. }
  21342. function send_code(s, c, tree) {
  21343. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  21344. }
  21345. /* ===========================================================================
  21346. * Reverse the first len bits of a code, using straightforward code (a faster
  21347. * method would use a table)
  21348. * IN assertion: 1 <= len <= 15
  21349. */
  21350. function bi_reverse(code, len) {
  21351. var res = 0;
  21352. do {
  21353. res |= code & 1;
  21354. code >>>= 1;
  21355. res <<= 1;
  21356. } while (--len > 0);
  21357. return res >>> 1;
  21358. }
  21359. /* ===========================================================================
  21360. * Flush the bit buffer, keeping at most 7 bits in it.
  21361. */
  21362. function bi_flush(s) {
  21363. if (s.bi_valid === 16) {
  21364. put_short(s, s.bi_buf);
  21365. s.bi_buf = 0;
  21366. s.bi_valid = 0;
  21367. } else if (s.bi_valid >= 8) {
  21368. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  21369. s.bi_buf >>= 8;
  21370. s.bi_valid -= 8;
  21371. }
  21372. }
  21373. /* ===========================================================================
  21374. * Compute the optimal bit lengths for a tree and update the total bit length
  21375. * for the current block.
  21376. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  21377. * above are the tree nodes sorted by increasing frequency.
  21378. * OUT assertions: the field len is set to the optimal bit length, the
  21379. * array bl_count contains the frequencies for each bit length.
  21380. * The length opt_len is updated; static_len is also updated if stree is
  21381. * not null.
  21382. */
  21383. function gen_bitlen(s, desc)
  21384. // deflate_state *s;
  21385. // tree_desc *desc; /* the tree descriptor */
  21386. {
  21387. var tree = desc.dyn_tree;
  21388. var max_code = desc.max_code;
  21389. var stree = desc.stat_desc.static_tree;
  21390. var has_stree = desc.stat_desc.has_stree;
  21391. var extra = desc.stat_desc.extra_bits;
  21392. var base = desc.stat_desc.extra_base;
  21393. var max_length = desc.stat_desc.max_length;
  21394. var h; /* heap index */
  21395. var n, m; /* iterate over the tree elements */
  21396. var bits; /* bit length */
  21397. var xbits; /* extra bits */
  21398. var f; /* frequency */
  21399. var overflow = 0; /* number of elements with bit length too large */
  21400. for (bits = 0; bits <= MAX_BITS; bits++) {
  21401. s.bl_count[bits] = 0;
  21402. }
  21403. /* In a first pass, compute the optimal bit lengths (which may
  21404. * overflow in the case of the bit length tree).
  21405. */
  21406. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  21407. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  21408. n = s.heap[h];
  21409. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  21410. if (bits > max_length) {
  21411. bits = max_length;
  21412. overflow++;
  21413. }
  21414. tree[n*2 + 1]/*.Len*/ = bits;
  21415. /* We overwrite tree[n].Dad which is no longer needed */
  21416. if (n > max_code) { continue; } /* not a leaf node */
  21417. s.bl_count[bits]++;
  21418. xbits = 0;
  21419. if (n >= base) {
  21420. xbits = extra[n-base];
  21421. }
  21422. f = tree[n * 2]/*.Freq*/;
  21423. s.opt_len += f * (bits + xbits);
  21424. if (has_stree) {
  21425. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  21426. }
  21427. }
  21428. if (overflow === 0) { return; }
  21429. // Trace((stderr,"\nbit length overflow\n"));
  21430. /* This happens for example on obj2 and pic of the Calgary corpus */
  21431. /* Find the first bit length which could increase: */
  21432. do {
  21433. bits = max_length-1;
  21434. while (s.bl_count[bits] === 0) { bits--; }
  21435. s.bl_count[bits]--; /* move one leaf down the tree */
  21436. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  21437. s.bl_count[max_length]--;
  21438. /* The brother of the overflow item also moves one step up,
  21439. * but this does not affect bl_count[max_length]
  21440. */
  21441. overflow -= 2;
  21442. } while (overflow > 0);
  21443. /* Now recompute all bit lengths, scanning in increasing frequency.
  21444. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  21445. * lengths instead of fixing only the wrong ones. This idea is taken
  21446. * from 'ar' written by Haruhiko Okumura.)
  21447. */
  21448. for (bits = max_length; bits !== 0; bits--) {
  21449. n = s.bl_count[bits];
  21450. while (n !== 0) {
  21451. m = s.heap[--h];
  21452. if (m > max_code) { continue; }
  21453. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  21454. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  21455. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  21456. tree[m*2 + 1]/*.Len*/ = bits;
  21457. }
  21458. n--;
  21459. }
  21460. }
  21461. }
  21462. /* ===========================================================================
  21463. * Generate the codes for a given tree and bit counts (which need not be
  21464. * optimal).
  21465. * IN assertion: the array bl_count contains the bit length statistics for
  21466. * the given tree and the field len is set for all tree elements.
  21467. * OUT assertion: the field code is set for all tree elements of non
  21468. * zero code length.
  21469. */
  21470. function gen_codes(tree, max_code, bl_count)
  21471. // ct_data *tree; /* the tree to decorate */
  21472. // int max_code; /* largest code with non zero frequency */
  21473. // ushf *bl_count; /* number of codes at each bit length */
  21474. {
  21475. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  21476. var code = 0; /* running code value */
  21477. var bits; /* bit index */
  21478. var n; /* code index */
  21479. /* The distribution counts are first used to generate the code values
  21480. * without bit reversal.
  21481. */
  21482. for (bits = 1; bits <= MAX_BITS; bits++) {
  21483. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  21484. }
  21485. /* Check that the bit counts in bl_count are consistent. The last code
  21486. * must be all ones.
  21487. */
  21488. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  21489. // "inconsistent bit counts");
  21490. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  21491. for (n = 0; n <= max_code; n++) {
  21492. var len = tree[n*2 + 1]/*.Len*/;
  21493. if (len === 0) { continue; }
  21494. /* Now reverse the bits */
  21495. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  21496. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  21497. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  21498. }
  21499. }
  21500. /* ===========================================================================
  21501. * Initialize the various 'constant' tables.
  21502. */
  21503. function tr_static_init() {
  21504. var n; /* iterates over tree elements */
  21505. var bits; /* bit counter */
  21506. var length; /* length value */
  21507. var code; /* code value */
  21508. var dist; /* distance index */
  21509. var bl_count = new Array(MAX_BITS+1);
  21510. /* number of codes at each bit length for an optimal tree */
  21511. // do check in _tr_init()
  21512. //if (static_init_done) return;
  21513. /* For some embedded targets, global variables are not initialized: */
  21514. /*#ifdef NO_INIT_GLOBAL_POINTERS
  21515. static_l_desc.static_tree = static_ltree;
  21516. static_l_desc.extra_bits = extra_lbits;
  21517. static_d_desc.static_tree = static_dtree;
  21518. static_d_desc.extra_bits = extra_dbits;
  21519. static_bl_desc.extra_bits = extra_blbits;
  21520. #endif*/
  21521. /* Initialize the mapping length (0..255) -> length code (0..28) */
  21522. length = 0;
  21523. for (code = 0; code < LENGTH_CODES-1; code++) {
  21524. base_length[code] = length;
  21525. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  21526. _length_code[length++] = code;
  21527. }
  21528. }
  21529. //Assert (length == 256, "tr_static_init: length != 256");
  21530. /* Note that the length 255 (match length 258) can be represented
  21531. * in two different ways: code 284 + 5 bits or code 285, so we
  21532. * overwrite length_code[255] to use the best encoding:
  21533. */
  21534. _length_code[length-1] = code;
  21535. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  21536. dist = 0;
  21537. for (code = 0 ; code < 16; code++) {
  21538. base_dist[code] = dist;
  21539. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  21540. _dist_code[dist++] = code;
  21541. }
  21542. }
  21543. //Assert (dist == 256, "tr_static_init: dist != 256");
  21544. dist >>= 7; /* from now on, all distances are divided by 128 */
  21545. for ( ; code < D_CODES; code++) {
  21546. base_dist[code] = dist << 7;
  21547. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  21548. _dist_code[256 + dist++] = code;
  21549. }
  21550. }
  21551. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  21552. /* Construct the codes of the static literal tree */
  21553. for (bits = 0; bits <= MAX_BITS; bits++) {
  21554. bl_count[bits] = 0;
  21555. }
  21556. n = 0;
  21557. while (n <= 143) {
  21558. static_ltree[n*2 + 1]/*.Len*/ = 8;
  21559. n++;
  21560. bl_count[8]++;
  21561. }
  21562. while (n <= 255) {
  21563. static_ltree[n*2 + 1]/*.Len*/ = 9;
  21564. n++;
  21565. bl_count[9]++;
  21566. }
  21567. while (n <= 279) {
  21568. static_ltree[n*2 + 1]/*.Len*/ = 7;
  21569. n++;
  21570. bl_count[7]++;
  21571. }
  21572. while (n <= 287) {
  21573. static_ltree[n*2 + 1]/*.Len*/ = 8;
  21574. n++;
  21575. bl_count[8]++;
  21576. }
  21577. /* Codes 286 and 287 do not exist, but we must include them in the
  21578. * tree construction to get a canonical Huffman tree (longest code
  21579. * all ones)
  21580. */
  21581. gen_codes(static_ltree, L_CODES+1, bl_count);
  21582. /* The static distance tree is trivial: */
  21583. for (n = 0; n < D_CODES; n++) {
  21584. static_dtree[n*2 + 1]/*.Len*/ = 5;
  21585. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  21586. }
  21587. // Now data ready and we can init static trees
  21588. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  21589. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  21590. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  21591. //static_init_done = true;
  21592. }
  21593. /* ===========================================================================
  21594. * Initialize a new block.
  21595. */
  21596. function init_block(s) {
  21597. var n; /* iterates over tree elements */
  21598. /* Initialize the trees. */
  21599. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  21600. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  21601. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  21602. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  21603. s.opt_len = s.static_len = 0;
  21604. s.last_lit = s.matches = 0;
  21605. }
  21606. /* ===========================================================================
  21607. * Flush the bit buffer and align the output on a byte boundary
  21608. */
  21609. function bi_windup(s)
  21610. {
  21611. if (s.bi_valid > 8) {
  21612. put_short(s, s.bi_buf);
  21613. } else if (s.bi_valid > 0) {
  21614. //put_byte(s, (Byte)s->bi_buf);
  21615. s.pending_buf[s.pending++] = s.bi_buf;
  21616. }
  21617. s.bi_buf = 0;
  21618. s.bi_valid = 0;
  21619. }
  21620. /* ===========================================================================
  21621. * Copy a stored block, storing first the length and its
  21622. * one's complement if requested.
  21623. */
  21624. function copy_block(s, buf, len, header)
  21625. //DeflateState *s;
  21626. //charf *buf; /* the input data */
  21627. //unsigned len; /* its length */
  21628. //int header; /* true if block header must be written */
  21629. {
  21630. bi_windup(s); /* align on byte boundary */
  21631. if (header) {
  21632. put_short(s, len);
  21633. put_short(s, ~len);
  21634. }
  21635. // while (len--) {
  21636. // put_byte(s, *buf++);
  21637. // }
  21638. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  21639. s.pending += len;
  21640. }
  21641. /* ===========================================================================
  21642. * Compares to subtrees, using the tree depth as tie breaker when
  21643. * the subtrees have equal frequency. This minimizes the worst case length.
  21644. */
  21645. function smaller(tree, n, m, depth) {
  21646. var _n2 = n*2;
  21647. var _m2 = m*2;
  21648. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  21649. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  21650. }
  21651. /* ===========================================================================
  21652. * Restore the heap property by moving down the tree starting at node k,
  21653. * exchanging a node with the smallest of its two sons if necessary, stopping
  21654. * when the heap property is re-established (each father smaller than its
  21655. * two sons).
  21656. */
  21657. function pqdownheap(s, tree, k)
  21658. // deflate_state *s;
  21659. // ct_data *tree; /* the tree to restore */
  21660. // int k; /* node to move down */
  21661. {
  21662. var v = s.heap[k];
  21663. var j = k << 1; /* left son of k */
  21664. while (j <= s.heap_len) {
  21665. /* Set j to the smallest of the two sons: */
  21666. if (j < s.heap_len &&
  21667. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  21668. j++;
  21669. }
  21670. /* Exit if v is smaller than both sons */
  21671. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  21672. /* Exchange v with the smallest son */
  21673. s.heap[k] = s.heap[j];
  21674. k = j;
  21675. /* And continue down the tree, setting j to the left son of k */
  21676. j <<= 1;
  21677. }
  21678. s.heap[k] = v;
  21679. }
  21680. // inlined manually
  21681. // var SMALLEST = 1;
  21682. /* ===========================================================================
  21683. * Send the block data compressed using the given Huffman trees
  21684. */
  21685. function compress_block(s, ltree, dtree)
  21686. // deflate_state *s;
  21687. // const ct_data *ltree; /* literal tree */
  21688. // const ct_data *dtree; /* distance tree */
  21689. {
  21690. var dist; /* distance of matched string */
  21691. var lc; /* match length or unmatched char (if dist == 0) */
  21692. var lx = 0; /* running index in l_buf */
  21693. var code; /* the code to send */
  21694. var extra; /* number of extra bits to send */
  21695. if (s.last_lit !== 0) {
  21696. do {
  21697. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  21698. lc = s.pending_buf[s.l_buf + lx];
  21699. lx++;
  21700. if (dist === 0) {
  21701. send_code(s, lc, ltree); /* send a literal byte */
  21702. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  21703. } else {
  21704. /* Here, lc is the match length - MIN_MATCH */
  21705. code = _length_code[lc];
  21706. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  21707. extra = extra_lbits[code];
  21708. if (extra !== 0) {
  21709. lc -= base_length[code];
  21710. send_bits(s, lc, extra); /* send the extra length bits */
  21711. }
  21712. dist--; /* dist is now the match distance - 1 */
  21713. code = d_code(dist);
  21714. //Assert (code < D_CODES, "bad d_code");
  21715. send_code(s, code, dtree); /* send the distance code */
  21716. extra = extra_dbits[code];
  21717. if (extra !== 0) {
  21718. dist -= base_dist[code];
  21719. send_bits(s, dist, extra); /* send the extra distance bits */
  21720. }
  21721. } /* literal or match pair ? */
  21722. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  21723. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  21724. // "pendingBuf overflow");
  21725. } while (lx < s.last_lit);
  21726. }
  21727. send_code(s, END_BLOCK, ltree);
  21728. }
  21729. /* ===========================================================================
  21730. * Construct one Huffman tree and assigns the code bit strings and lengths.
  21731. * Update the total bit length for the current block.
  21732. * IN assertion: the field freq is set for all tree elements.
  21733. * OUT assertions: the fields len and code are set to the optimal bit length
  21734. * and corresponding code. The length opt_len is updated; static_len is
  21735. * also updated if stree is not null. The field max_code is set.
  21736. */
  21737. function build_tree(s, desc)
  21738. // deflate_state *s;
  21739. // tree_desc *desc; /* the tree descriptor */
  21740. {
  21741. var tree = desc.dyn_tree;
  21742. var stree = desc.stat_desc.static_tree;
  21743. var has_stree = desc.stat_desc.has_stree;
  21744. var elems = desc.stat_desc.elems;
  21745. var n, m; /* iterate over heap elements */
  21746. var max_code = -1; /* largest code with non zero frequency */
  21747. var node; /* new node being created */
  21748. /* Construct the initial heap, with least frequent element in
  21749. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  21750. * heap[0] is not used.
  21751. */
  21752. s.heap_len = 0;
  21753. s.heap_max = HEAP_SIZE;
  21754. for (n = 0; n < elems; n++) {
  21755. if (tree[n * 2]/*.Freq*/ !== 0) {
  21756. s.heap[++s.heap_len] = max_code = n;
  21757. s.depth[n] = 0;
  21758. } else {
  21759. tree[n*2 + 1]/*.Len*/ = 0;
  21760. }
  21761. }
  21762. /* The pkzip format requires that at least one distance code exists,
  21763. * and that at least one bit should be sent even if there is only one
  21764. * possible code. So to avoid special checks later on we force at least
  21765. * two codes of non zero frequency.
  21766. */
  21767. while (s.heap_len < 2) {
  21768. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  21769. tree[node * 2]/*.Freq*/ = 1;
  21770. s.depth[node] = 0;
  21771. s.opt_len--;
  21772. if (has_stree) {
  21773. s.static_len -= stree[node*2 + 1]/*.Len*/;
  21774. }
  21775. /* node is 0 or 1 so it does not have extra bits */
  21776. }
  21777. desc.max_code = max_code;
  21778. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  21779. * establish sub-heaps of increasing lengths:
  21780. */
  21781. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  21782. /* Construct the Huffman tree by repeatedly combining the least two
  21783. * frequent nodes.
  21784. */
  21785. node = elems; /* next internal node of the tree */
  21786. do {
  21787. //pqremove(s, tree, n); /* n = node of least frequency */
  21788. /*** pqremove ***/
  21789. n = s.heap[1/*SMALLEST*/];
  21790. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  21791. pqdownheap(s, tree, 1/*SMALLEST*/);
  21792. /***/
  21793. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  21794. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  21795. s.heap[--s.heap_max] = m;
  21796. /* Create a new node father of n and m */
  21797. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  21798. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  21799. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  21800. /* and insert the new node in the heap */
  21801. s.heap[1/*SMALLEST*/] = node++;
  21802. pqdownheap(s, tree, 1/*SMALLEST*/);
  21803. } while (s.heap_len >= 2);
  21804. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  21805. /* At this point, the fields freq and dad are set. We can now
  21806. * generate the bit lengths.
  21807. */
  21808. gen_bitlen(s, desc);
  21809. /* The field len is now set, we can generate the bit codes */
  21810. gen_codes(tree, max_code, s.bl_count);
  21811. }
  21812. /* ===========================================================================
  21813. * Scan a literal or distance tree to determine the frequencies of the codes
  21814. * in the bit length tree.
  21815. */
  21816. function scan_tree(s, tree, max_code)
  21817. // deflate_state *s;
  21818. // ct_data *tree; /* the tree to be scanned */
  21819. // int max_code; /* and its largest code of non zero frequency */
  21820. {
  21821. var n; /* iterates over all tree elements */
  21822. var prevlen = -1; /* last emitted length */
  21823. var curlen; /* length of current code */
  21824. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  21825. var count = 0; /* repeat count of the current code */
  21826. var max_count = 7; /* max repeat count */
  21827. var min_count = 4; /* min repeat count */
  21828. if (nextlen === 0) {
  21829. max_count = 138;
  21830. min_count = 3;
  21831. }
  21832. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  21833. for (n = 0; n <= max_code; n++) {
  21834. curlen = nextlen;
  21835. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  21836. if (++count < max_count && curlen === nextlen) {
  21837. continue;
  21838. } else if (count < min_count) {
  21839. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  21840. } else if (curlen !== 0) {
  21841. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  21842. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  21843. } else if (count <= 10) {
  21844. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  21845. } else {
  21846. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  21847. }
  21848. count = 0;
  21849. prevlen = curlen;
  21850. if (nextlen === 0) {
  21851. max_count = 138;
  21852. min_count = 3;
  21853. } else if (curlen === nextlen) {
  21854. max_count = 6;
  21855. min_count = 3;
  21856. } else {
  21857. max_count = 7;
  21858. min_count = 4;
  21859. }
  21860. }
  21861. }
  21862. /* ===========================================================================
  21863. * Send a literal or distance tree in compressed form, using the codes in
  21864. * bl_tree.
  21865. */
  21866. function send_tree(s, tree, max_code)
  21867. // deflate_state *s;
  21868. // ct_data *tree; /* the tree to be scanned */
  21869. // int max_code; /* and its largest code of non zero frequency */
  21870. {
  21871. var n; /* iterates over all tree elements */
  21872. var prevlen = -1; /* last emitted length */
  21873. var curlen; /* length of current code */
  21874. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  21875. var count = 0; /* repeat count of the current code */
  21876. var max_count = 7; /* max repeat count */
  21877. var min_count = 4; /* min repeat count */
  21878. /* tree[max_code+1].Len = -1; */ /* guard already set */
  21879. if (nextlen === 0) {
  21880. max_count = 138;
  21881. min_count = 3;
  21882. }
  21883. for (n = 0; n <= max_code; n++) {
  21884. curlen = nextlen;
  21885. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  21886. if (++count < max_count && curlen === nextlen) {
  21887. continue;
  21888. } else if (count < min_count) {
  21889. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  21890. } else if (curlen !== 0) {
  21891. if (curlen !== prevlen) {
  21892. send_code(s, curlen, s.bl_tree);
  21893. count--;
  21894. }
  21895. //Assert(count >= 3 && count <= 6, " 3_6?");
  21896. send_code(s, REP_3_6, s.bl_tree);
  21897. send_bits(s, count-3, 2);
  21898. } else if (count <= 10) {
  21899. send_code(s, REPZ_3_10, s.bl_tree);
  21900. send_bits(s, count-3, 3);
  21901. } else {
  21902. send_code(s, REPZ_11_138, s.bl_tree);
  21903. send_bits(s, count-11, 7);
  21904. }
  21905. count = 0;
  21906. prevlen = curlen;
  21907. if (nextlen === 0) {
  21908. max_count = 138;
  21909. min_count = 3;
  21910. } else if (curlen === nextlen) {
  21911. max_count = 6;
  21912. min_count = 3;
  21913. } else {
  21914. max_count = 7;
  21915. min_count = 4;
  21916. }
  21917. }
  21918. }
  21919. /* ===========================================================================
  21920. * Construct the Huffman tree for the bit lengths and return the index in
  21921. * bl_order of the last bit length code to send.
  21922. */
  21923. function build_bl_tree(s) {
  21924. var max_blindex; /* index of last bit length code of non zero freq */
  21925. /* Determine the bit length frequencies for literal and distance trees */
  21926. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  21927. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  21928. /* Build the bit length tree: */
  21929. build_tree(s, s.bl_desc);
  21930. /* opt_len now includes the length of the tree representations, except
  21931. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  21932. */
  21933. /* Determine the number of bit length codes to send. The pkzip format
  21934. * requires that at least 4 bit length codes be sent. (appnote.txt says
  21935. * 3 but the actual value used is 4.)
  21936. */
  21937. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  21938. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  21939. break;
  21940. }
  21941. }
  21942. /* Update opt_len to include the bit length tree and counts */
  21943. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  21944. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  21945. // s->opt_len, s->static_len));
  21946. return max_blindex;
  21947. }
  21948. /* ===========================================================================
  21949. * Send the header for a block using dynamic Huffman trees: the counts, the
  21950. * lengths of the bit length codes, the literal tree and the distance tree.
  21951. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  21952. */
  21953. function send_all_trees(s, lcodes, dcodes, blcodes)
  21954. // deflate_state *s;
  21955. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  21956. {
  21957. var rank; /* index in bl_order */
  21958. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  21959. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  21960. // "too many codes");
  21961. //Tracev((stderr, "\nbl counts: "));
  21962. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  21963. send_bits(s, dcodes-1, 5);
  21964. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  21965. for (rank = 0; rank < blcodes; rank++) {
  21966. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  21967. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  21968. }
  21969. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  21970. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  21971. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  21972. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  21973. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  21974. }
  21975. /* ===========================================================================
  21976. * Check if the data type is TEXT or BINARY, using the following algorithm:
  21977. * - TEXT if the two conditions below are satisfied:
  21978. * a) There are no non-portable control characters belonging to the
  21979. * "black list" (0..6, 14..25, 28..31).
  21980. * b) There is at least one printable character belonging to the
  21981. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  21982. * - BINARY otherwise.
  21983. * - The following partially-portable control characters form a
  21984. * "gray list" that is ignored in this detection algorithm:
  21985. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  21986. * IN assertion: the fields Freq of dyn_ltree are set.
  21987. */
  21988. function detect_data_type(s) {
  21989. /* black_mask is the bit mask of black-listed bytes
  21990. * set bits 0..6, 14..25, and 28..31
  21991. * 0xf3ffc07f = binary 11110011111111111100000001111111
  21992. */
  21993. var black_mask = 0xf3ffc07f;
  21994. var n;
  21995. /* Check for non-textual ("black-listed") bytes. */
  21996. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  21997. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  21998. return Z_BINARY;
  21999. }
  22000. }
  22001. /* Check for textual ("white-listed") bytes. */
  22002. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  22003. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  22004. return Z_TEXT;
  22005. }
  22006. for (n = 32; n < LITERALS; n++) {
  22007. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  22008. return Z_TEXT;
  22009. }
  22010. }
  22011. /* There are no "black-listed" or "white-listed" bytes:
  22012. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  22013. */
  22014. return Z_BINARY;
  22015. }
  22016. var static_init_done = false;
  22017. /* ===========================================================================
  22018. * Initialize the tree data structures for a new zlib stream.
  22019. */
  22020. function _tr_init(s)
  22021. {
  22022. if (!static_init_done) {
  22023. tr_static_init();
  22024. static_init_done = true;
  22025. }
  22026. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  22027. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  22028. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  22029. s.bi_buf = 0;
  22030. s.bi_valid = 0;
  22031. /* Initialize the first block of the first file: */
  22032. init_block(s);
  22033. }
  22034. /* ===========================================================================
  22035. * Send a stored block
  22036. */
  22037. function _tr_stored_block(s, buf, stored_len, last)
  22038. //DeflateState *s;
  22039. //charf *buf; /* input block */
  22040. //ulg stored_len; /* length of input block */
  22041. //int last; /* one if this is the last block for a file */
  22042. {
  22043. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  22044. copy_block(s, buf, stored_len, true); /* with header */
  22045. }
  22046. /* ===========================================================================
  22047. * Send one empty static block to give enough lookahead for inflate.
  22048. * This takes 10 bits, of which 7 may remain in the bit buffer.
  22049. */
  22050. function _tr_align(s) {
  22051. send_bits(s, STATIC_TREES<<1, 3);
  22052. send_code(s, END_BLOCK, static_ltree);
  22053. bi_flush(s);
  22054. }
  22055. /* ===========================================================================
  22056. * Determine the best encoding for the current block: dynamic trees, static
  22057. * trees or store, and output the encoded block to the zip file.
  22058. */
  22059. function _tr_flush_block(s, buf, stored_len, last)
  22060. //DeflateState *s;
  22061. //charf *buf; /* input block, or NULL if too old */
  22062. //ulg stored_len; /* length of input block */
  22063. //int last; /* one if this is the last block for a file */
  22064. {
  22065. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  22066. var max_blindex = 0; /* index of last bit length code of non zero freq */
  22067. /* Build the Huffman trees unless a stored block is forced */
  22068. if (s.level > 0) {
  22069. /* Check if the file is binary or text */
  22070. if (s.strm.data_type === Z_UNKNOWN) {
  22071. s.strm.data_type = detect_data_type(s);
  22072. }
  22073. /* Construct the literal and distance trees */
  22074. build_tree(s, s.l_desc);
  22075. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  22076. // s->static_len));
  22077. build_tree(s, s.d_desc);
  22078. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  22079. // s->static_len));
  22080. /* At this point, opt_len and static_len are the total bit lengths of
  22081. * the compressed block data, excluding the tree representations.
  22082. */
  22083. /* Build the bit length tree for the above two trees, and get the index
  22084. * in bl_order of the last bit length code to send.
  22085. */
  22086. max_blindex = build_bl_tree(s);
  22087. /* Determine the best encoding. Compute the block lengths in bytes. */
  22088. opt_lenb = (s.opt_len+3+7) >>> 3;
  22089. static_lenb = (s.static_len+3+7) >>> 3;
  22090. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  22091. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  22092. // s->last_lit));
  22093. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  22094. } else {
  22095. // Assert(buf != (char*)0, "lost buf");
  22096. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  22097. }
  22098. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  22099. /* 4: two words for the lengths */
  22100. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  22101. * Otherwise we can't have processed more than WSIZE input bytes since
  22102. * the last block flush, because compression would have been
  22103. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  22104. * transform a block into a stored block.
  22105. */
  22106. _tr_stored_block(s, buf, stored_len, last);
  22107. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  22108. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  22109. compress_block(s, static_ltree, static_dtree);
  22110. } else {
  22111. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  22112. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  22113. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  22114. }
  22115. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  22116. /* The above check is made mod 2^32, for files larger than 512 MB
  22117. * and uLong implemented on 32 bits.
  22118. */
  22119. init_block(s);
  22120. if (last) {
  22121. bi_windup(s);
  22122. }
  22123. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  22124. // s->compressed_len-7*last));
  22125. }
  22126. /* ===========================================================================
  22127. * Save the match info and tally the frequency counts. Return true if
  22128. * the current block must be flushed.
  22129. */
  22130. function _tr_tally(s, dist, lc)
  22131. // deflate_state *s;
  22132. // unsigned dist; /* distance of matched string */
  22133. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  22134. {
  22135. //var out_length, in_length, dcode;
  22136. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  22137. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  22138. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  22139. s.last_lit++;
  22140. if (dist === 0) {
  22141. /* lc is the unmatched char */
  22142. s.dyn_ltree[lc*2]/*.Freq*/++;
  22143. } else {
  22144. s.matches++;
  22145. /* Here, lc is the match length - MIN_MATCH */
  22146. dist--; /* dist = match distance - 1 */
  22147. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  22148. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  22149. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  22150. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  22151. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  22152. }
  22153. // (!) This block is disabled in zlib defailts,
  22154. // don't enable it for binary compatibility
  22155. //#ifdef TRUNCATE_BLOCK
  22156. // /* Try to guess if it is profitable to stop the current block here */
  22157. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  22158. // /* Compute an upper bound for the compressed length */
  22159. // out_length = s.last_lit*8;
  22160. // in_length = s.strstart - s.block_start;
  22161. //
  22162. // for (dcode = 0; dcode < D_CODES; dcode++) {
  22163. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  22164. // }
  22165. // out_length >>>= 3;
  22166. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  22167. // // s->last_lit, in_length, out_length,
  22168. // // 100L - out_length*100L/in_length));
  22169. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  22170. // return true;
  22171. // }
  22172. // }
  22173. //#endif
  22174. return (s.last_lit === s.lit_bufsize-1);
  22175. /* We avoid equality with lit_bufsize because of wraparound at 64K
  22176. * on 16 bit machines and because stored blocks are restricted to
  22177. * 64K-1 bytes.
  22178. */
  22179. }
  22180. exports._tr_init = _tr_init;
  22181. exports._tr_stored_block = _tr_stored_block;
  22182. exports._tr_flush_block = _tr_flush_block;
  22183. exports._tr_tally = _tr_tally;
  22184. exports._tr_align = _tr_align;
  22185. },{"../utils/common":66}],78:[function(require,module,exports){
  22186. 'use strict';
  22187. function ZStream() {
  22188. /* next input byte */
  22189. this.input = null; // JS specific, because we have no pointers
  22190. this.next_in = 0;
  22191. /* number of bytes available at input */
  22192. this.avail_in = 0;
  22193. /* total number of input bytes read so far */
  22194. this.total_in = 0;
  22195. /* next output byte should be put there */
  22196. this.output = null; // JS specific, because we have no pointers
  22197. this.next_out = 0;
  22198. /* remaining free space at output */
  22199. this.avail_out = 0;
  22200. /* total number of bytes output so far */
  22201. this.total_out = 0;
  22202. /* last error message, NULL if no error */
  22203. this.msg = ''/*Z_NULL*/;
  22204. /* not visible by applications */
  22205. this.state = null;
  22206. /* best guess about the data type: binary or text */
  22207. this.data_type = 2/*Z_UNKNOWN*/;
  22208. /* adler32 value of the uncompressed data */
  22209. this.adler = 0;
  22210. }
  22211. module.exports = ZStream;
  22212. },{}],79:[function(require,module,exports){
  22213. var MediaStreamType = {
  22214. VIDEO_TYPE: "Video",
  22215. AUDIO_TYPE: "Audio"
  22216. };
  22217. module.exports = MediaStreamType;
  22218. },{}],80:[function(require,module,exports){
  22219. var RTCBrowserType = {
  22220. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  22221. RTC_BROWSER_FIREFOX: "rtc_browser.firefox"
  22222. };
  22223. module.exports = RTCBrowserType;
  22224. },{}],81:[function(require,module,exports){
  22225. var RTCEvents = {
  22226. LASTN_CHANGED: "rtc.lastn_changed",
  22227. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  22228. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  22229. SIMULCAST_LAYER_CHANGED: "rtc.simulcast_layer_changed",
  22230. SIMULCAST_LAYER_CHANGING: "rtc.simulcast_layer_changing",
  22231. SIMULCAST_START: "rtc.simlcast_start",
  22232. SIMULCAST_STOP: "rtc.simlcast_stop"
  22233. };
  22234. module.exports = RTCEvents;
  22235. },{}],82:[function(require,module,exports){
  22236. var Resolutions = {
  22237. "1080": {
  22238. width: 1920,
  22239. height: 1080,
  22240. order: 7
  22241. },
  22242. "fullhd": {
  22243. width: 1920,
  22244. height: 1080,
  22245. order: 7
  22246. },
  22247. "720": {
  22248. width: 1280,
  22249. height: 720,
  22250. order: 6
  22251. },
  22252. "hd": {
  22253. width: 1280,
  22254. height: 720,
  22255. order: 6
  22256. },
  22257. "960": {
  22258. width: 960,
  22259. height: 720,
  22260. order: 5
  22261. },
  22262. "640": {
  22263. width: 640,
  22264. height: 480,
  22265. order: 4
  22266. },
  22267. "vga": {
  22268. width: 640,
  22269. height: 480,
  22270. order: 4
  22271. },
  22272. "360": {
  22273. width: 640,
  22274. height: 360,
  22275. order: 3
  22276. },
  22277. "320": {
  22278. width: 320,
  22279. height: 240,
  22280. order: 2
  22281. },
  22282. "180": {
  22283. width: 320,
  22284. height: 180,
  22285. order: 1
  22286. }
  22287. };
  22288. module.exports = Resolutions;
  22289. },{}],83:[function(require,module,exports){
  22290. var StreamEventTypes = {
  22291. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  22292. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  22293. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  22294. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  22295. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended"
  22296. };
  22297. module.exports = StreamEventTypes;
  22298. },{}],84:[function(require,module,exports){
  22299. var UIEvents = {
  22300. NICKNAME_CHANGED: "UI.nickname_changed",
  22301. SELECTED_ENDPOINT: "UI.selected_endpoint",
  22302. PINNED_ENDPOINT: "UI.pinned_endpoint"
  22303. };
  22304. module.exports = UIEvents;
  22305. },{}],85:[function(require,module,exports){
  22306. var AuthenticationEvents = {
  22307. /**
  22308. * Event callback arguments:
  22309. * function(authenticationEnabled, userIdentity)
  22310. * authenticationEnabled - indicates whether authentication has been enabled
  22311. * in this session
  22312. * userIdentity - if user has been logged in then it contains user name. If
  22313. * contains 'null' or 'undefined' then user is not logged in.
  22314. */
  22315. IDENTITY_UPDATED: "authentication.identity_updated"
  22316. };
  22317. module.exports = AuthenticationEvents;
  22318. },{}],86:[function(require,module,exports){
  22319. var CQEvents = {
  22320. LOCALSTATS_UPDATED: "cq.localstats_updated",
  22321. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  22322. STOP: "cq.stop"
  22323. };
  22324. module.exports = CQEvents;
  22325. },{}],87:[function(require,module,exports){
  22326. var DesktopSharingEventTypes = {
  22327. INIT: "ds.init",
  22328. SWITCHING_DONE: "ds.switching_done",
  22329. NEW_STREAM_CREATED: "ds.new_stream_created"
  22330. };
  22331. module.exports = DesktopSharingEventTypes;
  22332. },{}],88:[function(require,module,exports){
  22333. module.exports = {
  22334. getLanguages : function () {
  22335. var languages = [];
  22336. for(var lang in this)
  22337. {
  22338. if(typeof this[lang] === "string")
  22339. languages.push(this[lang]);
  22340. }
  22341. return languages;
  22342. },
  22343. EN: "en"
  22344. }
  22345. },{}],89:[function(require,module,exports){
  22346. var XMPPEvents = {
  22347. CONFERENCE_CERATED: "xmpp.conferenceCreated.jingle",
  22348. CALL_TERMINATED: "xmpp.callterminated.jingle",
  22349. CALL_INCOMING: "xmpp.callincoming.jingle",
  22350. DISPOSE_CONFERENCE: "xmpp.dispoce_confernce",
  22351. KICKED: "xmpp.kicked",
  22352. BRIDGE_DOWN: "xmpp.bridge_down",
  22353. USER_ID_CHANGED: "xmpp.user_id_changed",
  22354. CHANGED_STREAMS: "xmpp.changed_streams",
  22355. MUC_JOINED: "xmpp.muc_joined",
  22356. MUC_ENTER: "xmpp.muc_enter",
  22357. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  22358. MUC_LEFT: "xmpp.muc_left",
  22359. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  22360. REMOTE_STATS: "xmpp.remote_stats",
  22361. LOCALROLE_CHANGED: "xmpp.localrole_changed",
  22362. PRESENCE_STATUS: "xmpp.presence_status",
  22363. SUBJECT_CHANGED: "xmpp.subject_changed",
  22364. MESSAGE_RECEIVED: "xmpp.message_received",
  22365. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  22366. PASSWORD_REQUIRED: "xmpp.password_required",
  22367. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  22368. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  22369. ETHERPAD: "xmpp.etherpad"
  22370. };
  22371. module.exports = XMPPEvents;
  22372. },{}]},{},[2])(2)
  22373. });