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

app.bundle.js 897KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230
  1. !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.APP=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. /* jshint -W117 */
  3. /* application specific logic */
  4. var APP =
  5. {
  6. init: function () {
  7. this.UI = require("./modules/UI/UI");
  8. this.API = require("./modules/API/API");
  9. this.connectionquality = require("./modules/connectionquality/connectionquality");
  10. this.statistics = require("./modules/statistics/statistics");
  11. this.RTC = require("./modules/RTC/RTC");
  12. this.simulcast = require("./modules/simulcast/simulcast");
  13. this.desktopsharing = require("./modules/desktopsharing/desktopsharing");
  14. this.xmpp = require("./modules/xmpp/xmpp");
  15. this.keyboardshortcut = require("./modules/keyboardshortcut/keyboardshortcut");
  16. this.translation = require("./modules/translation/translation");
  17. this.settings = require("./modules/settings/Settings");
  18. }
  19. };
  20. function init() {
  21. APP.RTC.start();
  22. APP.xmpp.start();
  23. APP.statistics.start();
  24. APP.connectionquality.init();
  25. // Set default desktop sharing method
  26. APP.desktopsharing.init();
  27. APP.keyboardshortcut.init();
  28. }
  29. $(document).ready(function () {
  30. APP.init();
  31. APP.translation.init();
  32. if(APP.API.isEnabled())
  33. APP.API.init();
  34. APP.UI.start(init);
  35. });
  36. $(window).bind('beforeunload', function () {
  37. if(APP.API.isEnabled())
  38. APP.API.dispose();
  39. });
  40. module.exports = APP;
  41. },{"./modules/API/API":2,"./modules/RTC/RTC":6,"./modules/UI/UI":8,"./modules/connectionquality/connectionquality":35,"./modules/desktopsharing/desktopsharing":36,"./modules/keyboardshortcut/keyboardshortcut":37,"./modules/settings/Settings":38,"./modules/simulcast/simulcast":43,"./modules/statistics/statistics":46,"./modules/translation/translation":47,"./modules/xmpp/xmpp":61}],2:[function(require,module,exports){
  42. /**
  43. * Implements API class that communicates with external api class
  44. * and provides interface to access Jitsi Meet features by external
  45. * applications that embed Jitsi Meet
  46. */
  47. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  48. /**
  49. * List of the available commands.
  50. * @type {{
  51. * displayName: inputDisplayNameHandler,
  52. * muteAudio: toggleAudio,
  53. * muteVideo: toggleVideo,
  54. * filmStrip: toggleFilmStrip
  55. * }}
  56. */
  57. var commands =
  58. {
  59. displayName: APP.UI.inputDisplayNameHandler,
  60. muteAudio: APP.UI.toggleAudio,
  61. muteVideo: APP.UI.toggleVideo,
  62. toggleFilmStrip: APP.UI.toggleFilmStrip,
  63. toggleChat: APP.UI.toggleChat,
  64. toggleContactList: APP.UI.toggleContactList
  65. };
  66. /**
  67. * Maps the supported events and their status
  68. * (true it the event is enabled and false if it is disabled)
  69. * @type {{
  70. * incomingMessage: boolean,
  71. * outgoingMessage: boolean,
  72. * displayNameChange: boolean,
  73. * participantJoined: boolean,
  74. * participantLeft: boolean
  75. * }}
  76. */
  77. var events =
  78. {
  79. incomingMessage: false,
  80. outgoingMessage:false,
  81. displayNameChange: false,
  82. participantJoined: false,
  83. participantLeft: false
  84. };
  85. var displayName = {};
  86. /**
  87. * Processes commands from external applicaiton.
  88. * @param message the object with the command
  89. */
  90. function processCommand(message)
  91. {
  92. if(message.action != "execute")
  93. {
  94. console.error("Unknown action of the message");
  95. return;
  96. }
  97. for(var key in message)
  98. {
  99. if(commands[key])
  100. commands[key].apply(null, message[key]);
  101. }
  102. }
  103. /**
  104. * Processes events objects from external applications
  105. * @param event the event
  106. */
  107. function processEvent(event) {
  108. if(!event.action)
  109. {
  110. console.error("Event with no action is received.");
  111. return;
  112. }
  113. var i = 0;
  114. switch(event.action)
  115. {
  116. case "add":
  117. for(; i < event.events.length; i++)
  118. {
  119. events[event.events[i]] = true;
  120. }
  121. break;
  122. case "remove":
  123. for(; i < event.events.length; i++)
  124. {
  125. events[event.events[i]] = false;
  126. }
  127. break;
  128. default:
  129. console.error("Unknown action for event.");
  130. }
  131. }
  132. /**
  133. * Sends message to the external application.
  134. * @param object
  135. */
  136. function sendMessage(object) {
  137. window.parent.postMessage(JSON.stringify(object), "*");
  138. }
  139. /**
  140. * Processes a message event from the external application
  141. * @param event the message event
  142. */
  143. function processMessage(event)
  144. {
  145. var message;
  146. try {
  147. message = JSON.parse(event.data);
  148. } catch (e) {}
  149. if(!message.type)
  150. return;
  151. switch (message.type)
  152. {
  153. case "command":
  154. processCommand(message);
  155. break;
  156. case "event":
  157. processEvent(message);
  158. break;
  159. default:
  160. console.error("Unknown type of the message");
  161. return;
  162. }
  163. }
  164. function setupListeners() {
  165. APP.xmpp.addListener(XMPPEvents.MUC_ENTER, function (from) {
  166. API.triggerEvent("participantJoined", {jid: from});
  167. });
  168. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid) {
  169. if (from != myjid)
  170. API.triggerEvent("incomingMessage",
  171. {"from": from, "nick": nick, "message": txt});
  172. });
  173. APP.xmpp.addListener(XMPPEvents.MUC_LEFT, function (jid) {
  174. API.triggerEvent("participantLeft", {jid: jid});
  175. });
  176. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {
  177. name = displayName[jid];
  178. if(!name || name != newDisplayName) {
  179. API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});
  180. displayName[jid] = newDisplayName;
  181. }
  182. });
  183. APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {
  184. APP.API.triggerEvent("outgoingMessage", {"message": body});
  185. });
  186. }
  187. var API = {
  188. /**
  189. * Check whether the API should be enabled or not.
  190. * @returns {boolean}
  191. */
  192. isEnabled: function () {
  193. var hash = location.hash;
  194. if(hash && hash.indexOf("external") > -1 && window.postMessage)
  195. return true;
  196. return false;
  197. },
  198. /**
  199. * Initializes the APIConnector. Setups message event listeners that will
  200. * receive information from external applications that embed Jitsi Meet.
  201. * It also sends a message to the external application that APIConnector
  202. * is initialized.
  203. */
  204. init: function () {
  205. if (window.addEventListener)
  206. {
  207. window.addEventListener('message',
  208. processMessage, false);
  209. }
  210. else
  211. {
  212. window.attachEvent('onmessage', processMessage);
  213. }
  214. sendMessage({type: "system", loaded: true});
  215. setupListeners();
  216. },
  217. /**
  218. * Checks whether the event is enabled ot not.
  219. * @param name the name of the event.
  220. * @returns {*}
  221. */
  222. isEventEnabled: function (name) {
  223. return events[name];
  224. },
  225. /**
  226. * Sends event object to the external application that has been subscribed
  227. * for that event.
  228. * @param name the name event
  229. * @param object data associated with the event
  230. */
  231. triggerEvent: function (name, object) {
  232. if(this.isEnabled() && this.isEventEnabled(name))
  233. sendMessage({
  234. type: "event", action: "result", event: name, result: object});
  235. },
  236. /**
  237. * Removes the listeners.
  238. */
  239. dispose: function () {
  240. if(window.removeEventListener)
  241. {
  242. window.removeEventListener("message",
  243. processMessage, false);
  244. }
  245. else
  246. {
  247. window.detachEvent('onmessage', processMessage);
  248. }
  249. }
  250. };
  251. module.exports = API;
  252. },{"../../service/xmpp/XMPPEvents":97}],3:[function(require,module,exports){
  253. /* global Strophe, focusedVideoSrc*/
  254. // cache datachannels to avoid garbage collection
  255. // https://code.google.com/p/chromium/issues/detail?id=405545
  256. var RTCEvents = require("../../service/RTC/RTCEvents");
  257. var _dataChannels = [];
  258. var eventEmitter = null;
  259. var DataChannels =
  260. {
  261. /**
  262. * Callback triggered by PeerConnection when new data channel is opened
  263. * on the bridge.
  264. * @param event the event info object.
  265. */
  266. onDataChannel: function (event)
  267. {
  268. var dataChannel = event.channel;
  269. dataChannel.onopen = function () {
  270. console.info("Data channel opened by the Videobridge!", dataChannel);
  271. // Code sample for sending string and/or binary data
  272. // Sends String message to the bridge
  273. //dataChannel.send("Hello bridge!");
  274. // Sends 12 bytes binary message to the bridge
  275. //dataChannel.send(new ArrayBuffer(12));
  276. // when the data channel becomes available, tell the bridge about video
  277. // selections so that it can do adaptive simulcast,
  278. // we want the notification to trigger even if userJid is undefined,
  279. // or null.
  280. var userJid = APP.UI.getLargeVideoState().userResourceJid;
  281. // we want the notification to trigger even if userJid is undefined,
  282. // or null.
  283. onSelectedEndpointChanged(userJid);
  284. };
  285. dataChannel.onerror = function (error) {
  286. console.error("Data Channel Error:", error, dataChannel);
  287. };
  288. dataChannel.onmessage = function (event) {
  289. var data = event.data;
  290. // JSON
  291. var obj;
  292. try {
  293. obj = JSON.parse(data);
  294. }
  295. catch (e) {
  296. console.error(
  297. "Failed to parse data channel message as JSON: ",
  298. data,
  299. dataChannel);
  300. }
  301. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  302. var colibriClass = obj.colibriClass;
  303. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  304. // Endpoint ID from the Videobridge.
  305. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  306. console.info(
  307. "Data channel new dominant speaker event: ",
  308. dominantSpeakerEndpoint);
  309. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  310. }
  311. else if ("InLastNChangeEvent" === colibriClass)
  312. {
  313. var oldValue = obj.oldValue;
  314. var newValue = obj.newValue;
  315. // Make sure that oldValue and newValue are of type boolean.
  316. var type;
  317. if ((type = typeof oldValue) !== 'boolean') {
  318. if (type === 'string') {
  319. oldValue = (oldValue == "true");
  320. } else {
  321. oldValue = new Boolean(oldValue).valueOf();
  322. }
  323. }
  324. if ((type = typeof newValue) !== 'boolean') {
  325. if (type === 'string') {
  326. newValue = (newValue == "true");
  327. } else {
  328. newValue = new Boolean(newValue).valueOf();
  329. }
  330. }
  331. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  332. }
  333. else if ("LastNEndpointsChangeEvent" === colibriClass)
  334. {
  335. // The new/latest list of last-n endpoint IDs.
  336. var lastNEndpoints = obj.lastNEndpoints;
  337. // The list of endpoint IDs which are entering the list of
  338. // last-n at this time i.e. were not in the old list of last-n
  339. // endpoint IDs.
  340. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  341. var stream = obj.stream;
  342. console.log(
  343. "Data channel new last-n event: ",
  344. lastNEndpoints, endpointsEnteringLastN, obj);
  345. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  346. lastNEndpoints, endpointsEnteringLastN, obj);
  347. }
  348. else if ("SimulcastLayersChangedEvent" === colibriClass)
  349. {
  350. eventEmitter.emit(RTCEvents.SIMULCAST_LAYER_CHANGED,
  351. obj.endpointSimulcastLayers);
  352. }
  353. else if ("SimulcastLayersChangingEvent" === colibriClass)
  354. {
  355. eventEmitter.emit(RTCEvents.SIMULCAST_LAYER_CHANGING,
  356. obj.endpointSimulcastLayers);
  357. }
  358. else if ("StartSimulcastLayerEvent" === colibriClass)
  359. {
  360. eventEmitter.emit(RTCEvents.SIMULCAST_START, obj.simulcastLayer);
  361. }
  362. else if ("StopSimulcastLayerEvent" === colibriClass)
  363. {
  364. eventEmitter.emit(RTCEvents.SIMULCAST_STOP, obj.simulcastLayer);
  365. }
  366. else
  367. {
  368. console.debug("Data channel JSON-formatted message: ", obj);
  369. }
  370. }
  371. };
  372. dataChannel.onclose = function ()
  373. {
  374. console.info("The Data Channel closed", dataChannel);
  375. var idx = _dataChannels.indexOf(dataChannel);
  376. if (idx > -1)
  377. _dataChannels = _dataChannels.splice(idx, 1);
  378. };
  379. _dataChannels.push(dataChannel);
  380. },
  381. /**
  382. * Binds "ondatachannel" event listener to given PeerConnection instance.
  383. * @param peerConnection WebRTC peer connection instance.
  384. */
  385. init: function (peerConnection, emitter) {
  386. if(!config.openSctp)
  387. return;
  388. peerConnection.ondatachannel = this.onDataChannel;
  389. eventEmitter = emitter;
  390. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  391. // Although it's not a requirement to open separate channels from both bridge
  392. // and peer as single channel can be used for sending and receiving data.
  393. // So either channel opened by the bridge or the one opened here is enough
  394. // for communication with the bridge.
  395. /*var dataChannelOptions =
  396. {
  397. reliable: true
  398. };
  399. var dataChannel
  400. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  401. // Can be used only when is in open state
  402. dataChannel.onopen = function ()
  403. {
  404. dataChannel.send("My channel !!!");
  405. };
  406. dataChannel.onmessage = function (event)
  407. {
  408. var msgData = event.data;
  409. console.info("Got My Data Channel Message:", msgData, dataChannel);
  410. };*/
  411. },
  412. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  413. handlePinnedEndpointEvent: onPinnedEndpointChanged
  414. };
  415. function onSelectedEndpointChanged(userResource)
  416. {
  417. console.log('selected endpoint changed: ', userResource);
  418. if (_dataChannels && _dataChannels.length != 0)
  419. {
  420. _dataChannels.some(function (dataChannel) {
  421. if (dataChannel.readyState == 'open')
  422. {
  423. console.log('sending selected endpoint changed '
  424. + 'notification to the bridge: ', userResource);
  425. dataChannel.send(JSON.stringify({
  426. 'colibriClass': 'SelectedEndpointChangedEvent',
  427. 'selectedEndpoint':
  428. (!userResource || userResource === null)?
  429. null : userResource
  430. }));
  431. return true;
  432. }
  433. });
  434. }
  435. }
  436. function onPinnedEndpointChanged(userResource)
  437. {
  438. console.log('pinned endpoint changed: ', userResource);
  439. if (_dataChannels && _dataChannels.length != 0)
  440. {
  441. _dataChannels.some(function (dataChannel) {
  442. if (dataChannel.readyState == 'open')
  443. {
  444. dataChannel.send(JSON.stringify({
  445. 'colibriClass': 'PinnedEndpointChangedEvent',
  446. 'pinnedEndpoint':
  447. (!userResource || userResource == null)?
  448. null : userResource
  449. }));
  450. return true;
  451. }
  452. });
  453. }
  454. }
  455. module.exports = DataChannels;
  456. },{"../../service/RTC/RTCEvents":89}],4:[function(require,module,exports){
  457. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  458. function LocalStream(stream, type, eventEmitter, videoType)
  459. {
  460. this.stream = stream;
  461. this.eventEmitter = eventEmitter;
  462. this.type = type;
  463. this.videoType = videoType;
  464. var self = this;
  465. if(type == "audio")
  466. {
  467. this.getTracks = function () {
  468. return self.stream.getAudioTracks();
  469. };
  470. }
  471. else
  472. {
  473. this.getTracks = function () {
  474. return self.stream.getVideoTracks();
  475. };
  476. }
  477. this.stream.onended = function()
  478. {
  479. self.streamEnded();
  480. };
  481. }
  482. LocalStream.prototype.streamEnded = function () {
  483. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  484. }
  485. LocalStream.prototype.getOriginalStream = function()
  486. {
  487. return this.stream;
  488. }
  489. LocalStream.prototype.isAudioStream = function () {
  490. return (this.stream.getAudioTracks() && this.stream.getAudioTracks().length > 0);
  491. };
  492. LocalStream.prototype.mute = function()
  493. {
  494. var ismuted = false;
  495. var tracks = this.getTracks();
  496. for (var idx = 0; idx < tracks.length; idx++) {
  497. ismuted = !tracks[idx].enabled;
  498. tracks[idx].enabled = ismuted;
  499. }
  500. return ismuted;
  501. };
  502. LocalStream.prototype.setMute = function(mute)
  503. {
  504. var tracks = this.getTracks();
  505. for (var idx = 0; idx < tracks.length; idx++) {
  506. tracks[idx].enabled = mute;
  507. }
  508. };
  509. LocalStream.prototype.isMuted = function () {
  510. var tracks = [];
  511. if(this.type == "audio")
  512. {
  513. tracks = this.stream.getAudioTracks();
  514. }
  515. else
  516. {
  517. tracks = this.stream.getVideoTracks();
  518. }
  519. for (var idx = 0; idx < tracks.length; idx++) {
  520. if(tracks[idx].enabled)
  521. return false;
  522. }
  523. return true;
  524. }
  525. LocalStream.prototype.getId = function () {
  526. return this.stream.getTracks()[0].id;
  527. }
  528. module.exports = LocalStream;
  529. },{"../../service/RTC/StreamEventTypes.js":91}],5:[function(require,module,exports){
  530. ////These lines should be uncommented when require works in app.js
  531. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  532. var StreamEventType = require("../../service/RTC/StreamEventTypes");
  533. /**
  534. * Creates a MediaStream object for the given data, session id and ssrc.
  535. * It is a wrapper class for the MediaStream.
  536. *
  537. * @param data the data object from which we obtain the stream,
  538. * the peerjid, etc.
  539. * @param sid the session id
  540. * @param ssrc the ssrc corresponding to this MediaStream
  541. *
  542. * @constructor
  543. */
  544. function MediaStream(data, sid, ssrc, browser, eventEmitter) {
  545. // XXX(gp) to minimize headaches in the future, we should build our
  546. // abstractions around tracks and not streams. ORTC is track based API.
  547. // Mozilla expects m-lines to represent media tracks.
  548. //
  549. // Practically, what I'm saying is that we should have a MediaTrack class
  550. // and not a MediaStream class.
  551. //
  552. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  553. // a track might have an associated RTX and FEC sources.
  554. this.sid = sid;
  555. this.stream = data.stream;
  556. this.peerjid = data.peerjid;
  557. this.ssrc = ssrc;
  558. this.type = (this.stream.getVideoTracks().length > 0)?
  559. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  560. this.videoType = null;
  561. this.muted = false;
  562. this.eventEmitter = eventEmitter;
  563. }
  564. MediaStream.prototype.getOriginalStream = function()
  565. {
  566. return this.stream;
  567. };
  568. MediaStream.prototype.setMute = function (value)
  569. {
  570. this.stream.muted = value;
  571. this.muted = value;
  572. };
  573. MediaStream.prototype.setVideoType = function (value) {
  574. if(this.videoType === value)
  575. return;
  576. this.videoType = value;
  577. this.eventEmitter.emit(StreamEventType.EVENT_TYPE_REMOTE_CHANGED,
  578. this.peerjid);
  579. };
  580. module.exports = MediaStream;
  581. },{"../../service/RTC/MediaStreamTypes":87,"../../service/RTC/StreamEventTypes":91}],6:[function(require,module,exports){
  582. var EventEmitter = require("events");
  583. var RTCUtils = require("./RTCUtils.js");
  584. var LocalStream = require("./LocalStream.js");
  585. var DataChannels = require("./DataChannels");
  586. var MediaStream = require("./MediaStream.js");
  587. var DesktopSharingEventTypes
  588. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  589. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  590. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  591. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  592. var UIEvents = require("../../service/UI/UIEvents");
  593. var eventEmitter = new EventEmitter();
  594. var RTC = {
  595. rtcUtils: null,
  596. localStreams: [],
  597. remoteStreams: {},
  598. localAudio: null,
  599. localVideo: null,
  600. addStreamListener: function (listener, eventType) {
  601. eventEmitter.on(eventType, listener);
  602. },
  603. addListener: function (type, listener) {
  604. eventEmitter.on(type, listener);
  605. },
  606. removeStreamListener: function (listener, eventType) {
  607. if(!(eventType instanceof StreamEventTypes))
  608. throw "Illegal argument";
  609. eventEmitter.removeListener(eventType, listener);
  610. },
  611. createLocalStream: function (stream, type, change) {
  612. var localStream = new LocalStream(stream, type, eventEmitter);
  613. //in firefox we have only one stream object
  614. if(this.localStreams.length == 0 ||
  615. this.localStreams[0].getOriginalStream() != stream)
  616. this.localStreams.push(localStream);
  617. if(type == "audio")
  618. {
  619. this.localAudio = localStream;
  620. }
  621. else
  622. {
  623. this.localVideo = localStream;
  624. }
  625. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  626. if(change)
  627. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  628. eventEmitter.emit(eventType, localStream);
  629. return localStream;
  630. },
  631. removeLocalStream: function (stream) {
  632. for(var i = 0; i < this.localStreams.length; i++)
  633. {
  634. if(this.localStreams[i].getOriginalStream() === stream) {
  635. delete this.localStreams[i];
  636. return;
  637. }
  638. }
  639. },
  640. createRemoteStream: function (data, sid, thessrc) {
  641. var remoteStream = new MediaStream(data, sid, thessrc,
  642. this.getBrowserType(), eventEmitter);
  643. var jid = data.peerjid || APP.xmpp.myJid();
  644. if(!this.remoteStreams[jid]) {
  645. this.remoteStreams[jid] = {};
  646. }
  647. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  648. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  649. return remoteStream;
  650. },
  651. getBrowserType: function () {
  652. return this.rtcUtils.browser;
  653. },
  654. getPCConstraints: function () {
  655. return this.rtcUtils.pc_constraints;
  656. },
  657. getUserMediaWithConstraints:function(um, success_callback,
  658. failure_callback, resolution,
  659. bandwidth, fps, desktopStream)
  660. {
  661. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  662. failure_callback, resolution, bandwidth, fps, desktopStream);
  663. },
  664. attachMediaStream: function (element, stream) {
  665. this.rtcUtils.attachMediaStream(element, stream);
  666. },
  667. getStreamID: function (stream) {
  668. return this.rtcUtils.getStreamID(stream);
  669. },
  670. getVideoSrc: function (element) {
  671. return this.rtcUtils.getVideoSrc(element);
  672. },
  673. setVideoSrc: function (element, src) {
  674. this.rtcUtils.setVideoSrc(element, src);
  675. },
  676. dispose: function() {
  677. if (this.rtcUtils) {
  678. this.rtcUtils = null;
  679. }
  680. },
  681. stop: function () {
  682. this.dispose();
  683. },
  684. start: function () {
  685. var self = this;
  686. APP.desktopsharing.addListener(
  687. function (stream, isUsingScreenStream, callback) {
  688. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  689. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  690. APP.xmpp.addListener(XMPPEvents.CHANGED_STREAMS, function (jid, changedStreams) {
  691. for(var i = 0; i < changedStreams.length; i++) {
  692. var type = changedStreams[i].type;
  693. if (type != "audio") {
  694. var peerStreams = self.remoteStreams[jid];
  695. if(!peerStreams)
  696. continue;
  697. var videoStream = peerStreams[MediaStreamType.VIDEO_TYPE];
  698. if(!videoStream)
  699. continue;
  700. videoStream.setVideoType(changedStreams[i].type);
  701. }
  702. }
  703. });
  704. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  705. DataChannels.init(event.peerconnection, eventEmitter);
  706. });
  707. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  708. DataChannels.handleSelectedEndpointEvent);
  709. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  710. DataChannels.handlePinnedEndpointEvent);
  711. this.rtcUtils = new RTCUtils(this);
  712. this.rtcUtils.obtainAudioAndVideoPermissions();
  713. },
  714. muteRemoteVideoStream: function (jid, value) {
  715. var stream;
  716. if(this.remoteStreams[jid] &&
  717. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE])
  718. {
  719. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  720. }
  721. if(!stream)
  722. return false;
  723. if (value != stream.muted) {
  724. stream.setMute(value);
  725. return true;
  726. }
  727. return false;
  728. },
  729. switchVideoStreams: function (new_stream) {
  730. this.localVideo.stream = new_stream;
  731. this.localStreams = [];
  732. //in firefox we have only one stream object
  733. if (this.localAudio.getOriginalStream() != new_stream)
  734. this.localStreams.push(this.localAudio);
  735. this.localStreams.push(this.localVideo);
  736. },
  737. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  738. var oldStream = this.localVideo.getOriginalStream();
  739. var type = (isUsingScreenStream? "screen" : "video");
  740. this.localVideo = this.createLocalStream(stream, "video", true, type);
  741. // Stop the stream to trigger onended event for old stream
  742. oldStream.stop();
  743. APP.xmpp.switchStreams(stream, oldStream,callback);
  744. },
  745. /**
  746. * Checks if video identified by given src is desktop stream.
  747. * @param videoSrc eg.
  748. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  749. * @returns {boolean}
  750. */
  751. isVideoSrcDesktop: function (jid) {
  752. if(!jid)
  753. return false;
  754. var isDesktop = false;
  755. var stream = null;
  756. if (APP.xmpp.myJid() === jid) {
  757. // local video
  758. stream = this.localVideo;
  759. } else {
  760. var peerStreams = this.remoteStreams[jid];
  761. if(!peerStreams)
  762. return false;
  763. stream = peerStreams[MediaStreamType.VIDEO_TYPE];
  764. }
  765. if(stream)
  766. isDesktop = (stream.videoType === "screen");
  767. return isDesktop;
  768. }
  769. };
  770. module.exports = RTC;
  771. },{"../../service/RTC/MediaStreamTypes":87,"../../service/RTC/StreamEventTypes.js":91,"../../service/UI/UIEvents":92,"../../service/desktopsharing/DesktopSharingEventTypes":95,"../../service/xmpp/XMPPEvents":97,"./DataChannels":3,"./LocalStream.js":4,"./MediaStream.js":5,"./RTCUtils.js":7,"events":98}],7:[function(require,module,exports){
  772. var RTCBrowserType = require("../../service/RTC/RTCBrowserType.js");
  773. var Resolutions = require("../../service/RTC/Resolutions");
  774. var currentResolution = null;
  775. function getPreviousResolution(resolution) {
  776. if(!Resolutions[resolution])
  777. return null;
  778. var order = Resolutions[resolution].order;
  779. var res = null;
  780. var resName = null;
  781. for(var i in Resolutions)
  782. {
  783. var tmp = Resolutions[i];
  784. if(res == null || (res.order < tmp.order && tmp.order < order))
  785. {
  786. resName = i;
  787. res = tmp;
  788. }
  789. }
  790. return resName;
  791. }
  792. function setResolutionConstraints(constraints, resolution, isAndroid)
  793. {
  794. if (resolution && !constraints.video || isAndroid) {
  795. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  796. }
  797. if(Resolutions[resolution])
  798. {
  799. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  800. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  801. }
  802. else
  803. {
  804. if (isAndroid) {
  805. constraints.video.mandatory.minWidth = 320;
  806. constraints.video.mandatory.minHeight = 240;
  807. constraints.video.mandatory.maxFrameRate = 15;
  808. }
  809. }
  810. if (constraints.video.mandatory.minWidth)
  811. constraints.video.mandatory.maxWidth = constraints.video.mandatory.minWidth;
  812. if (constraints.video.mandatory.minHeight)
  813. constraints.video.mandatory.maxHeight = constraints.video.mandatory.minHeight;
  814. }
  815. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  816. {
  817. var constraints = {audio: false, video: false};
  818. if (um.indexOf('video') >= 0) {
  819. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  820. }
  821. if (um.indexOf('audio') >= 0) {
  822. constraints.audio = { mandatory: {}, optional: []};// same behaviour as true
  823. }
  824. if (um.indexOf('screen') >= 0) {
  825. constraints.video = {
  826. mandatory: {
  827. chromeMediaSource: "screen",
  828. googLeakyBucket: true,
  829. maxWidth: window.screen.width,
  830. maxHeight: window.screen.height,
  831. maxFrameRate: 3
  832. },
  833. optional: []
  834. };
  835. }
  836. if (um.indexOf('desktop') >= 0) {
  837. constraints.video = {
  838. mandatory: {
  839. chromeMediaSource: "desktop",
  840. chromeMediaSourceId: desktopStream,
  841. googLeakyBucket: true,
  842. maxWidth: window.screen.width,
  843. maxHeight: window.screen.height,
  844. maxFrameRate: 3
  845. },
  846. optional: []
  847. };
  848. }
  849. if (constraints.audio) {
  850. // if it is good enough for hangouts...
  851. constraints.audio.optional.push(
  852. {googEchoCancellation: true},
  853. {googAutoGainControl: true},
  854. {googNoiseSupression: true},
  855. {googHighpassFilter: true},
  856. {googNoisesuppression2: true},
  857. {googEchoCancellation2: true},
  858. {googAutoGainControl2: true}
  859. );
  860. }
  861. if (constraints.video) {
  862. constraints.video.optional.push(
  863. {googNoiseReduction: false} // chrome 37 workaround for issue 3807, reenable in M38
  864. );
  865. if (um.indexOf('video') >= 0) {
  866. constraints.video.optional.push(
  867. {googLeakyBucket: true}
  868. );
  869. }
  870. }
  871. if (um.indexOf('video') >= 0) {
  872. setResolutionConstraints(constraints, resolution, isAndroid);
  873. }
  874. if (bandwidth) { // doesn't work currently, see webrtc issue 1846
  875. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};//same behaviour as true
  876. constraints.video.optional.push({bandwidth: bandwidth});
  877. }
  878. if (fps) { // for some cameras it might be necessary to request 30fps
  879. // so they choose 30fps mjpg over 10fps yuy2
  880. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};// same behaviour as true;
  881. constraints.video.mandatory.minFrameRate = fps;
  882. }
  883. return constraints;
  884. }
  885. function RTCUtils(RTCService)
  886. {
  887. this.service = RTCService;
  888. if (navigator.mozGetUserMedia) {
  889. console.log('This appears to be Firefox');
  890. var version = parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  891. if (version >= 39) {
  892. this.peerconnection = mozRTCPeerConnection;
  893. this.browser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  894. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  895. this.pc_constraints = {};
  896. this.attachMediaStream = function (element, stream) {
  897. // srcObject is being standardized and FF will eventually
  898. // support that unprefixed. FF also supports the
  899. // "element.src = URL.createObjectURL(...)" combo, but that
  900. // will be deprecated in favour of srcObject.
  901. //
  902. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  903. // https://github.com/webrtc/samples/issues/302
  904. element[0].mozSrcObject = stream;
  905. element[0].play();
  906. };
  907. this.getStreamID = function (stream) {
  908. var tracks = stream.getVideoTracks();
  909. if(!tracks || tracks.length == 0)
  910. {
  911. tracks = stream.getAudioTracks();
  912. }
  913. return tracks[0].id.replace(/[\{,\}]/g,"");
  914. };
  915. this.getVideoSrc = function (element) {
  916. return element.mozSrcObject;
  917. };
  918. this.setVideoSrc = function (element, src) {
  919. element.mozSrcObject = src;
  920. };
  921. RTCSessionDescription = mozRTCSessionDescription;
  922. RTCIceCandidate = mozRTCIceCandidate;
  923. } else {
  924. window.location.href = 'unsupported_browser.html';
  925. return;
  926. }
  927. } else if (navigator.webkitGetUserMedia) {
  928. console.log('This appears to be Chrome');
  929. this.peerconnection = webkitRTCPeerConnection;
  930. this.browser = RTCBrowserType.RTC_BROWSER_CHROME;
  931. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  932. this.attachMediaStream = function (element, stream) {
  933. element.attr('src', webkitURL.createObjectURL(stream));
  934. };
  935. this.getStreamID = function (stream) {
  936. // streams from FF endpoints have the characters '{' and '}'
  937. // that make jQuery choke.
  938. return stream.id.replace(/[\{,\}]/g,"");
  939. };
  940. this.getVideoSrc = function (element) {
  941. return element.getAttribute("src");
  942. };
  943. this.setVideoSrc = function (element, src) {
  944. element.setAttribute("src", src);
  945. };
  946. // DTLS should now be enabled by default but..
  947. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  948. if (navigator.userAgent.indexOf('Android') != -1) {
  949. this.pc_constraints = {}; // disable DTLS on Android
  950. }
  951. if (!webkitMediaStream.prototype.getVideoTracks) {
  952. webkitMediaStream.prototype.getVideoTracks = function () {
  953. return this.videoTracks;
  954. };
  955. }
  956. if (!webkitMediaStream.prototype.getAudioTracks) {
  957. webkitMediaStream.prototype.getAudioTracks = function () {
  958. return this.audioTracks;
  959. };
  960. }
  961. }
  962. else
  963. {
  964. try { console.log('Browser does not appear to be WebRTC-capable'); } catch (e) { }
  965. window.location.href = 'unsupported_browser.html';
  966. return;
  967. }
  968. }
  969. RTCUtils.prototype.getUserMediaWithConstraints = function(
  970. um, success_callback, failure_callback, resolution,bandwidth, fps,
  971. desktopStream)
  972. {
  973. currentResolution = resolution;
  974. // Check if we are running on Android device
  975. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  976. var constraints = getConstraints(
  977. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  978. var isFF = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
  979. try {
  980. if (config.enableSimulcast
  981. && constraints.video
  982. && constraints.video.chromeMediaSource !== 'screen'
  983. && constraints.video.chromeMediaSource !== 'desktop'
  984. && !isAndroid
  985. // We currently do not support FF, as it doesn't have multistream support.
  986. && !isFF) {
  987. APP.simulcast.getUserMedia(constraints, function (stream) {
  988. console.log('onUserMediaSuccess');
  989. success_callback(stream);
  990. },
  991. function (error) {
  992. console.warn('Failed to get access to local media. Error ', error);
  993. if (failure_callback) {
  994. failure_callback(error);
  995. }
  996. });
  997. } else {
  998. this.getUserMedia(constraints,
  999. function (stream) {
  1000. console.log('onUserMediaSuccess');
  1001. success_callback(stream);
  1002. },
  1003. function (error) {
  1004. console.warn('Failed to get access to local media. Error ',
  1005. error, constraints);
  1006. if (failure_callback) {
  1007. failure_callback(error);
  1008. }
  1009. });
  1010. }
  1011. } catch (e) {
  1012. console.error('GUM failed: ', e);
  1013. if(failure_callback) {
  1014. failure_callback(e);
  1015. }
  1016. }
  1017. };
  1018. /**
  1019. * We ask for audio and video combined stream in order to get permissions and
  1020. * not to ask twice.
  1021. */
  1022. RTCUtils.prototype.obtainAudioAndVideoPermissions = function() {
  1023. var self = this;
  1024. // Get AV
  1025. this.getUserMediaWithConstraints(
  1026. ['audio', 'video'],
  1027. function (stream) {
  1028. self.successCallback(stream);
  1029. },
  1030. function (error) {
  1031. self.errorCallback(error);
  1032. },
  1033. config.resolution || '360');
  1034. }
  1035. RTCUtils.prototype.successCallback = function (stream) {
  1036. console.log('got', stream, stream.getAudioTracks().length,
  1037. stream.getVideoTracks().length);
  1038. this.handleLocalStream(stream);
  1039. };
  1040. RTCUtils.prototype.errorCallback = function (error) {
  1041. var self = this;
  1042. console.error('failed to obtain audio/video stream - trying audio only', error);
  1043. var resolution = getPreviousResolution(currentResolution);
  1044. if(typeof error == "object" && error.constraintName && error.name
  1045. && (error.name == "ConstraintNotSatisfiedError" ||
  1046. error.name == "OverconstrainedError") &&
  1047. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1048. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1049. && resolution != null)
  1050. {
  1051. self.getUserMediaWithConstraints(['audio', 'video'],
  1052. function (stream) {
  1053. return self.successCallback(stream);
  1054. }, function (error) {
  1055. return self.errorCallback(error);
  1056. }, resolution);
  1057. }
  1058. else
  1059. {
  1060. self.getUserMediaWithConstraints(
  1061. ['audio'],
  1062. function (stream) {
  1063. return self.successCallback(stream);
  1064. },
  1065. function (error) {
  1066. console.error('failed to obtain audio/video stream - stop',
  1067. error);
  1068. APP.UI.messageHandler.showError("dialog.error",
  1069. "dialog.failedpermissions");
  1070. }
  1071. );
  1072. }
  1073. }
  1074. RTCUtils.prototype.handleLocalStream = function(stream)
  1075. {
  1076. if(window.webkitMediaStream)
  1077. {
  1078. var audioStream = new webkitMediaStream();
  1079. var videoStream = new webkitMediaStream();
  1080. var audioTracks = stream.getAudioTracks();
  1081. var videoTracks = stream.getVideoTracks();
  1082. for (var i = 0; i < audioTracks.length; i++) {
  1083. audioStream.addTrack(audioTracks[i]);
  1084. }
  1085. this.service.createLocalStream(audioStream, "audio");
  1086. for (i = 0; i < videoTracks.length; i++) {
  1087. videoStream.addTrack(videoTracks[i]);
  1088. }
  1089. this.service.createLocalStream(videoStream, "video");
  1090. }
  1091. else
  1092. {//firefox
  1093. this.service.createLocalStream(stream, "stream");
  1094. }
  1095. };
  1096. module.exports = RTCUtils;
  1097. },{"../../service/RTC/RTCBrowserType.js":88,"../../service/RTC/Resolutions":90}],8:[function(require,module,exports){
  1098. var UI = {};
  1099. var VideoLayout = require("./videolayout/VideoLayout.js");
  1100. var AudioLevels = require("./audio_levels/AudioLevels.js");
  1101. var Prezi = require("./prezi/Prezi.js");
  1102. var Etherpad = require("./etherpad/Etherpad.js");
  1103. var Chat = require("./side_pannels/chat/Chat.js");
  1104. var Toolbar = require("./toolbars/Toolbar");
  1105. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  1106. var BottomToolbar = require("./toolbars/BottomToolbar");
  1107. var ContactList = require("./side_pannels/contactlist/ContactList");
  1108. var Avatar = require("./avatar/Avatar");
  1109. var EventEmitter = require("events");
  1110. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  1111. var Settings = require("./../settings/Settings");
  1112. var PanelToggler = require("./side_pannels/SidePanelToggler");
  1113. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  1114. UI.messageHandler = require("./util/MessageHandler");
  1115. var messageHandler = UI.messageHandler;
  1116. var Authentication = require("./authentication/Authentication");
  1117. var UIUtil = require("./util/UIUtil");
  1118. var NicknameHandler = require("./util/NicknameHandler");
  1119. var CQEvents = require("../../service/connectionquality/CQEvents");
  1120. var DesktopSharingEventTypes
  1121. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1122. var RTCEvents = require("../../service/RTC/RTCEvents");
  1123. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  1124. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  1125. var eventEmitter = new EventEmitter();
  1126. var roomName = null;
  1127. function setupPrezi()
  1128. {
  1129. $("#reloadPresentationLink").click(function()
  1130. {
  1131. Prezi.reloadPresentation();
  1132. });
  1133. }
  1134. function setupChat()
  1135. {
  1136. Chat.init();
  1137. $("#toggle_smileys").click(function() {
  1138. Chat.toggleSmileys();
  1139. });
  1140. }
  1141. function setupToolbars() {
  1142. Toolbar.init(UI);
  1143. Toolbar.setupButtonsFromConfig();
  1144. BottomToolbar.init();
  1145. }
  1146. function streamHandler(stream) {
  1147. switch (stream.type)
  1148. {
  1149. case "audio":
  1150. VideoLayout.changeLocalAudio(stream);
  1151. break;
  1152. case "video":
  1153. VideoLayout.changeLocalVideo(stream);
  1154. break;
  1155. case "stream":
  1156. VideoLayout.changeLocalStream(stream);
  1157. break;
  1158. }
  1159. }
  1160. function onDisposeConference(unload) {
  1161. Toolbar.showAuthenticateButton(false);
  1162. };
  1163. function onDisplayNameChanged(jid, displayName) {
  1164. ContactList.onDisplayNameChange(jid, displayName);
  1165. SettingsMenu.onDisplayNameChange(jid, displayName);
  1166. VideoLayout.onDisplayNameChanged(jid, displayName);
  1167. }
  1168. function registerListeners() {
  1169. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  1170. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  1171. APP.RTC.addStreamListener(function (stream) {
  1172. VideoLayout.onRemoteStreamAdded(stream);
  1173. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  1174. APP.RTC.addStreamListener(function (jid) {
  1175. VideoLayout.onVideoTypeChanged(jid);
  1176. }, StreamEventTypes.EVENT_TYPE_REMOTE_CHANGED);
  1177. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  1178. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (resourceJid) {
  1179. VideoLayout.onDominantSpeakerChanged(resourceJid);
  1180. });
  1181. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1182. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  1183. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  1184. endpointsEnteringLastN, stream);
  1185. });
  1186. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  1187. function (endpointSimulcastLayers) {
  1188. VideoLayout.onSimulcastLayersChanged(endpointSimulcastLayers);
  1189. });
  1190. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGING,
  1191. function (endpointSimulcastLayers) {
  1192. VideoLayout.onSimulcastLayersChanging(endpointSimulcastLayers);
  1193. });
  1194. APP.statistics.addAudioLevelListener(function(jid, audioLevel)
  1195. {
  1196. var resourceJid;
  1197. if(jid === APP.statistics.LOCAL_JID)
  1198. {
  1199. resourceJid = AudioLevels.LOCAL_LEVEL;
  1200. if(APP.RTC.localAudio.isMuted())
  1201. {
  1202. audioLevel = 0;
  1203. }
  1204. }
  1205. else
  1206. {
  1207. resourceJid = Strophe.getResourceFromJid(jid);
  1208. }
  1209. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  1210. UI.getLargeVideoState().userResourceJid);
  1211. });
  1212. APP.desktopsharing.addListener(function () {
  1213. ToolbarToggler.showDesktopSharingButton();
  1214. }, DesktopSharingEventTypes.INIT);
  1215. APP.desktopsharing.addListener(
  1216. Toolbar.changeDesktopSharingButtonState,
  1217. DesktopSharingEventTypes.SWITCHING_DONE);
  1218. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  1219. VideoLayout.updateLocalConnectionStats);
  1220. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  1221. VideoLayout.updateConnectionStats);
  1222. APP.connectionquality.addListener(CQEvents.STOP,
  1223. VideoLayout.onStatsStop);
  1224. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  1225. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  1226. messageHandler.openMessageDialog(
  1227. 'dialog.serviceUnavailable',
  1228. 'dialog.gracefulShutdown'
  1229. );
  1230. });
  1231. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  1232. var title = APP.translation.generateTranslatonHTML(
  1233. "dialog.reservationError");
  1234. var message = APP.translation.generateTranslatonHTML(
  1235. "dialog.reservationErrorMsg", {code: code, msg: msg});
  1236. messageHandler.openDialog(
  1237. title,
  1238. message,
  1239. true, {},
  1240. function (event, value, message, formVals)
  1241. {
  1242. return false;
  1243. }
  1244. );
  1245. });
  1246. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  1247. messageHandler.openMessageDialog("dialog.sessTerminated",
  1248. "dialog.kickMessage");
  1249. });
  1250. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  1251. //FIXME: use Session Terminated from translation, but
  1252. // 'reason' text comes from XMPP packet and is not translated
  1253. var title = APP.translation.generateTranslatonHTML("dialog.sessTerminated");
  1254. messageHandler.openDialog(
  1255. title, reason, true, {},
  1256. function (event, value, message, formVals)
  1257. {
  1258. return false;
  1259. }
  1260. );
  1261. });
  1262. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  1263. messageHandler.showError("dialog.error",
  1264. "dialog.bridgeUnavailable");
  1265. });
  1266. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  1267. Avatar.setUserAvatar(from, id);
  1268. });
  1269. APP.xmpp.addListener(XMPPEvents.CHANGED_STREAMS, function (jid, changedStreams) {
  1270. for(stream in changedStreams)
  1271. {
  1272. // might need to update the direction if participant just went from sendrecv to recvonly
  1273. if (stream.type === 'video' || stream.type === 'screen') {
  1274. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  1275. switch (stream.direction) {
  1276. case 'sendrecv':
  1277. el.show();
  1278. break;
  1279. case 'recvonly':
  1280. el.hide();
  1281. // FIXME: Check if we have to change large video
  1282. //VideoLayout.updateLargeVideo(el);
  1283. break;
  1284. }
  1285. }
  1286. }
  1287. });
  1288. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  1289. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  1290. APP.xmpp.addListener(XMPPEvents.LOCALROLE_CHANGED, onLocalRoleChange);
  1291. APP.xmpp.addListener(XMPPEvents.MUC_ENTER, onMucEntered);
  1292. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  1293. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  1294. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  1295. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  1296. APP.xmpp.addListener(XMPPEvents.MUC_LEFT, onMucLeft);
  1297. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordReqiured);
  1298. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  1299. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  1300. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED, onAuthenticationRequired);
  1301. }
  1302. /**
  1303. * Mutes/unmutes the local video.
  1304. *
  1305. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  1306. * @param options an object which specifies optional arguments such as the
  1307. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  1308. * specifies whether the method was initiated in response to a user command (in
  1309. * contrast to an automatic decision taken by the application logic)
  1310. */
  1311. function setVideoMute(mute, options) {
  1312. APP.xmpp.setVideoMute(
  1313. mute,
  1314. function (mute) {
  1315. var video = $('#video');
  1316. var communicativeClass = "icon-camera";
  1317. var muteClass = "icon-camera icon-camera-disabled";
  1318. if (mute) {
  1319. video.removeClass(communicativeClass);
  1320. video.addClass(muteClass);
  1321. } else {
  1322. video.removeClass(muteClass);
  1323. video.addClass(communicativeClass);
  1324. }
  1325. },
  1326. options);
  1327. }
  1328. function bindEvents()
  1329. {
  1330. /**
  1331. * Resizes and repositions videos in full screen mode.
  1332. */
  1333. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1334. function () {
  1335. VideoLayout.resizeLargeVideoContainer();
  1336. VideoLayout.positionLarge();
  1337. }
  1338. );
  1339. $(window).resize(function () {
  1340. VideoLayout.resizeLargeVideoContainer();
  1341. VideoLayout.positionLarge();
  1342. });
  1343. }
  1344. UI.start = function (init) {
  1345. document.title = interfaceConfig.APP_NAME;
  1346. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1347. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1348. {
  1349. $("#videoconference_page").hide();
  1350. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1351. setupWelcomePage();
  1352. return;
  1353. }
  1354. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  1355. var leftWatermarkDiv
  1356. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  1357. leftWatermarkDiv.css({display: 'block'});
  1358. leftWatermarkDiv.parent().get(0).href
  1359. = interfaceConfig.JITSI_WATERMARK_LINK;
  1360. }
  1361. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1362. var rightWatermarkDiv
  1363. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  1364. rightWatermarkDiv.css({display: 'block'});
  1365. rightWatermarkDiv.parent().get(0).href
  1366. = interfaceConfig.BRAND_WATERMARK_LINK;
  1367. rightWatermarkDiv.get(0).style.backgroundImage
  1368. = "url(images/rightwatermark.png)";
  1369. }
  1370. if (interfaceConfig.SHOW_POWERED_BY) {
  1371. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  1372. }
  1373. $("#welcome_page").hide();
  1374. VideoLayout.resizeLargeVideoContainer();
  1375. $("#videospace").mousemove(function () {
  1376. return ToolbarToggler.showToolbar();
  1377. });
  1378. // Set the defaults for prompt dialogs.
  1379. jQuery.prompt.setDefaults({persistent: false});
  1380. VideoLayout.init(eventEmitter);
  1381. AudioLevels.init();
  1382. NicknameHandler.init(eventEmitter);
  1383. registerListeners();
  1384. bindEvents();
  1385. setupPrezi();
  1386. setupToolbars();
  1387. setupChat();
  1388. document.title = interfaceConfig.APP_NAME;
  1389. $("#downloadlog").click(function (event) {
  1390. dump(event.target);
  1391. });
  1392. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1393. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1394. {
  1395. $("#videoconference_page").hide();
  1396. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1397. setupWelcomePage();
  1398. return;
  1399. }
  1400. $("#welcome_page").hide();
  1401. // Display notice message at the top of the toolbar
  1402. if (config.noticeMessage) {
  1403. $('#noticeText').text(config.noticeMessage);
  1404. $('#notice').css({display: 'block'});
  1405. }
  1406. document.getElementById('largeVideo').volume = 0;
  1407. if (!$('#settings').is(':visible')) {
  1408. console.log('init');
  1409. init();
  1410. } else {
  1411. loginInfo.onsubmit = function (e) {
  1412. if (e.preventDefault) e.preventDefault();
  1413. $('#settings').hide();
  1414. init();
  1415. };
  1416. }
  1417. toastr.options = {
  1418. "closeButton": true,
  1419. "debug": false,
  1420. "positionClass": "notification-bottom-right",
  1421. "onclick": null,
  1422. "showDuration": "300",
  1423. "hideDuration": "1000",
  1424. "timeOut": "2000",
  1425. "extendedTimeOut": "1000",
  1426. "showEasing": "swing",
  1427. "hideEasing": "linear",
  1428. "showMethod": "fadeIn",
  1429. "hideMethod": "fadeOut",
  1430. "reposition": function() {
  1431. if(PanelToggler.isVisible()) {
  1432. $("#toast-container").addClass("notification-bottom-right-center");
  1433. } else {
  1434. $("#toast-container").removeClass("notification-bottom-right-center");
  1435. }
  1436. },
  1437. "newestOnTop": false
  1438. };
  1439. SettingsMenu.init();
  1440. };
  1441. function chatAddError(errorMessage, originalText)
  1442. {
  1443. return Chat.chatAddError(errorMessage, originalText);
  1444. };
  1445. function chatSetSubject(text)
  1446. {
  1447. return Chat.chatSetSubject(text);
  1448. };
  1449. function updateChatConversation(from, displayName, message) {
  1450. return Chat.updateChatConversation(from, displayName, message);
  1451. };
  1452. function onMucJoined(jid, info) {
  1453. Toolbar.updateRoomUrl(window.location.href);
  1454. var meHTML = APP.translation.generateTranslatonHTML("me");
  1455. $("#localNick").html(Strophe.getResourceFromJid(jid) + " (" + meHTML + ")");
  1456. var settings = Settings.getSettings();
  1457. // Add myself to the contact list.
  1458. ContactList.addContact(jid, settings.email || settings.uid);
  1459. // Once we've joined the muc show the toolbar
  1460. ToolbarToggler.showToolbar();
  1461. var displayName = !config.displayJids
  1462. ? info.displayName : Strophe.getResourceFromJid(jid);
  1463. if (displayName)
  1464. onDisplayNameChanged('localVideoContainer', displayName);
  1465. }
  1466. function initEtherpad(name) {
  1467. Etherpad.init(name);
  1468. };
  1469. function onMucLeft(jid) {
  1470. console.log('left.muc', jid);
  1471. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  1472. '>.displayname').html();
  1473. messageHandler.notify(displayName,'notify.somebody',
  1474. 'disconnected',
  1475. 'notify.disconnected');
  1476. // Need to call this with a slight delay, otherwise the element couldn't be
  1477. // found for some reason.
  1478. // XXX(gp) it works fine without the timeout for me (with Chrome 38).
  1479. window.setTimeout(function () {
  1480. var container = document.getElementById(
  1481. 'participant_' + Strophe.getResourceFromJid(jid));
  1482. if (container) {
  1483. ContactList.removeContact(jid);
  1484. VideoLayout.removeConnectionIndicator(jid);
  1485. // hide here, wait for video to close before removing
  1486. $(container).hide();
  1487. VideoLayout.resizeThumbnails();
  1488. }
  1489. }, 10);
  1490. VideoLayout.participantLeft(jid);
  1491. };
  1492. function onLocalRoleChange(jid, info, pres, isModerator)
  1493. {
  1494. console.info("My role changed, new role: " + info.role);
  1495. onModeratorStatusChanged(isModerator);
  1496. VideoLayout.showModeratorIndicator();
  1497. if (isModerator) {
  1498. Authentication.closeAuthenticationWindow();
  1499. messageHandler.notify(null, "notify.me",
  1500. 'connected', "notify.moderator");
  1501. }
  1502. }
  1503. function onModeratorStatusChanged(isModerator) {
  1504. Toolbar.showSipCallButton(isModerator);
  1505. Toolbar.showRecordingButton(
  1506. isModerator); //&&
  1507. // FIXME:
  1508. // Recording visible if
  1509. // there are at least 2(+ 1 focus) participants
  1510. //Object.keys(connection.emuc.members).length >= 3);
  1511. if (isModerator && config.etherpad_base) {
  1512. Etherpad.init();
  1513. }
  1514. };
  1515. function onPasswordReqiured(callback) {
  1516. // password is required
  1517. Toolbar.lockLockButton();
  1518. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1519. message += APP.translation.translateString(
  1520. "dialog.passwordRequired");
  1521. message += '</h2>' +
  1522. '<input name="lockKey" type="text" data-i18n=' +
  1523. '"[placeholder]dialog.password" placeholder="' +
  1524. APP.translation.translateString("dialog.password") +
  1525. '" autofocus>';
  1526. messageHandler.openTwoButtonDialog(null, null, null, message,
  1527. true,
  1528. "dialog.Ok",
  1529. function (e, v, m, f) {},
  1530. null,
  1531. function (e, v, m, f) {
  1532. if (v) {
  1533. var lockKey = f.lockKey;
  1534. if (lockKey) {
  1535. Toolbar.setSharedKey(lockKey);
  1536. callback(lockKey);
  1537. }
  1538. }
  1539. },
  1540. ':input:first'
  1541. );
  1542. }
  1543. function onMucEntered(jid, id, displayName) {
  1544. messageHandler.notify(displayName,'notify.somebody',
  1545. 'connected',
  1546. 'notify.connected');
  1547. // Add Peer's container
  1548. VideoLayout.ensurePeerContainerExists(jid,id);
  1549. }
  1550. function onMucPresenceStatus( jid, info) {
  1551. VideoLayout.setPresenceStatus(
  1552. 'participant_' + Strophe.getResourceFromJid(jid), info.status);
  1553. }
  1554. function onMucRoleChanged(role, displayName) {
  1555. VideoLayout.showModeratorIndicator();
  1556. if (role === 'moderator') {
  1557. var messageKey, messageOptions = {};
  1558. if (!displayName) {
  1559. messageKey = "notify.grantedToUnknown";
  1560. }
  1561. else
  1562. {
  1563. messageKey = "notify.grantedTo";
  1564. messageOptions = {to: displayName};
  1565. }
  1566. messageHandler.notify(
  1567. displayName,'notify.somebody',
  1568. 'connected', messageKey,
  1569. messageOptions);
  1570. }
  1571. }
  1572. function onAuthenticationRequired(intervalCallback) {
  1573. Authentication.openAuthenticationDialog(
  1574. roomName, intervalCallback, function () {
  1575. Toolbar.authenticateClicked();
  1576. });
  1577. };
  1578. function onLastNChanged(oldValue, newValue) {
  1579. if (config.muteLocalVideoIfNotInLastN) {
  1580. setVideoMute(!newValue, { 'byUser': false });
  1581. }
  1582. }
  1583. UI.toggleSmileys = function () {
  1584. Chat.toggleSmileys();
  1585. };
  1586. UI.getSettings = function () {
  1587. return Settings.getSettings();
  1588. };
  1589. UI.toggleFilmStrip = function () {
  1590. return BottomToolbar.toggleFilmStrip();
  1591. };
  1592. UI.toggleChat = function () {
  1593. return BottomToolbar.toggleChat();
  1594. };
  1595. UI.toggleContactList = function () {
  1596. return BottomToolbar.toggleContactList();
  1597. };
  1598. UI.inputDisplayNameHandler = function (value) {
  1599. VideoLayout.inputDisplayNameHandler(value);
  1600. };
  1601. UI.getLargeVideoState = function()
  1602. {
  1603. return VideoLayout.getLargeVideoState();
  1604. };
  1605. UI.generateRoomName = function() {
  1606. if(roomName)
  1607. return roomName;
  1608. var roomnode = null;
  1609. var path = window.location.pathname;
  1610. // determinde the room node from the url
  1611. // TODO: just the roomnode or the whole bare jid?
  1612. if (config.getroomnode && typeof config.getroomnode === 'function') {
  1613. // custom function might be responsible for doing the pushstate
  1614. roomnode = config.getroomnode(path);
  1615. } else {
  1616. /* fall back to default strategy
  1617. * this is making assumptions about how the URL->room mapping happens.
  1618. * It currently assumes deployment at root, with a rewrite like the
  1619. * following one (for nginx):
  1620. location ~ ^/([a-zA-Z0-9]+)$ {
  1621. rewrite ^/(.*)$ / break;
  1622. }
  1623. */
  1624. if (path.length > 1) {
  1625. roomnode = path.substr(1).toLowerCase();
  1626. } else {
  1627. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  1628. roomnode = word.toLowerCase();
  1629. window.history.pushState('VideoChat',
  1630. 'Room: ' + word, window.location.pathname + word);
  1631. }
  1632. }
  1633. roomName = roomnode + '@' + config.hosts.muc;
  1634. return roomName;
  1635. };
  1636. UI.connectionIndicatorShowMore = function(id)
  1637. {
  1638. return VideoLayout.connectionIndicators[id].showMore();
  1639. };
  1640. UI.showLoginPopup = function(callback)
  1641. {
  1642. console.log('password is required');
  1643. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1644. message += APP.translation.translateString(
  1645. "dialog.passwordRequired");
  1646. message += '</h2>' +
  1647. '<input name="username" type="text" ' +
  1648. 'placeholder="user@domain.net" autofocus>' +
  1649. '<input name="password" ' +
  1650. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  1651. ' placeholder="user password">';
  1652. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  1653. true,
  1654. "dialog.Ok",
  1655. function (e, v, m, f) {
  1656. if (v) {
  1657. if (f.username !== null && f.password != null) {
  1658. callback(f.username, f.password);
  1659. }
  1660. }
  1661. },
  1662. null, null, ':input:first'
  1663. );
  1664. }
  1665. UI.checkForNicknameAndJoin = function () {
  1666. Authentication.closeAuthenticationDialog();
  1667. Authentication.stopInterval();
  1668. var nick = null;
  1669. if (config.useNicks) {
  1670. nick = window.prompt('Your nickname (optional)');
  1671. }
  1672. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  1673. };
  1674. function dump(elem, filename) {
  1675. elem = elem.parentNode;
  1676. elem.download = filename || 'meetlog.json';
  1677. elem.href = 'data:application/json;charset=utf-8,\n';
  1678. var data = APP.xmpp.populateData();
  1679. var metadata = {};
  1680. metadata.time = new Date();
  1681. metadata.url = window.location.href;
  1682. metadata.ua = navigator.userAgent;
  1683. var log = APP.xmpp.getLogger();
  1684. if (log) {
  1685. metadata.xmpp = log;
  1686. }
  1687. data.metadata = metadata;
  1688. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  1689. return false;
  1690. }
  1691. UI.getRoomName = function () {
  1692. return roomName;
  1693. };
  1694. /**
  1695. * Mutes/unmutes the local video.
  1696. */
  1697. UI.toggleVideo = function () {
  1698. setVideoMute(!APP.RTC.localVideo.isMuted());
  1699. };
  1700. /**
  1701. * Mutes / unmutes audio for the local participant.
  1702. */
  1703. UI.toggleAudio = function() {
  1704. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  1705. };
  1706. /**
  1707. * Sets muted audio state for the local participant.
  1708. */
  1709. UI.setAudioMuted = function (mute) {
  1710. if(!APP.xmpp.setAudioMute(mute, function () {
  1711. VideoLayout.showLocalAudioIndicator(mute);
  1712. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1713. }))
  1714. {
  1715. // We still click the button.
  1716. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1717. return;
  1718. }
  1719. }
  1720. UI.addListener = function (type, listener) {
  1721. eventEmitter.on(type, listener);
  1722. }
  1723. UI.clickOnVideo = function (videoNumber) {
  1724. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  1725. if (remoteVideos.length > videoNumber) {
  1726. remoteVideos[videoNumber].click();
  1727. }
  1728. }
  1729. //Used by torture
  1730. UI.showToolbar = function () {
  1731. return ToolbarToggler.showToolbar();
  1732. }
  1733. //Used by torture
  1734. UI.dockToolbar = function (isDock) {
  1735. return ToolbarToggler.dockToolbar(isDock);
  1736. }
  1737. module.exports = UI;
  1738. },{"../../service/RTC/RTCEvents":89,"../../service/RTC/StreamEventTypes":91,"../../service/connectionquality/CQEvents":94,"../../service/desktopsharing/DesktopSharingEventTypes":95,"../../service/xmpp/XMPPEvents":97,"./../settings/Settings":38,"./audio_levels/AudioLevels.js":9,"./authentication/Authentication":11,"./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":98}],9:[function(require,module,exports){
  1739. var CanvasUtil = require("./CanvasUtils");
  1740. var ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  1741. function initActiveSpeakerAudioLevels() {
  1742. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  1743. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  1744. // Draw a circle.
  1745. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  1746. // Add a shadow around the circle
  1747. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  1748. ASDrawContext.shadowOffsetX = 0;
  1749. ASDrawContext.shadowOffsetY = 0;
  1750. }
  1751. /**
  1752. * The audio Levels plugin.
  1753. */
  1754. var AudioLevels = (function(my) {
  1755. var audioLevelCanvasCache = {};
  1756. my.LOCAL_LEVEL = 'local';
  1757. my.init = function () {
  1758. initActiveSpeakerAudioLevels();
  1759. }
  1760. /**
  1761. * Updates the audio level canvas for the given peerJid. If the canvas
  1762. * didn't exist we create it.
  1763. */
  1764. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  1765. var resourceJid = null;
  1766. var videoSpanId = null;
  1767. if (!peerJid)
  1768. videoSpanId = 'localVideoContainer';
  1769. else {
  1770. resourceJid = Strophe.getResourceFromJid(peerJid);
  1771. videoSpanId = 'participant_' + resourceJid;
  1772. }
  1773. var videoSpan = document.getElementById(videoSpanId);
  1774. if (!videoSpan) {
  1775. if (resourceJid)
  1776. console.error("No video element for jid", resourceJid);
  1777. else
  1778. console.error("No video element for local video.");
  1779. return;
  1780. }
  1781. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  1782. var videoSpaceWidth = $('#remoteVideos').width();
  1783. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  1784. var thumbnailWidth = thumbnailSize[0];
  1785. var thumbnailHeight = thumbnailSize[1];
  1786. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  1787. audioLevelCanvas = document.createElement('canvas');
  1788. audioLevelCanvas.className = "audiolevel";
  1789. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  1790. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  1791. resizeAudioLevelCanvas( audioLevelCanvas,
  1792. thumbnailWidth,
  1793. thumbnailHeight);
  1794. videoSpan.appendChild(audioLevelCanvas);
  1795. } else {
  1796. audioLevelCanvas = audioLevelCanvas.get(0);
  1797. resizeAudioLevelCanvas( audioLevelCanvas,
  1798. thumbnailWidth,
  1799. thumbnailHeight);
  1800. }
  1801. };
  1802. /**
  1803. * Updates the audio level UI for the given resourceJid.
  1804. *
  1805. * @param resourceJid the resource jid indicating the video element for
  1806. * which we draw the audio level
  1807. * @param audioLevel the newAudio level to render
  1808. */
  1809. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  1810. drawAudioLevelCanvas(resourceJid, audioLevel);
  1811. var videoSpanId = getVideoSpanId(resourceJid);
  1812. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  1813. if (!audioLevelCanvas)
  1814. return;
  1815. var drawContext = audioLevelCanvas.getContext('2d');
  1816. var canvasCache = audioLevelCanvasCache[resourceJid];
  1817. drawContext.clearRect (0, 0,
  1818. audioLevelCanvas.width, audioLevelCanvas.height);
  1819. drawContext.drawImage(canvasCache, 0, 0);
  1820. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  1821. if(!APP.xmpp.myJid()) {
  1822. return;
  1823. }
  1824. resourceJid = APP.xmpp.myResource();
  1825. }
  1826. if(resourceJid === largeVideoResourceJid) {
  1827. window.requestAnimationFrame(function () {
  1828. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  1829. });
  1830. }
  1831. };
  1832. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  1833. if($("#activeSpeaker").css("visibility") == "hidden")
  1834. return;
  1835. ASDrawContext.clearRect(0, 0, 300, 300);
  1836. if(audioLevel == 0)
  1837. return;
  1838. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  1839. // Fill the shape.
  1840. ASDrawContext.fill();
  1841. };
  1842. /**
  1843. * Resizes the given audio level canvas to match the given thumbnail size.
  1844. */
  1845. function resizeAudioLevelCanvas(audioLevelCanvas,
  1846. thumbnailWidth,
  1847. thumbnailHeight) {
  1848. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  1849. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  1850. }
  1851. /**
  1852. * Draws the audio level canvas into the cached canvas object.
  1853. *
  1854. * @param resourceJid the resource jid indicating the video element for
  1855. * which we draw the audio level
  1856. * @param audioLevel the newAudio level to render
  1857. */
  1858. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  1859. if (!audioLevelCanvasCache[resourceJid]) {
  1860. var videoSpanId = getVideoSpanId(resourceJid);
  1861. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  1862. /*
  1863. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  1864. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  1865. * error. Since audio levels are frequently updated, the errors have
  1866. * been observed to pile into the console, strain the CPU.
  1867. */
  1868. if (audioLevelCanvasOrig)
  1869. {
  1870. audioLevelCanvasCache[resourceJid]
  1871. = CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  1872. }
  1873. }
  1874. var canvas = audioLevelCanvasCache[resourceJid];
  1875. if (!canvas)
  1876. return;
  1877. var drawContext = canvas.getContext('2d');
  1878. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  1879. var shadowLevel = getShadowLevel(audioLevel);
  1880. if (shadowLevel > 0)
  1881. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  1882. CanvasUtil.drawRoundRectGlow( drawContext,
  1883. interfaceConfig.CANVAS_EXTRA/2, interfaceConfig.CANVAS_EXTRA/2,
  1884. canvas.width - interfaceConfig.CANVAS_EXTRA,
  1885. canvas.height - interfaceConfig.CANVAS_EXTRA,
  1886. interfaceConfig.CANVAS_RADIUS,
  1887. interfaceConfig.SHADOW_COLOR,
  1888. shadowLevel);
  1889. }
  1890. /**
  1891. * Returns the shadow/glow level for the given audio level.
  1892. *
  1893. * @param audioLevel the audio level from which we determine the shadow
  1894. * level
  1895. */
  1896. function getShadowLevel (audioLevel) {
  1897. var shadowLevel = 0;
  1898. if (audioLevel <= 0.3) {
  1899. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  1900. }
  1901. else if (audioLevel <= 0.6) {
  1902. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  1903. }
  1904. else {
  1905. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  1906. }
  1907. return shadowLevel;
  1908. }
  1909. /**
  1910. * Returns the video span id corresponding to the given resourceJid or local
  1911. * user.
  1912. */
  1913. function getVideoSpanId(resourceJid) {
  1914. var videoSpanId = null;
  1915. if (resourceJid === AudioLevels.LOCAL_LEVEL
  1916. || (APP.xmpp.myResource() && resourceJid
  1917. === APP.xmpp.myResource()))
  1918. videoSpanId = 'localVideoContainer';
  1919. else
  1920. videoSpanId = 'participant_' + resourceJid;
  1921. return videoSpanId;
  1922. }
  1923. /**
  1924. * Indicates that the remote video has been resized.
  1925. */
  1926. $(document).bind('remotevideo.resized', function (event, width, height) {
  1927. var resized = false;
  1928. $('#remoteVideos>span>canvas').each(function() {
  1929. var canvas = $(this).get(0);
  1930. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  1931. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  1932. resized = true;
  1933. }
  1934. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  1935. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  1936. resized = true;
  1937. }
  1938. });
  1939. if (resized)
  1940. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  1941. audioLevelCanvasCache[resourceJid].width
  1942. = width + interfaceConfig.CANVAS_EXTRA;
  1943. audioLevelCanvasCache[resourceJid].height
  1944. = height + interfaceConfig.CANVAS_EXTRA;
  1945. });
  1946. });
  1947. return my;
  1948. })(AudioLevels || {});
  1949. module.exports = AudioLevels;
  1950. },{"./CanvasUtils":10}],10:[function(require,module,exports){
  1951. /**
  1952. * Utility class for drawing canvas shapes.
  1953. */
  1954. var CanvasUtil = (function(my) {
  1955. /**
  1956. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  1957. * of the glow.
  1958. *
  1959. * @param drawContext the context of the canvas to draw to
  1960. * @param x the x coordinate of the round rectangle
  1961. * @param y the y coordinate of the round rectangle
  1962. * @param w the width of the round rectangle
  1963. * @param h the height of the round rectangle
  1964. * @param glowColor the color of the glow
  1965. * @param glowWidth the width of the glow
  1966. */
  1967. my.drawRoundRectGlow
  1968. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  1969. // Save the previous state of the context.
  1970. drawContext.save();
  1971. if (w < 2 * r) r = w / 2;
  1972. if (h < 2 * r) r = h / 2;
  1973. // Draw a round rectangle.
  1974. drawContext.beginPath();
  1975. drawContext.moveTo(x+r, y);
  1976. drawContext.arcTo(x+w, y, x+w, y+h, r);
  1977. drawContext.arcTo(x+w, y+h, x, y+h, r);
  1978. drawContext.arcTo(x, y+h, x, y, r);
  1979. drawContext.arcTo(x, y, x+w, y, r);
  1980. drawContext.closePath();
  1981. // Add a shadow around the rectangle
  1982. drawContext.shadowColor = glowColor;
  1983. drawContext.shadowBlur = glowWidth;
  1984. drawContext.shadowOffsetX = 0;
  1985. drawContext.shadowOffsetY = 0;
  1986. // Fill the shape.
  1987. drawContext.fill();
  1988. drawContext.save();
  1989. drawContext.restore();
  1990. // 1) Uncomment this line to use Composite Operation, which is doing the
  1991. // same as the clip function below and is also antialiasing the round
  1992. // border, but is said to be less fast performance wise.
  1993. // drawContext.globalCompositeOperation='destination-out';
  1994. drawContext.beginPath();
  1995. drawContext.moveTo(x+r, y);
  1996. drawContext.arcTo(x+w, y, x+w, y+h, r);
  1997. drawContext.arcTo(x+w, y+h, x, y+h, r);
  1998. drawContext.arcTo(x, y+h, x, y, r);
  1999. drawContext.arcTo(x, y, x+w, y, r);
  2000. drawContext.closePath();
  2001. // 2) Uncomment this line to use Composite Operation, which is doing the
  2002. // same as the clip function below and is also antialiasing the round
  2003. // border, but is said to be less fast performance wise.
  2004. // drawContext.fill();
  2005. // Comment these two lines if choosing to do the same with composite
  2006. // operation above 1 and 2.
  2007. drawContext.clip();
  2008. drawContext.clearRect(0, 0, 277, 200);
  2009. // Restore the previous context state.
  2010. drawContext.restore();
  2011. };
  2012. /**
  2013. * Clones the given canvas.
  2014. *
  2015. * @return the new cloned canvas.
  2016. */
  2017. my.cloneCanvas = function (oldCanvas) {
  2018. /*
  2019. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  2020. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  2021. * levels are frequently updated, the errors have been observed to pile
  2022. * into the console, strain the CPU.
  2023. */
  2024. if (!oldCanvas)
  2025. return oldCanvas;
  2026. //create a new canvas
  2027. var newCanvas = document.createElement('canvas');
  2028. var context = newCanvas.getContext('2d');
  2029. //set dimensions
  2030. newCanvas.width = oldCanvas.width;
  2031. newCanvas.height = oldCanvas.height;
  2032. //apply the old canvas to the new one
  2033. context.drawImage(oldCanvas, 0, 0);
  2034. //return the new canvas
  2035. return newCanvas;
  2036. };
  2037. return my;
  2038. })(CanvasUtil || {});
  2039. module.exports = CanvasUtil;
  2040. },{}],11:[function(require,module,exports){
  2041. /* global $, APP*/
  2042. var LoginDialog = require('./LoginDialog');
  2043. var Moderator = require('../../xmpp/moderator');
  2044. /* Initial "authentication required" dialog */
  2045. var authDialog = null;
  2046. /* Loop retry ID that wits for other user to create the room */
  2047. var authRetryId = null;
  2048. var authenticationWindow = null;
  2049. var Authentication = {
  2050. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  2051. // This is the loop that will wait for the room to be created by
  2052. // someone else. 'auth_required.moderator' will bring us back here.
  2053. authRetryId = window.setTimeout(intervalCallback, 5000);
  2054. // Show prompt only if it's not open
  2055. if (authDialog !== null) {
  2056. return;
  2057. }
  2058. // extract room name from 'room@muc.server.net'
  2059. var room = roomName.substr(0, roomName.indexOf('@'));
  2060. var title = APP.translation.generateTranslatonHTML("dialog.Stop");
  2061. var msg = APP.translation.generateTranslatonHTML("dialog.AuthMsg",
  2062. {room: room});
  2063. var buttonTxt
  2064. = APP.translation.generateTranslatonHTML("dialog.Authenticate");
  2065. var buttons = [];
  2066. buttons.push({title: buttonTxt, value: "authNow"});
  2067. authDialog = APP.UI.messageHandler.openDialog(
  2068. title,
  2069. msg,
  2070. true,
  2071. buttons,
  2072. function (onSubmitEvent, submitValue) {
  2073. // Do not close the dialog yet
  2074. onSubmitEvent.preventDefault();
  2075. // Open login popup
  2076. if (submitValue === 'authNow') {
  2077. callback();
  2078. }
  2079. }
  2080. );
  2081. },
  2082. closeAuthenticationWindow: function () {
  2083. if (authenticationWindow) {
  2084. authenticationWindow.close();
  2085. authenticationWindow = null;
  2086. }
  2087. },
  2088. xmppAuthenticate: function () {
  2089. var loginDialog = LoginDialog.show(
  2090. function (connection, state) {
  2091. if (!state) {
  2092. // User cancelled
  2093. loginDialog.close();
  2094. return;
  2095. } else if (state == APP.xmpp.Status.CONNECTED) {
  2096. loginDialog.close();
  2097. Authentication.stopInterval();
  2098. Authentication.closeAuthenticationDialog();
  2099. // Close the connection as anonymous one will be used
  2100. // to create the conference. Session-id will authorize
  2101. // the request.
  2102. connection.disconnect();
  2103. var roomName = APP.UI.generateRoomName();
  2104. Moderator.allocateConferenceFocus(roomName, function () {
  2105. // If it's not "on the fly" authentication now join
  2106. // the conference room
  2107. if (!APP.xmpp.getMUCJoined()) {
  2108. APP.UI.checkForNicknameAndJoin();
  2109. }
  2110. });
  2111. }
  2112. }, true);
  2113. },
  2114. focusAuthenticationWindow: function () {
  2115. // If auth window exists just bring it to the front
  2116. if (authenticationWindow) {
  2117. authenticationWindow.focus();
  2118. return;
  2119. }
  2120. },
  2121. closeAuthenticationDialog: function () {
  2122. // Close authentication dialog if opened
  2123. if (authDialog) {
  2124. authDialog.close();
  2125. authDialog = null;
  2126. }
  2127. },
  2128. createAuthenticationWindow: function (callback, url) {
  2129. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  2130. url, 910, 660,
  2131. // On closed
  2132. function () {
  2133. // Close authentication dialog if opened
  2134. Authentication.closeAuthenticationDialog();
  2135. callback();
  2136. authenticationWindow = null;
  2137. });
  2138. return authenticationWindow;
  2139. },
  2140. stopInterval: function () {
  2141. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  2142. if (authRetryId) {
  2143. window.clearTimeout(authRetryId);
  2144. authRetryId = null;
  2145. }
  2146. }
  2147. };
  2148. module.exports = Authentication;
  2149. },{"../../xmpp/moderator":53,"./LoginDialog":12}],12:[function(require,module,exports){
  2150. /* global $, APP, config*/
  2151. var XMPP = require('../../xmpp/xmpp');
  2152. var Moderator = require('../../xmpp/moderator');
  2153. //FIXME: use LoginDialog to add retries to XMPP.connect method used when
  2154. // anonymous domain is not enabled
  2155. /**
  2156. * Creates new <tt>Dialog</tt> instance.
  2157. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt> called
  2158. * when we either fail to connect or succeed(check Strophe.Status).
  2159. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to Jicofo
  2160. * in order to create session-id after the connection is established.
  2161. * @constructor
  2162. */
  2163. function Dialog(callback, obtainSession) {
  2164. var self = this;
  2165. var stop = false;
  2166. var connection = APP.xmpp.createConnection();
  2167. var message = '<h2 data-i18n="dialog.passwordRequired">';
  2168. message += APP.translation.translateString("dialog.passwordRequired");
  2169. message += '</h2>' +
  2170. '<input name="username" type="text" ' +
  2171. 'placeholder="user@domain.net" autofocus>' +
  2172. '<input name="password" ' +
  2173. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  2174. ' placeholder="user password">';
  2175. var okButton = APP.translation.generateTranslatonHTML("dialog.Ok");
  2176. var cancelButton = APP.translation.generateTranslatonHTML("dialog.Cancel");
  2177. var states = {
  2178. login: {
  2179. html: message,
  2180. buttons: [
  2181. { title: okButton, value: true},
  2182. { title: cancelButton, value: false}
  2183. ],
  2184. focus: ':input:first',
  2185. submit: function (e, v, m, f) {
  2186. e.preventDefault();
  2187. if (v) {
  2188. var jid = f.username;
  2189. var password = f.password;
  2190. if (jid && password) {
  2191. stop = false;
  2192. connection.reset();
  2193. connDialog.goToState('connecting');
  2194. connection.connect(jid, password, stateHandler);
  2195. }
  2196. } else {
  2197. // User cancelled
  2198. stop = true;
  2199. callback();
  2200. }
  2201. }
  2202. },
  2203. connecting: {
  2204. title: APP.translation.translateString('dialog.connecting'),
  2205. html: '<div id="connectionStatus"></div>',
  2206. buttons: [],
  2207. defaultButton: 0
  2208. },
  2209. finished: {
  2210. title: APP.translation.translateString('dialog.error'),
  2211. html: '<div id="errorMessage"></div>',
  2212. buttons: [
  2213. {
  2214. title: APP.translation.translateString('dialog.retry'),
  2215. value: 'retry'
  2216. },
  2217. {
  2218. title: APP.translation.translateString('dialog.Cancel'),
  2219. value: 'cancel'
  2220. },
  2221. ],
  2222. defaultButton: 0,
  2223. submit: function (e, v, m, f) {
  2224. e.preventDefault();
  2225. if (v === 'retry')
  2226. connDialog.goToState('login');
  2227. else
  2228. callback();
  2229. }
  2230. }
  2231. };
  2232. var connDialog
  2233. = APP.UI.messageHandler.openDialogWithStates(states,
  2234. { persistent: true, closeText: '' }, null);
  2235. var stateHandler = function (status, message) {
  2236. if (stop) {
  2237. return;
  2238. }
  2239. var translateKey = "connection." + XMPP.getStatusString(status);
  2240. var statusStr = APP.translation.translateString(translateKey);
  2241. // Display current state
  2242. var connectionStatus =
  2243. connDialog.getState('connecting').find('#connectionStatus');
  2244. connectionStatus.text(statusStr);
  2245. switch (status) {
  2246. case XMPP.Status.CONNECTED:
  2247. stop = true;
  2248. if (!obtainSession) {
  2249. callback(connection, status);
  2250. return;
  2251. }
  2252. // Obtaining session-id status
  2253. connectionStatus.text(
  2254. APP.translation.translateString(
  2255. 'connection.FETCH_SESSION_ID'));
  2256. // Authenticate with Jicofo and obtain session-id
  2257. var roomName = APP.UI.generateRoomName();
  2258. // Jicofo will return new session-id when connected
  2259. // from authenticated domain
  2260. connection.sendIQ(
  2261. Moderator.createConferenceIq(roomName),
  2262. function (result) {
  2263. connectionStatus.text(
  2264. APP.translation.translateString(
  2265. 'connection.GOT_SESSION_ID'));
  2266. stop = true;
  2267. // Parse session-id
  2268. Moderator.parseSessionId(result);
  2269. callback(connection, status);
  2270. },
  2271. function (error) {
  2272. console.error("Auth on the fly failed", error);
  2273. stop = true;
  2274. var errorMsg =
  2275. APP.translation.translateString(
  2276. 'connection.GET_SESSION_ID_ERROR') +
  2277. $(error).find('>error').attr('code');
  2278. self.displayError(errorMsg);
  2279. connection.disconnect();
  2280. });
  2281. break;
  2282. case XMPP.Status.AUTHFAIL:
  2283. case XMPP.Status.CONNFAIL:
  2284. case XMPP.Status.DISCONNECTED:
  2285. stop = true;
  2286. callback(connection, status);
  2287. var errorMessage = statusStr;
  2288. if (message)
  2289. {
  2290. errorMessage += ': ' + message;
  2291. }
  2292. self.displayError(errorMessage);
  2293. break;
  2294. default:
  2295. break;
  2296. }
  2297. };
  2298. /**
  2299. * Displays error message in 'finished' state which allows either to cancel
  2300. * or retry.
  2301. * @param message the final message to be displayed.
  2302. */
  2303. this.displayError = function (message) {
  2304. var finishedState = connDialog.getState('finished');
  2305. var errorMessageElem = finishedState.find('#errorMessage');
  2306. errorMessageElem.text(message);
  2307. connDialog.goToState('finished');
  2308. };
  2309. /**
  2310. * Closes LoginDialog.
  2311. */
  2312. this.close = function () {
  2313. stop = true;
  2314. connDialog.close();
  2315. };
  2316. }
  2317. var LoginDialog = {
  2318. /**
  2319. * Displays login prompt used to establish new XMPP connection. Given
  2320. * <tt>callback(Strophe.Connection, Strophe.Status)</tt> function will be
  2321. * called when we connect successfully(status === CONNECTED) or when we fail
  2322. * to do so. On connection failure program can call Dialog.close() method in
  2323. * order to cancel or do nothing to let the user retry.
  2324. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt>
  2325. * called when we either fail to connect or succeed(check
  2326. * Strophe.Status).
  2327. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to
  2328. * Jicofo in order to create session-id after the connection is
  2329. * established.
  2330. * @returns {Dialog}
  2331. */
  2332. show: function (callback, obtainSession) {
  2333. return new Dialog(callback, obtainSession);
  2334. }
  2335. };
  2336. module.exports = LoginDialog;
  2337. },{"../../xmpp/moderator":53,"../../xmpp/xmpp":61}],13:[function(require,module,exports){
  2338. var Settings = require("../../settings/Settings");
  2339. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  2340. var users = {};
  2341. var activeSpeakerJid;
  2342. function setVisibility(selector, show) {
  2343. if (selector && selector.length > 0) {
  2344. selector.css("visibility", show ? "visible" : "hidden");
  2345. }
  2346. }
  2347. function isUserMuted(jid) {
  2348. // XXX(gp) we may want to rename this method to something like
  2349. // isUserStreaming, for example.
  2350. if (jid && jid != APP.xmpp.myJid()) {
  2351. var resource = Strophe.getResourceFromJid(jid);
  2352. if (!require("../videolayout/VideoLayout").isInLastN(resource)) {
  2353. return true;
  2354. }
  2355. }
  2356. if (!APP.RTC.remoteStreams[jid] || !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  2357. return null;
  2358. }
  2359. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  2360. }
  2361. function getGravatarUrl(id, size) {
  2362. if(id === APP.xmpp.myJid() || !id) {
  2363. id = Settings.getSettings().uid;
  2364. }
  2365. return 'https://www.gravatar.com/avatar/' +
  2366. MD5.hexdigest(id.trim().toLowerCase()) +
  2367. "?d=wavatar&size=" + (size || "30");
  2368. }
  2369. var Avatar = {
  2370. /**
  2371. * Sets the user's avatar in the settings menu(if local user), contact list
  2372. * and thumbnail
  2373. * @param jid jid of the user
  2374. * @param id email or userID to be used as a hash
  2375. */
  2376. setUserAvatar: function (jid, id) {
  2377. if (id) {
  2378. if (users[jid] === id) {
  2379. return;
  2380. }
  2381. users[jid] = id;
  2382. }
  2383. var thumbUrl = getGravatarUrl(users[jid] || jid, 100);
  2384. var contactListUrl = getGravatarUrl(users[jid] || jid);
  2385. var resourceJid = Strophe.getResourceFromJid(jid);
  2386. var thumbnail = $('#participant_' + resourceJid);
  2387. var avatar = $('#avatar_' + resourceJid);
  2388. // set the avatar in the settings menu if it is local user and get the
  2389. // local video container
  2390. if (jid === APP.xmpp.myJid()) {
  2391. $('#avatar').get(0).src = thumbUrl;
  2392. thumbnail = $('#localVideoContainer');
  2393. }
  2394. // set the avatar in the contact list
  2395. var contact = $('#' + resourceJid + '>img');
  2396. if (contact && contact.length > 0) {
  2397. contact.get(0).src = contactListUrl;
  2398. }
  2399. // set the avatar in the thumbnail
  2400. if (avatar && avatar.length > 0) {
  2401. avatar[0].src = thumbUrl;
  2402. } else {
  2403. if (thumbnail && thumbnail.length > 0) {
  2404. avatar = document.createElement('img');
  2405. avatar.id = 'avatar_' + resourceJid;
  2406. avatar.className = 'userAvatar';
  2407. avatar.src = thumbUrl;
  2408. thumbnail.append(avatar);
  2409. }
  2410. }
  2411. //if the user is the current active speaker - update the active speaker
  2412. // avatar
  2413. if (jid === activeSpeakerJid) {
  2414. this.updateActiveSpeakerAvatarSrc(jid);
  2415. }
  2416. },
  2417. /**
  2418. * Hides or shows the user's avatar
  2419. * @param jid jid of the user
  2420. * @param show whether we should show the avatar or not
  2421. * video because there is no dominant speaker and no focused speaker
  2422. */
  2423. showUserAvatar: function (jid, show) {
  2424. if (users[jid]) {
  2425. var resourceJid = Strophe.getResourceFromJid(jid);
  2426. var video = $('#participant_' + resourceJid + '>video');
  2427. var avatar = $('#avatar_' + resourceJid);
  2428. if (jid === APP.xmpp.myJid()) {
  2429. video = $('#localVideoWrapper>video');
  2430. }
  2431. if (show === undefined || show === null) {
  2432. show = isUserMuted(jid);
  2433. }
  2434. //if the user is the currently focused, the dominant speaker or if
  2435. //there is no focused and no dominant speaker and the large video is
  2436. //currently shown
  2437. if (activeSpeakerJid === jid && require("../videolayout/VideoLayout").isLargeVideoOnTop()) {
  2438. setVisibility($("#largeVideo"), !show);
  2439. setVisibility($('#activeSpeaker'), show);
  2440. setVisibility(avatar, false);
  2441. setVisibility(video, false);
  2442. } else {
  2443. if (video && video.length > 0) {
  2444. setVisibility(video, !show);
  2445. setVisibility(avatar, show);
  2446. }
  2447. }
  2448. }
  2449. },
  2450. /**
  2451. * Updates the src of the active speaker avatar
  2452. * @param jid of the current active speaker
  2453. */
  2454. updateActiveSpeakerAvatarSrc: function (jid) {
  2455. if (!jid) {
  2456. jid = APP.xmpp.findJidFromResource(
  2457. require("../videolayout/VideoLayout").getLargeVideoState().userResourceJid);
  2458. }
  2459. var avatar = $("#activeSpeakerAvatar")[0];
  2460. var url = getGravatarUrl(users[jid],
  2461. interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE);
  2462. if (jid === activeSpeakerJid && avatar.src === url) {
  2463. return;
  2464. }
  2465. activeSpeakerJid = jid;
  2466. var isMuted = isUserMuted(jid);
  2467. if (jid && isMuted !== null) {
  2468. avatar.src = url;
  2469. setVisibility($("#largeVideo"), !isMuted);
  2470. Avatar.showUserAvatar(jid, isMuted);
  2471. }
  2472. }
  2473. };
  2474. module.exports = Avatar;
  2475. },{"../../../service/RTC/MediaStreamTypes":87,"../../settings/Settings":38,"../videolayout/VideoLayout":32}],14:[function(require,module,exports){
  2476. /* global $, config,
  2477. setLargeVideoVisible, Util */
  2478. var VideoLayout = require("../videolayout/VideoLayout");
  2479. var Prezi = require("../prezi/Prezi");
  2480. var UIUtil = require("../util/UIUtil");
  2481. var etherpadName = null;
  2482. var etherpadIFrame = null;
  2483. var domain = null;
  2484. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  2485. /**
  2486. * Resizes the etherpad.
  2487. */
  2488. function resize() {
  2489. if ($('#etherpad>iframe').length) {
  2490. var remoteVideos = $('#remoteVideos');
  2491. var availableHeight
  2492. = window.innerHeight - remoteVideos.outerHeight();
  2493. var availableWidth = UIUtil.getAvailableVideoWidth();
  2494. $('#etherpad>iframe').width(availableWidth);
  2495. $('#etherpad>iframe').height(availableHeight);
  2496. }
  2497. }
  2498. /**
  2499. * Shares the Etherpad name with other participants.
  2500. */
  2501. function shareEtherpad() {
  2502. APP.xmpp.addToPresence("etherpad", etherpadName);
  2503. }
  2504. /**
  2505. * Creates the Etherpad button and adds it to the toolbar.
  2506. */
  2507. function enableEtherpadButton() {
  2508. if (!$('#etherpadButton').is(":visible"))
  2509. $('#etherpadButton').css({display: 'inline-block'});
  2510. }
  2511. /**
  2512. * Creates the IFrame for the etherpad.
  2513. */
  2514. function createIFrame() {
  2515. etherpadIFrame = document.createElement('iframe');
  2516. etherpadIFrame.src = domain + etherpadName + options;
  2517. etherpadIFrame.frameBorder = 0;
  2518. etherpadIFrame.scrolling = "no";
  2519. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  2520. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  2521. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  2522. document.getElementById('etherpad').appendChild(etherpadIFrame);
  2523. etherpadIFrame.onload = function() {
  2524. document.domain = document.domain;
  2525. bubbleIframeMouseMove(etherpadIFrame);
  2526. setTimeout(function() {
  2527. // the iframes inside of the etherpad are
  2528. // not yet loaded when the etherpad iframe is loaded
  2529. var outer = etherpadIFrame.
  2530. contentDocument.getElementsByName("ace_outer")[0];
  2531. bubbleIframeMouseMove(outer);
  2532. var inner = outer.
  2533. contentDocument.getElementsByName("ace_inner")[0];
  2534. bubbleIframeMouseMove(inner);
  2535. }, 2000);
  2536. };
  2537. }
  2538. function bubbleIframeMouseMove(iframe){
  2539. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  2540. iframe.contentWindow.onmousemove = function(e){
  2541. if(existingOnMouseMove) existingOnMouseMove(e);
  2542. var evt = document.createEvent("MouseEvents");
  2543. var boundingClientRect = iframe.getBoundingClientRect();
  2544. evt.initMouseEvent(
  2545. "mousemove",
  2546. true, // bubbles
  2547. false, // not cancelable
  2548. window,
  2549. e.detail,
  2550. e.screenX,
  2551. e.screenY,
  2552. e.clientX + boundingClientRect.left,
  2553. e.clientY + boundingClientRect.top,
  2554. e.ctrlKey,
  2555. e.altKey,
  2556. e.shiftKey,
  2557. e.metaKey,
  2558. e.button,
  2559. null // no related element
  2560. );
  2561. iframe.dispatchEvent(evt);
  2562. };
  2563. }
  2564. /**
  2565. * On video selected event.
  2566. */
  2567. $(document).bind('video.selected', function (event, isPresentation) {
  2568. if (config.etherpad_base && etherpadIFrame && etherpadIFrame.style.visibility !== 'hidden')
  2569. Etherpad.toggleEtherpad(isPresentation);
  2570. });
  2571. var Etherpad = {
  2572. /**
  2573. * Initializes the etherpad.
  2574. */
  2575. init: function (name) {
  2576. if (config.etherpad_base && !etherpadName) {
  2577. domain = config.etherpad_base;
  2578. if (!name) {
  2579. // In case we're the focus we generate the name.
  2580. etherpadName = Math.random().toString(36).substring(7) +
  2581. '_' + (new Date().getTime()).toString();
  2582. shareEtherpad();
  2583. }
  2584. else
  2585. etherpadName = name;
  2586. enableEtherpadButton();
  2587. /**
  2588. * Resizes the etherpad, when the window is resized.
  2589. */
  2590. $(window).resize(function () {
  2591. resize();
  2592. });
  2593. }
  2594. },
  2595. /**
  2596. * Opens/hides the Etherpad.
  2597. */
  2598. toggleEtherpad: function (isPresentation) {
  2599. if (!etherpadIFrame)
  2600. createIFrame();
  2601. var largeVideo = null;
  2602. if (Prezi.isPresentationVisible())
  2603. largeVideo = $('#presentation>iframe');
  2604. else
  2605. largeVideo = $('#largeVideo');
  2606. if ($('#etherpad>iframe').css('visibility') === 'hidden') {
  2607. $('#activeSpeaker').css('visibility', 'hidden');
  2608. largeVideo.fadeOut(300, function () {
  2609. if (Prezi.isPresentationVisible()) {
  2610. largeVideo.css({opacity: '0'});
  2611. } else {
  2612. VideoLayout.setLargeVideoVisible(false);
  2613. }
  2614. });
  2615. $('#etherpad>iframe').fadeIn(300, function () {
  2616. document.body.style.background = '#eeeeee';
  2617. $('#etherpad>iframe').css({visibility: 'visible'});
  2618. $('#etherpad').css({zIndex: 2});
  2619. });
  2620. }
  2621. else if ($('#etherpad>iframe')) {
  2622. $('#etherpad>iframe').fadeOut(300, function () {
  2623. $('#etherpad>iframe').css({visibility: 'hidden'});
  2624. $('#etherpad').css({zIndex: 0});
  2625. document.body.style.background = 'black';
  2626. });
  2627. if (!isPresentation) {
  2628. $('#largeVideo').fadeIn(300, function () {
  2629. VideoLayout.setLargeVideoVisible(true);
  2630. });
  2631. }
  2632. }
  2633. resize();
  2634. },
  2635. isVisible: function() {
  2636. var etherpadIframe = $('#etherpad>iframe');
  2637. return etherpadIframe && etherpadIframe.is(':visible');
  2638. }
  2639. };
  2640. module.exports = Etherpad;
  2641. },{"../prezi/Prezi":15,"../util/UIUtil":30,"../videolayout/VideoLayout":32}],15:[function(require,module,exports){
  2642. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  2643. var UIUtil = require("../util/UIUtil");
  2644. var VideoLayout = require("../videolayout/VideoLayout");
  2645. var messageHandler = require("../util/MessageHandler");
  2646. var PreziPlayer = require("./PreziPlayer");
  2647. var preziPlayer = null;
  2648. var Prezi = {
  2649. /**
  2650. * Reloads the current presentation.
  2651. */
  2652. reloadPresentation: function() {
  2653. var iframe = document.getElementById(preziPlayer.options.preziId);
  2654. iframe.src = iframe.src;
  2655. },
  2656. /**
  2657. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  2658. * otherwise.
  2659. */
  2660. isPresentationVisible: function () {
  2661. return ($('#presentation>iframe') != null
  2662. && $('#presentation>iframe').css('opacity') == 1);
  2663. },
  2664. /**
  2665. * Opens the Prezi dialog, from which the user could choose a presentation
  2666. * to load.
  2667. */
  2668. openPreziDialog: function() {
  2669. var myprezi = APP.xmpp.getPrezi();
  2670. if (myprezi) {
  2671. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  2672. null,
  2673. "dialog.removePreziMsg",
  2674. null,
  2675. false,
  2676. "dialog.Remove",
  2677. function(e,v,m,f) {
  2678. if(v) {
  2679. APP.xmpp.removePreziFromPresence();
  2680. }
  2681. }
  2682. );
  2683. }
  2684. else if (preziPlayer != null) {
  2685. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  2686. null, "dialog.sharePreziMsg",
  2687. null,
  2688. false,
  2689. "dialog.Ok",
  2690. function(e,v,m,f) {
  2691. $.prompt.close();
  2692. }
  2693. );
  2694. }
  2695. else {
  2696. var html = APP.translation.generateTranslatonHTML(
  2697. "dialog.sharePreziTitle");
  2698. var cancelButton = APP.translation.generateTranslatonHTML(
  2699. "dialog.Cancel");
  2700. var shareButton = APP.translation.generateTranslatonHTML(
  2701. "dialog.Share");
  2702. var backButton = APP.translation.generateTranslatonHTML(
  2703. "dialog.Back");
  2704. var buttons = [];
  2705. var buttons1 = [];
  2706. // Cancel button to both states
  2707. buttons.push({title: cancelButton, value: false});
  2708. buttons1.push({title: cancelButton, value: false});
  2709. // Share button
  2710. buttons.push({title: shareButton, value: true});
  2711. // Back button
  2712. buttons1.push({title: backButton, value: true});
  2713. var linkError = APP.translation.generateTranslatonHTML(
  2714. "dialog.preziLinkError");
  2715. var defaultUrl = APP.translation.translateString("defaultPreziLink",
  2716. {url: "http://prezi.com/wz7vhjycl7e6/my-prezi"});
  2717. var openPreziState = {
  2718. state0: {
  2719. html: '<h2>' + html + '</h2>' +
  2720. '<input name="preziUrl" type="text" ' +
  2721. 'data-i18n="[placeholder]defaultPreziLink" data-i18n-options=\'' +
  2722. JSON.stringify({"url": "http://prezi.com/wz7vhjycl7e6/my-prezi"}) +
  2723. '\' placeholder="' + defaultUrl + '" autofocus>',
  2724. persistent: false,
  2725. buttons: buttons,
  2726. focus: ':input:first',
  2727. defaultButton: 0,
  2728. submit: function (e, v, m, f) {
  2729. e.preventDefault();
  2730. if(v)
  2731. {
  2732. var preziUrl = f.preziUrl;
  2733. if (preziUrl)
  2734. {
  2735. var urlValue
  2736. = encodeURI(UIUtil.escapeHtml(preziUrl));
  2737. if (urlValue.indexOf('http://prezi.com/') != 0
  2738. && urlValue.indexOf('https://prezi.com/') != 0)
  2739. {
  2740. $.prompt.goToState('state1');
  2741. return false;
  2742. }
  2743. else {
  2744. var presIdTmp = urlValue.substring(
  2745. urlValue.indexOf("prezi.com/") + 10);
  2746. if (!isAlphanumeric(presIdTmp)
  2747. || presIdTmp.indexOf('/') < 2) {
  2748. $.prompt.goToState('state1');
  2749. return false;
  2750. }
  2751. else {
  2752. APP.xmpp.addToPresence("prezi", urlValue);
  2753. $.prompt.close();
  2754. }
  2755. }
  2756. }
  2757. }
  2758. else
  2759. $.prompt.close();
  2760. }
  2761. },
  2762. state1: {
  2763. html: '<h2>' + html + '</h2>' +
  2764. linkError,
  2765. persistent: false,
  2766. buttons: buttons1,
  2767. focus: ':input:first',
  2768. defaultButton: 1,
  2769. submit: function (e, v, m, f) {
  2770. e.preventDefault();
  2771. if (v === 0)
  2772. $.prompt.close();
  2773. else
  2774. $.prompt.goToState('state0');
  2775. }
  2776. }
  2777. };
  2778. messageHandler.openDialogWithStates(openPreziState);
  2779. }
  2780. }
  2781. };
  2782. /**
  2783. * A new presentation has been added.
  2784. *
  2785. * @param event the event indicating the add of a presentation
  2786. * @param jid the jid from which the presentation was added
  2787. * @param presUrl url of the presentation
  2788. * @param currentSlide the current slide to which we should move
  2789. */
  2790. function presentationAdded(event, jid, presUrl, currentSlide) {
  2791. console.log("presentation added", presUrl);
  2792. var presId = getPresentationId(presUrl);
  2793. var elementId = 'participant_'
  2794. + Strophe.getResourceFromJid(jid)
  2795. + '_' + presId;
  2796. // We explicitly don't specify the peer jid here, because we don't want
  2797. // this video to be dealt with as a peer related one (for example we
  2798. // don't want to show a mute/kick menu for this one, etc.).
  2799. VideoLayout.addRemoteVideoContainer(null, elementId);
  2800. VideoLayout.resizeThumbnails();
  2801. var controlsEnabled = false;
  2802. if (jid === APP.xmpp.myJid())
  2803. controlsEnabled = true;
  2804. setPresentationVisible(true);
  2805. $('#largeVideoContainer').hover(
  2806. function (event) {
  2807. if (Prezi.isPresentationVisible()) {
  2808. var reloadButtonRight = window.innerWidth
  2809. - $('#presentation>iframe').offset().left
  2810. - $('#presentation>iframe').width();
  2811. $('#reloadPresentation').css({ right: reloadButtonRight,
  2812. display:'inline-block'});
  2813. }
  2814. },
  2815. function (event) {
  2816. if (!Prezi.isPresentationVisible())
  2817. $('#reloadPresentation').css({display:'none'});
  2818. else {
  2819. var e = event.toElement || event.relatedTarget;
  2820. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  2821. $('#reloadPresentation').css({display:'none'});
  2822. }
  2823. });
  2824. preziPlayer = new PreziPlayer(
  2825. 'presentation',
  2826. {preziId: presId,
  2827. width: getPresentationWidth(),
  2828. height: getPresentationHeihgt(),
  2829. controls: controlsEnabled,
  2830. debug: true
  2831. });
  2832. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  2833. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  2834. console.log("prezi status", event.value);
  2835. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  2836. if (jid != APP.xmpp.myJid())
  2837. preziPlayer.flyToStep(currentSlide);
  2838. }
  2839. });
  2840. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  2841. console.log("event value", event.value);
  2842. APP.xmpp.addToPresence("preziSlide", event.value);
  2843. });
  2844. $("#" + elementId).css( 'background-image',
  2845. 'url(../images/avatarprezi.png)');
  2846. $("#" + elementId).click(
  2847. function () {
  2848. setPresentationVisible(true);
  2849. }
  2850. );
  2851. };
  2852. /**
  2853. * A presentation has been removed.
  2854. *
  2855. * @param event the event indicating the remove of a presentation
  2856. * @param jid the jid for which the presentation was removed
  2857. * @param the url of the presentation
  2858. */
  2859. function presentationRemoved(event, jid, presUrl) {
  2860. console.log('presentation removed', presUrl);
  2861. var presId = getPresentationId(presUrl);
  2862. setPresentationVisible(false);
  2863. $('#participant_'
  2864. + Strophe.getResourceFromJid(jid)
  2865. + '_' + presId).remove();
  2866. $('#presentation>iframe').remove();
  2867. if (preziPlayer != null) {
  2868. preziPlayer.destroy();
  2869. preziPlayer = null;
  2870. }
  2871. };
  2872. /**
  2873. * Indicates if the given string is an alphanumeric string.
  2874. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  2875. * purpose of checking URIs.
  2876. */
  2877. function isAlphanumeric(unsafeText) {
  2878. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  2879. return regex.test(unsafeText);
  2880. }
  2881. /**
  2882. * Returns the presentation id from the given url.
  2883. */
  2884. function getPresentationId (presUrl) {
  2885. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  2886. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  2887. }
  2888. /**
  2889. * Returns the presentation width.
  2890. */
  2891. function getPresentationWidth() {
  2892. var availableWidth = UIUtil.getAvailableVideoWidth();
  2893. var availableHeight = getPresentationHeihgt();
  2894. var aspectRatio = 16.0 / 9.0;
  2895. if (availableHeight < availableWidth / aspectRatio) {
  2896. availableWidth = Math.floor(availableHeight * aspectRatio);
  2897. }
  2898. return availableWidth;
  2899. }
  2900. /**
  2901. * Returns the presentation height.
  2902. */
  2903. function getPresentationHeihgt() {
  2904. var remoteVideos = $('#remoteVideos');
  2905. return window.innerHeight - remoteVideos.outerHeight();
  2906. }
  2907. /**
  2908. * Resizes the presentation iframe.
  2909. */
  2910. function resize() {
  2911. if ($('#presentation>iframe')) {
  2912. $('#presentation>iframe').width(getPresentationWidth());
  2913. $('#presentation>iframe').height(getPresentationHeihgt());
  2914. }
  2915. }
  2916. /**
  2917. * Shows/hides a presentation.
  2918. */
  2919. function setPresentationVisible(visible) {
  2920. var prezi = $('#presentation>iframe');
  2921. if (visible) {
  2922. // Trigger the video.selected event to indicate a change in the
  2923. // large video.
  2924. $(document).trigger("video.selected", [true]);
  2925. $('#largeVideo').fadeOut(300);
  2926. prezi.fadeIn(300, function() {
  2927. prezi.css({opacity:'1'});
  2928. ToolbarToggler.dockToolbar(true);
  2929. VideoLayout.setLargeVideoVisible(false);
  2930. });
  2931. $('#activeSpeaker').css('visibility', 'hidden');
  2932. }
  2933. else {
  2934. if (prezi.css('opacity') == '1') {
  2935. prezi.fadeOut(300, function () {
  2936. prezi.css({opacity:'0'});
  2937. $('#reloadPresentation').css({display:'none'});
  2938. $('#largeVideo').fadeIn(300, function() {
  2939. VideoLayout.setLargeVideoVisible(true);
  2940. ToolbarToggler.dockToolbar(false);
  2941. });
  2942. });
  2943. }
  2944. }
  2945. }
  2946. /**
  2947. * Presentation has been removed.
  2948. */
  2949. $(document).bind('presentationremoved.muc', presentationRemoved);
  2950. /**
  2951. * Presentation has been added.
  2952. */
  2953. $(document).bind('presentationadded.muc', presentationAdded);
  2954. /*
  2955. * Indicates presentation slide change.
  2956. */
  2957. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  2958. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  2959. preziPlayer.flyToStep(current);
  2960. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  2961. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  2962. preziPlayer.flyToStep(current, i);
  2963. }
  2964. }
  2965. });
  2966. /**
  2967. * On video selected event.
  2968. */
  2969. $(document).bind('video.selected', function (event, isPresentation) {
  2970. if (!isPresentation && $('#presentation>iframe')) {
  2971. setPresentationVisible(false);
  2972. }
  2973. });
  2974. $(window).resize(function () {
  2975. resize();
  2976. });
  2977. module.exports = Prezi;
  2978. },{"../toolbars/ToolbarToggler":26,"../util/MessageHandler":28,"../util/UIUtil":30,"../videolayout/VideoLayout":32,"./PreziPlayer":16}],16:[function(require,module,exports){
  2979. (function() {
  2980. "use strict";
  2981. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  2982. window.PreziPlayer = (function() {
  2983. PreziPlayer.API_VERSION = 1;
  2984. PreziPlayer.CURRENT_STEP = 'currentStep';
  2985. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  2986. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  2987. PreziPlayer.STATUS_LOADING = 'loading';
  2988. PreziPlayer.STATUS_READY = 'ready';
  2989. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  2990. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  2991. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  2992. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  2993. PreziPlayer.EVENT_STATUS = "statusChange";
  2994. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  2995. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  2996. PreziPlayer.domain = "https://prezi.com";
  2997. PreziPlayer.path = "/player/";
  2998. PreziPlayer.players = {};
  2999. PreziPlayer.binded_methods = ['changesHandler'];
  3000. PreziPlayer.createMultiplePlayers = function(optionArray){
  3001. for(var i=0; i<optionArray.length; i++) {
  3002. var optionSet = optionArray[i];
  3003. new PreziPlayer(optionSet.id, optionSet);
  3004. };
  3005. };
  3006. PreziPlayer.messageReceived = function(event){
  3007. var message, item, player;
  3008. try {
  3009. message = JSON.parse(event.data);
  3010. if (message.id && (player = PreziPlayer.players[message.id])) {
  3011. if (player.options.debug === true) {
  3012. if (console && console.log)
  3013. console.log('received', message);
  3014. }
  3015. if (message.type === "changes") {
  3016. player.changesHandler(message);
  3017. }
  3018. for (var i = 0; i < player.callbacks.length; i++) {
  3019. item = player.callbacks[i];
  3020. if (item && message.type === item.event) {
  3021. item.callback(message);
  3022. }
  3023. }
  3024. }
  3025. } catch (e) { }
  3026. };
  3027. function PreziPlayer(id, options) {
  3028. var params, paramString = "", _this = this;
  3029. if (PreziPlayer.players[id]){
  3030. PreziPlayer.players[id].destroy();
  3031. }
  3032. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  3033. var method_name = PreziPlayer.binded_methods[i];
  3034. _this[method_name] = __bind(_this[method_name], _this);
  3035. };
  3036. options = options || {};
  3037. this.options = options;
  3038. this.values = {'status': PreziPlayer.STATUS_LOADING};
  3039. this.values[PreziPlayer.CURRENT_STEP] = 0;
  3040. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  3041. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  3042. this.callbacks = [];
  3043. this.id = id;
  3044. this.embedTo = document.getElementById(id);
  3045. if (!this.embedTo) {
  3046. throw "The element id is not available.";
  3047. }
  3048. this.iframe = document.createElement('iframe');
  3049. params = [
  3050. { name: 'oid', value: options.preziId },
  3051. { name: 'explorable', value: options.explorable ? 1 : 0 },
  3052. { name: 'controls', value: options.controls ? 1 : 0 }
  3053. ];
  3054. for(var i=0; i<params.length; i++) {
  3055. var param = params[i];
  3056. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  3057. };
  3058. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  3059. this.iframe.frameBorder = 0;
  3060. this.iframe.scrolling = "no";
  3061. this.iframe.width = options.width || 640;
  3062. this.iframe.height = options.height || 480;
  3063. this.embedTo.innerHTML = '';
  3064. // JITSI: IN CASE SOMETHING GOES WRONG.
  3065. try {
  3066. this.embedTo.appendChild(this.iframe);
  3067. }
  3068. catch (err) {
  3069. console.log("CATCH ERROR");
  3070. }
  3071. // JITSI: Increase interval from 200 to 500, which fixes prezi
  3072. // crashes for us.
  3073. this.initPollInterval = setInterval(function(){
  3074. _this.sendMessage({'action': 'init'});
  3075. }, 500);
  3076. PreziPlayer.players[id] = this;
  3077. }
  3078. PreziPlayer.prototype.changesHandler = function(message) {
  3079. var key, value, j, item;
  3080. if (this.initPollInterval) {
  3081. clearInterval(this.initPollInterval);
  3082. this.initPollInterval = false;
  3083. }
  3084. for (key in message.data) {
  3085. if (message.data.hasOwnProperty(key)){
  3086. value = message.data[key];
  3087. this.values[key] = value;
  3088. for (j=0; j<this.callbacks.length; j++) {
  3089. item = this.callbacks[j];
  3090. if (item && item.event === key + "Change"){
  3091. item.callback({type: item.event, value: value});
  3092. }
  3093. }
  3094. }
  3095. }
  3096. };
  3097. PreziPlayer.prototype.destroy = function() {
  3098. if (this.initPollInterval) {
  3099. clearInterval(this.initPollInterval);
  3100. this.initPollInterval = false;
  3101. }
  3102. this.embedTo.innerHTML = '';
  3103. };
  3104. PreziPlayer.prototype.sendMessage = function(message) {
  3105. if (this.options.debug === true) {
  3106. if (console && console.log) console.log('sent', message);
  3107. }
  3108. message.version = PreziPlayer.API_VERSION;
  3109. message.id = this.id;
  3110. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  3111. };
  3112. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  3113. PreziPlayer.prototype.flyToNextStep = function() {
  3114. return this.sendMessage({
  3115. 'action': 'present',
  3116. 'data': ['moveToNextStep']
  3117. });
  3118. };
  3119. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  3120. PreziPlayer.prototype.flyToPreviousStep = function() {
  3121. return this.sendMessage({
  3122. 'action': 'present',
  3123. 'data': ['moveToPrevStep']
  3124. });
  3125. };
  3126. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  3127. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  3128. var obj = this;
  3129. // check animation_step
  3130. if (animation_step > 0 &&
  3131. obj.values.animationCountOnSteps &&
  3132. obj.values.animationCountOnSteps[step] <= animation_step) {
  3133. animation_step = obj.values.animationCountOnSteps[step];
  3134. }
  3135. // jump to animation steps by calling flyToNextStep()
  3136. function doAnimationSteps() {
  3137. if (obj.values.isMoving == true) {
  3138. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  3139. return;
  3140. }
  3141. while (animation_step-- > 0) {
  3142. obj.flyToNextStep(); // do the animation steps
  3143. }
  3144. }
  3145. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  3146. // jump to the step
  3147. return this.sendMessage({
  3148. 'action': 'present',
  3149. 'data': ['moveToStep', step]
  3150. });
  3151. };
  3152. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  3153. PreziPlayer.prototype.flyToObject = function(objectId) {
  3154. return this.sendMessage({
  3155. 'action': 'present',
  3156. 'data': ['moveToObject', objectId]
  3157. });
  3158. };
  3159. PreziPlayer.prototype.play = function(defaultDelay) {
  3160. return this.sendMessage({
  3161. 'action': 'present',
  3162. 'data': ['startAutoPlay', defaultDelay]
  3163. });
  3164. };
  3165. PreziPlayer.prototype.stop = function() {
  3166. return this.sendMessage({
  3167. 'action': 'present',
  3168. 'data': ['stopAutoPlay']
  3169. });
  3170. };
  3171. PreziPlayer.prototype.pause = function(defaultDelay) {
  3172. return this.sendMessage({
  3173. 'action': 'present',
  3174. 'data': ['pauseAutoPlay', defaultDelay]
  3175. });
  3176. };
  3177. PreziPlayer.prototype.getCurrentStep = function() {
  3178. return this.values.currentStep;
  3179. };
  3180. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  3181. return this.values.currentAnimationStep;
  3182. };
  3183. PreziPlayer.prototype.getCurrentObject = function() {
  3184. return this.values.currentObject;
  3185. };
  3186. PreziPlayer.prototype.getStatus = function() {
  3187. return this.values.status;
  3188. };
  3189. PreziPlayer.prototype.isPlaying = function() {
  3190. return this.values.isAutoPlaying;
  3191. };
  3192. PreziPlayer.prototype.getStepCount = function() {
  3193. return this.values.stepCount;
  3194. };
  3195. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  3196. return this.values.animationCountOnSteps;
  3197. };
  3198. PreziPlayer.prototype.getTitle = function() {
  3199. return this.values.title;
  3200. };
  3201. PreziPlayer.prototype.setDimensions = function(dims) {
  3202. for (var parameter in dims) {
  3203. this.iframe[parameter] = dims[parameter];
  3204. }
  3205. }
  3206. PreziPlayer.prototype.getDimensions = function() {
  3207. return {
  3208. width: parseInt(this.iframe.width, 10),
  3209. height: parseInt(this.iframe.height, 10)
  3210. }
  3211. }
  3212. PreziPlayer.prototype.on = function(event, callback) {
  3213. this.callbacks.push({
  3214. event: event,
  3215. callback: callback
  3216. });
  3217. };
  3218. PreziPlayer.prototype.off = function(event, callback) {
  3219. var j, item;
  3220. if (event === undefined) {
  3221. this.callbacks = [];
  3222. }
  3223. j = this.callbacks.length;
  3224. while (j--) {
  3225. item = this.callbacks[j];
  3226. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  3227. this.callbacks.splice(j, 1);
  3228. }
  3229. }
  3230. };
  3231. if (window.addEventListener) {
  3232. window.addEventListener('message', PreziPlayer.messageReceived, false);
  3233. } else {
  3234. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  3235. }
  3236. return PreziPlayer;
  3237. })();
  3238. })();
  3239. module.exports = PreziPlayer;
  3240. },{}],17:[function(require,module,exports){
  3241. var Chat = require("./chat/Chat");
  3242. var ContactList = require("./contactlist/ContactList");
  3243. var Settings = require("./../../settings/Settings");
  3244. var SettingsMenu = require("./settings/SettingsMenu");
  3245. var VideoLayout = require("../videolayout/VideoLayout");
  3246. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  3247. var UIUtil = require("../util/UIUtil");
  3248. /**
  3249. * Toggler for the chat, contact list, settings menu, etc..
  3250. */
  3251. var PanelToggler = (function(my) {
  3252. var currentlyOpen = null;
  3253. var buttons = {
  3254. '#chatspace': '#chatBottomButton',
  3255. '#contactlist': '#contactListButton',
  3256. '#settingsmenu': '#settingsButton'
  3257. };
  3258. /**
  3259. * Resizes the video area
  3260. * @param isClosing whether the side panel is going to be closed or is going to open / remain opened
  3261. * @param completeFunction a function to be called when the video space is resized
  3262. */
  3263. var resizeVideoArea = function(isClosing, completeFunction) {
  3264. var videospace = $('#videospace');
  3265. var panelSize = isClosing ? [0, 0] : PanelToggler.getPanelSize();
  3266. var videospaceWidth = window.innerWidth - panelSize[0];
  3267. var videospaceHeight = window.innerHeight;
  3268. var videoSize
  3269. = VideoLayout.getVideoSize(null, null, videospaceWidth, videospaceHeight);
  3270. var videoWidth = videoSize[0];
  3271. var videoHeight = videoSize[1];
  3272. var videoPosition = VideoLayout.getVideoPosition(videoWidth,
  3273. videoHeight,
  3274. videospaceWidth,
  3275. videospaceHeight);
  3276. var horizontalIndent = videoPosition[0];
  3277. var verticalIndent = videoPosition[1];
  3278. var thumbnailSize = VideoLayout.calculateThumbnailSize(videospaceWidth);
  3279. var thumbnailsWidth = thumbnailSize[0];
  3280. var thumbnailsHeight = thumbnailSize[1];
  3281. //for chat
  3282. videospace.animate({
  3283. right: panelSize[0],
  3284. width: videospaceWidth,
  3285. height: videospaceHeight
  3286. },
  3287. {
  3288. queue: false,
  3289. duration: 500,
  3290. complete: completeFunction
  3291. });
  3292. $('#remoteVideos').animate({
  3293. height: thumbnailsHeight
  3294. },
  3295. {
  3296. queue: false,
  3297. duration: 500
  3298. });
  3299. $('#remoteVideos>span').animate({
  3300. height: thumbnailsHeight,
  3301. width: thumbnailsWidth
  3302. },
  3303. {
  3304. queue: false,
  3305. duration: 500,
  3306. complete: function () {
  3307. $(document).trigger(
  3308. "remotevideo.resized",
  3309. [thumbnailsWidth,
  3310. thumbnailsHeight]);
  3311. }
  3312. });
  3313. $('#largeVideoContainer').animate({
  3314. width: videospaceWidth,
  3315. height: videospaceHeight
  3316. },
  3317. {
  3318. queue: false,
  3319. duration: 500
  3320. });
  3321. $('#largeVideo').animate({
  3322. width: videoWidth,
  3323. height: videoHeight,
  3324. top: verticalIndent,
  3325. bottom: verticalIndent,
  3326. left: horizontalIndent,
  3327. right: horizontalIndent
  3328. },
  3329. {
  3330. queue: false,
  3331. duration: 500
  3332. });
  3333. };
  3334. /**
  3335. * Toggles the windows in the side panel
  3336. * @param object the window that should be shown
  3337. * @param selector the selector for the element containing the panel
  3338. * @param onOpenComplete function to be called when the panel is opened
  3339. * @param onOpen function to be called if the window is going to be opened
  3340. * @param onClose function to be called if the window is going to be closed
  3341. */
  3342. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  3343. UIUtil.buttonClick(buttons[selector], "active");
  3344. if (object.isVisible()) {
  3345. $("#toast-container").animate({
  3346. right: '5px'
  3347. },
  3348. {
  3349. queue: false,
  3350. duration: 500
  3351. });
  3352. $(selector).hide("slide", {
  3353. direction: "right",
  3354. queue: false,
  3355. duration: 500
  3356. });
  3357. if(typeof onClose === "function") {
  3358. onClose();
  3359. }
  3360. currentlyOpen = null;
  3361. }
  3362. else {
  3363. // Undock the toolbar when the chat is shown and if we're in a
  3364. // video mode.
  3365. if (VideoLayout.isLargeVideoVisible()) {
  3366. ToolbarToggler.dockToolbar(false);
  3367. }
  3368. if(currentlyOpen) {
  3369. var current = $(currentlyOpen);
  3370. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  3371. current.css('z-index', 4);
  3372. setTimeout(function () {
  3373. current.css('display', 'none');
  3374. current.css('z-index', 5);
  3375. }, 500);
  3376. }
  3377. $("#toast-container").animate({
  3378. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  3379. },
  3380. {
  3381. queue: false,
  3382. duration: 500
  3383. });
  3384. $(selector).show("slide", {
  3385. direction: "right",
  3386. queue: false,
  3387. duration: 500,
  3388. complete: onOpenComplete
  3389. });
  3390. if(typeof onOpen === "function") {
  3391. onOpen();
  3392. }
  3393. currentlyOpen = selector;
  3394. }
  3395. };
  3396. /**
  3397. * Opens / closes the chat area.
  3398. */
  3399. my.toggleChat = function() {
  3400. var chatCompleteFunction = Chat.isVisible() ?
  3401. function() {} : function () {
  3402. Chat.scrollChatToBottom();
  3403. $('#chatspace').trigger('shown');
  3404. };
  3405. resizeVideoArea(Chat.isVisible(), chatCompleteFunction);
  3406. toggle(Chat,
  3407. '#chatspace',
  3408. function () {
  3409. // Request the focus in the nickname field or the chat input field.
  3410. if ($('#nickname').css('visibility') === 'visible') {
  3411. $('#nickinput').focus();
  3412. } else {
  3413. $('#usermsg').focus();
  3414. }
  3415. },
  3416. null,
  3417. Chat.resizeChat,
  3418. null);
  3419. };
  3420. /**
  3421. * Opens / closes the contact list area.
  3422. */
  3423. my.toggleContactList = function () {
  3424. var completeFunction = ContactList.isVisible() ?
  3425. function() {} : function () { $('#contactlist').trigger('shown');};
  3426. resizeVideoArea(ContactList.isVisible(), completeFunction);
  3427. toggle(ContactList,
  3428. '#contactlist',
  3429. null,
  3430. function() {
  3431. ContactList.setVisualNotification(false);
  3432. },
  3433. null);
  3434. };
  3435. /**
  3436. * Opens / closes the settings menu
  3437. */
  3438. my.toggleSettingsMenu = function() {
  3439. resizeVideoArea(SettingsMenu.isVisible(), function (){});
  3440. toggle(SettingsMenu,
  3441. '#settingsmenu',
  3442. null,
  3443. function() {
  3444. var settings = Settings.getSettings();
  3445. $('#setDisplayName').get(0).value = settings.displayName;
  3446. $('#setEmail').get(0).value = settings.email;
  3447. },
  3448. null);
  3449. };
  3450. /**
  3451. * Returns the size of the side panel.
  3452. */
  3453. my.getPanelSize = function () {
  3454. var availableHeight = window.innerHeight;
  3455. var availableWidth = window.innerWidth;
  3456. var panelWidth = 200;
  3457. if (availableWidth * 0.2 < 200) {
  3458. panelWidth = availableWidth * 0.2;
  3459. }
  3460. return [panelWidth, availableHeight];
  3461. };
  3462. my.isVisible = function() {
  3463. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  3464. };
  3465. return my;
  3466. }(PanelToggler || {}));
  3467. module.exports = PanelToggler;
  3468. },{"../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){
  3469. /* global $, Util, nickname:true */
  3470. var Replacement = require("./Replacement");
  3471. var CommandsProcessor = require("./Commands");
  3472. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  3473. var smileys = require("./smileys.json").smileys;
  3474. var NicknameHandler = require("../../util/NicknameHandler");
  3475. var UIUtil = require("../../util/UIUtil");
  3476. var UIEvents = require("../../../../service/UI/UIEvents");
  3477. var notificationInterval = false;
  3478. var unreadMessages = 0;
  3479. /**
  3480. * Shows/hides a visual notification, indicating that a message has arrived.
  3481. */
  3482. function setVisualNotification(show) {
  3483. var unreadMsgElement = document.getElementById('unreadMessages');
  3484. var unreadMsgBottomElement
  3485. = document.getElementById('bottomUnreadMessages');
  3486. var glower = $('#chatButton');
  3487. var bottomGlower = $('#chatBottomButton');
  3488. if (unreadMessages) {
  3489. unreadMsgElement.innerHTML = unreadMessages.toString();
  3490. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  3491. ToolbarToggler.dockToolbar(true);
  3492. var chatButtonElement
  3493. = document.getElementById('chatButton').parentNode;
  3494. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  3495. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  3496. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  3497. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  3498. unreadMsgElement.setAttribute(
  3499. 'style',
  3500. 'top:' + topIndent +
  3501. '; left:' + leftIndent + ';');
  3502. var chatBottomButtonElement
  3503. = document.getElementById('chatBottomButton').parentNode;
  3504. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  3505. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  3506. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  3507. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  3508. unreadMsgBottomElement.setAttribute(
  3509. 'style',
  3510. 'top:' + bottomTopIndent +
  3511. '; left:' + bottomLeftIndent + ';');
  3512. if (!glower.hasClass('icon-chat-simple')) {
  3513. glower.removeClass('icon-chat');
  3514. glower.addClass('icon-chat-simple');
  3515. }
  3516. }
  3517. else {
  3518. unreadMsgElement.innerHTML = '';
  3519. unreadMsgBottomElement.innerHTML = '';
  3520. glower.removeClass('icon-chat-simple');
  3521. glower.addClass('icon-chat');
  3522. }
  3523. if (show && !notificationInterval) {
  3524. notificationInterval = window.setInterval(function () {
  3525. glower.toggleClass('active');
  3526. bottomGlower.toggleClass('active glowing');
  3527. }, 800);
  3528. }
  3529. else if (!show && notificationInterval) {
  3530. window.clearInterval(notificationInterval);
  3531. notificationInterval = false;
  3532. glower.removeClass('active');
  3533. bottomGlower.removeClass('glowing');
  3534. bottomGlower.addClass('active');
  3535. }
  3536. }
  3537. /**
  3538. * Returns the current time in the format it is shown to the user
  3539. * @returns {string}
  3540. */
  3541. function getCurrentTime() {
  3542. var now = new Date();
  3543. var hour = now.getHours();
  3544. var minute = now.getMinutes();
  3545. var second = now.getSeconds();
  3546. if(hour.toString().length === 1) {
  3547. hour = '0'+hour;
  3548. }
  3549. if(minute.toString().length === 1) {
  3550. minute = '0'+minute;
  3551. }
  3552. if(second.toString().length === 1) {
  3553. second = '0'+second;
  3554. }
  3555. return hour+':'+minute+':'+second;
  3556. }
  3557. function toggleSmileys()
  3558. {
  3559. var smileys = $('#smileysContainer');
  3560. if(!smileys.is(':visible')) {
  3561. smileys.show("slide", { direction: "down", duration: 300});
  3562. } else {
  3563. smileys.hide("slide", { direction: "down", duration: 300});
  3564. }
  3565. $('#usermsg').focus();
  3566. }
  3567. function addClickFunction(smiley, number) {
  3568. smiley.onclick = function addSmileyToMessage() {
  3569. var usermsg = $('#usermsg');
  3570. var message = usermsg.val();
  3571. message += smileys['smiley' + number];
  3572. usermsg.val(message);
  3573. usermsg.get(0).setSelectionRange(message.length, message.length);
  3574. toggleSmileys();
  3575. usermsg.focus();
  3576. };
  3577. }
  3578. /**
  3579. * Adds the smileys container to the chat
  3580. */
  3581. function addSmileys() {
  3582. var smileysContainer = document.createElement('div');
  3583. smileysContainer.id = 'smileysContainer';
  3584. for(var i = 1; i <= 21; i++) {
  3585. var smileyContainer = document.createElement('div');
  3586. smileyContainer.id = 'smiley' + i;
  3587. smileyContainer.className = 'smileyContainer';
  3588. var smiley = document.createElement('img');
  3589. smiley.src = 'images/smileys/smiley' + i + '.svg';
  3590. smiley.className = 'smiley';
  3591. addClickFunction(smiley, i);
  3592. smileyContainer.appendChild(smiley);
  3593. smileysContainer.appendChild(smileyContainer);
  3594. }
  3595. $("#chatspace").append(smileysContainer);
  3596. }
  3597. /**
  3598. * Resizes the chat conversation.
  3599. */
  3600. function resizeChatConversation() {
  3601. var msgareaHeight = $('#usermsg').outerHeight();
  3602. var chatspace = $('#chatspace');
  3603. var width = chatspace.width();
  3604. var chat = $('#chatconversation');
  3605. var smileys = $('#smileysarea');
  3606. smileys.height(msgareaHeight);
  3607. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  3608. $('#smileysContainer').css('bottom', msgareaHeight);
  3609. chat.width(width - 10);
  3610. chat.height(window.innerHeight - 15 - msgareaHeight);
  3611. }
  3612. /**
  3613. * Chat related user interface.
  3614. */
  3615. var Chat = (function (my) {
  3616. /**
  3617. * Initializes chat related interface.
  3618. */
  3619. my.init = function () {
  3620. if(NicknameHandler.getNickname())
  3621. Chat.setChatConversationMode(true);
  3622. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  3623. function (nickname) {
  3624. Chat.setChatConversationMode(true);
  3625. });
  3626. $('#nickinput').keydown(function (event) {
  3627. if (event.keyCode === 13) {
  3628. event.preventDefault();
  3629. var val = UIUtil.escapeHtml(this.value);
  3630. this.value = '';
  3631. if (!NicknameHandler.getNickname()) {
  3632. NicknameHandler.setNickname(val);
  3633. return;
  3634. }
  3635. }
  3636. });
  3637. $('#usermsg').keydown(function (event) {
  3638. if (event.keyCode === 13) {
  3639. event.preventDefault();
  3640. var value = this.value;
  3641. $('#usermsg').val('').trigger('autosize.resize');
  3642. this.focus();
  3643. var command = new CommandsProcessor(value);
  3644. if(command.isCommand())
  3645. {
  3646. command.processCommand();
  3647. }
  3648. else
  3649. {
  3650. var message = UIUtil.escapeHtml(value);
  3651. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  3652. }
  3653. }
  3654. });
  3655. var onTextAreaResize = function () {
  3656. resizeChatConversation();
  3657. Chat.scrollChatToBottom();
  3658. };
  3659. $('#usermsg').autosize({callback: onTextAreaResize});
  3660. $("#chatspace").bind("shown",
  3661. function () {
  3662. unreadMessages = 0;
  3663. setVisualNotification(false);
  3664. });
  3665. addSmileys();
  3666. };
  3667. /**
  3668. * Appends the given message to the chat conversation.
  3669. */
  3670. my.updateChatConversation = function (from, displayName, message) {
  3671. var divClassName = '';
  3672. if (APP.xmpp.myJid() === from) {
  3673. divClassName = "localuser";
  3674. }
  3675. else {
  3676. divClassName = "remoteuser";
  3677. if (!Chat.isVisible()) {
  3678. unreadMessages++;
  3679. UIUtil.playSoundNotification('chatNotification');
  3680. setVisualNotification(true);
  3681. }
  3682. }
  3683. // replace links and smileys
  3684. // Strophe already escapes special symbols on sending,
  3685. // so we escape here only tags to avoid double &amp;
  3686. var escMessage = message.replace(/</g, '&lt;').
  3687. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  3688. var escDisplayName = UIUtil.escapeHtml(displayName);
  3689. message = Replacement.processReplacements(escMessage);
  3690. var messageContainer =
  3691. '<div class="chatmessage">'+
  3692. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  3693. '<div class="username ' + divClassName +'">' + escDisplayName +
  3694. '</div>' + '<div class="timestamp">' + getCurrentTime() +
  3695. '</div>' + '<div class="usermessage">' + message + '</div>' +
  3696. '</div>';
  3697. $('#chatconversation').append(messageContainer);
  3698. $('#chatconversation').animate(
  3699. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3700. };
  3701. /**
  3702. * Appends error message to the conversation
  3703. * @param errorMessage the received error message.
  3704. * @param originalText the original message.
  3705. */
  3706. my.chatAddError = function(errorMessage, originalText)
  3707. {
  3708. errorMessage = UIUtil.escapeHtml(errorMessage);
  3709. originalText = UIUtil.escapeHtml(originalText);
  3710. $('#chatconversation').append(
  3711. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  3712. (originalText? (' \"'+ originalText + '\"') : "") +
  3713. ' was not sent.' +
  3714. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  3715. $('#chatconversation').animate(
  3716. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3717. };
  3718. /**
  3719. * Sets the subject to the UI
  3720. * @param subject the subject
  3721. */
  3722. my.chatSetSubject = function(subject)
  3723. {
  3724. if(subject)
  3725. subject = subject.trim();
  3726. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  3727. if(subject === "")
  3728. {
  3729. $("#subject").css({display: "none"});
  3730. }
  3731. else
  3732. {
  3733. $("#subject").css({display: "block"});
  3734. }
  3735. };
  3736. /**
  3737. * Sets the chat conversation mode.
  3738. */
  3739. my.setChatConversationMode = function (isConversationMode) {
  3740. if (isConversationMode) {
  3741. $('#nickname').css({visibility: 'hidden'});
  3742. $('#chatconversation').css({visibility: 'visible'});
  3743. $('#usermsg').css({visibility: 'visible'});
  3744. $('#smileysarea').css({visibility: 'visible'});
  3745. $('#usermsg').focus();
  3746. }
  3747. };
  3748. /**
  3749. * Resizes the chat area.
  3750. */
  3751. my.resizeChat = function () {
  3752. var chatSize = require("../SidePanelToggler").getPanelSize();
  3753. $('#chatspace').width(chatSize[0]);
  3754. $('#chatspace').height(chatSize[1]);
  3755. resizeChatConversation();
  3756. };
  3757. /**
  3758. * Indicates if the chat is currently visible.
  3759. */
  3760. my.isVisible = function () {
  3761. return $('#chatspace').is(":visible");
  3762. };
  3763. /**
  3764. * Shows and hides the window with the smileys
  3765. */
  3766. my.toggleSmileys = toggleSmileys;
  3767. /**
  3768. * Scrolls chat to the bottom.
  3769. */
  3770. my.scrollChatToBottom = function() {
  3771. setTimeout(function () {
  3772. $('#chatconversation').scrollTop(
  3773. $('#chatconversation')[0].scrollHeight);
  3774. }, 5);
  3775. };
  3776. return my;
  3777. }(Chat || {}));
  3778. module.exports = Chat;
  3779. },{"../../../../service/UI/UIEvents":92,"../../toolbars/ToolbarToggler":26,"../../util/NicknameHandler":29,"../../util/UIUtil":30,"../SidePanelToggler":17,"./Commands":19,"./Replacement":20,"./smileys.json":21}],19:[function(require,module,exports){
  3780. var UIUtil = require("../../util/UIUtil");
  3781. /**
  3782. * List with supported commands. The keys are the names of the commands and
  3783. * the value is the function that processes the message.
  3784. * @type {{String: function}}
  3785. */
  3786. var commands = {
  3787. "topic" : processTopic
  3788. };
  3789. /**
  3790. * Extracts the command from the message.
  3791. * @param message the received message
  3792. * @returns {string} the command
  3793. */
  3794. function getCommand(message)
  3795. {
  3796. if(message)
  3797. {
  3798. for(var command in commands)
  3799. {
  3800. if(message.indexOf("/" + command) == 0)
  3801. return command;
  3802. }
  3803. }
  3804. return "";
  3805. };
  3806. /**
  3807. * Processes the data for topic command.
  3808. * @param commandArguments the arguments of the topic command.
  3809. */
  3810. function processTopic(commandArguments)
  3811. {
  3812. var topic = UIUtil.escapeHtml(commandArguments);
  3813. APP.xmpp.setSubject(topic);
  3814. }
  3815. /**
  3816. * Constructs new CommandProccessor instance from a message that
  3817. * handles commands received via chat messages.
  3818. * @param message the message
  3819. * @constructor
  3820. */
  3821. function CommandsProcessor(message)
  3822. {
  3823. var command = getCommand(message);
  3824. /**
  3825. * Returns the name of the command.
  3826. * @returns {String} the command
  3827. */
  3828. this.getCommand = function()
  3829. {
  3830. return command;
  3831. };
  3832. var messageArgument = message.substr(command.length + 2);
  3833. /**
  3834. * Returns the arguments of the command.
  3835. * @returns {string}
  3836. */
  3837. this.getArgument = function()
  3838. {
  3839. return messageArgument;
  3840. };
  3841. }
  3842. /**
  3843. * Checks whether this instance is valid command or not.
  3844. * @returns {boolean}
  3845. */
  3846. CommandsProcessor.prototype.isCommand = function()
  3847. {
  3848. if(this.getCommand())
  3849. return true;
  3850. return false;
  3851. };
  3852. /**
  3853. * Processes the command.
  3854. */
  3855. CommandsProcessor.prototype.processCommand = function()
  3856. {
  3857. if(!this.isCommand())
  3858. return;
  3859. commands[this.getCommand()](this.getArgument());
  3860. };
  3861. module.exports = CommandsProcessor;
  3862. },{"../../util/UIUtil":30}],20:[function(require,module,exports){
  3863. var Smileys = require("./smileys.json");
  3864. /**
  3865. * Processes links and smileys in "body"
  3866. */
  3867. function processReplacements(body)
  3868. {
  3869. //make links clickable
  3870. body = linkify(body);
  3871. //add smileys
  3872. body = smilify(body);
  3873. return body;
  3874. }
  3875. /**
  3876. * Finds and replaces all links in the links in "body"
  3877. * with their <a href=""></a>
  3878. */
  3879. function linkify(inputText)
  3880. {
  3881. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  3882. //URLs starting with http://, https://, or ftp://
  3883. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  3884. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  3885. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  3886. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  3887. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  3888. //Change email addresses to mailto:: links.
  3889. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  3890. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  3891. return replacedText;
  3892. }
  3893. /**
  3894. * Replaces common smiley strings with images
  3895. */
  3896. function smilify(body)
  3897. {
  3898. if(!body) {
  3899. return body;
  3900. }
  3901. var regexs = Smileys["regexs"];
  3902. for(var smiley in regexs) {
  3903. if(regexs.hasOwnProperty(smiley)) {
  3904. body = body.replace(regexs[smiley],
  3905. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  3906. }
  3907. }
  3908. return body;
  3909. }
  3910. module.exports = {
  3911. processReplacements: processReplacements,
  3912. linkify: linkify
  3913. };
  3914. },{"./smileys.json":21}],21:[function(require,module,exports){
  3915. module.exports={
  3916. "smileys": {
  3917. "smiley1": ":)",
  3918. "smiley2": ":(",
  3919. "smiley3": ":D",
  3920. "smiley4": "(y)",
  3921. "smiley5": " :P",
  3922. "smiley6": "(wave)",
  3923. "smiley7": "(blush)",
  3924. "smiley8": "(chuckle)",
  3925. "smiley9": "(shocked)",
  3926. "smiley10": ":*",
  3927. "smiley11": "(n)",
  3928. "smiley12": "(search)",
  3929. "smiley13": " <3",
  3930. "smiley14": "(oops)",
  3931. "smiley15": "(angry)",
  3932. "smiley16": "(angel)",
  3933. "smiley17": "(sick)",
  3934. "smiley18": ";(",
  3935. "smiley19": "(bomb)",
  3936. "smiley20": "(clap)",
  3937. "smiley21": " ;)"
  3938. },
  3939. "regexs": {
  3940. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  3941. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  3942. "smiley1": /(:-\)|:\))/gi,
  3943. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  3944. "smiley5": /(:-P|:P|:-p|:p)/gi,
  3945. "smiley6": /(\(wave\))/gi,
  3946. "smiley7": /(\(blush\))/gi,
  3947. "smiley8": /(\(chuckle\))/gi,
  3948. "smiley9": /(:-0|\(shocked\))/gi,
  3949. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  3950. "smiley11": /(\(n\))/gi,
  3951. "smiley12": /(\(search\))/g,
  3952. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  3953. "smiley14": /(\(oops\))/gi,
  3954. "smiley15": /(\(angry\))/gi,
  3955. "smiley16": /(\(angel\))/gi,
  3956. "smiley17": /(\(sick\))/gi,
  3957. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  3958. "smiley19": /(\(bomb\))/gi,
  3959. "smiley20": /(\(clap\))/gi,
  3960. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  3961. }
  3962. }
  3963. },{}],22:[function(require,module,exports){
  3964. var numberOfContacts = 0;
  3965. var notificationInterval;
  3966. /**
  3967. * Updates the number of participants in the contact list button and sets
  3968. * the glow
  3969. * @param delta indicates whether a new user has joined (1) or someone has
  3970. * left(-1)
  3971. */
  3972. function updateNumberOfParticipants(delta) {
  3973. //when the user is alone we don't show the number of participants
  3974. if(numberOfContacts === 0) {
  3975. $("#numberOfParticipants").text('');
  3976. numberOfContacts += delta;
  3977. } else if(numberOfContacts !== 0 && !ContactList.isVisible()) {
  3978. ContactList.setVisualNotification(true);
  3979. numberOfContacts += delta;
  3980. $("#numberOfParticipants").text(numberOfContacts);
  3981. }
  3982. }
  3983. /**
  3984. * Creates the avatar element.
  3985. *
  3986. * @return the newly created avatar element
  3987. */
  3988. function createAvatar(id) {
  3989. var avatar = document.createElement('img');
  3990. avatar.className = "icon-avatar avatar";
  3991. avatar.src = "https://www.gravatar.com/avatar/" + id + "?d=wavatar&size=30";
  3992. return avatar;
  3993. }
  3994. /**
  3995. * Creates the display name paragraph.
  3996. *
  3997. * @param displayName the display name to set
  3998. */
  3999. function createDisplayNameParagraph(key, displayName) {
  4000. var p = document.createElement('p');
  4001. if(displayName)
  4002. p.innerText = displayName;
  4003. else if(key)
  4004. {
  4005. p.setAttribute("data-i18n",key);
  4006. p.innerText = APP.translation.translateString(key);
  4007. }
  4008. return p;
  4009. }
  4010. function stopGlowing(glower) {
  4011. window.clearInterval(notificationInterval);
  4012. notificationInterval = false;
  4013. glower.removeClass('glowing');
  4014. if (!ContactList.isVisible()) {
  4015. glower.removeClass('active');
  4016. }
  4017. }
  4018. /**
  4019. * Contact list.
  4020. */
  4021. var ContactList = {
  4022. /**
  4023. * Indicates if the chat is currently visible.
  4024. *
  4025. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  4026. * otherwise
  4027. */
  4028. isVisible: function () {
  4029. return $('#contactlist').is(":visible");
  4030. },
  4031. /**
  4032. * Adds a contact for the given peerJid if such doesn't yet exist.
  4033. *
  4034. * @param peerJid the peerJid corresponding to the contact
  4035. * @param id the user's email or userId used to get the user's avatar
  4036. */
  4037. ensureAddContact: function (peerJid, id) {
  4038. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4039. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4040. if (!contact || contact.length <= 0)
  4041. ContactList.addContact(peerJid, id);
  4042. },
  4043. /**
  4044. * Adds a contact for the given peer jid.
  4045. *
  4046. * @param peerJid the jid of the contact to add
  4047. * @param id the email or userId of the user
  4048. */
  4049. addContact: function (peerJid, id) {
  4050. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4051. var contactlist = $('#contactlist>ul');
  4052. var newContact = document.createElement('li');
  4053. newContact.id = resourceJid;
  4054. newContact.className = "clickable";
  4055. newContact.onclick = function (event) {
  4056. if (event.currentTarget.className === "clickable") {
  4057. $(ContactList).trigger('contactclicked', [peerJid]);
  4058. }
  4059. };
  4060. newContact.appendChild(createAvatar(id));
  4061. newContact.appendChild(createDisplayNameParagraph("participant"));
  4062. var clElement = contactlist.get(0);
  4063. if (resourceJid === APP.xmpp.myResource()
  4064. && $('#contactlist>ul .title')[0].nextSibling.nextSibling) {
  4065. clElement.insertBefore(newContact,
  4066. $('#contactlist>ul .title')[0].nextSibling.nextSibling);
  4067. }
  4068. else {
  4069. clElement.appendChild(newContact);
  4070. }
  4071. updateNumberOfParticipants(1);
  4072. },
  4073. /**
  4074. * Removes a contact for the given peer jid.
  4075. *
  4076. * @param peerJid the peerJid corresponding to the contact to remove
  4077. */
  4078. removeContact: function (peerJid) {
  4079. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4080. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4081. if (contact && contact.length > 0) {
  4082. var contactlist = $('#contactlist>ul');
  4083. contactlist.get(0).removeChild(contact.get(0));
  4084. updateNumberOfParticipants(-1);
  4085. }
  4086. },
  4087. setVisualNotification: function (show, stopGlowingIn) {
  4088. var glower = $('#contactListButton');
  4089. if (show && !notificationInterval) {
  4090. notificationInterval = window.setInterval(function () {
  4091. glower.toggleClass('active glowing');
  4092. }, 800);
  4093. }
  4094. else if (!show && notificationInterval) {
  4095. stopGlowing(glower);
  4096. }
  4097. if (stopGlowingIn) {
  4098. setTimeout(function () {
  4099. stopGlowing(glower);
  4100. }, stopGlowingIn);
  4101. }
  4102. },
  4103. setClickable: function (resourceJid, isClickable) {
  4104. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4105. if (isClickable) {
  4106. contact.addClass('clickable');
  4107. } else {
  4108. contact.removeClass('clickable');
  4109. }
  4110. },
  4111. onDisplayNameChange: function (peerJid, displayName) {
  4112. if (peerJid === 'localVideoContainer')
  4113. peerJid = APP.xmpp.myJid();
  4114. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4115. var contactName = $('#contactlist #' + resourceJid + '>p');
  4116. if (contactName && displayName && displayName.length > 0)
  4117. contactName.html(displayName);
  4118. }
  4119. };
  4120. module.exports = ContactList;
  4121. },{}],23:[function(require,module,exports){
  4122. var Avatar = require("../../avatar/Avatar");
  4123. var Settings = require("./../../../settings/Settings");
  4124. var UIUtil = require("../../util/UIUtil");
  4125. var languages = require("../../../../service/translation/languages");
  4126. function generateLanguagesSelectBox()
  4127. {
  4128. var currentLang = APP.translation.getCurrentLanguage();
  4129. var html = "<select id=\"languages_selectbox\">";
  4130. var langArray = languages.getLanguages();
  4131. for(var i = 0; i < langArray.length; i++)
  4132. {
  4133. var lang = langArray[i];
  4134. html += "<option ";
  4135. if(lang === currentLang)
  4136. html += "selected ";
  4137. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  4138. html += "</option>";
  4139. }
  4140. return html + "</select>";
  4141. }
  4142. var SettingsMenu = {
  4143. init: function () {
  4144. $("#updateSettings").before(generateLanguagesSelectBox());
  4145. APP.translation.translateElement($("#languages_selectbox"));
  4146. $('#settingsmenu>input').keyup(function(event){
  4147. if(event.keyCode === 13) {//enter
  4148. SettingsMenu.update();
  4149. }
  4150. });
  4151. $("#updateSettings").click(function () {
  4152. SettingsMenu.update();
  4153. });
  4154. },
  4155. update: function() {
  4156. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  4157. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  4158. if(newDisplayName) {
  4159. var displayName = Settings.setDisplayName(newDisplayName);
  4160. APP.xmpp.addToPresence("displayName", displayName, true);
  4161. }
  4162. var language = $("#languages_selectbox").val();
  4163. APP.translation.setLanguage(language);
  4164. Settings.setLanguage(language);
  4165. APP.xmpp.addToPresence("email", newEmail);
  4166. var email = Settings.setEmail(newEmail);
  4167. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  4168. },
  4169. isVisible: function() {
  4170. return $('#settingsmenu').is(':visible');
  4171. },
  4172. setDisplayName: function(newDisplayName) {
  4173. var displayName = Settings.setDisplayName(newDisplayName);
  4174. $('#setDisplayName').get(0).value = displayName;
  4175. },
  4176. onDisplayNameChange: function(peerJid, newDisplayName) {
  4177. if(peerJid === 'localVideoContainer' ||
  4178. peerJid === APP.xmpp.myJid()) {
  4179. this.setDisplayName(newDisplayName);
  4180. }
  4181. }
  4182. };
  4183. module.exports = SettingsMenu;
  4184. },{"../../../../service/translation/languages":96,"../../avatar/Avatar":13,"../../util/UIUtil":30,"./../../../settings/Settings":38}],24:[function(require,module,exports){
  4185. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4186. var buttonHandlers = {
  4187. "bottom_toolbar_contact_list": function () {
  4188. BottomToolbar.toggleContactList();
  4189. },
  4190. "bottom_toolbar_film_strip": function () {
  4191. BottomToolbar.toggleFilmStrip();
  4192. },
  4193. "bottom_toolbar_chat": function () {
  4194. BottomToolbar.toggleChat();
  4195. }
  4196. };
  4197. var BottomToolbar = (function (my) {
  4198. my.init = function () {
  4199. for(var k in buttonHandlers)
  4200. $("#" + k).click(buttonHandlers[k]);
  4201. };
  4202. my.toggleChat = function() {
  4203. PanelToggler.toggleChat();
  4204. };
  4205. my.toggleContactList = function() {
  4206. PanelToggler.toggleContactList();
  4207. };
  4208. my.toggleFilmStrip = function() {
  4209. var filmstrip = $("#remoteVideos");
  4210. filmstrip.toggleClass("hidden");
  4211. };
  4212. $(document).bind("remotevideo.resized", function (event, width, height) {
  4213. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  4214. $('#bottomToolbar').css({bottom: bottom + 'px'});
  4215. });
  4216. return my;
  4217. }(BottomToolbar || {}));
  4218. module.exports = BottomToolbar;
  4219. },{"../side_pannels/SidePanelToggler":17}],25:[function(require,module,exports){
  4220. /* global APP,$, buttonClick, config, lockRoom,
  4221. setSharedKey, Util */
  4222. var messageHandler = require("../util/MessageHandler");
  4223. var BottomToolbar = require("./BottomToolbar");
  4224. var Prezi = require("../prezi/Prezi");
  4225. var Etherpad = require("../etherpad/Etherpad");
  4226. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4227. var Authentication = require("../authentication/Authentication");
  4228. var UIUtil = require("../util/UIUtil");
  4229. var AuthenticationEvents
  4230. = require("../../../service/authentication/AuthenticationEvents");
  4231. var roomUrl = null;
  4232. var sharedKey = '';
  4233. var UI = null;
  4234. var buttonHandlers =
  4235. {
  4236. "toolbar_button_mute": function () {
  4237. return APP.UI.toggleAudio();
  4238. },
  4239. "toolbar_button_camera": function () {
  4240. return APP.UI.toggleVideo();
  4241. },
  4242. /*"toolbar_button_authentication": function () {
  4243. return Toolbar.authenticateClicked();
  4244. },*/
  4245. "toolbar_button_record": function () {
  4246. return toggleRecording();
  4247. },
  4248. "toolbar_button_security": function () {
  4249. return Toolbar.openLockDialog();
  4250. },
  4251. "toolbar_button_link": function () {
  4252. return Toolbar.openLinkDialog();
  4253. },
  4254. "toolbar_button_chat": function () {
  4255. return BottomToolbar.toggleChat();
  4256. },
  4257. "toolbar_button_prezi": function () {
  4258. return Prezi.openPreziDialog();
  4259. },
  4260. "toolbar_button_etherpad": function () {
  4261. return Etherpad.toggleEtherpad(0);
  4262. },
  4263. "toolbar_button_desktopsharing": function () {
  4264. return APP.desktopsharing.toggleScreenSharing();
  4265. },
  4266. "toolbar_button_fullScreen": function()
  4267. {
  4268. UIUtil.buttonClick("#fullScreen", "icon-full-screen icon-exit-full-screen");
  4269. return Toolbar.toggleFullScreen();
  4270. },
  4271. "toolbar_button_sip": function () {
  4272. return callSipButtonClicked();
  4273. },
  4274. "toolbar_button_settings": function () {
  4275. PanelToggler.toggleSettingsMenu();
  4276. },
  4277. "toolbar_button_hangup": function () {
  4278. return hangup();
  4279. },
  4280. "toolbar_button_login": function () {
  4281. Toolbar.authenticateClicked();
  4282. },
  4283. "toolbar_button_logout": function () {
  4284. // Ask for confirmation
  4285. messageHandler.openTwoButtonDialog(
  4286. "dialog.logoutTitle",
  4287. null,
  4288. "dialog.logoutQuestion",
  4289. null,
  4290. false,
  4291. "dialog.Yes",
  4292. function (evt, yes) {
  4293. if (yes) {
  4294. APP.xmpp.logout(function (url) {
  4295. if (url) {
  4296. window.location.href = url;
  4297. } else {
  4298. hangup();
  4299. }
  4300. });
  4301. }
  4302. });
  4303. }
  4304. };
  4305. function hangup() {
  4306. APP.xmpp.disposeConference();
  4307. if(config.enableWelcomePage)
  4308. {
  4309. setTimeout(function()
  4310. {
  4311. window.localStorage.welcomePageDisabled = false;
  4312. window.location.pathname = "/";
  4313. }, 10000);
  4314. }
  4315. var title = APP.translation.generateTranslatonHTML(
  4316. "dialog.sessTerminated");
  4317. var msg = APP.translation.generateTranslatonHTML(
  4318. "dialog.hungUp");
  4319. var button = APP.translation.generateTranslatonHTML(
  4320. "dialog.joinAgain");
  4321. var buttons = [];
  4322. buttons.push({title: button, value: true});
  4323. UI.messageHandler.openDialog(
  4324. title,
  4325. msg,
  4326. true,
  4327. buttons,
  4328. function(event, value, message, formVals)
  4329. {
  4330. window.location.reload();
  4331. return false;
  4332. }
  4333. );
  4334. }
  4335. /**
  4336. * Starts or stops the recording for the conference.
  4337. */
  4338. function toggleRecording() {
  4339. APP.xmpp.toggleRecording(function (callback) {
  4340. var msg = APP.translation.generateTranslatonHTML(
  4341. "dialog.recordingToken");
  4342. var token = APP.translation.translateString("dialog.token");
  4343. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  4344. '<h2>' + msg + '</h2>' +
  4345. '<input name="recordingToken" type="text" ' +
  4346. ' data-i18n="[placeholder]dialog.token" ' +
  4347. 'placeholder="' + token + '" autofocus>',
  4348. false,
  4349. "dialog.Save",
  4350. function (e, v, m, f) {
  4351. if (v) {
  4352. var token = f.recordingToken;
  4353. if (token) {
  4354. callback(UIUtil.escapeHtml(token));
  4355. }
  4356. }
  4357. },
  4358. null,
  4359. function () { },
  4360. ':input:first'
  4361. );
  4362. }, Toolbar.setRecordingButtonState, Toolbar.setRecordingButtonState);
  4363. }
  4364. /**
  4365. * Locks / unlocks the room.
  4366. */
  4367. function lockRoom(lock) {
  4368. var currentSharedKey = '';
  4369. if (lock)
  4370. currentSharedKey = sharedKey;
  4371. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  4372. // password is required
  4373. if (sharedKey)
  4374. {
  4375. console.log('set room password');
  4376. Toolbar.lockLockButton();
  4377. }
  4378. else
  4379. {
  4380. console.log('removed room password');
  4381. Toolbar.unlockLockButton();
  4382. }
  4383. }, function (err) {
  4384. console.warn('setting password failed', err);
  4385. messageHandler.showError("dialog.lockTitle",
  4386. "dialog.lockMessage");
  4387. Toolbar.setSharedKey('');
  4388. }, function () {
  4389. console.warn('room passwords not supported');
  4390. messageHandler.showError("dialog.warning",
  4391. "dialog.passwordNotSupported");
  4392. Toolbar.setSharedKey('');
  4393. });
  4394. };
  4395. /**
  4396. * Invite participants to conference.
  4397. */
  4398. function inviteParticipants() {
  4399. if (roomUrl === null)
  4400. return;
  4401. var sharedKeyText = "";
  4402. if (sharedKey && sharedKey.length > 0) {
  4403. sharedKeyText =
  4404. APP.translation.translateString("email.sharedKey",
  4405. {sharedKey: sharedKey});
  4406. sharedKeyText = sharedKeyText.replace(/\n/g, "%0D%0A");
  4407. }
  4408. var supportedBrowsers = "Chromium, Google Chrome " +
  4409. APP.translation.translateString("email.and") + " Opera";
  4410. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  4411. var subject = APP.translation.translateString("email.subject",
  4412. {appName:interfaceConfig.APP_NAME, conferenceName: conferenceName});
  4413. var body = APP.translation.translateString("email.body",
  4414. {appName:interfaceConfig.APP_NAME, sharedKeyText: sharedKeyText,
  4415. roomUrl: roomUrl, supportedBrowsers: supportedBrowsers});
  4416. body = body.replace(/\n/g, "%0D%0A");
  4417. if (window.localStorage.displayname) {
  4418. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  4419. }
  4420. if (interfaceConfig.INVITATION_POWERED_BY) {
  4421. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  4422. }
  4423. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  4424. }
  4425. function callSipButtonClicked()
  4426. {
  4427. var defaultNumber
  4428. = config.defaultSipNumber ? config.defaultSipNumber : '';
  4429. var sipMsg = APP.translation.generateTranslatonHTML(
  4430. "dialog.sipMsg");
  4431. messageHandler.openTwoButtonDialog(null, null, null,
  4432. '<h2>' + sipMsg + '</h2>' +
  4433. '<input name="sipNumber" type="text"' +
  4434. ' value="' + defaultNumber + '" autofocus>',
  4435. false,
  4436. "dialog.Dial",
  4437. function (e, v, m, f) {
  4438. if (v) {
  4439. var numberInput = f.sipNumber;
  4440. if (numberInput) {
  4441. APP.xmpp.dial(
  4442. numberInput, 'fromnumber', UI.getRoomName(), sharedKey);
  4443. }
  4444. }
  4445. },
  4446. null,
  4447. ':input:first'
  4448. );
  4449. }
  4450. var Toolbar = (function (my) {
  4451. my.init = function (ui) {
  4452. for(var k in buttonHandlers)
  4453. $("#" + k).click(buttonHandlers[k]);
  4454. UI = ui;
  4455. // Update login info
  4456. APP.xmpp.addListener(
  4457. AuthenticationEvents.IDENTITY_UPDATED,
  4458. function (authenticationEnabled, userIdentity) {
  4459. var loggedIn = false;
  4460. if (userIdentity) {
  4461. loggedIn = true;
  4462. }
  4463. Toolbar.showAuthenticateButton(authenticationEnabled);
  4464. if (authenticationEnabled) {
  4465. Toolbar.setAuthenticatedIdentity(userIdentity);
  4466. Toolbar.showLoginButton(!loggedIn);
  4467. Toolbar.showLogoutButton(loggedIn);
  4468. }
  4469. }
  4470. );
  4471. },
  4472. /**
  4473. * Sets shared key
  4474. * @param sKey the shared key
  4475. */
  4476. my.setSharedKey = function (sKey) {
  4477. sharedKey = sKey;
  4478. };
  4479. my.authenticateClicked = function () {
  4480. Authentication.focusAuthenticationWindow();
  4481. if (!APP.xmpp.isExternalAuthEnabled()) {
  4482. Authentication.xmppAuthenticate();
  4483. return;
  4484. }
  4485. // Get authentication URL
  4486. if (!APP.xmpp.getMUCJoined()) {
  4487. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  4488. // If conference has not been started yet - redirect to login page
  4489. window.location.href = url;
  4490. });
  4491. } else {
  4492. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  4493. // Otherwise - open popup with authentication URL
  4494. var authenticationWindow = Authentication.createAuthenticationWindow(
  4495. function () {
  4496. // On popup closed - retry room allocation
  4497. APP.xmpp.allocateConferenceFocus(
  4498. APP.UI.getRoomName(),
  4499. function () { console.info("AUTH DONE"); }
  4500. );
  4501. }, url);
  4502. if (!authenticationWindow) {
  4503. messageHandler.openMessageDialog(
  4504. null, "dialog.popupError");
  4505. }
  4506. });
  4507. }
  4508. };
  4509. /**
  4510. * Updates the room invite url.
  4511. */
  4512. my.updateRoomUrl = function (newRoomUrl) {
  4513. roomUrl = newRoomUrl;
  4514. // If the invite dialog has been already opened we update the information.
  4515. var inviteLink = document.getElementById('inviteLinkRef');
  4516. if (inviteLink) {
  4517. inviteLink.value = roomUrl;
  4518. inviteLink.select();
  4519. document.getElementById('jqi_state0_buttonInvite').disabled = false;
  4520. }
  4521. };
  4522. /**
  4523. * Disables and enables some of the buttons.
  4524. */
  4525. my.setupButtonsFromConfig = function () {
  4526. if (config.disablePrezi)
  4527. {
  4528. $("#prezi_button").css({display: "none"});
  4529. }
  4530. };
  4531. /**
  4532. * Opens the lock room dialog.
  4533. */
  4534. my.openLockDialog = function () {
  4535. // Only the focus is able to set a shared key.
  4536. if (!APP.xmpp.isModerator()) {
  4537. if (sharedKey) {
  4538. messageHandler.openMessageDialog(null,
  4539. "dialog.passwordError");
  4540. } else {
  4541. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  4542. }
  4543. } else {
  4544. if (sharedKey) {
  4545. messageHandler.openTwoButtonDialog(null, null,
  4546. "dialog.passwordCheck",
  4547. null,
  4548. false,
  4549. "dialog.Remove",
  4550. function (e, v) {
  4551. if (v) {
  4552. Toolbar.setSharedKey('');
  4553. lockRoom(false);
  4554. }
  4555. });
  4556. } else {
  4557. var msg = APP.translation.generateTranslatonHTML(
  4558. "dialog.passwordMsg");
  4559. var yourPassword = APP.translation.translateString(
  4560. "dialog.yourPassword");
  4561. messageHandler.openTwoButtonDialog(null, null, null,
  4562. '<h2>' + msg + '</h2>' +
  4563. '<input name="lockKey" type="text"' +
  4564. ' data-i18n="[placeholder]dialog.yourPassword" ' +
  4565. 'placeholder="' + yourPassword + '" autofocus>',
  4566. false,
  4567. "dialog.Save",
  4568. function (e, v, m, f) {
  4569. if (v) {
  4570. var lockKey = f.lockKey;
  4571. if (lockKey) {
  4572. Toolbar.setSharedKey(
  4573. UIUtil.escapeHtml(lockKey));
  4574. lockRoom(true);
  4575. }
  4576. }
  4577. },
  4578. null, null, 'input:first'
  4579. );
  4580. }
  4581. }
  4582. };
  4583. /**
  4584. * Opens the invite link dialog.
  4585. */
  4586. my.openLinkDialog = function () {
  4587. var inviteAttreibutes;
  4588. if (roomUrl === null) {
  4589. inviteAttreibutes = 'data-i18n="[value]roomUrlDefaultMsg" value="' +
  4590. APP.translation.translateString("roomUrlDefaultMsg") + '"';
  4591. } else {
  4592. inviteAttreibutes = "value=\"" + encodeURI(roomUrl) + "\"";
  4593. }
  4594. messageHandler.openTwoButtonDialog("dialog.shareLink",
  4595. null, null,
  4596. '<input id="inviteLinkRef" type="text" ' +
  4597. inviteAttreibutes + ' onclick="this.select();" readonly>',
  4598. false,
  4599. "dialog.Invite",
  4600. function (e, v) {
  4601. if (v) {
  4602. if (roomUrl) {
  4603. inviteParticipants();
  4604. }
  4605. }
  4606. },
  4607. function () {
  4608. if (roomUrl) {
  4609. document.getElementById('inviteLinkRef').select();
  4610. } else {
  4611. document.getElementById('jqi_state0_buttonInvite')
  4612. .disabled = true;
  4613. }
  4614. }
  4615. );
  4616. };
  4617. /**
  4618. * Opens the settings dialog.
  4619. * FIXME: not used ?
  4620. */
  4621. my.openSettingsDialog = function () {
  4622. var settings1 = APP.translation.generateTranslatonHTML(
  4623. "dialog.settings1");
  4624. var settings2 = APP.translation.generateTranslatonHTML(
  4625. "dialog.settings2");
  4626. var settings3 = APP.translation.generateTranslatonHTML(
  4627. "dialog.settings3");
  4628. var yourPassword = APP.translation.translateString(
  4629. "dialog.yourPassword");
  4630. messageHandler.openTwoButtonDialog(null,
  4631. '<h2>' + settings1 + '</h2>' +
  4632. '<input type="checkbox" id="initMuted">' +
  4633. settings2 + '<br/>' +
  4634. '<input type="checkbox" id="requireNicknames">' +
  4635. settings3 +
  4636. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  4637. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  4638. null,
  4639. null,
  4640. false,
  4641. "dialog.Save",
  4642. function () {
  4643. document.getElementById('lockKey').focus();
  4644. },
  4645. function (e, v) {
  4646. if (v) {
  4647. if ($('#initMuted').is(":checked")) {
  4648. // it is checked
  4649. }
  4650. if ($('#requireNicknames').is(":checked")) {
  4651. // it is checked
  4652. }
  4653. /*
  4654. var lockKey = document.getElementById('lockKey');
  4655. if (lockKey.value) {
  4656. setSharedKey(lockKey.value);
  4657. lockRoom(true);
  4658. }
  4659. */
  4660. }
  4661. }
  4662. );
  4663. };
  4664. /**
  4665. * Toggles the application in and out of full screen mode
  4666. * (a.k.a. presentation mode in Chrome).
  4667. */
  4668. my.toggleFullScreen = function () {
  4669. var fsElement = document.documentElement;
  4670. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  4671. //Enter Full Screen
  4672. if (fsElement.mozRequestFullScreen) {
  4673. fsElement.mozRequestFullScreen();
  4674. }
  4675. else {
  4676. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  4677. }
  4678. } else {
  4679. //Exit Full Screen
  4680. if (document.mozCancelFullScreen) {
  4681. document.mozCancelFullScreen();
  4682. } else {
  4683. document.webkitCancelFullScreen();
  4684. }
  4685. }
  4686. };
  4687. /**
  4688. * Unlocks the lock button state.
  4689. */
  4690. my.unlockLockButton = function () {
  4691. if ($("#lockIcon").hasClass("icon-security-locked"))
  4692. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  4693. };
  4694. /**
  4695. * Updates the lock button state to locked.
  4696. */
  4697. my.lockLockButton = function () {
  4698. if ($("#lockIcon").hasClass("icon-security"))
  4699. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  4700. };
  4701. /**
  4702. * Shows or hides authentication button
  4703. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  4704. */
  4705. my.showAuthenticateButton = function (show) {
  4706. if (show) {
  4707. $('#authentication').css({display: "inline"});
  4708. }
  4709. else {
  4710. $('#authentication').css({display: "none"});
  4711. }
  4712. };
  4713. // Shows or hides the 'recording' button.
  4714. my.showRecordingButton = function (show) {
  4715. if (!config.enableRecording) {
  4716. return;
  4717. }
  4718. if (show) {
  4719. $('#recording').css({display: "inline"});
  4720. }
  4721. else {
  4722. $('#recording').css({display: "none"});
  4723. }
  4724. };
  4725. // Sets the state of the recording button
  4726. my.setRecordingButtonState = function (isRecording) {
  4727. if (isRecording) {
  4728. $('#recordButton').removeClass("icon-recEnable");
  4729. $('#recordButton').addClass("icon-recEnable active");
  4730. } else {
  4731. $('#recordButton').removeClass("icon-recEnable active");
  4732. $('#recordButton').addClass("icon-recEnable");
  4733. }
  4734. };
  4735. // Shows or hides SIP calls button
  4736. my.showSipCallButton = function (show) {
  4737. if (APP.xmpp.isSipGatewayEnabled() && show) {
  4738. $('#sipCallButton').css({display: "inline-block"});
  4739. } else {
  4740. $('#sipCallButton').css({display: "none"});
  4741. }
  4742. };
  4743. /**
  4744. * Displays user authenticated identity name(login).
  4745. * @param authIdentity identity name to be displayed.
  4746. */
  4747. my.setAuthenticatedIdentity = function (authIdentity) {
  4748. if (authIdentity) {
  4749. $('#toolbar_auth_identity').css({display: "list-item"});
  4750. $('#toolbar_auth_identity').text(authIdentity);
  4751. } else {
  4752. $('#toolbar_auth_identity').css({display: "none"});
  4753. }
  4754. };
  4755. /**
  4756. * Shows/hides login button.
  4757. * @param show <tt>true</tt> to show
  4758. */
  4759. my.showLoginButton = function (show) {
  4760. if (show) {
  4761. $('#toolbar_button_login').css({display: "list-item"});
  4762. } else {
  4763. $('#toolbar_button_login').css({display: "none"});
  4764. }
  4765. };
  4766. /**
  4767. * Shows/hides logout button.
  4768. * @param show <tt>true</tt> to show
  4769. */
  4770. my.showLogoutButton = function (show) {
  4771. if (show) {
  4772. $('#toolbar_button_logout').css({display: "list-item"});
  4773. } else {
  4774. $('#toolbar_button_logout').css({display: "none"});
  4775. }
  4776. };
  4777. /**
  4778. * Sets the state of the button. The button has blue glow if desktop
  4779. * streaming is active.
  4780. * @param active the state of the desktop streaming.
  4781. */
  4782. my.changeDesktopSharingButtonState = function (active) {
  4783. var button = $("#desktopsharing > a");
  4784. if (active)
  4785. {
  4786. button.addClass("glow");
  4787. }
  4788. else
  4789. {
  4790. button.removeClass("glow");
  4791. }
  4792. };
  4793. return my;
  4794. }(Toolbar || {}));
  4795. module.exports = Toolbar;
  4796. },{"../../../service/authentication/AuthenticationEvents":93,"../authentication/Authentication":11,"../etherpad/Etherpad":14,"../prezi/Prezi":15,"../side_pannels/SidePanelToggler":17,"../util/MessageHandler":28,"../util/UIUtil":30,"./BottomToolbar":24}],26:[function(require,module,exports){
  4797. /* global $, interfaceConfig, Moderator, DesktopStreaming.showDesktopSharingButton */
  4798. var toolbarTimeoutObject,
  4799. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  4800. function showDesktopSharingButton() {
  4801. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  4802. $('#desktopsharing').css({display: "inline"});
  4803. } else {
  4804. $('#desktopsharing').css({display: "none"});
  4805. }
  4806. }
  4807. /**
  4808. * Hides the toolbar.
  4809. */
  4810. function hideToolbar() {
  4811. var header = $("#header"),
  4812. bottomToolbar = $("#bottomToolbar");
  4813. var isToolbarHover = false;
  4814. header.find('*').each(function () {
  4815. var id = $(this).attr('id');
  4816. if ($("#" + id + ":hover").length > 0) {
  4817. isToolbarHover = true;
  4818. }
  4819. });
  4820. if ($("#bottomToolbar:hover").length > 0) {
  4821. isToolbarHover = true;
  4822. }
  4823. clearTimeout(toolbarTimeoutObject);
  4824. toolbarTimeoutObject = null;
  4825. if (!isToolbarHover) {
  4826. header.hide("slide", { direction: "up", duration: 300});
  4827. $('#subject').animate({top: "-=40"}, 300);
  4828. if ($("#remoteVideos").hasClass("hidden")) {
  4829. bottomToolbar.hide(
  4830. "slide", {direction: "right", duration: 300});
  4831. }
  4832. }
  4833. else {
  4834. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4835. }
  4836. }
  4837. var ToolbarToggler = {
  4838. /**
  4839. * Shows the main toolbar.
  4840. */
  4841. showToolbar: function () {
  4842. var header = $("#header"),
  4843. bottomToolbar = $("#bottomToolbar");
  4844. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  4845. header.show("slide", { direction: "up", duration: 300});
  4846. $('#subject').animate({top: "+=40"}, 300);
  4847. if (!bottomToolbar.is(":visible")) {
  4848. bottomToolbar.show(
  4849. "slide", {direction: "right", duration: 300});
  4850. }
  4851. if (toolbarTimeoutObject) {
  4852. clearTimeout(toolbarTimeoutObject);
  4853. toolbarTimeoutObject = null;
  4854. }
  4855. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4856. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  4857. }
  4858. if (APP.xmpp.isModerator())
  4859. {
  4860. // TODO: Enable settings functionality.
  4861. // Need to uncomment the settings button in index.html.
  4862. // $('#settingsButton').css({visibility:"visible"});
  4863. }
  4864. // Show/hide desktop sharing button
  4865. showDesktopSharingButton();
  4866. },
  4867. /**
  4868. * Docks/undocks the toolbar.
  4869. *
  4870. * @param isDock indicates what operation to perform
  4871. */
  4872. dockToolbar: function (isDock) {
  4873. if (isDock) {
  4874. // First make sure the toolbar is shown.
  4875. if (!$('#header').is(':visible')) {
  4876. this.showToolbar();
  4877. }
  4878. // Then clear the time out, to dock the toolbar.
  4879. if (toolbarTimeoutObject) {
  4880. clearTimeout(toolbarTimeoutObject);
  4881. toolbarTimeoutObject = null;
  4882. }
  4883. }
  4884. else {
  4885. if (!$('#header').is(':visible')) {
  4886. this.showToolbar();
  4887. }
  4888. else {
  4889. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4890. }
  4891. }
  4892. },
  4893. showDesktopSharingButton: showDesktopSharingButton
  4894. };
  4895. module.exports = ToolbarToggler;
  4896. },{}],27:[function(require,module,exports){
  4897. var JitsiPopover = (function () {
  4898. /**
  4899. * Constructs new JitsiPopover and attaches it to the element
  4900. * @param element jquery selector
  4901. * @param options the options for the popover.
  4902. * @constructor
  4903. */
  4904. function JitsiPopover(element, options)
  4905. {
  4906. this.options = {
  4907. skin: "white",
  4908. content: ""
  4909. };
  4910. if(options)
  4911. {
  4912. if(options.skin)
  4913. this.options.skin = options.skin;
  4914. if(options.content)
  4915. this.options.content = options.content;
  4916. }
  4917. this.elementIsHovered = false;
  4918. this.popoverIsHovered = false;
  4919. this.popoverShown = false;
  4920. element.data("jitsi_popover", this);
  4921. this.element = element;
  4922. this.template = ' <div class="jitsipopover ' + this.options.skin +
  4923. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  4924. '<div class="jitsiPopupmenuPadding"></div></div>';
  4925. var self = this;
  4926. this.element.on("mouseenter", function () {
  4927. self.elementIsHovered = true;
  4928. self.show();
  4929. }).on("mouseleave", function () {
  4930. self.elementIsHovered = false;
  4931. setTimeout(function () {
  4932. self.hide();
  4933. }, 10);
  4934. });
  4935. }
  4936. /**
  4937. * Shows the popover
  4938. */
  4939. JitsiPopover.prototype.show = function () {
  4940. this.createPopover();
  4941. this.popoverShown = true;
  4942. };
  4943. /**
  4944. * Hides the popover
  4945. */
  4946. JitsiPopover.prototype.hide = function () {
  4947. if(!this.elementIsHovered && !this.popoverIsHovered && this.popoverShown)
  4948. {
  4949. this.forceHide();
  4950. }
  4951. };
  4952. /**
  4953. * Hides the popover
  4954. */
  4955. JitsiPopover.prototype.forceHide = function () {
  4956. $(".jitsipopover").remove();
  4957. this.popoverShown = false;
  4958. };
  4959. /**
  4960. * Creates the popover html
  4961. */
  4962. JitsiPopover.prototype.createPopover = function () {
  4963. $("body").append(this.template);
  4964. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  4965. var self = this;
  4966. $(".jitsipopover").on("mouseenter", function () {
  4967. self.popoverIsHovered = true;
  4968. }).on("mouseleave", function () {
  4969. self.popoverIsHovered = false;
  4970. self.hide();
  4971. });
  4972. this.refreshPosition();
  4973. };
  4974. /**
  4975. * Refreshes the position of the popover
  4976. */
  4977. JitsiPopover.prototype.refreshPosition = function () {
  4978. $(".jitsipopover").position({
  4979. my: "bottom",
  4980. at: "top",
  4981. collision: "fit",
  4982. of: this.element,
  4983. using: function (position, elements) {
  4984. var calcLeft = elements.target.left - elements.element.left + elements.target.width/2;
  4985. $(".jitsipopover").css({top: position.top, left: position.left, display: "table"});
  4986. $(".jitsipopover > .arrow").css({left: calcLeft});
  4987. $(".jitsipopover > .jitsiPopupmenuPadding").css({left: calcLeft - 50});
  4988. }
  4989. });
  4990. };
  4991. /**
  4992. * Updates the content of popover.
  4993. * @param content new content
  4994. */
  4995. JitsiPopover.prototype.updateContent = function (content) {
  4996. this.options.content = content;
  4997. if(!this.popoverShown)
  4998. return;
  4999. $(".jitsipopover").remove();
  5000. this.createPopover();
  5001. };
  5002. return JitsiPopover;
  5003. })();
  5004. module.exports = JitsiPopover;
  5005. },{}],28:[function(require,module,exports){
  5006. /* global $, APP, jQuery, toastr */
  5007. var messageHandler = (function(my) {
  5008. /**
  5009. * Shows a message to the user.
  5010. *
  5011. * @param titleString the title of the message
  5012. * @param messageString the text of the message
  5013. */
  5014. my.openMessageDialog = function(titleKey, messageKey) {
  5015. var title = null;
  5016. if(titleKey)
  5017. {
  5018. title = APP.translation.generateTranslatonHTML(titleKey);
  5019. }
  5020. var message = APP.translation.generateTranslatonHTML(messageKey);
  5021. $.prompt(message,
  5022. {
  5023. title: title,
  5024. persistent: false
  5025. }
  5026. );
  5027. };
  5028. /**
  5029. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  5030. *
  5031. * @param titleString the title of the message
  5032. * @param msgString the text of the message
  5033. * @param persistent boolean value which determines whether the message is persistent or not
  5034. * @param leftButton the fist button's text
  5035. * @param submitFunction function to be called on submit
  5036. * @param loadedFunction function to be called after the prompt is fully loaded
  5037. * @param closeFunction function to be called after the prompt is closed
  5038. * @param focus optional focus selector or button index to be focused after
  5039. * the dialog is opened
  5040. * @param defaultButton index of default button which will be activated when
  5041. * the user press 'enter'. Indexed from 0.
  5042. */
  5043. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  5044. persistent, leftButtonKey, submitFunction, loadedFunction,
  5045. closeFunction, focus, defaultButton)
  5046. {
  5047. var buttons = [];
  5048. var leftButton = APP.translation.generateTranslatonHTML(leftButtonKey);
  5049. buttons.push({ title: leftButton, value: true});
  5050. var cancelButton
  5051. = APP.translation.generateTranslatonHTML("dialog.Cancel");
  5052. buttons.push({title: cancelButton, value: false});
  5053. var message = msgString, title = titleString;
  5054. if (titleKey)
  5055. {
  5056. title = APP.translation.generateTranslatonHTML(titleKey);
  5057. }
  5058. if (msgKey) {
  5059. message = APP.translation.generateTranslatonHTML(msgKey);
  5060. }
  5061. $.prompt(message, {
  5062. title: title,
  5063. persistent: false,
  5064. buttons: buttons,
  5065. defaultButton: defaultButton,
  5066. focus: focus,
  5067. loaded: loadedFunction,
  5068. submit: submitFunction,
  5069. close: closeFunction
  5070. });
  5071. };
  5072. /**
  5073. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  5074. *
  5075. * @param titleString the title of the message
  5076. * @param msgString the text of the message
  5077. * @param persistent boolean value which determines whether the message is persistent or not
  5078. * @param buttons object with the buttons. The keys must be the name of the button and value is the value
  5079. * that will be passed to submitFunction
  5080. * @param submitFunction function to be called on submit
  5081. * @param loadedFunction function to be called after the prompt is fully loaded
  5082. */
  5083. my.openDialog = function (titleString, msgString, persistent, buttons,
  5084. submitFunction, loadedFunction) {
  5085. var args = {
  5086. title: titleString,
  5087. persistent: persistent,
  5088. buttons: buttons,
  5089. defaultButton: 1,
  5090. loaded: loadedFunction,
  5091. submit: submitFunction
  5092. };
  5093. if (persistent) {
  5094. args.closeText = '';
  5095. }
  5096. return new Impromptu(msgString, args);
  5097. };
  5098. /**
  5099. * Closes currently opened dialog.
  5100. */
  5101. my.closeDialog = function () {
  5102. $.prompt.close();
  5103. };
  5104. /**
  5105. * Shows a dialog with different states to the user.
  5106. *
  5107. * @param statesObject object containing all the states of the dialog
  5108. */
  5109. my.openDialogWithStates = function (statesObject, options) {
  5110. return new Impromptu(statesObject, options);
  5111. };
  5112. /**
  5113. * Opens new popup window for given <tt>url</tt> centered over current
  5114. * window.
  5115. *
  5116. * @param url the URL to be displayed in the popup window
  5117. * @param w the width of the popup window
  5118. * @param h the height of the popup window
  5119. * @param onPopupClosed optional callback function called when popup window
  5120. * has been closed.
  5121. *
  5122. * @returns popup window object if opened successfully or undefined
  5123. * in case we failed to open it(popup blocked)
  5124. */
  5125. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  5126. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  5127. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  5128. var popup = window.open(
  5129. url, '_blank',
  5130. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  5131. if (popup && onPopupClosed) {
  5132. var pollTimer = window.setInterval(function () {
  5133. if (popup.closed !== false) {
  5134. window.clearInterval(pollTimer);
  5135. onPopupClosed();
  5136. }
  5137. }, 200);
  5138. }
  5139. return popup;
  5140. };
  5141. /**
  5142. * Shows a dialog prompting the user to send an error report.
  5143. *
  5144. * @param titleString the title of the message
  5145. * @param msgString the text of the message
  5146. * @param error the error that is being reported
  5147. */
  5148. my.openReportDialog = function(titleKey, msgKey, error) {
  5149. my.openMessageDialog(titleKey, msgKey);
  5150. console.log(error);
  5151. //FIXME send the error to the server
  5152. };
  5153. /**
  5154. * Shows an error dialog to the user.
  5155. * @param title the title of the message
  5156. * @param message the text of the messafe
  5157. */
  5158. my.showError = function(titleKey, msgKey) {
  5159. if(!titleKey) {
  5160. titleKey = "dialog.oops";
  5161. }
  5162. if(!msgKey)
  5163. {
  5164. msgKey = "dialog.defaultError";
  5165. }
  5166. messageHandler.openMessageDialog(titleKey, msgKey);
  5167. };
  5168. my.notify = function(displayName, displayNameKey,
  5169. cls, messageKey, messageArguments) {
  5170. var displayNameSpan = '<span class="nickname" ';
  5171. if(displayName)
  5172. {
  5173. displayNameSpan += ">" + displayName;
  5174. }
  5175. else
  5176. {
  5177. displayNameSpan += "data-i18n='" + displayNameKey +
  5178. "'>" + APP.translation.translateString(displayNameKey);
  5179. }
  5180. displayNameSpan += "</span>";
  5181. toastr.info(
  5182. displayNameSpan + '<br>' +
  5183. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  5184. (messageArguments?
  5185. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  5186. : "") + ">" +
  5187. APP.translation.translateString(messageKey,
  5188. messageArguments) +
  5189. '</span>');
  5190. };
  5191. return my;
  5192. }(messageHandler || {}));
  5193. module.exports = messageHandler;
  5194. },{}],29:[function(require,module,exports){
  5195. var UIEvents = require("../../../service/UI/UIEvents");
  5196. var nickname = null;
  5197. var eventEmitter = null;
  5198. var NickanameHandler = {
  5199. init: function (emitter) {
  5200. eventEmitter = emitter;
  5201. var storedDisplayName = window.localStorage.displayname;
  5202. if (storedDisplayName) {
  5203. nickname = storedDisplayName;
  5204. }
  5205. },
  5206. setNickname: function (newNickname) {
  5207. if (!newNickname || nickname === newNickname)
  5208. return;
  5209. nickname = newNickname;
  5210. window.localStorage.displayname = nickname;
  5211. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  5212. },
  5213. getNickname: function () {
  5214. return nickname;
  5215. },
  5216. addListener: function (type, listener) {
  5217. eventEmitter.on(type, listener);
  5218. }
  5219. };
  5220. module.exports = NickanameHandler;
  5221. },{"../../../service/UI/UIEvents":92}],30:[function(require,module,exports){
  5222. /**
  5223. * Created by hristo on 12/22/14.
  5224. */
  5225. module.exports = {
  5226. /**
  5227. * Returns the available video width.
  5228. */
  5229. getAvailableVideoWidth: function () {
  5230. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5231. var rightPanelWidth
  5232. = PanelToggler.isVisible() ? PanelToggler.getPanelSize()[0] : 0;
  5233. return window.innerWidth - rightPanelWidth;
  5234. },
  5235. /**
  5236. * Changes the style class of the element given by id.
  5237. */
  5238. buttonClick: function(id, classname) {
  5239. $(id).toggleClass(classname); // add the class to the clicked element
  5240. },
  5241. /**
  5242. * Returns the text width for the given element.
  5243. *
  5244. * @param el the element
  5245. */
  5246. getTextWidth: function (el) {
  5247. return (el.clientWidth + 1);
  5248. },
  5249. /**
  5250. * Returns the text height for the given element.
  5251. *
  5252. * @param el the element
  5253. */
  5254. getTextHeight: function (el) {
  5255. return (el.clientHeight + 1);
  5256. },
  5257. /**
  5258. * Plays the sound given by id.
  5259. *
  5260. * @param id the identifier of the audio element.
  5261. */
  5262. playSoundNotification: function (id) {
  5263. document.getElementById(id).play();
  5264. },
  5265. /**
  5266. * Escapes the given text.
  5267. */
  5268. escapeHtml: function (unsafeText) {
  5269. return $('<div/>').text(unsafeText).html();
  5270. },
  5271. imageToGrayScale: function (canvas) {
  5272. var context = canvas.getContext('2d');
  5273. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  5274. var pixels = imgData.data;
  5275. for (var i = 0, n = pixels.length; i < n; i += 4) {
  5276. var grayscale
  5277. = pixels[i] * .3 + pixels[i+1] * .59 + pixels[i+2] * .11;
  5278. pixels[i ] = grayscale; // red
  5279. pixels[i+1] = grayscale; // green
  5280. pixels[i+2] = grayscale; // blue
  5281. // pixels[i+3] is alpha
  5282. }
  5283. // redraw the image in black & white
  5284. context.putImageData(imgData, 0, 0);
  5285. },
  5286. setTooltip: function (element, key, position) {
  5287. element.setAttribute("data-i18n", "[data-content]" + key);
  5288. element.setAttribute("data-toggle", "popover");
  5289. element.setAttribute("data-placement", position);
  5290. element.setAttribute("data-html", true);
  5291. element.setAttribute("data-container", "body");
  5292. }
  5293. };
  5294. },{"../side_pannels/SidePanelToggler":17}],31:[function(require,module,exports){
  5295. var JitsiPopover = require("../util/JitsiPopover");
  5296. /**
  5297. * Constructs new connection indicator.
  5298. * @param videoContainer the video container associated with the indicator.
  5299. * @constructor
  5300. */
  5301. function ConnectionIndicator(videoContainer, jid, VideoLayout)
  5302. {
  5303. this.videoContainer = videoContainer;
  5304. this.bandwidth = null;
  5305. this.packetLoss = null;
  5306. this.bitrate = null;
  5307. this.showMoreValue = false;
  5308. this.resolution = null;
  5309. this.transport = [];
  5310. this.popover = null;
  5311. this.jid = jid;
  5312. this.create();
  5313. this.videoLayout = VideoLayout;
  5314. }
  5315. /**
  5316. * Values for the connection quality
  5317. * @type {{98: string,
  5318. * 81: string,
  5319. * 64: string,
  5320. * 47: string,
  5321. * 30: string,
  5322. * 0: string}}
  5323. */
  5324. ConnectionIndicator.connectionQualityValues = {
  5325. 98: "18px", //full
  5326. 81: "15px",//4 bars
  5327. 64: "11px",//3 bars
  5328. 47: "7px",//2 bars
  5329. 30: "3px",//1 bar
  5330. 0: "0px"//empty
  5331. };
  5332. ConnectionIndicator.getIP = function(value)
  5333. {
  5334. return value.substring(0, value.lastIndexOf(":"));
  5335. };
  5336. ConnectionIndicator.getPort = function(value)
  5337. {
  5338. return value.substring(value.lastIndexOf(":") + 1, value.length);
  5339. };
  5340. ConnectionIndicator.getStringFromArray = function (array) {
  5341. var res = "";
  5342. for(var i = 0; i < array.length; i++)
  5343. {
  5344. res += (i === 0? "" : ", ") + array[i];
  5345. }
  5346. return res;
  5347. };
  5348. /**
  5349. * Generates the html content.
  5350. * @returns {string} the html content.
  5351. */
  5352. ConnectionIndicator.prototype.generateText = function () {
  5353. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  5354. var translate = APP.translation.translateString;
  5355. if(this.bitrate === null)
  5356. {
  5357. downloadBitrate = "N/A";
  5358. uploadBitrate = "N/A";
  5359. }
  5360. else
  5361. {
  5362. downloadBitrate =
  5363. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  5364. uploadBitrate =
  5365. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  5366. }
  5367. if(this.packetLoss === null)
  5368. {
  5369. packetLoss = "N/A";
  5370. }
  5371. else
  5372. {
  5373. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  5374. (this.packetLoss.download !== null? this.packetLoss.download : "N/A") +
  5375. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  5376. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") + "%";
  5377. }
  5378. var resolutionValue = null;
  5379. if(this.resolution && this.jid != null)
  5380. {
  5381. var keys = Object.keys(this.resolution);
  5382. if(keys.length == 1)
  5383. {
  5384. for(var ssrc in this.resolution)
  5385. {
  5386. resolutionValue = this.resolution[ssrc];
  5387. }
  5388. }
  5389. else if(keys.length > 1)
  5390. {
  5391. var displayedSsrc = APP.simulcast.getReceivingSSRC(this.jid);
  5392. resolutionValue = this.resolution[displayedSsrc];
  5393. }
  5394. }
  5395. if(this.jid === null)
  5396. {
  5397. resolution = "";
  5398. if(this.resolution === null || !Object.keys(this.resolution) ||
  5399. Object.keys(this.resolution).length === 0)
  5400. {
  5401. resolution = "N/A";
  5402. }
  5403. else
  5404. for(i in this.resolution)
  5405. {
  5406. resolutionValue = this.resolution[i];
  5407. if(resolutionValue)
  5408. {
  5409. if(resolutionValue.height &&
  5410. resolutionValue.width)
  5411. {
  5412. resolution += (resolution === ""? "" : ", ") +
  5413. resolutionValue.width + "x" +
  5414. resolutionValue.height;
  5415. }
  5416. }
  5417. }
  5418. }
  5419. else if(!resolutionValue ||
  5420. !resolutionValue.height ||
  5421. !resolutionValue.width)
  5422. {
  5423. resolution = "N/A";
  5424. }
  5425. else
  5426. {
  5427. resolution = resolutionValue.width + "x" + resolutionValue.height;
  5428. }
  5429. var result = "<table style='width:100%'>" +
  5430. "<tr>" +
  5431. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  5432. translate("connectionindicator.bitrate") + "</span></td>" +
  5433. "<td><span class='jitsipopover_green'>&darr;</span>" +
  5434. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  5435. uploadBitrate + "</td>" +
  5436. "</tr><tr>" +
  5437. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  5438. translate("connectionindicator.packetloss") + "</span></td>" +
  5439. "<td>" + packetLoss + "</td>" +
  5440. "</tr><tr>" +
  5441. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  5442. translate("connectionindicator.resolution") + "</span></td>" +
  5443. "<td>" + resolution + "</td></tr></table>";
  5444. if(this.videoContainer.id == "localVideoContainer") {
  5445. result += "<div class=\"jitsipopover_showmore\" " +
  5446. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  5447. this.videoContainer.id + "')\" data-i18n='connectionindicator." +
  5448. (this.showMoreValue ? "less" : "more") + "'>" +
  5449. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  5450. "</div><br />";
  5451. }
  5452. if(this.showMoreValue)
  5453. {
  5454. var downloadBandwidth, uploadBandwidth, transport;
  5455. if(this.bandwidth === null)
  5456. {
  5457. downloadBandwidth = "N/A";
  5458. uploadBandwidth = "N/A";
  5459. }
  5460. else
  5461. {
  5462. downloadBandwidth = this.bandwidth.download?
  5463. this.bandwidth.download + " Kbps" :
  5464. "N/A";
  5465. uploadBandwidth = this.bandwidth.upload?
  5466. this.bandwidth.upload + " Kbps" :
  5467. "N/A";
  5468. }
  5469. if(!this.transport || this.transport.length === 0)
  5470. {
  5471. transport = "<tr>" +
  5472. "<td><span class='jitsipopover_blue' " +
  5473. "data-i18n='connectionindicator.address'>" +
  5474. translate("connectionindicator.address") + "</span></td>" +
  5475. "<td> N/A</td></tr>";
  5476. }
  5477. else
  5478. {
  5479. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  5480. for(i = 0; i < this.transport.length; i++)
  5481. {
  5482. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  5483. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  5484. var localIP =
  5485. ConnectionIndicator.getIP(this.transport[i].localip);
  5486. var localPort =
  5487. ConnectionIndicator.getPort(this.transport[i].localip);
  5488. if(data.remoteIP.indexOf(ip) == -1)
  5489. {
  5490. data.remoteIP.push(ip);
  5491. }
  5492. if(data.remotePort.indexOf(port) == -1)
  5493. {
  5494. data.remotePort.push(port);
  5495. }
  5496. if(data.localIP.indexOf(localIP) == -1)
  5497. {
  5498. data.localIP.push(localIP);
  5499. }
  5500. if(data.localPort.indexOf(localPort) == -1)
  5501. {
  5502. data.localPort.push(localPort);
  5503. }
  5504. }
  5505. var local_address_key = "connectionindicator.localaddress";
  5506. var remote_address_key = "connectionindicator.remoteaddress";
  5507. var localTransport =
  5508. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5509. local_address_key +"' data-i18n-options='" +
  5510. JSON.stringify({count: data.localIP.length}) + "'>" +
  5511. translate(local_address_key, {count: data.localIP.length}) +
  5512. "</span></td><td> " +
  5513. ConnectionIndicator.getStringFromArray(data.localIP) +
  5514. "</td></tr>";
  5515. transport =
  5516. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5517. remote_address_key + "' data-i18n-options='" +
  5518. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  5519. translate(remote_address_key,
  5520. {count: data.remoteIP.length}) +
  5521. "</span></td><td> " +
  5522. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  5523. "</td></tr>";
  5524. var key_remote = "connectionindicator.remoteport",
  5525. key_local = "connectionindicator.localport";
  5526. transport += "<tr>" +
  5527. "<td>" +
  5528. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  5529. "' data-i18n-options='" +
  5530. JSON.stringify({count: this.transport.length}) + "'>" +
  5531. translate(key_remote, {count: this.transport.length}) +
  5532. "</span></td><td>";
  5533. localTransport += "<tr>" +
  5534. "<td>" +
  5535. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  5536. "' data-i18n-options='" +
  5537. JSON.stringify({count: this.transport.length}) + "'>" +
  5538. translate(key_local, {count: this.transport.length}) +
  5539. "</span></td><td>";
  5540. transport +=
  5541. ConnectionIndicator.getStringFromArray(data.remotePort);
  5542. localTransport +=
  5543. ConnectionIndicator.getStringFromArray(data.localPort);
  5544. transport += "</td></tr>";
  5545. transport += localTransport + "</td></tr>";
  5546. transport +="<tr>" +
  5547. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  5548. translate("connectionindicator.transport") + "</span></td>" +
  5549. "<td>" + this.transport[0].type + "</td></tr>";
  5550. }
  5551. result += "<table style='width:100%'>" +
  5552. "<tr>" +
  5553. "<td>" +
  5554. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  5555. translate("connectionindicator.bandwidth") + "</span>" +
  5556. "</td><td>" +
  5557. "<span class='jitsipopover_green'>&darr;</span>" +
  5558. downloadBandwidth +
  5559. " <span class='jitsipopover_orange'>&uarr;</span>" +
  5560. uploadBandwidth + "</td></tr>";
  5561. result += transport + "</table>";
  5562. }
  5563. return result;
  5564. };
  5565. /**
  5566. * Shows or hide the additional information.
  5567. */
  5568. ConnectionIndicator.prototype.showMore = function () {
  5569. this.showMoreValue = !this.showMoreValue;
  5570. this.updatePopoverData();
  5571. };
  5572. function createIcon(classes)
  5573. {
  5574. var icon = document.createElement("span");
  5575. for(var i in classes)
  5576. {
  5577. icon.classList.add(classes[i]);
  5578. }
  5579. icon.appendChild(
  5580. document.createElement("i")).classList.add("icon-connection");
  5581. return icon;
  5582. }
  5583. /**
  5584. * Creates the indicator
  5585. */
  5586. ConnectionIndicator.prototype.create = function () {
  5587. this.connectionIndicatorContainer = document.createElement("div");
  5588. this.connectionIndicatorContainer.className = "connectionindicator";
  5589. this.connectionIndicatorContainer.style.display = "none";
  5590. this.videoContainer.appendChild(this.connectionIndicatorContainer);
  5591. this.popover = new JitsiPopover(
  5592. $("#" + this.videoContainer.id + " > .connectionindicator"),
  5593. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  5594. APP.translation.translateString("connectionindicator.na") + "</div>",
  5595. skin: "black"});
  5596. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  5597. createIcon(["connection", "connection_empty"]));
  5598. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  5599. createIcon(["connection", "connection_full"]));
  5600. };
  5601. /**
  5602. * Removes the indicator
  5603. */
  5604. ConnectionIndicator.prototype.remove = function()
  5605. {
  5606. this.connectionIndicatorContainer.remove();
  5607. this.popover.forceHide();
  5608. };
  5609. /**
  5610. * Updates the data of the indicator
  5611. * @param percent the percent of connection quality
  5612. * @param object the statistics data.
  5613. */
  5614. ConnectionIndicator.prototype.updateConnectionQuality =
  5615. function (percent, object) {
  5616. if(percent === null)
  5617. {
  5618. this.connectionIndicatorContainer.style.display = "none";
  5619. this.popover.forceHide();
  5620. return;
  5621. }
  5622. else
  5623. {
  5624. if(this.connectionIndicatorContainer.style.display == "none") {
  5625. this.connectionIndicatorContainer.style.display = "block";
  5626. this.videoLayout.updateMutePosition(this.videoContainer.id);
  5627. }
  5628. }
  5629. this.bandwidth = object.bandwidth;
  5630. this.bitrate = object.bitrate;
  5631. this.packetLoss = object.packetLoss;
  5632. this.transport = object.transport;
  5633. if(object.resolution)
  5634. {
  5635. this.resolution = object.resolution;
  5636. }
  5637. for(var quality in ConnectionIndicator.connectionQualityValues)
  5638. {
  5639. if(percent >= quality)
  5640. {
  5641. this.fullIcon.style.width =
  5642. ConnectionIndicator.connectionQualityValues[quality];
  5643. }
  5644. }
  5645. this.updatePopoverData();
  5646. };
  5647. /**
  5648. * Updates the resolution
  5649. * @param resolution the new resolution
  5650. */
  5651. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  5652. this.resolution = resolution;
  5653. this.updatePopoverData();
  5654. };
  5655. /**
  5656. * Updates the content of the popover
  5657. */
  5658. ConnectionIndicator.prototype.updatePopoverData = function () {
  5659. this.popover.updateContent(
  5660. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  5661. APP.translation.translateElement($(".connection_info"));
  5662. };
  5663. /**
  5664. * Hides the popover
  5665. */
  5666. ConnectionIndicator.prototype.hide = function () {
  5667. this.popover.forceHide();
  5668. };
  5669. /**
  5670. * Hides the indicator
  5671. */
  5672. ConnectionIndicator.prototype.hideIndicator = function () {
  5673. this.connectionIndicatorContainer.style.display = "none";
  5674. if(this.popover)
  5675. this.popover.forceHide();
  5676. };
  5677. module.exports = ConnectionIndicator;
  5678. },{"../util/JitsiPopover":27}],32:[function(require,module,exports){
  5679. var AudioLevels = require("../audio_levels/AudioLevels");
  5680. var Avatar = require("../avatar/Avatar");
  5681. var Chat = require("../side_pannels/chat/Chat");
  5682. var ContactList = require("../side_pannels/contactlist/ContactList");
  5683. var UIUtil = require("../util/UIUtil");
  5684. var ConnectionIndicator = require("./ConnectionIndicator");
  5685. var NicknameHandler = require("../util/NicknameHandler");
  5686. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  5687. var UIEvents = require("../../../service/UI/UIEvents");
  5688. var currentDominantSpeaker = null;
  5689. var lastNCount = config.channelLastN;
  5690. var localLastNCount = config.channelLastN;
  5691. var localLastNSet = [];
  5692. var lastNEndpointsCache = [];
  5693. var lastNPickupJid = null;
  5694. var largeVideoState = {
  5695. updateInProgress: false,
  5696. newSrc: ''
  5697. };
  5698. var eventEmitter = null;
  5699. /**
  5700. * Currently focused video "src"(displayed in large video).
  5701. * @type {String}
  5702. */
  5703. var focusedVideoInfo = null;
  5704. /**
  5705. * Indicates if we have muted our audio before the conference has started.
  5706. * @type {boolean}
  5707. */
  5708. var preMuted = false;
  5709. var mutedAudios = {};
  5710. var flipXLocalVideo = true;
  5711. var currentVideoWidth = null;
  5712. var currentVideoHeight = null;
  5713. var localVideoSrc = null;
  5714. function videoactive( videoelem) {
  5715. if (videoelem.attr('id').indexOf('mixedmslabel') === -1) {
  5716. // ignore mixedmslabela0 and v0
  5717. videoelem.show();
  5718. VideoLayout.resizeThumbnails();
  5719. var videoParent = videoelem.parent();
  5720. var parentResourceJid = null;
  5721. if (videoParent)
  5722. parentResourceJid
  5723. = VideoLayout.getPeerContainerResourceJid(videoParent[0]);
  5724. // Update the large video to the last added video only if there's no
  5725. // current dominant, focused speaker or prezi playing or update it to
  5726. // the current dominant speaker.
  5727. if ((!focusedVideoInfo &&
  5728. !VideoLayout.getDominantSpeakerResourceJid() &&
  5729. !require("../prezi/Prezi").isPresentationVisible()) ||
  5730. (parentResourceJid &&
  5731. VideoLayout.getDominantSpeakerResourceJid() === parentResourceJid)) {
  5732. VideoLayout.updateLargeVideo(
  5733. APP.RTC.getVideoSrc(videoelem[0]),
  5734. 1,
  5735. parentResourceJid);
  5736. }
  5737. VideoLayout.showModeratorIndicator();
  5738. }
  5739. }
  5740. function waitForRemoteVideo(selector, ssrc, stream, jid) {
  5741. // XXX(gp) so, every call to this function is *always* preceded by a call
  5742. // to the RTC.attachMediaStream() function but that call is *not* followed
  5743. // by an update to the videoSrcToSsrc map!
  5744. //
  5745. // The above way of doing things results in video SRCs that don't correspond
  5746. // to any SSRC for a short period of time (to be more precise, for as long
  5747. // the waitForRemoteVideo takes to complete). This causes problems (see
  5748. // bellow).
  5749. //
  5750. // I'm wondering why we need to do that; i.e. why call RTC.attachMediaStream()
  5751. // a second time in here and only then update the videoSrcToSsrc map? Why
  5752. // not simply update the videoSrcToSsrc map when the RTC.attachMediaStream()
  5753. // is called the first time? I actually do that in the lastN changed event
  5754. // handler because the "orphan" video SRC is causing troubles there. The
  5755. // purpose of this method would then be to fire the "videoactive.jingle".
  5756. //
  5757. // Food for though I guess :-)
  5758. if (selector.removed || !selector.parent().is(":visible")) {
  5759. console.warn("Media removed before had started", selector);
  5760. return;
  5761. }
  5762. if (stream.id === 'mixedmslabel') return;
  5763. if (selector[0].currentTime > 0) {
  5764. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  5765. APP.RTC.attachMediaStream(selector, videoStream); // FIXME: why do i have to do this for FF?
  5766. videoactive(selector);
  5767. } else {
  5768. setTimeout(function () {
  5769. waitForRemoteVideo(selector, ssrc, stream, jid);
  5770. }, 250);
  5771. }
  5772. }
  5773. /**
  5774. * Returns an array of the video horizontal and vertical indents,
  5775. * so that if fits its parent.
  5776. *
  5777. * @return an array with 2 elements, the horizontal indent and the vertical
  5778. * indent
  5779. */
  5780. function getCameraVideoPosition(videoWidth,
  5781. videoHeight,
  5782. videoSpaceWidth,
  5783. videoSpaceHeight) {
  5784. // Parent height isn't completely calculated when we position the video in
  5785. // full screen mode and this is why we use the screen height in this case.
  5786. // Need to think it further at some point and implement it properly.
  5787. var isFullScreen = document.fullScreen ||
  5788. document.mozFullScreen ||
  5789. document.webkitIsFullScreen;
  5790. if (isFullScreen)
  5791. videoSpaceHeight = window.innerHeight;
  5792. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  5793. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  5794. return [horizontalIndent, verticalIndent];
  5795. }
  5796. /**
  5797. * Returns an array of the video horizontal and vertical indents.
  5798. * Centers horizontally and top aligns vertically.
  5799. *
  5800. * @return an array with 2 elements, the horizontal indent and the vertical
  5801. * indent
  5802. */
  5803. function getDesktopVideoPosition(videoWidth,
  5804. videoHeight,
  5805. videoSpaceWidth,
  5806. videoSpaceHeight) {
  5807. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  5808. var verticalIndent = 0;// Top aligned
  5809. return [horizontalIndent, verticalIndent];
  5810. }
  5811. /**
  5812. * Returns an array of the video dimensions, so that it covers the screen.
  5813. * It leaves no empty areas, but some parts of the video might not be visible.
  5814. *
  5815. * @return an array with 2 elements, the video width and the video height
  5816. */
  5817. function getCameraVideoSize(videoWidth,
  5818. videoHeight,
  5819. videoSpaceWidth,
  5820. videoSpaceHeight) {
  5821. if (!videoWidth)
  5822. videoWidth = currentVideoWidth;
  5823. if (!videoHeight)
  5824. videoHeight = currentVideoHeight;
  5825. var aspectRatio = videoWidth / videoHeight;
  5826. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  5827. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  5828. if (availableWidth / aspectRatio < videoSpaceHeight) {
  5829. availableHeight = videoSpaceHeight;
  5830. availableWidth = availableHeight * aspectRatio;
  5831. }
  5832. if (availableHeight * aspectRatio < videoSpaceWidth) {
  5833. availableWidth = videoSpaceWidth;
  5834. availableHeight = availableWidth / aspectRatio;
  5835. }
  5836. return [availableWidth, availableHeight];
  5837. }
  5838. /**
  5839. * Sets the display name for the given video span id.
  5840. */
  5841. function setDisplayName(videoSpanId, displayName, key) {
  5842. var nameSpan = $('#' + videoSpanId + '>span.displayname');
  5843. var defaultLocalDisplayName = APP.translation.generateTranslatonHTML(
  5844. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  5845. // If we already have a display name for this video.
  5846. if (nameSpan.length > 0) {
  5847. var nameSpanElement = nameSpan.get(0);
  5848. if (nameSpanElement.id === 'localDisplayName' &&
  5849. $('#localDisplayName').text() !== displayName) {
  5850. if (displayName && displayName.length > 0)
  5851. {
  5852. var meHTML = APP.translation.generateTranslatonHTML("me");
  5853. $('#localDisplayName').html(displayName + ' (' + meHTML + ')');
  5854. }
  5855. else
  5856. $('#localDisplayName').html(defaultLocalDisplayName);
  5857. } else {
  5858. if (displayName && displayName.length > 0)
  5859. {
  5860. $('#' + videoSpanId + '_name').html(displayName);
  5861. }
  5862. else if (key && key.length > 0)
  5863. {
  5864. var nameHtml = APP.translation.generateTranslatonHTML(key);
  5865. $('#' + videoSpanId + '_name').html(nameHtml);
  5866. }
  5867. else
  5868. $('#' + videoSpanId + '_name').text(
  5869. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  5870. }
  5871. } else {
  5872. var editButton = null;
  5873. nameSpan = document.createElement('span');
  5874. nameSpan.className = 'displayname';
  5875. $('#' + videoSpanId)[0].appendChild(nameSpan);
  5876. if (videoSpanId === 'localVideoContainer') {
  5877. editButton = createEditDisplayNameButton();
  5878. if (displayName && displayName.length > 0) {
  5879. var meHTML = APP.translation.generateTranslatonHTML("me");
  5880. nameSpan.innerHTML = displayName + meHTML;
  5881. }
  5882. else
  5883. nameSpan.innerHTML = defaultLocalDisplayName;
  5884. }
  5885. else {
  5886. if (displayName && displayName.length > 0) {
  5887. nameSpan.innerText = displayName;
  5888. }
  5889. else
  5890. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  5891. }
  5892. if (!editButton) {
  5893. nameSpan.id = videoSpanId + '_name';
  5894. } else {
  5895. nameSpan.id = 'localDisplayName';
  5896. $('#' + videoSpanId)[0].appendChild(editButton);
  5897. //translates popover of edit button
  5898. APP.translation.translateElement($("a.displayname"));
  5899. var editableText = document.createElement('input');
  5900. editableText.className = 'displayname';
  5901. editableText.type = 'text';
  5902. editableText.id = 'editDisplayName';
  5903. if (displayName && displayName.length) {
  5904. editableText.value
  5905. = displayName;
  5906. }
  5907. var defaultNickname = APP.translation.translateString(
  5908. "defaultNickname", {name: "Jane Pink"});
  5909. editableText.setAttribute('style', 'display:none;');
  5910. editableText.setAttribute('data-18n',
  5911. '[placeholder]defaultNickname');
  5912. editableText.setAttribute("data-i18n-options",
  5913. JSON.stringify({name: "Jane Pink"}));
  5914. editableText.setAttribute("placeholder", defaultNickname);
  5915. $('#' + videoSpanId)[0].appendChild(editableText);
  5916. $('#localVideoContainer .displayname')
  5917. .bind("click", function (e) {
  5918. e.preventDefault();
  5919. e.stopPropagation();
  5920. $('#localDisplayName').hide();
  5921. $('#editDisplayName').show();
  5922. $('#editDisplayName').focus();
  5923. $('#editDisplayName').select();
  5924. $('#editDisplayName').one("focusout", function (e) {
  5925. VideoLayout.inputDisplayNameHandler(this.value);
  5926. });
  5927. $('#editDisplayName').on('keydown', function (e) {
  5928. if (e.keyCode === 13) {
  5929. e.preventDefault();
  5930. VideoLayout.inputDisplayNameHandler(this.value);
  5931. }
  5932. });
  5933. });
  5934. }
  5935. }
  5936. }
  5937. /**
  5938. * Gets the selector of video thumbnail container for the user identified by
  5939. * given <tt>userJid</tt>
  5940. * @param resourceJid user's Jid for whom we want to get the video container.
  5941. */
  5942. function getParticipantContainer(resourceJid)
  5943. {
  5944. if (!resourceJid)
  5945. return null;
  5946. if (resourceJid === APP.xmpp.myResource())
  5947. return $("#localVideoContainer");
  5948. else
  5949. return $("#participant_" + resourceJid);
  5950. }
  5951. /**
  5952. * Sets the size and position of the given video element.
  5953. *
  5954. * @param video the video element to position
  5955. * @param width the desired video width
  5956. * @param height the desired video height
  5957. * @param horizontalIndent the left and right indent
  5958. * @param verticalIndent the top and bottom indent
  5959. */
  5960. function positionVideo(video,
  5961. width,
  5962. height,
  5963. horizontalIndent,
  5964. verticalIndent) {
  5965. video.width(width);
  5966. video.height(height);
  5967. video.css({ top: verticalIndent + 'px',
  5968. bottom: verticalIndent + 'px',
  5969. left: horizontalIndent + 'px',
  5970. right: horizontalIndent + 'px'});
  5971. }
  5972. /**
  5973. * Adds the remote video menu element for the given <tt>jid</tt> in the
  5974. * given <tt>parentElement</tt>.
  5975. *
  5976. * @param jid the jid indicating the video for which we're adding a menu.
  5977. * @param parentElement the parent element where this menu will be added
  5978. */
  5979. function addRemoteVideoMenu(jid, parentElement) {
  5980. var spanElement = document.createElement('span');
  5981. spanElement.className = 'remotevideomenu';
  5982. parentElement.appendChild(spanElement);
  5983. var menuElement = document.createElement('i');
  5984. menuElement.className = 'fa fa-angle-down';
  5985. menuElement.title = 'Remote user controls';
  5986. spanElement.appendChild(menuElement);
  5987. // <ul class="popupmenu">
  5988. // <li><a href="#">Mute</a></li>
  5989. // <li><a href="#">Eject</a></li>
  5990. // </ul>
  5991. var popupmenuElement = document.createElement('ul');
  5992. popupmenuElement.className = 'popupmenu';
  5993. popupmenuElement.id
  5994. = 'remote_popupmenu_' + Strophe.getResourceFromJid(jid);
  5995. spanElement.appendChild(popupmenuElement);
  5996. var muteMenuItem = document.createElement('li');
  5997. var muteLinkItem = document.createElement('a');
  5998. var mutedIndicator = "<i style='float:left;' class='icon-mic-disabled'></i>";
  5999. if (!mutedAudios[jid]) {
  6000. muteLinkItem.innerHTML = mutedIndicator +
  6001. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  6002. muteLinkItem.className = 'mutelink';
  6003. }
  6004. else {
  6005. muteLinkItem.innerHTML = mutedIndicator +
  6006. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  6007. muteLinkItem.className = 'mutelink disabled';
  6008. }
  6009. muteLinkItem.onclick = function(){
  6010. if ($(this).attr('disabled') != undefined) {
  6011. event.preventDefault();
  6012. }
  6013. var isMute = mutedAudios[jid] == true;
  6014. APP.xmpp.setMute(jid, !isMute);
  6015. popupmenuElement.setAttribute('style', 'display:none;');
  6016. if (isMute) {
  6017. this.innerHTML = mutedIndicator +
  6018. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  6019. this.className = 'mutelink disabled';
  6020. }
  6021. else {
  6022. this.innerHTML = mutedIndicator +
  6023. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  6024. this.className = 'mutelink';
  6025. }
  6026. };
  6027. muteMenuItem.appendChild(muteLinkItem);
  6028. popupmenuElement.appendChild(muteMenuItem);
  6029. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  6030. var ejectMenuItem = document.createElement('li');
  6031. var ejectLinkItem = document.createElement('a');
  6032. var ejectText = "<div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.kick'>&nbsp;</div>";
  6033. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  6034. ejectLinkItem.onclick = function(){
  6035. APP.xmpp.eject(jid);
  6036. popupmenuElement.setAttribute('style', 'display:none;');
  6037. };
  6038. ejectMenuItem.appendChild(ejectLinkItem);
  6039. popupmenuElement.appendChild(ejectMenuItem);
  6040. var paddingSpan = document.createElement('span');
  6041. paddingSpan.className = 'popupmenuPadding';
  6042. popupmenuElement.appendChild(paddingSpan);
  6043. APP.translation.translateElement($("#" + popupmenuElement.id + " > li > a > div"));
  6044. }
  6045. /**
  6046. * Removes remote video menu element from video element identified by
  6047. * given <tt>videoElementId</tt>.
  6048. *
  6049. * @param videoElementId the id of local or remote video element.
  6050. */
  6051. function removeRemoteVideoMenu(videoElementId) {
  6052. var menuSpan = $('#' + videoElementId + '>span.remotevideomenu');
  6053. if (menuSpan.length) {
  6054. menuSpan.remove();
  6055. }
  6056. }
  6057. /**
  6058. * Updates the data for the indicator
  6059. * @param id the id of the indicator
  6060. * @param percent the percent for connection quality
  6061. * @param object the data
  6062. */
  6063. function updateStatsIndicator(id, percent, object) {
  6064. if(VideoLayout.connectionIndicators[id])
  6065. VideoLayout.connectionIndicators[id].updateConnectionQuality(percent, object);
  6066. }
  6067. /**
  6068. * Returns an array of the video dimensions, so that it keeps it's aspect
  6069. * ratio and fits available area with it's larger dimension. This method
  6070. * ensures that whole video will be visible and can leave empty areas.
  6071. *
  6072. * @return an array with 2 elements, the video width and the video height
  6073. */
  6074. function getDesktopVideoSize(videoWidth,
  6075. videoHeight,
  6076. videoSpaceWidth,
  6077. videoSpaceHeight) {
  6078. if (!videoWidth)
  6079. videoWidth = currentVideoWidth;
  6080. if (!videoHeight)
  6081. videoHeight = currentVideoHeight;
  6082. var aspectRatio = videoWidth / videoHeight;
  6083. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  6084. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  6085. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  6086. if (availableWidth / aspectRatio >= videoSpaceHeight)
  6087. {
  6088. availableHeight = videoSpaceHeight;
  6089. availableWidth = availableHeight * aspectRatio;
  6090. }
  6091. if (availableHeight * aspectRatio >= videoSpaceWidth)
  6092. {
  6093. availableWidth = videoSpaceWidth;
  6094. availableHeight = availableWidth / aspectRatio;
  6095. }
  6096. return [availableWidth, availableHeight];
  6097. }
  6098. /**
  6099. * Creates the edit display name button.
  6100. *
  6101. * @returns the edit button
  6102. */
  6103. function createEditDisplayNameButton() {
  6104. var editButton = document.createElement('a');
  6105. editButton.className = 'displayname';
  6106. UIUtil.setTooltip(editButton,
  6107. "videothumbnail.editnickname",
  6108. "top");
  6109. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  6110. return editButton;
  6111. }
  6112. /**
  6113. * Creates the element indicating the moderator(owner) of the conference.
  6114. *
  6115. * @param parentElement the parent element where the owner indicator will
  6116. * be added
  6117. */
  6118. function createModeratorIndicatorElement(parentElement) {
  6119. var moderatorIndicator = document.createElement('i');
  6120. moderatorIndicator.className = 'fa fa-star';
  6121. parentElement.appendChild(moderatorIndicator);
  6122. UIUtil.setTooltip(parentElement,
  6123. "videothumbnail.moderator",
  6124. "top");
  6125. }
  6126. var VideoLayout = (function (my) {
  6127. my.connectionIndicators = {};
  6128. // By default we use camera
  6129. my.getVideoSize = getCameraVideoSize;
  6130. my.getVideoPosition = getCameraVideoPosition;
  6131. my.init = function (emitter) {
  6132. // Listen for large video size updates
  6133. document.getElementById('largeVideo')
  6134. .addEventListener('loadedmetadata', function (e) {
  6135. currentVideoWidth = this.videoWidth;
  6136. currentVideoHeight = this.videoHeight;
  6137. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  6138. });
  6139. eventEmitter = emitter;
  6140. };
  6141. my.isInLastN = function(resource) {
  6142. return lastNCount < 0 // lastN is disabled, return true
  6143. || (lastNCount > 0 && lastNEndpointsCache.length == 0) // lastNEndpoints cache not built yet, return true
  6144. || (lastNEndpointsCache && lastNEndpointsCache.indexOf(resource) !== -1);
  6145. };
  6146. my.changeLocalStream = function (stream) {
  6147. VideoLayout.changeLocalVideo(stream);
  6148. };
  6149. my.changeLocalAudio = function(stream) {
  6150. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  6151. document.getElementById('localAudio').autoplay = true;
  6152. document.getElementById('localAudio').volume = 0;
  6153. if (preMuted) {
  6154. if(!APP.UI.setAudioMuted(true))
  6155. {
  6156. preMuted = mute;
  6157. }
  6158. preMuted = false;
  6159. }
  6160. };
  6161. my.changeLocalVideo = function(stream) {
  6162. var flipX = true;
  6163. if(stream.videoType == "screen")
  6164. flipX = false;
  6165. var localVideo = document.createElement('video');
  6166. localVideo.id = 'localVideo_' +
  6167. APP.RTC.getStreamID(stream.getOriginalStream());
  6168. localVideo.autoplay = true;
  6169. localVideo.volume = 0; // is it required if audio is separated ?
  6170. localVideo.oncontextmenu = function () { return false; };
  6171. var localVideoContainer = document.getElementById('localVideoWrapper');
  6172. localVideoContainer.appendChild(localVideo);
  6173. // Set default display name.
  6174. setDisplayName('localVideoContainer');
  6175. if(!VideoLayout.connectionIndicators["localVideoContainer"]) {
  6176. VideoLayout.connectionIndicators["localVideoContainer"]
  6177. = new ConnectionIndicator($("#localVideoContainer")[0], null, VideoLayout);
  6178. }
  6179. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  6180. var localVideoSelector = $('#' + localVideo.id);
  6181. function localVideoClick(event) {
  6182. event.stopPropagation();
  6183. VideoLayout.handleVideoThumbClicked(
  6184. APP.RTC.getVideoSrc(localVideo),
  6185. false,
  6186. APP.xmpp.myResource());
  6187. }
  6188. // Add click handler to both video and video wrapper elements in case
  6189. // there's no video.
  6190. localVideoSelector.click(localVideoClick);
  6191. $('#localVideoContainer').click(localVideoClick);
  6192. // Add hover handler
  6193. $('#localVideoContainer').hover(
  6194. function() {
  6195. VideoLayout.showDisplayName('localVideoContainer', true);
  6196. },
  6197. function() {
  6198. if (!VideoLayout.isLargeVideoVisible()
  6199. || APP.RTC.getVideoSrc(localVideo) !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  6200. VideoLayout.showDisplayName('localVideoContainer', false);
  6201. }
  6202. );
  6203. // Add stream ended handler
  6204. stream.getOriginalStream().onended = function () {
  6205. localVideoContainer.removeChild(localVideo);
  6206. VideoLayout.updateRemovedVideo(APP.RTC.getVideoSrc(localVideo));
  6207. };
  6208. // Flip video x axis if needed
  6209. flipXLocalVideo = flipX;
  6210. if (flipX) {
  6211. localVideoSelector.addClass("flipVideoX");
  6212. }
  6213. // Attach WebRTC stream
  6214. var videoStream = APP.simulcast.getLocalVideoStream();
  6215. APP.RTC.attachMediaStream(localVideoSelector, videoStream);
  6216. localVideoSrc = APP.RTC.getVideoSrc(localVideo);
  6217. var myResourceJid = APP.xmpp.myResource();
  6218. VideoLayout.updateLargeVideo(localVideoSrc, 0,
  6219. myResourceJid);
  6220. };
  6221. /**
  6222. * Checks if removed video is currently displayed and tries to display
  6223. * another one instead.
  6224. * @param removedVideoSrc src stream identifier of the video.
  6225. */
  6226. my.updateRemovedVideo = function(removedVideoSrc) {
  6227. if (removedVideoSrc === APP.RTC.getVideoSrc($('#largeVideo')[0])) {
  6228. // this is currently displayed as large
  6229. // pick the last visible video in the row
  6230. // if nobody else is left, this picks the local video
  6231. var pick
  6232. = $('#remoteVideos>span[id!="mixedstream"]:visible:last>video')
  6233. .get(0);
  6234. if (!pick) {
  6235. console.info("Last visible video no longer exists");
  6236. pick = $('#remoteVideos>span[id!="mixedstream"]>video').get(0);
  6237. if (!pick || !APP.RTC.getVideoSrc(pick)) {
  6238. // Try local video
  6239. console.info("Fallback to local video...");
  6240. pick = $('#remoteVideos>span>span>video').get(0);
  6241. }
  6242. }
  6243. // mute if localvideo
  6244. if (pick) {
  6245. var container = pick.parentNode;
  6246. var jid = null;
  6247. if(container)
  6248. {
  6249. if(container.id == "localVideoWrapper")
  6250. {
  6251. jid = APP.xmpp.myResource();
  6252. }
  6253. else
  6254. {
  6255. jid = VideoLayout.getPeerContainerResourceJid(container);
  6256. }
  6257. }
  6258. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(pick), pick.volume, jid);
  6259. } else {
  6260. console.warn("Failed to elect large video");
  6261. }
  6262. }
  6263. };
  6264. my.onRemoteStreamAdded = function (stream) {
  6265. var container;
  6266. var remotes = document.getElementById('remoteVideos');
  6267. if (stream.peerjid) {
  6268. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  6269. container = document.getElementById(
  6270. 'participant_' + Strophe.getResourceFromJid(stream.peerjid));
  6271. } else {
  6272. var id = stream.getOriginalStream().id;
  6273. if (id !== 'mixedmslabel'
  6274. // FIXME: default stream is added always with new focus
  6275. // (to be investigated)
  6276. && id !== 'default') {
  6277. console.error('can not associate stream',
  6278. id,
  6279. 'with a participant');
  6280. // We don't want to add it here since it will cause troubles
  6281. return;
  6282. }
  6283. // FIXME: for the mixed ms we dont need a video -- currently
  6284. container = document.createElement('span');
  6285. container.id = 'mixedstream';
  6286. container.className = 'videocontainer';
  6287. remotes.appendChild(container);
  6288. UIUtil.playSoundNotification('userJoined');
  6289. }
  6290. if (container) {
  6291. VideoLayout.addRemoteStreamElement( container,
  6292. stream.sid,
  6293. stream.getOriginalStream(),
  6294. stream.peerjid,
  6295. stream.ssrc);
  6296. }
  6297. }
  6298. my.getLargeVideoState = function () {
  6299. return largeVideoState;
  6300. };
  6301. /**
  6302. * Updates the large video with the given new video source.
  6303. */
  6304. my.updateLargeVideo = function(newSrc, vol, resourceJid) {
  6305. console.log('hover in', newSrc);
  6306. if (APP.RTC.getVideoSrc($('#largeVideo')[0]) !== newSrc) {
  6307. $('#activeSpeaker').css('visibility', 'hidden');
  6308. // Due to the simulcast the localVideoSrc may have changed when the
  6309. // fadeOut event triggers. In that case the getJidFromVideoSrc and
  6310. // isVideoSrcDesktop methods will not function correctly.
  6311. //
  6312. // Also, again due to the simulcast, the updateLargeVideo method can
  6313. // be called multiple times almost simultaneously. Therefore, we
  6314. // store the state here and update only once.
  6315. largeVideoState.newSrc = newSrc;
  6316. largeVideoState.isVisible = $('#largeVideo').is(':visible');
  6317. largeVideoState.isDesktop = APP.RTC.isVideoSrcDesktop(
  6318. APP.xmpp.findJidFromResource(resourceJid));
  6319. if(largeVideoState.userResourceJid) {
  6320. largeVideoState.oldResourceJid = largeVideoState.userResourceJid;
  6321. } else {
  6322. largeVideoState.oldResourceJid = null;
  6323. }
  6324. largeVideoState.userResourceJid = resourceJid;
  6325. // Screen stream is already rotated
  6326. largeVideoState.flipX = (newSrc === localVideoSrc) && flipXLocalVideo;
  6327. var userChanged = false;
  6328. if (largeVideoState.oldResourceJid !== largeVideoState.userResourceJid) {
  6329. userChanged = true;
  6330. // we want the notification to trigger even if userJid is undefined,
  6331. // or null.
  6332. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT,
  6333. largeVideoState.userResourceJid);
  6334. }
  6335. if (!largeVideoState.updateInProgress) {
  6336. largeVideoState.updateInProgress = true;
  6337. var doUpdate = function () {
  6338. Avatar.updateActiveSpeakerAvatarSrc(
  6339. APP.xmpp.findJidFromResource(
  6340. largeVideoState.userResourceJid));
  6341. if (!userChanged && largeVideoState.preload &&
  6342. largeVideoState.preload !== null &&
  6343. APP.RTC.getVideoSrc($(largeVideoState.preload)[0]) === newSrc)
  6344. {
  6345. console.info('Switching to preloaded video');
  6346. var attributes = $('#largeVideo').prop("attributes");
  6347. // loop through largeVideo attributes and apply them on
  6348. // preload.
  6349. $.each(attributes, function () {
  6350. if (this.name !== 'id' && this.name !== 'src') {
  6351. largeVideoState.preload.attr(this.name, this.value);
  6352. }
  6353. });
  6354. largeVideoState.preload.appendTo($('#largeVideoContainer'));
  6355. $('#largeVideo').attr('id', 'previousLargeVideo');
  6356. largeVideoState.preload.attr('id', 'largeVideo');
  6357. $('#previousLargeVideo').remove();
  6358. largeVideoState.preload.on('loadedmetadata', function (e) {
  6359. currentVideoWidth = this.videoWidth;
  6360. currentVideoHeight = this.videoHeight;
  6361. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  6362. });
  6363. largeVideoState.preload = null;
  6364. largeVideoState.preload_ssrc = 0;
  6365. } else {
  6366. APP.RTC.setVideoSrc($('#largeVideo')[0], largeVideoState.newSrc);
  6367. }
  6368. var videoTransform = document.getElementById('largeVideo')
  6369. .style.webkitTransform;
  6370. if (largeVideoState.flipX && videoTransform !== 'scaleX(-1)') {
  6371. document.getElementById('largeVideo').style.webkitTransform
  6372. = "scaleX(-1)";
  6373. }
  6374. else if (!largeVideoState.flipX && videoTransform === 'scaleX(-1)') {
  6375. document.getElementById('largeVideo').style.webkitTransform
  6376. = "none";
  6377. }
  6378. // Change the way we'll be measuring and positioning large video
  6379. VideoLayout.getVideoSize = largeVideoState.isDesktop
  6380. ? getDesktopVideoSize
  6381. : getCameraVideoSize;
  6382. VideoLayout.getVideoPosition = largeVideoState.isDesktop
  6383. ? getDesktopVideoPosition
  6384. : getCameraVideoPosition;
  6385. // Only if the large video is currently visible.
  6386. // Disable previous dominant speaker video.
  6387. if (largeVideoState.oldResourceJid) {
  6388. VideoLayout.enableDominantSpeaker(
  6389. largeVideoState.oldResourceJid,
  6390. false);
  6391. }
  6392. // Enable new dominant speaker in the remote videos section.
  6393. if (largeVideoState.userResourceJid) {
  6394. VideoLayout.enableDominantSpeaker(
  6395. largeVideoState.userResourceJid,
  6396. true);
  6397. }
  6398. if (userChanged && largeVideoState.isVisible) {
  6399. // using "this" should be ok because we're called
  6400. // from within the fadeOut event.
  6401. $(this).fadeIn(300);
  6402. }
  6403. if(userChanged) {
  6404. Avatar.showUserAvatar(
  6405. APP.xmpp.findJidFromResource(
  6406. largeVideoState.oldResourceJid));
  6407. }
  6408. largeVideoState.updateInProgress = false;
  6409. };
  6410. if (userChanged) {
  6411. $('#largeVideo').fadeOut(300, doUpdate);
  6412. } else {
  6413. doUpdate();
  6414. }
  6415. }
  6416. } else {
  6417. Avatar.showUserAvatar(
  6418. APP.xmpp.findJidFromResource(
  6419. largeVideoState.userResourceJid));
  6420. }
  6421. };
  6422. my.handleVideoThumbClicked = function(videoSrc,
  6423. noPinnedEndpointChangedEvent,
  6424. resourceJid) {
  6425. // Restore style for previously focused video
  6426. var oldContainer = null;
  6427. if(focusedVideoInfo) {
  6428. var focusResourceJid = focusedVideoInfo.resourceJid;
  6429. oldContainer = getParticipantContainer(focusResourceJid);
  6430. }
  6431. if (oldContainer) {
  6432. oldContainer.removeClass("videoContainerFocused");
  6433. }
  6434. // Unlock current focused.
  6435. if (focusedVideoInfo && focusedVideoInfo.src === videoSrc)
  6436. {
  6437. focusedVideoInfo = null;
  6438. var dominantSpeakerVideo = null;
  6439. // Enable the currently set dominant speaker.
  6440. if (currentDominantSpeaker) {
  6441. dominantSpeakerVideo
  6442. = $('#participant_' + currentDominantSpeaker + '>video')
  6443. .get(0);
  6444. if (dominantSpeakerVideo) {
  6445. VideoLayout.updateLargeVideo(
  6446. APP.RTC.getVideoSrc(dominantSpeakerVideo),
  6447. 1,
  6448. currentDominantSpeaker);
  6449. }
  6450. }
  6451. if (!noPinnedEndpointChangedEvent) {
  6452. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  6453. }
  6454. return;
  6455. }
  6456. // Lock new video
  6457. focusedVideoInfo = {
  6458. src: videoSrc,
  6459. resourceJid: resourceJid
  6460. };
  6461. // Update focused/pinned interface.
  6462. if (resourceJid)
  6463. {
  6464. var container = getParticipantContainer(resourceJid);
  6465. container.addClass("videoContainerFocused");
  6466. if (!noPinnedEndpointChangedEvent) {
  6467. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  6468. }
  6469. }
  6470. if ($('#largeVideo').attr('src') === videoSrc &&
  6471. VideoLayout.isLargeVideoOnTop()) {
  6472. return;
  6473. }
  6474. // Triggers a "video.selected" event. The "false" parameter indicates
  6475. // this isn't a prezi.
  6476. $(document).trigger("video.selected", [false]);
  6477. VideoLayout.updateLargeVideo(videoSrc, 1, resourceJid);
  6478. $('audio').each(function (idx, el) {
  6479. if (el.id.indexOf('mixedmslabel') !== -1) {
  6480. el.volume = 0;
  6481. el.volume = 1;
  6482. }
  6483. });
  6484. };
  6485. /**
  6486. * Positions the large video.
  6487. *
  6488. * @param videoWidth the stream video width
  6489. * @param videoHeight the stream video height
  6490. */
  6491. my.positionLarge = function (videoWidth, videoHeight) {
  6492. var videoSpaceWidth = $('#videospace').width();
  6493. var videoSpaceHeight = window.innerHeight;
  6494. var videoSize = VideoLayout.getVideoSize(videoWidth,
  6495. videoHeight,
  6496. videoSpaceWidth,
  6497. videoSpaceHeight);
  6498. var largeVideoWidth = videoSize[0];
  6499. var largeVideoHeight = videoSize[1];
  6500. var videoPosition = VideoLayout.getVideoPosition(largeVideoWidth,
  6501. largeVideoHeight,
  6502. videoSpaceWidth,
  6503. videoSpaceHeight);
  6504. var horizontalIndent = videoPosition[0];
  6505. var verticalIndent = videoPosition[1];
  6506. positionVideo($('#largeVideo'),
  6507. largeVideoWidth,
  6508. largeVideoHeight,
  6509. horizontalIndent, verticalIndent);
  6510. };
  6511. /**
  6512. * Shows/hides the large video.
  6513. */
  6514. my.setLargeVideoVisible = function(isVisible) {
  6515. var resourceJid = largeVideoState.userResourceJid;
  6516. if (isVisible) {
  6517. $('#largeVideo').css({visibility: 'visible'});
  6518. $('.watermark').css({visibility: 'visible'});
  6519. VideoLayout.enableDominantSpeaker(resourceJid, true);
  6520. }
  6521. else {
  6522. $('#largeVideo').css({visibility: 'hidden'});
  6523. $('#activeSpeaker').css('visibility', 'hidden');
  6524. $('.watermark').css({visibility: 'hidden'});
  6525. VideoLayout.enableDominantSpeaker(resourceJid, false);
  6526. if(focusedVideoInfo) {
  6527. var focusResourceJid = focusedVideoInfo.resourceJid;
  6528. var oldContainer = getParticipantContainer(focusResourceJid);
  6529. if (oldContainer && oldContainer.length > 0) {
  6530. oldContainer.removeClass("videoContainerFocused");
  6531. }
  6532. focusedVideoInfo = null;
  6533. if(focusResourceJid) {
  6534. Avatar.showUserAvatar(
  6535. APP.xmpp.findJidFromResource(focusResourceJid));
  6536. }
  6537. }
  6538. }
  6539. };
  6540. /**
  6541. * Indicates if the large video is currently visible.
  6542. *
  6543. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  6544. */
  6545. my.isLargeVideoVisible = function() {
  6546. return $('#largeVideo').is(':visible');
  6547. };
  6548. my.isLargeVideoOnTop = function () {
  6549. var Etherpad = require("../etherpad/Etherpad");
  6550. var Prezi = require("../prezi/Prezi");
  6551. return !Prezi.isPresentationVisible() && !Etherpad.isVisible();
  6552. };
  6553. /**
  6554. * Checks if container for participant identified by given peerJid exists
  6555. * in the document and creates it eventually.
  6556. *
  6557. * @param peerJid peer Jid to check.
  6558. * @param userId user email or id for setting the avatar
  6559. *
  6560. * @return Returns <tt>true</tt> if the peer container exists,
  6561. * <tt>false</tt> - otherwise
  6562. */
  6563. my.ensurePeerContainerExists = function(peerJid, userId) {
  6564. ContactList.ensureAddContact(peerJid, userId);
  6565. var resourceJid = Strophe.getResourceFromJid(peerJid);
  6566. var videoSpanId = 'participant_' + resourceJid;
  6567. if (!$('#' + videoSpanId).length) {
  6568. var container =
  6569. VideoLayout.addRemoteVideoContainer(peerJid, videoSpanId, userId);
  6570. Avatar.setUserAvatar(peerJid, userId);
  6571. // Set default display name.
  6572. setDisplayName(videoSpanId);
  6573. VideoLayout.connectionIndicators[videoSpanId] =
  6574. new ConnectionIndicator(container, peerJid, VideoLayout);
  6575. var nickfield = document.createElement('span');
  6576. nickfield.className = "nick";
  6577. nickfield.appendChild(document.createTextNode(resourceJid));
  6578. container.appendChild(nickfield);
  6579. // In case this is not currently in the last n we don't show it.
  6580. if (localLastNCount
  6581. && localLastNCount > 0
  6582. && $('#remoteVideos>span').length >= localLastNCount + 2) {
  6583. showPeerContainer(resourceJid, 'hide');
  6584. }
  6585. else
  6586. VideoLayout.resizeThumbnails();
  6587. }
  6588. };
  6589. my.addRemoteVideoContainer = function(peerJid, spanId) {
  6590. var container = document.createElement('span');
  6591. container.id = spanId;
  6592. container.className = 'videocontainer';
  6593. var remotes = document.getElementById('remoteVideos');
  6594. remotes.appendChild(container);
  6595. // If the peerJid is null then this video span couldn't be directly
  6596. // associated with a participant (this could happen in the case of prezi).
  6597. if (APP.xmpp.isModerator() && peerJid !== null)
  6598. addRemoteVideoMenu(peerJid, container);
  6599. AudioLevels.updateAudioLevelCanvas(peerJid, VideoLayout);
  6600. return container;
  6601. };
  6602. /**
  6603. * Creates an audio or video stream element.
  6604. */
  6605. my.createStreamElement = function (sid, stream) {
  6606. var isVideo = stream.getVideoTracks().length > 0;
  6607. var element = isVideo
  6608. ? document.createElement('video')
  6609. : document.createElement('audio');
  6610. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_')
  6611. + sid + '_' + APP.RTC.getStreamID(stream);
  6612. element.id = id;
  6613. element.autoplay = true;
  6614. element.oncontextmenu = function () { return false; };
  6615. return element;
  6616. };
  6617. my.addRemoteStreamElement
  6618. = function (container, sid, stream, peerJid, thessrc) {
  6619. var newElementId = null;
  6620. var isVideo = stream.getVideoTracks().length > 0;
  6621. if (container) {
  6622. var streamElement = VideoLayout.createStreamElement(sid, stream);
  6623. newElementId = streamElement.id;
  6624. container.appendChild(streamElement);
  6625. var sel = $('#' + newElementId);
  6626. sel.hide();
  6627. // If the container is currently visible we attach the stream.
  6628. if (!isVideo
  6629. || (container.offsetParent !== null && isVideo)) {
  6630. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  6631. APP.RTC.attachMediaStream(sel, videoStream);
  6632. if (isVideo)
  6633. waitForRemoteVideo(sel, thessrc, stream, peerJid);
  6634. }
  6635. stream.onended = function () {
  6636. console.log('stream ended', this);
  6637. VideoLayout.removeRemoteStreamElement(
  6638. stream, isVideo, container);
  6639. // NOTE(gp) it seems that under certain circumstances, the
  6640. // onended event is not fired and thus the contact list is not
  6641. // updated.
  6642. //
  6643. // The onended event of a stream should be fired when the SSRCs
  6644. // corresponding to that stream are removed from the SDP; but
  6645. // this doesn't seem to always be the case, resulting in ghost
  6646. // contacts.
  6647. //
  6648. // In an attempt to fix the ghost contacts problem, I'm moving
  6649. // the removeContact() method call in app.js, inside the
  6650. // 'muc.left' event handler.
  6651. //if (peerJid)
  6652. // ContactList.removeContact(peerJid);
  6653. };
  6654. // Add click handler.
  6655. container.onclick = function (event) {
  6656. /*
  6657. * FIXME It turns out that videoThumb may not exist (if there is
  6658. * no actual video).
  6659. */
  6660. var videoThumb = $('#' + container.id + '>video').get(0);
  6661. if (videoThumb) {
  6662. VideoLayout.handleVideoThumbClicked(
  6663. APP.RTC.getVideoSrc(videoThumb),
  6664. false,
  6665. Strophe.getResourceFromJid(peerJid));
  6666. }
  6667. event.stopPropagation();
  6668. event.preventDefault();
  6669. return false;
  6670. };
  6671. // Add hover handler
  6672. $(container).hover(
  6673. function() {
  6674. VideoLayout.showDisplayName(container.id, true);
  6675. },
  6676. function() {
  6677. var videoSrc = null;
  6678. if ($('#' + container.id + '>video')
  6679. && $('#' + container.id + '>video').length > 0) {
  6680. videoSrc = APP.RTC.getVideoSrc($('#' + container.id + '>video').get(0));
  6681. }
  6682. // If the video has been "pinned" by the user we want to
  6683. // keep the display name on place.
  6684. if (!VideoLayout.isLargeVideoVisible()
  6685. || videoSrc !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  6686. VideoLayout.showDisplayName(container.id, false);
  6687. }
  6688. );
  6689. }
  6690. return newElementId;
  6691. };
  6692. /**
  6693. * Removes the remote stream element corresponding to the given stream and
  6694. * parent container.
  6695. *
  6696. * @param stream the stream
  6697. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  6698. * @param container
  6699. */
  6700. my.removeRemoteStreamElement = function (stream, isVideo, container) {
  6701. if (!container)
  6702. return;
  6703. var select = null;
  6704. var removedVideoSrc = null;
  6705. if (isVideo) {
  6706. select = $('#' + container.id + '>video');
  6707. removedVideoSrc = APP.RTC.getVideoSrc(select.get(0));
  6708. }
  6709. else
  6710. select = $('#' + container.id + '>audio');
  6711. // Mark video as removed to cancel waiting loop(if video is removed
  6712. // before has started)
  6713. select.removed = true;
  6714. select.remove();
  6715. var audioCount = $('#' + container.id + '>audio').length;
  6716. var videoCount = $('#' + container.id + '>video').length;
  6717. if (!audioCount && !videoCount) {
  6718. console.log("Remove whole user", container.id);
  6719. if(VideoLayout.connectionIndicators[container.id])
  6720. VideoLayout.connectionIndicators[container.id].remove();
  6721. // Remove whole container
  6722. container.remove();
  6723. UIUtil.playSoundNotification('userLeft');
  6724. VideoLayout.resizeThumbnails();
  6725. }
  6726. if (removedVideoSrc)
  6727. VideoLayout.updateRemovedVideo(removedVideoSrc);
  6728. };
  6729. /**
  6730. * Show/hide peer container for the given resourceJid.
  6731. */
  6732. function showPeerContainer(resourceJid, state) {
  6733. var peerContainer = $('#participant_' + resourceJid);
  6734. if (!peerContainer)
  6735. return;
  6736. var isHide = state === 'hide';
  6737. var resizeThumbnails = false;
  6738. if (!isHide) {
  6739. if (!peerContainer.is(':visible')) {
  6740. resizeThumbnails = true;
  6741. peerContainer.show();
  6742. }
  6743. var jid = APP.xmpp.findJidFromResource(resourceJid);
  6744. if (state == 'show')
  6745. {
  6746. // peerContainer.css('-webkit-filter', '');
  6747. Avatar.showUserAvatar(jid, false);
  6748. }
  6749. else // if (state == 'avatar')
  6750. {
  6751. // peerContainer.css('-webkit-filter', 'grayscale(100%)');
  6752. Avatar.showUserAvatar(jid, true);
  6753. }
  6754. }
  6755. else if (peerContainer.is(':visible') && isHide)
  6756. {
  6757. resizeThumbnails = true;
  6758. peerContainer.hide();
  6759. if(VideoLayout.connectionIndicators['participant_' + resourceJid])
  6760. VideoLayout.connectionIndicators['participant_' + resourceJid].hide();
  6761. }
  6762. if (resizeThumbnails) {
  6763. VideoLayout.resizeThumbnails();
  6764. }
  6765. // We want to be able to pin a participant from the contact list, even
  6766. // if he's not in the lastN set!
  6767. // ContactList.setClickable(resourceJid, !isHide);
  6768. };
  6769. my.inputDisplayNameHandler = function (name) {
  6770. NicknameHandler.setNickname(name);
  6771. if (!$('#localDisplayName').is(":visible")) {
  6772. if (NicknameHandler.getNickname())
  6773. {
  6774. var meHTML = APP.translation.generateTranslatonHTML("me");
  6775. $('#localDisplayName').html(NicknameHandler.getNickname() + " (" + meHTML + ")");
  6776. }
  6777. else
  6778. {
  6779. var defaultHTML = APP.translation.generateTranslatonHTML(
  6780. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  6781. $('#localDisplayName')
  6782. .html(defaultHTML);
  6783. }
  6784. $('#localDisplayName').show();
  6785. }
  6786. $('#editDisplayName').hide();
  6787. };
  6788. /**
  6789. * Shows/hides the display name on the remote video.
  6790. * @param videoSpanId the identifier of the video span element
  6791. * @param isShow indicates if the display name should be shown or hidden
  6792. */
  6793. my.showDisplayName = function(videoSpanId, isShow) {
  6794. var nameSpan = $('#' + videoSpanId + '>span.displayname').get(0);
  6795. if (isShow) {
  6796. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  6797. nameSpan.setAttribute("style", "display:inline-block;");
  6798. }
  6799. else {
  6800. if (nameSpan)
  6801. nameSpan.setAttribute("style", "display:none;");
  6802. }
  6803. };
  6804. /**
  6805. * Shows the presence status message for the given video.
  6806. */
  6807. my.setPresenceStatus = function (videoSpanId, statusMsg) {
  6808. if (!$('#' + videoSpanId).length) {
  6809. // No container
  6810. return;
  6811. }
  6812. var statusSpan = $('#' + videoSpanId + '>span.status');
  6813. if (!statusSpan.length) {
  6814. //Add status span
  6815. statusSpan = document.createElement('span');
  6816. statusSpan.className = 'status';
  6817. statusSpan.id = videoSpanId + '_status';
  6818. $('#' + videoSpanId)[0].appendChild(statusSpan);
  6819. statusSpan = $('#' + videoSpanId + '>span.status');
  6820. }
  6821. // Display status
  6822. if (statusMsg && statusMsg.length) {
  6823. $('#' + videoSpanId + '_status').text(statusMsg);
  6824. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  6825. }
  6826. else {
  6827. // Hide
  6828. statusSpan.get(0).setAttribute("style", "display:none;");
  6829. }
  6830. };
  6831. /**
  6832. * Shows a visual indicator for the moderator of the conference.
  6833. */
  6834. my.showModeratorIndicator = function () {
  6835. var isModerator = APP.xmpp.isModerator();
  6836. if (isModerator) {
  6837. var indicatorSpan = $('#localVideoContainer .focusindicator');
  6838. if (indicatorSpan.children().length === 0)
  6839. {
  6840. createModeratorIndicatorElement(indicatorSpan[0]);
  6841. //translates text in focus indicator
  6842. APP.translation.translateElement($('#localVideoContainer .focusindicator'));
  6843. }
  6844. }
  6845. var members = APP.xmpp.getMembers();
  6846. Object.keys(members).forEach(function (jid) {
  6847. if (Strophe.getResourceFromJid(jid) === 'focus') {
  6848. // Skip server side focus
  6849. return;
  6850. }
  6851. var resourceJid = Strophe.getResourceFromJid(jid);
  6852. var videoSpanId = 'participant_' + resourceJid;
  6853. var videoContainer = document.getElementById(videoSpanId);
  6854. if (!videoContainer) {
  6855. console.error("No video container for " + jid);
  6856. return;
  6857. }
  6858. var member = members[jid];
  6859. if (member.role === 'moderator') {
  6860. // Remove menu if peer is moderator
  6861. var menuSpan = $('#' + videoSpanId + '>span.remotevideomenu');
  6862. if (menuSpan.length) {
  6863. removeRemoteVideoMenu(videoSpanId);
  6864. }
  6865. // Show moderator indicator
  6866. var indicatorSpan
  6867. = $('#' + videoSpanId + ' .focusindicator');
  6868. if (!indicatorSpan || indicatorSpan.length === 0) {
  6869. indicatorSpan = document.createElement('span');
  6870. indicatorSpan.className = 'focusindicator';
  6871. videoContainer.appendChild(indicatorSpan);
  6872. createModeratorIndicatorElement(indicatorSpan);
  6873. //translates text in focus indicators
  6874. APP.translation.translateElement($('#' + videoSpanId + ' .focusindicator'));
  6875. }
  6876. } else if (isModerator) {
  6877. // We are moderator, but user is not - add menu
  6878. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  6879. addRemoteVideoMenu(
  6880. jid,
  6881. document.getElementById('participant_' + resourceJid));
  6882. }
  6883. }
  6884. });
  6885. };
  6886. /**
  6887. * Shows video muted indicator over small videos.
  6888. */
  6889. my.showVideoIndicator = function(videoSpanId, isMuted) {
  6890. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  6891. if (isMuted === 'false') {
  6892. if (videoMutedSpan.length > 0) {
  6893. videoMutedSpan.remove();
  6894. }
  6895. }
  6896. else {
  6897. if(videoMutedSpan.length == 0) {
  6898. videoMutedSpan = document.createElement('span');
  6899. videoMutedSpan.className = 'videoMuted';
  6900. $('#' + videoSpanId)[0].appendChild(videoMutedSpan);
  6901. var mutedIndicator = document.createElement('i');
  6902. mutedIndicator.className = 'icon-camera-disabled';
  6903. UIUtil.setTooltip(mutedIndicator,
  6904. "videothumbnail.videomute",
  6905. "top");
  6906. videoMutedSpan.appendChild(mutedIndicator);
  6907. //translate texts for muted indicator
  6908. APP.translation.translateElement($('#' + videoSpanId + " > span > i"));
  6909. }
  6910. VideoLayout.updateMutePosition(videoSpanId);
  6911. }
  6912. };
  6913. my.updateMutePosition = function (videoSpanId) {
  6914. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  6915. var connectionIndicator = $('#' + videoSpanId + '>div.connectionindicator');
  6916. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  6917. if(connectionIndicator.length > 0
  6918. && connectionIndicator[0].style.display != "none") {
  6919. audioMutedSpan.css({right: "23px"});
  6920. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  6921. }
  6922. else
  6923. {
  6924. audioMutedSpan.css({right: "0px"});
  6925. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  6926. }
  6927. }
  6928. /**
  6929. * Shows audio muted indicator over small videos.
  6930. * @param {string} isMuted
  6931. */
  6932. my.showAudioIndicator = function(videoSpanId, isMuted) {
  6933. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  6934. if (isMuted === 'false') {
  6935. if (audioMutedSpan.length > 0) {
  6936. audioMutedSpan.popover('hide');
  6937. audioMutedSpan.remove();
  6938. }
  6939. }
  6940. else {
  6941. if(audioMutedSpan.length == 0 ) {
  6942. audioMutedSpan = document.createElement('span');
  6943. audioMutedSpan.className = 'audioMuted';
  6944. UIUtil.setTooltip(audioMutedSpan,
  6945. "videothumbnail.mute",
  6946. "top");
  6947. $('#' + videoSpanId)[0].appendChild(audioMutedSpan);
  6948. APP.translation.translateElement($('#' + videoSpanId + " > span"));
  6949. var mutedIndicator = document.createElement('i');
  6950. mutedIndicator.className = 'icon-mic-disabled';
  6951. audioMutedSpan.appendChild(mutedIndicator);
  6952. }
  6953. VideoLayout.updateMutePosition(videoSpanId);
  6954. }
  6955. };
  6956. /*
  6957. * Shows or hides the audio muted indicator over the local thumbnail video.
  6958. * @param {boolean} isMuted
  6959. */
  6960. my.showLocalAudioIndicator = function(isMuted) {
  6961. VideoLayout.showAudioIndicator('localVideoContainer', isMuted.toString());
  6962. };
  6963. /**
  6964. * Resizes the large video container.
  6965. */
  6966. my.resizeLargeVideoContainer = function () {
  6967. Chat.resizeChat();
  6968. var availableHeight = window.innerHeight;
  6969. var availableWidth = UIUtil.getAvailableVideoWidth();
  6970. if (availableWidth < 0 || availableHeight < 0) return;
  6971. $('#videospace').width(availableWidth);
  6972. $('#videospace').height(availableHeight);
  6973. $('#largeVideoContainer').width(availableWidth);
  6974. $('#largeVideoContainer').height(availableHeight);
  6975. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  6976. var top = availableHeight / 2 - avatarSize / 4 * 3;
  6977. $('#activeSpeaker').css('top', top);
  6978. VideoLayout.resizeThumbnails();
  6979. };
  6980. /**
  6981. * Resizes thumbnails.
  6982. */
  6983. my.resizeThumbnails = function() {
  6984. var videoSpaceWidth = $('#remoteVideos').width();
  6985. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  6986. var width = thumbnailSize[0];
  6987. var height = thumbnailSize[1];
  6988. // size videos so that while keeping AR and max height, we have a
  6989. // nice fit
  6990. $('#remoteVideos').height(height);
  6991. $('#remoteVideos>span').width(width);
  6992. $('#remoteVideos>span').height(height);
  6993. $('.userAvatar').css('left', (width - height) / 2);
  6994. $(document).trigger("remotevideo.resized", [width, height]);
  6995. };
  6996. /**
  6997. * Enables the dominant speaker UI.
  6998. *
  6999. * @param resourceJid the jid indicating the video element to
  7000. * activate/deactivate
  7001. * @param isEnable indicates if the dominant speaker should be enabled or
  7002. * disabled
  7003. */
  7004. my.enableDominantSpeaker = function(resourceJid, isEnable) {
  7005. var videoSpanId = null;
  7006. var videoContainerId = null;
  7007. if (resourceJid
  7008. === APP.xmpp.myResource()) {
  7009. videoSpanId = 'localVideoWrapper';
  7010. videoContainerId = 'localVideoContainer';
  7011. }
  7012. else {
  7013. videoSpanId = 'participant_' + resourceJid;
  7014. videoContainerId = videoSpanId;
  7015. }
  7016. var displayName = resourceJid;
  7017. var nameSpan = $('#' + videoContainerId + '>span.displayname');
  7018. if (nameSpan.length > 0)
  7019. displayName = nameSpan.html();
  7020. console.log("UI enable dominant speaker",
  7021. displayName,
  7022. resourceJid,
  7023. isEnable);
  7024. videoSpan = document.getElementById(videoContainerId);
  7025. if (!videoSpan) {
  7026. return;
  7027. }
  7028. var video = $('#' + videoSpanId + '>video');
  7029. if (video && video.length > 0) {
  7030. if (isEnable) {
  7031. var isLargeVideoVisible = VideoLayout.isLargeVideoOnTop();
  7032. VideoLayout.showDisplayName(videoContainerId, isLargeVideoVisible);
  7033. if (!videoSpan.classList.contains("dominantspeaker"))
  7034. videoSpan.classList.add("dominantspeaker");
  7035. }
  7036. else {
  7037. VideoLayout.showDisplayName(videoContainerId, false);
  7038. if (videoSpan.classList.contains("dominantspeaker"))
  7039. videoSpan.classList.remove("dominantspeaker");
  7040. }
  7041. Avatar.showUserAvatar(
  7042. APP.xmpp.findJidFromResource(resourceJid));
  7043. }
  7044. };
  7045. /**
  7046. * Calculates the thumbnail size.
  7047. *
  7048. * @param videoSpaceWidth the width of the video space
  7049. */
  7050. my.calculateThumbnailSize = function (videoSpaceWidth) {
  7051. // Calculate the available height, which is the inner window height minus
  7052. // 39px for the header minus 2px for the delimiter lines on the top and
  7053. // bottom of the large video, minus the 36px space inside the remoteVideos
  7054. // container used for highlighting shadow.
  7055. var availableHeight = 100;
  7056. var numvids = $('#remoteVideos>span:visible').length;
  7057. if (localLastNCount && localLastNCount > 0) {
  7058. numvids = Math.min(localLastNCount + 1, numvids);
  7059. }
  7060. // Remove the 3px borders arround videos and border around the remote
  7061. // videos area and the 4 pixels between the local video and the others
  7062. //TODO: Find out where the 4 pixels come from and remove them
  7063. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  7064. var availableWidth = availableWinWidth / numvids;
  7065. var aspectRatio = 16.0 / 9.0;
  7066. var maxHeight = Math.min(160, availableHeight);
  7067. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  7068. if (availableHeight < availableWidth / aspectRatio) {
  7069. availableWidth = Math.floor(availableHeight * aspectRatio);
  7070. }
  7071. return [availableWidth, availableHeight];
  7072. };
  7073. /**
  7074. * Updates the remote video menu.
  7075. *
  7076. * @param jid the jid indicating the video for which we're adding a menu.
  7077. * @param isMuted indicates the current mute state
  7078. */
  7079. my.updateRemoteVideoMenu = function(jid, isMuted) {
  7080. var muteMenuItem
  7081. = $('#remote_popupmenu_'
  7082. + Strophe.getResourceFromJid(jid)
  7083. + '>li>a.mutelink');
  7084. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  7085. if (muteMenuItem.length) {
  7086. var muteLink = muteMenuItem.get(0);
  7087. if (isMuted === 'true') {
  7088. muteLink.innerHTML = mutedIndicator + ' Muted';
  7089. muteLink.className = 'mutelink disabled';
  7090. }
  7091. else {
  7092. muteLink.innerHTML = mutedIndicator + ' Mute';
  7093. muteLink.className = 'mutelink';
  7094. }
  7095. }
  7096. };
  7097. /**
  7098. * Returns the current dominant speaker resource jid.
  7099. */
  7100. my.getDominantSpeakerResourceJid = function () {
  7101. return currentDominantSpeaker;
  7102. };
  7103. /**
  7104. * Returns the corresponding resource jid to the given peer container
  7105. * DOM element.
  7106. *
  7107. * @return the corresponding resource jid to the given peer container
  7108. * DOM element
  7109. */
  7110. my.getPeerContainerResourceJid = function (containerElement) {
  7111. var i = containerElement.id.indexOf('participant_');
  7112. if (i >= 0)
  7113. return containerElement.id.substring(i + 12);
  7114. };
  7115. /**
  7116. * On contact list item clicked.
  7117. */
  7118. $(ContactList).bind('contactclicked', function(event, jid) {
  7119. if (!jid) {
  7120. return;
  7121. }
  7122. var resource = Strophe.getResourceFromJid(jid);
  7123. var videoContainer = $("#participant_" + resource);
  7124. if (videoContainer.length > 0) {
  7125. var videoThumb = $('video', videoContainer).get(0);
  7126. // It is not always the case that a videoThumb exists (if there is
  7127. // no actual video).
  7128. if (videoThumb) {
  7129. if (videoThumb.src && videoThumb.src != '') {
  7130. // We have a video src, great! Let's update the large video
  7131. // now.
  7132. VideoLayout.handleVideoThumbClicked(
  7133. videoThumb.src,
  7134. false,
  7135. Strophe.getResourceFromJid(jid));
  7136. } else {
  7137. // If we don't have a video src for jid, there's absolutely
  7138. // no point in calling handleVideoThumbClicked; Quite
  7139. // simply, it won't work because it needs an src to attach
  7140. // to the large video.
  7141. //
  7142. // Instead, we trigger the pinned endpoint changed event to
  7143. // let the bridge adjust its lastN set for myjid and store
  7144. // the pinned user in the lastNPickupJid variable to be
  7145. // picked up later by the lastN changed event handler.
  7146. lastNPickupJid = jid;
  7147. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  7148. Strophe.getResourceFromJid(jid));
  7149. }
  7150. } else if (jid == APP.xmpp.myJid()) {
  7151. $("#localVideoContainer").click();
  7152. }
  7153. }
  7154. });
  7155. /**
  7156. * On audio muted event.
  7157. */
  7158. $(document).bind('audiomuted.muc', function (event, jid, isMuted) {
  7159. /*
  7160. // FIXME: but focus can not mute in this case ? - check
  7161. if (jid === xmpp.myJid()) {
  7162. // The local mute indicator is controlled locally
  7163. return;
  7164. }*/
  7165. var videoSpanId = null;
  7166. if (jid === APP.xmpp.myJid()) {
  7167. videoSpanId = 'localVideoContainer';
  7168. } else {
  7169. VideoLayout.ensurePeerContainerExists(jid);
  7170. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  7171. }
  7172. mutedAudios[jid] = isMuted;
  7173. if (APP.xmpp.isModerator()) {
  7174. VideoLayout.updateRemoteVideoMenu(jid, isMuted);
  7175. }
  7176. if (videoSpanId)
  7177. VideoLayout.showAudioIndicator(videoSpanId, isMuted);
  7178. });
  7179. /**
  7180. * On video muted event.
  7181. */
  7182. $(document).bind('videomuted.muc', function (event, jid, value) {
  7183. var isMuted = (value === "true");
  7184. if(jid !== APP.xmpp.myJid() && !APP.RTC.muteRemoteVideoStream(jid, isMuted))
  7185. return;
  7186. Avatar.showUserAvatar(jid, isMuted);
  7187. var videoSpanId = null;
  7188. if (jid === APP.xmpp.myJid()) {
  7189. videoSpanId = 'localVideoContainer';
  7190. } else {
  7191. VideoLayout.ensurePeerContainerExists(jid);
  7192. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  7193. }
  7194. if (videoSpanId)
  7195. VideoLayout.showVideoIndicator(videoSpanId, value);
  7196. });
  7197. /**
  7198. * Display name changed.
  7199. */
  7200. my.onDisplayNameChanged =
  7201. function (jid, displayName, status) {
  7202. if (jid === 'localVideoContainer'
  7203. || jid === APP.xmpp.myJid()) {
  7204. setDisplayName('localVideoContainer',
  7205. displayName);
  7206. } else {
  7207. VideoLayout.ensurePeerContainerExists(jid);
  7208. setDisplayName(
  7209. 'participant_' + Strophe.getResourceFromJid(jid),
  7210. displayName,
  7211. status);
  7212. }
  7213. };
  7214. /**
  7215. * On dominant speaker changed event.
  7216. */
  7217. my.onDominantSpeakerChanged = function (resourceJid) {
  7218. // We ignore local user events.
  7219. if (resourceJid
  7220. === APP.xmpp.myResource())
  7221. return;
  7222. var members = APP.xmpp.getMembers();
  7223. // Update the current dominant speaker.
  7224. if (resourceJid !== currentDominantSpeaker) {
  7225. var oldSpeakerVideoSpanId = "participant_" + currentDominantSpeaker,
  7226. newSpeakerVideoSpanId = "participant_" + resourceJid;
  7227. var currentJID = APP.xmpp.findJidFromResource(currentDominantSpeaker);
  7228. var newJID = APP.xmpp.findJidFromResource(resourceJid);
  7229. if(currentDominantSpeaker && (!members || !members[currentJID] ||
  7230. !members[currentJID].displayName)) {
  7231. setDisplayName(oldSpeakerVideoSpanId, null);
  7232. }
  7233. if(resourceJid && (!members || !members[newJID] ||
  7234. !members[newJID].displayName)) {
  7235. setDisplayName(newSpeakerVideoSpanId, null,
  7236. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  7237. }
  7238. currentDominantSpeaker = resourceJid;
  7239. } else {
  7240. return;
  7241. }
  7242. // Obtain container for new dominant speaker.
  7243. var container = document.getElementById(
  7244. 'participant_' + resourceJid);
  7245. // Local video will not have container found, but that's ok
  7246. // since we don't want to switch to local video.
  7247. if (container && !focusedVideoInfo)
  7248. {
  7249. var video = container.getElementsByTagName("video");
  7250. // Update the large video if the video source is already available,
  7251. // otherwise wait for the "videoactive.jingle" event.
  7252. if (video.length && video[0].currentTime > 0)
  7253. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(video[0]), resourceJid);
  7254. }
  7255. };
  7256. /**
  7257. * On last N change event.
  7258. *
  7259. * @param lastNEndpoints the list of last N endpoints
  7260. * @param endpointsEnteringLastN the list currently entering last N
  7261. * endpoints
  7262. */
  7263. my.onLastNEndpointsChanged = function ( lastNEndpoints,
  7264. endpointsEnteringLastN,
  7265. stream) {
  7266. if (lastNCount !== lastNEndpoints.length)
  7267. lastNCount = lastNEndpoints.length;
  7268. lastNEndpointsCache = lastNEndpoints;
  7269. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  7270. //
  7271. // If LastN drops to, say, 2, because of adaptivity, then E should see
  7272. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  7273. // so E sees them. C is only in E's local LastN set.
  7274. //
  7275. // If F starts talking and LastN = 3, then E should see thumbnails for
  7276. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  7277. // enters E's local LastN ejecting C.
  7278. // Increase the local LastN set size, if necessary.
  7279. if (lastNCount > localLastNCount) {
  7280. localLastNCount = lastNCount;
  7281. }
  7282. // Update the local LastN set preserving the order in which the
  7283. // endpoints appeared in the LastN/local LastN set.
  7284. var nextLocalLastNSet = lastNEndpoints.slice(0);
  7285. for (var i = 0; i < localLastNSet.length; i++) {
  7286. if (nextLocalLastNSet.length >= localLastNCount) {
  7287. break;
  7288. }
  7289. var resourceJid = localLastNSet[i];
  7290. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  7291. nextLocalLastNSet.push(resourceJid);
  7292. }
  7293. }
  7294. localLastNSet = nextLocalLastNSet;
  7295. var updateLargeVideo = false;
  7296. // Handle LastN/local LastN changes.
  7297. $('#remoteVideos>span').each(function( index, element ) {
  7298. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  7299. var isReceived = true;
  7300. if (resourceJid
  7301. && lastNEndpoints.indexOf(resourceJid) < 0
  7302. && localLastNSet.indexOf(resourceJid) < 0) {
  7303. console.log("Remove from last N", resourceJid);
  7304. showPeerContainer(resourceJid, 'hide');
  7305. isReceived = false;
  7306. } else if (resourceJid
  7307. && $('#participant_' + resourceJid).is(':visible')
  7308. && lastNEndpoints.indexOf(resourceJid) < 0
  7309. && localLastNSet.indexOf(resourceJid) >= 0) {
  7310. showPeerContainer(resourceJid, 'avatar');
  7311. isReceived = false;
  7312. }
  7313. if (!isReceived) {
  7314. // resourceJid has dropped out of the server side lastN set, so
  7315. // it is no longer being received. If resourceJid was being
  7316. // displayed in the large video we have to switch to another
  7317. // user.
  7318. var largeVideoResource = largeVideoState.userResourceJid;
  7319. if (!updateLargeVideo && resourceJid === largeVideoResource) {
  7320. updateLargeVideo = true;
  7321. }
  7322. }
  7323. });
  7324. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  7325. endpointsEnteringLastN = lastNEndpoints;
  7326. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  7327. endpointsEnteringLastN.forEach(function (resourceJid) {
  7328. var isVisible = $('#participant_' + resourceJid).is(':visible');
  7329. showPeerContainer(resourceJid, 'show');
  7330. if (!isVisible) {
  7331. console.log("Add to last N", resourceJid);
  7332. var jid = APP.xmpp.findJidFromResource(resourceJid);
  7333. var mediaStream = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  7334. var sel = $('#participant_' + resourceJid + '>video');
  7335. var videoStream = APP.simulcast.getReceivingVideoStream(
  7336. mediaStream.stream);
  7337. APP.RTC.attachMediaStream(sel, videoStream);
  7338. if (lastNPickupJid == mediaStream.peerjid) {
  7339. // Clean up the lastN pickup jid.
  7340. lastNPickupJid = null;
  7341. // Don't fire the events again, they've already
  7342. // been fired in the contact list click handler.
  7343. VideoLayout.handleVideoThumbClicked(
  7344. $(sel).attr('src'),
  7345. false,
  7346. Strophe.getResourceFromJid(mediaStream.peerjid));
  7347. updateLargeVideo = false;
  7348. }
  7349. waitForRemoteVideo(sel, mediaStream.ssrc, mediaStream.stream, resourceJid);
  7350. }
  7351. })
  7352. }
  7353. // The endpoint that was being shown in the large video has dropped out
  7354. // of the lastN set and there was no lastN pickup jid. We need to update
  7355. // the large video now.
  7356. if (updateLargeVideo) {
  7357. var resource, container, src;
  7358. var myResource
  7359. = APP.xmpp.myResource();
  7360. // Find out which endpoint to show in the large video.
  7361. for (var i = 0; i < lastNEndpoints.length; i++) {
  7362. resource = lastNEndpoints[i];
  7363. if (!resource || resource === myResource)
  7364. continue;
  7365. container = $("#participant_" + resource);
  7366. if (container.length == 0)
  7367. continue;
  7368. src = $('video', container).attr('src');
  7369. if (!src)
  7370. continue;
  7371. // videoSrcToSsrc needs to be update for this call to succeed.
  7372. VideoLayout.updateLargeVideo(src);
  7373. break;
  7374. }
  7375. }
  7376. };
  7377. my.onSimulcastLayersChanging = function (endpointSimulcastLayers) {
  7378. endpointSimulcastLayers.forEach(function (esl) {
  7379. var resource = esl.endpoint;
  7380. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7381. // then ignore the event (= do not preload anything).
  7382. //
  7383. // The bridge could probably stop sending this message if it's for
  7384. // an endpoint that's not in lastN.
  7385. if (lastNCount != -1
  7386. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7387. return;
  7388. }
  7389. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7390. // Get session and stream from primary ssrc.
  7391. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7392. var sid = res.sid;
  7393. var electedStream = res.stream;
  7394. if (sid && electedStream) {
  7395. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7396. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7397. var preload = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC)) == largeVideoState.userResourceJid);
  7398. if (preload) {
  7399. if (largeVideoState.preload)
  7400. {
  7401. $(largeVideoState.preload).remove();
  7402. }
  7403. console.info('Preloading remote video');
  7404. largeVideoState.preload = $('<video autoplay></video>');
  7405. // ssrcs are unique in an rtp session
  7406. largeVideoState.preload_ssrc = primarySSRC;
  7407. APP.RTC.attachMediaStream(largeVideoState.preload, electedStream)
  7408. }
  7409. } else {
  7410. console.error('Could not find a stream or a session.', sid, electedStream);
  7411. }
  7412. });
  7413. };
  7414. /**
  7415. * On simulcast layers changed event.
  7416. */
  7417. my.onSimulcastLayersChanged = function (endpointSimulcastLayers) {
  7418. endpointSimulcastLayers.forEach(function (esl) {
  7419. var resource = esl.endpoint;
  7420. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7421. // then ignore the event (= do not change large video/thumbnail
  7422. // SRCs).
  7423. //
  7424. // Note that even if we ignore the "changed" event in this event
  7425. // handler, the bridge must continue sending these events because
  7426. // the simulcast code in simulcast.js uses it to know what's going
  7427. // to be streamed by the bridge when/if the endpoint gets back into
  7428. // the lastN set.
  7429. if (lastNCount != -1
  7430. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7431. return;
  7432. }
  7433. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7434. // Get session and stream from primary ssrc.
  7435. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7436. var sid = res.sid;
  7437. var electedStream = res.stream;
  7438. if (sid && electedStream) {
  7439. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7440. console.info('Switching simulcast substream.');
  7441. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7442. var msidParts = msid.split(' ');
  7443. var selRemoteVideo = $(['#', 'remoteVideo_', sid, '_', msidParts[0]].join(''));
  7444. var updateLargeVideo = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC))
  7445. == largeVideoState.userResourceJid);
  7446. var updateFocusedVideoSrc = (focusedVideoInfo && focusedVideoInfo.src && focusedVideoInfo.src != '' &&
  7447. (APP.RTC.getVideoSrc(selRemoteVideo[0]) == focusedVideoInfo.src));
  7448. var electedStreamUrl;
  7449. if (largeVideoState.preload_ssrc == primarySSRC)
  7450. {
  7451. APP.RTC.setVideoSrc(selRemoteVideo[0], APP.RTC.getVideoSrc(largeVideoState.preload[0]));
  7452. }
  7453. else
  7454. {
  7455. if (largeVideoState.preload
  7456. && largeVideoState.preload != null) {
  7457. $(largeVideoState.preload).remove();
  7458. }
  7459. largeVideoState.preload_ssrc = 0;
  7460. APP.RTC.attachMediaStream(selRemoteVideo, electedStream);
  7461. }
  7462. var jid = APP.xmpp.getJidFromSSRC(primarySSRC);
  7463. if (updateLargeVideo) {
  7464. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(selRemoteVideo[0]), null,
  7465. Strophe.getResourceFromJid(jid));
  7466. }
  7467. if (updateFocusedVideoSrc) {
  7468. focusedVideoInfo.src = APP.RTC.getVideoSrc(selRemoteVideo[0]);
  7469. }
  7470. var videoId;
  7471. if(resource == APP.xmpp.myResource())
  7472. {
  7473. videoId = "localVideoContainer";
  7474. }
  7475. else
  7476. {
  7477. videoId = "participant_" + resource;
  7478. }
  7479. var connectionIndicator = VideoLayout.connectionIndicators[videoId];
  7480. if(connectionIndicator)
  7481. connectionIndicator.updatePopoverData();
  7482. } else {
  7483. console.error('Could not find a stream or a sid.', sid, electedStream);
  7484. }
  7485. });
  7486. };
  7487. /**
  7488. * Updates local stats
  7489. * @param percent
  7490. * @param object
  7491. */
  7492. my.updateLocalConnectionStats = function (percent, object) {
  7493. var resolution = null;
  7494. if(object.resolution !== null)
  7495. {
  7496. resolution = object.resolution;
  7497. object.resolution = resolution[APP.xmpp.myJid()];
  7498. delete resolution[APP.xmpp.myJid()];
  7499. }
  7500. updateStatsIndicator("localVideoContainer", percent, object);
  7501. for(var jid in resolution)
  7502. {
  7503. if(resolution[jid] === null)
  7504. continue;
  7505. var id = 'participant_' + Strophe.getResourceFromJid(jid);
  7506. if(VideoLayout.connectionIndicators[id])
  7507. {
  7508. VideoLayout.connectionIndicators[id].updateResolution(resolution[jid]);
  7509. }
  7510. }
  7511. };
  7512. /**
  7513. * Updates remote stats.
  7514. * @param jid the jid associated with the stats
  7515. * @param percent the connection quality percent
  7516. * @param object the stats data
  7517. */
  7518. my.updateConnectionStats = function (jid, percent, object) {
  7519. var resourceJid = Strophe.getResourceFromJid(jid);
  7520. var videoSpanId = 'participant_' + resourceJid;
  7521. updateStatsIndicator(videoSpanId, percent, object);
  7522. };
  7523. /**
  7524. * Removes the connection
  7525. * @param jid
  7526. */
  7527. my.removeConnectionIndicator = function (jid) {
  7528. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7529. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].remove();
  7530. };
  7531. /**
  7532. * Hides the connection indicator
  7533. * @param jid
  7534. */
  7535. my.hideConnectionIndicator = function (jid) {
  7536. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7537. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].hide();
  7538. };
  7539. /**
  7540. * Hides all the indicators
  7541. */
  7542. my.onStatsStop = function () {
  7543. for(var indicator in VideoLayout.connectionIndicators)
  7544. {
  7545. VideoLayout.connectionIndicators[indicator].hideIndicator();
  7546. }
  7547. };
  7548. my.participantLeft = function (jid) {
  7549. // Unlock large video
  7550. if (focusedVideoInfo && focusedVideoInfo.jid === jid)
  7551. {
  7552. console.info("Focused video owner has left the conference");
  7553. focusedVideoInfo = null;
  7554. }
  7555. }
  7556. my.onVideoTypeChanged = function (jid) {
  7557. if(jid &&
  7558. Strophe.getResourceFromJid(jid) === largeVideoState.userResourceJid)
  7559. {
  7560. largeVideoState.isDesktop = APP.RTC.isVideoSrcDesktop(jid);
  7561. VideoLayout.getVideoSize = largeVideoState.isDesktop
  7562. ? getDesktopVideoSize
  7563. : getCameraVideoSize;
  7564. VideoLayout.getVideoPosition = largeVideoState.isDesktop
  7565. ? getDesktopVideoPosition
  7566. : getCameraVideoPosition;
  7567. VideoLayout.positionLarge(null, null);
  7568. }
  7569. }
  7570. return my;
  7571. }(VideoLayout || {}));
  7572. module.exports = VideoLayout;
  7573. },{"../../../service/RTC/MediaStreamTypes":87,"../../../service/UI/UIEvents":92,"../audio_levels/AudioLevels":9,"../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){
  7574. //var nouns = [
  7575. //];
  7576. var pluralNouns = [
  7577. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  7578. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  7579. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  7580. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  7581. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  7582. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  7583. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  7584. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  7585. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  7586. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  7587. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  7588. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  7589. ];
  7590. //var places = [
  7591. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  7592. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  7593. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  7594. // "Bridge"
  7595. //];
  7596. var verbs = [
  7597. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  7598. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  7599. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  7600. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  7601. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  7602. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  7603. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  7604. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  7605. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  7606. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  7607. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  7608. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  7609. ];
  7610. var adverbs = [
  7611. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  7612. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  7613. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  7614. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  7615. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  7616. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  7617. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  7618. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  7619. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  7620. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  7621. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  7622. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  7623. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  7624. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  7625. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly", "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  7626. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  7627. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  7628. ];
  7629. var adjectives = [
  7630. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  7631. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  7632. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  7633. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  7634. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  7635. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  7636. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  7637. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  7638. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  7639. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  7640. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  7641. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  7642. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  7643. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  7644. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  7645. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  7646. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  7647. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  7648. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  7649. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  7650. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  7651. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  7652. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  7653. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  7654. "Zealous"
  7655. ];
  7656. //var pronouns = [
  7657. //];
  7658. //var conjunctions = [
  7659. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  7660. //];
  7661. /*
  7662. * Maps a string (category name) to the array of words from that category.
  7663. */
  7664. var CATEGORIES =
  7665. {
  7666. //"_NOUN_": nouns,
  7667. "_PLURALNOUN_": pluralNouns,
  7668. //"_PLACE_": places,
  7669. "_VERB_": verbs,
  7670. "_ADVERB_": adverbs,
  7671. "_ADJECTIVE_": adjectives
  7672. //"_PRONOUN_": pronouns,
  7673. //"_CONJUNCTION_": conjunctions,
  7674. };
  7675. var PATTERNS = [
  7676. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  7677. // BeautifulFungiOrSpaghetti
  7678. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  7679. // AmazinglyScaryToy
  7680. //"_ADVERB__ADJECTIVE__NOUN_",
  7681. // NeitherTrashNorRifle
  7682. //"Neither_NOUN_Nor_NOUN_",
  7683. //"Either_NOUN_Or_NOUN_",
  7684. // EitherCopulateOrInvestigate
  7685. //"Either_VERB_Or_VERB_",
  7686. //"Neither_VERB_Nor_VERB_",
  7687. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  7688. //"The_ADVERB__ADJECTIVE__NOUN_",
  7689. //"The_ADVERB__ADJECTIVE__NOUN_s",
  7690. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  7691. // WolvesComputeBadly
  7692. //"_PLURALNOUN__VERB__ADVERB_",
  7693. // UniteFacilitateAndMerge
  7694. //"_VERB__VERB_And_VERB_",
  7695. //NastyWitchesAtThePub
  7696. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  7697. ];
  7698. /*
  7699. * Returns a random element from the array 'arr'
  7700. */
  7701. function randomElement(arr)
  7702. {
  7703. return arr[Math.floor(Math.random() * arr.length)];
  7704. }
  7705. /*
  7706. * Returns true if the string 's' contains one of the
  7707. * template strings.
  7708. */
  7709. function hasTemplate(s)
  7710. {
  7711. for (var template in CATEGORIES){
  7712. if (s.indexOf(template) >= 0){
  7713. return true;
  7714. }
  7715. }
  7716. }
  7717. /**
  7718. * Generates new room name.
  7719. */
  7720. var RoomNameGenerator = {
  7721. generateRoomWithoutSeparator: function()
  7722. {
  7723. // Note that if more than one pattern is available, the choice of 'name' won't be random (names from patterns
  7724. // with fewer options will have higher probability of being chosen that names from patterns with more options).
  7725. var name = randomElement(PATTERNS);
  7726. var word;
  7727. while (hasTemplate(name)){
  7728. for (var template in CATEGORIES){
  7729. word = randomElement(CATEGORIES[template]);
  7730. name = name.replace(template, word);
  7731. }
  7732. }
  7733. return name;
  7734. }
  7735. }
  7736. module.exports = RoomNameGenerator;
  7737. },{}],34:[function(require,module,exports){
  7738. var animateTimeout, updateTimeout;
  7739. var RoomNameGenerator = require("./RoomnameGenerator");
  7740. function enter_room()
  7741. {
  7742. var val = $("#enter_room_field").val();
  7743. if(!val) {
  7744. val = $("#enter_room_field").attr("room_name");
  7745. }
  7746. if (val) {
  7747. window.location.pathname = "/" + val;
  7748. }
  7749. }
  7750. function animate(word) {
  7751. var currentVal = $("#enter_room_field").attr("placeholder");
  7752. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  7753. animateTimeout = setTimeout(function() {
  7754. animate(word.substring(1, word.length))
  7755. }, 70);
  7756. }
  7757. function update_roomname()
  7758. {
  7759. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  7760. $("#enter_room_field").attr("room_name", word);
  7761. $("#enter_room_field").attr("placeholder", "");
  7762. clearTimeout(animateTimeout);
  7763. animate(word);
  7764. updateTimeout = setTimeout(update_roomname, 10000);
  7765. }
  7766. function setupWelcomePage()
  7767. {
  7768. $("#videoconference_page").hide();
  7769. $("#domain_name").text(
  7770. window.location.protocol + "//" + window.location.host + "/");
  7771. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  7772. var leftWatermarkDiv
  7773. = $("#welcome_page_header div[class='watermark leftwatermark']");
  7774. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  7775. {
  7776. leftWatermarkDiv.css({display: 'block'});
  7777. leftWatermarkDiv.parent().get(0).href
  7778. = interfaceConfig.JITSI_WATERMARK_LINK;
  7779. }
  7780. }
  7781. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  7782. var rightWatermarkDiv
  7783. = $("#welcome_page_header div[class='watermark rightwatermark']");
  7784. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  7785. rightWatermarkDiv.css({display: 'block'});
  7786. rightWatermarkDiv.parent().get(0).href
  7787. = interfaceConfig.BRAND_WATERMARK_LINK;
  7788. rightWatermarkDiv.get(0).style.backgroundImage
  7789. = "url(images/rightwatermark.png)";
  7790. }
  7791. }
  7792. if (interfaceConfig.SHOW_POWERED_BY) {
  7793. $("#welcome_page_header>a[class='poweredby']")
  7794. .css({display: 'block'});
  7795. }
  7796. $("#enter_room_button").click(function()
  7797. {
  7798. enter_room();
  7799. });
  7800. $("#enter_room_field").keydown(function (event) {
  7801. if (event.keyCode === 13 /* enter */) {
  7802. enter_room();
  7803. }
  7804. });
  7805. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  7806. var updateTimeout;
  7807. var animateTimeout;
  7808. $("#reload_roomname").click(function () {
  7809. clearTimeout(updateTimeout);
  7810. clearTimeout(animateTimeout);
  7811. update_roomname();
  7812. });
  7813. $("#reload_roomname").show();
  7814. update_roomname();
  7815. }
  7816. $("#disable_welcome").click(function () {
  7817. window.localStorage.welcomePageDisabled
  7818. = $("#disable_welcome").is(":checked");
  7819. });
  7820. }
  7821. module.exports = setupWelcomePage;
  7822. },{"./RoomnameGenerator":33}],35:[function(require,module,exports){
  7823. var EventEmitter = require("events");
  7824. var eventEmitter = new EventEmitter();
  7825. var CQEvents = require("../../service/connectionquality/CQEvents");
  7826. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7827. /**
  7828. * local stats
  7829. * @type {{}}
  7830. */
  7831. var stats = {};
  7832. /**
  7833. * remote stats
  7834. * @type {{}}
  7835. */
  7836. var remoteStats = {};
  7837. /**
  7838. * Interval for sending statistics to other participants
  7839. * @type {null}
  7840. */
  7841. var sendIntervalId = null;
  7842. /**
  7843. * Start statistics sending.
  7844. */
  7845. function startSendingStats() {
  7846. sendStats();
  7847. sendIntervalId = setInterval(sendStats, 10000);
  7848. }
  7849. /**
  7850. * Sends statistics to other participants
  7851. */
  7852. function sendStats() {
  7853. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  7854. }
  7855. /**
  7856. * Converts statistics to format for sending through XMPP
  7857. * @param stats the statistics
  7858. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  7859. */
  7860. function convertToMUCStats(stats) {
  7861. return {
  7862. "bitrate_download": stats.bitrate.download,
  7863. "bitrate_upload": stats.bitrate.upload,
  7864. "packetLoss_total": stats.packetLoss.total,
  7865. "packetLoss_download": stats.packetLoss.download,
  7866. "packetLoss_upload": stats.packetLoss.upload
  7867. };
  7868. }
  7869. /**
  7870. * Converts statitistics to format used by VideoLayout
  7871. * @param stats
  7872. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  7873. */
  7874. function parseMUCStats(stats) {
  7875. return {
  7876. bitrate: {
  7877. download: stats.bitrate_download,
  7878. upload: stats.bitrate_upload
  7879. },
  7880. packetLoss: {
  7881. total: stats.packetLoss_total,
  7882. download: stats.packetLoss_download,
  7883. upload: stats.packetLoss_upload
  7884. }
  7885. };
  7886. }
  7887. var ConnectionQuality = {
  7888. init: function () {
  7889. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  7890. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  7891. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  7892. },
  7893. /**
  7894. * Updates the local statistics
  7895. * @param data new statistics
  7896. */
  7897. updateLocalStats: function (data) {
  7898. stats = data;
  7899. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  7900. if (sendIntervalId == null) {
  7901. startSendingStats();
  7902. }
  7903. },
  7904. /**
  7905. * Updates remote statistics
  7906. * @param jid the jid associated with the statistics
  7907. * @param data the statistics
  7908. */
  7909. updateRemoteStats: function (jid, data) {
  7910. if (data == null || data.packetLoss_total == null) {
  7911. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  7912. return;
  7913. }
  7914. remoteStats[jid] = parseMUCStats(data);
  7915. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  7916. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  7917. },
  7918. /**
  7919. * Stops statistics sending.
  7920. */
  7921. stopSendingStats: function () {
  7922. clearInterval(sendIntervalId);
  7923. sendIntervalId = null;
  7924. //notify UI about stopping statistics gathering
  7925. eventEmitter.emit(CQEvents.STOP);
  7926. },
  7927. /**
  7928. * Returns the local statistics.
  7929. */
  7930. getStats: function () {
  7931. return stats;
  7932. },
  7933. addListener: function (type, listener) {
  7934. eventEmitter.on(type, listener);
  7935. }
  7936. };
  7937. module.exports = ConnectionQuality;
  7938. },{"../../service/connectionquality/CQEvents":94,"../../service/xmpp/XMPPEvents":97,"events":98}],36:[function(require,module,exports){
  7939. /* global $, alert, changeLocalVideo, chrome, config, getConferenceHandler, getUserMediaWithConstraints */
  7940. /**
  7941. * Indicates that desktop stream is currently in use(for toggle purpose).
  7942. * @type {boolean}
  7943. */
  7944. var isUsingScreenStream = false;
  7945. /**
  7946. * Indicates that switch stream operation is in progress and prevent from triggering new events.
  7947. * @type {boolean}
  7948. */
  7949. var switchInProgress = false;
  7950. /**
  7951. * Method used to get screen sharing stream.
  7952. *
  7953. * @type {function (stream_callback, failure_callback}
  7954. */
  7955. var obtainDesktopStream = null;
  7956. /**
  7957. * Flag used to cache desktop sharing enabled state. Do not use directly as it can be <tt>null</tt>.
  7958. * @type {null|boolean}
  7959. */
  7960. var _desktopSharingEnabled = null;
  7961. var EventEmitter = require("events");
  7962. var eventEmitter = new EventEmitter();
  7963. var DesktopSharingEventTypes = require("../../service/desktopsharing/DesktopSharingEventTypes");
  7964. /**
  7965. * Method obtains desktop stream from WebRTC 'screen' source.
  7966. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  7967. */
  7968. function obtainWebRTCScreen(streamCallback, failCallback) {
  7969. APP.RTC.getUserMediaWithConstraints(
  7970. ['screen'],
  7971. streamCallback,
  7972. failCallback
  7973. );
  7974. }
  7975. /**
  7976. * Constructs inline install URL for Chrome desktop streaming extension.
  7977. * The 'chromeExtensionId' must be defined in config.js.
  7978. * @returns {string}
  7979. */
  7980. function getWebStoreInstallUrl()
  7981. {
  7982. return "https://chrome.google.com/webstore/detail/" + config.chromeExtensionId;
  7983. }
  7984. /**
  7985. * Checks whether extension update is required.
  7986. * @param minVersion minimal required version
  7987. * @param extVersion current extension version
  7988. * @returns {boolean}
  7989. */
  7990. function isUpdateRequired(minVersion, extVersion)
  7991. {
  7992. try
  7993. {
  7994. var s1 = minVersion.split('.');
  7995. var s2 = extVersion.split('.');
  7996. var len = Math.max(s1.length, s2.length);
  7997. for (var i = 0; i < len; i++)
  7998. {
  7999. var n1 = 0,
  8000. n2 = 0;
  8001. if (i < s1.length)
  8002. n1 = parseInt(s1[i]);
  8003. if (i < s2.length)
  8004. n2 = parseInt(s2[i]);
  8005. if (isNaN(n1) || isNaN(n2))
  8006. {
  8007. return true;
  8008. }
  8009. else if (n1 !== n2)
  8010. {
  8011. return n1 > n2;
  8012. }
  8013. }
  8014. // will happen if boths version has identical numbers in
  8015. // their components (even if one of them is longer, has more components)
  8016. return false;
  8017. }
  8018. catch (e)
  8019. {
  8020. console.error("Failed to parse extension version", e);
  8021. APP.UI.messageHandler.showError("dialog.error",
  8022. "dialog.detectext");
  8023. return true;
  8024. }
  8025. }
  8026. function checkExtInstalled(isInstalledCallback) {
  8027. if (!chrome.runtime) {
  8028. // No API, so no extension for sure
  8029. isInstalledCallback(false);
  8030. return;
  8031. }
  8032. chrome.runtime.sendMessage(
  8033. config.chromeExtensionId,
  8034. { getVersion: true },
  8035. function (response) {
  8036. if (!response || !response.version) {
  8037. // Communication failure - assume that no endpoint exists
  8038. console.warn("Extension not installed?: " + chrome.runtime.lastError);
  8039. isInstalledCallback(false);
  8040. } else {
  8041. // Check installed extension version
  8042. var extVersion = response.version;
  8043. console.log('Extension version is: ' + extVersion);
  8044. var updateRequired = isUpdateRequired(config.minChromeExtVersion, extVersion);
  8045. if (updateRequired) {
  8046. alert(
  8047. 'Jitsi Desktop Streamer requires update. ' +
  8048. 'Changes will take effect after next Chrome restart.');
  8049. }
  8050. isInstalledCallback(!updateRequired);
  8051. }
  8052. }
  8053. );
  8054. }
  8055. function doGetStreamFromExtension(streamCallback, failCallback) {
  8056. // Sends 'getStream' msg to the extension. Extension id must be defined in the config.
  8057. chrome.runtime.sendMessage(
  8058. config.chromeExtensionId,
  8059. { getStream: true, sources: config.desktopSharingSources },
  8060. function (response) {
  8061. if (!response) {
  8062. failCallback(chrome.runtime.lastError);
  8063. return;
  8064. }
  8065. console.log("Response from extension: " + response);
  8066. if (response.streamId) {
  8067. APP.RTC.getUserMediaWithConstraints(
  8068. ['desktop'],
  8069. function (stream) {
  8070. streamCallback(stream);
  8071. },
  8072. failCallback,
  8073. null, null, null,
  8074. response.streamId);
  8075. } else {
  8076. failCallback("Extension failed to get the stream");
  8077. }
  8078. }
  8079. );
  8080. }
  8081. /**
  8082. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop' stream for returned stream token.
  8083. */
  8084. function obtainScreenFromExtension(streamCallback, failCallback) {
  8085. checkExtInstalled(
  8086. function (isInstalled) {
  8087. if (isInstalled) {
  8088. doGetStreamFromExtension(streamCallback, failCallback);
  8089. } else {
  8090. chrome.webstore.install(
  8091. getWebStoreInstallUrl(),
  8092. function (arg) {
  8093. console.log("Extension installed successfully", arg);
  8094. // We need to reload the page in order to get the access to chrome.runtime
  8095. window.location.reload(false);
  8096. },
  8097. function (arg) {
  8098. console.log("Failed to install the extension", arg);
  8099. failCallback(arg);
  8100. APP.UI.messageHandler.showError("dialog.error",
  8101. "dialog.failtoinstall");
  8102. }
  8103. );
  8104. }
  8105. }
  8106. );
  8107. }
  8108. /**
  8109. * Call this method to toggle desktop sharing feature.
  8110. * @param method pass "ext" to use chrome extension for desktop capture(chrome extension required),
  8111. * pass "webrtc" to use WebRTC "screen" desktop source('chrome://flags/#enable-usermedia-screen-capture'
  8112. * must be enabled), pass any other string or nothing in order to disable this feature completely.
  8113. */
  8114. function setDesktopSharing(method) {
  8115. // Check if we are running chrome
  8116. if (!navigator.webkitGetUserMedia) {
  8117. obtainDesktopStream = null;
  8118. console.info("Desktop sharing disabled");
  8119. } else if (method == "ext") {
  8120. obtainDesktopStream = obtainScreenFromExtension;
  8121. console.info("Using Chrome extension for desktop sharing");
  8122. } else if (method == "webrtc") {
  8123. obtainDesktopStream = obtainWebRTCScreen;
  8124. console.info("Using Chrome WebRTC for desktop sharing");
  8125. }
  8126. // Reset enabled cache
  8127. _desktopSharingEnabled = null;
  8128. }
  8129. /**
  8130. * Initializes <link rel=chrome-webstore-item /> with extension id set in config.js to support inline installs.
  8131. * Host site must be selected as main website of published extension.
  8132. */
  8133. function initInlineInstalls()
  8134. {
  8135. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  8136. }
  8137. function getSwitchStreamFailed(error) {
  8138. console.error("Failed to obtain the stream to switch to", error);
  8139. switchInProgress = false;
  8140. }
  8141. function streamSwitchDone() {
  8142. switchInProgress = false;
  8143. eventEmitter.emit(
  8144. DesktopSharingEventTypes.SWITCHING_DONE,
  8145. isUsingScreenStream);
  8146. }
  8147. function newStreamCreated(stream)
  8148. {
  8149. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  8150. stream, isUsingScreenStream, streamSwitchDone);
  8151. }
  8152. module.exports = {
  8153. isUsingScreenStream: function () {
  8154. return isUsingScreenStream;
  8155. },
  8156. /**
  8157. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available and enabled.
  8158. */
  8159. isDesktopSharingEnabled: function () {
  8160. if (_desktopSharingEnabled === null) {
  8161. if (obtainDesktopStream === obtainScreenFromExtension) {
  8162. // Parse chrome version
  8163. var userAgent = navigator.userAgent.toLowerCase();
  8164. // We can assume that user agent is chrome, because it's enforced when 'ext' streaming method is set
  8165. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  8166. console.log("Chrome version" + userAgent, ver);
  8167. _desktopSharingEnabled = ver >= 34;
  8168. } else {
  8169. _desktopSharingEnabled = obtainDesktopStream === obtainWebRTCScreen;
  8170. }
  8171. }
  8172. return _desktopSharingEnabled;
  8173. },
  8174. init: function () {
  8175. setDesktopSharing(config.desktopSharing);
  8176. // Initialize Chrome extension inline installs
  8177. if (config.chromeExtensionId) {
  8178. initInlineInstalls();
  8179. }
  8180. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  8181. },
  8182. addListener: function(listener, type)
  8183. {
  8184. eventEmitter.on(type, listener);
  8185. },
  8186. removeListener: function (listener,type) {
  8187. eventEmitter.removeListener(type, listener);
  8188. },
  8189. /*
  8190. * Toggles screen sharing.
  8191. */
  8192. toggleScreenSharing: function () {
  8193. if (switchInProgress || !obtainDesktopStream) {
  8194. console.warn("Switch in progress or no method defined");
  8195. return;
  8196. }
  8197. switchInProgress = true;
  8198. if (!isUsingScreenStream)
  8199. {
  8200. // Switch to desktop stream
  8201. obtainDesktopStream(
  8202. function (stream) {
  8203. // We now use screen stream
  8204. isUsingScreenStream = true;
  8205. // Hook 'ended' event to restore camera when screen stream stops
  8206. stream.addEventListener('ended',
  8207. function (e) {
  8208. if (!switchInProgress && isUsingScreenStream) {
  8209. toggleScreenSharing();
  8210. }
  8211. }
  8212. );
  8213. newStreamCreated(stream);
  8214. },
  8215. getSwitchStreamFailed);
  8216. } else {
  8217. // Disable screen stream
  8218. APP.RTC.getUserMediaWithConstraints(
  8219. ['video'],
  8220. function (stream) {
  8221. // We are now using camera stream
  8222. isUsingScreenStream = false;
  8223. newStreamCreated(stream);
  8224. },
  8225. getSwitchStreamFailed, config.resolution || '360'
  8226. );
  8227. }
  8228. }
  8229. };
  8230. },{"../../service/desktopsharing/DesktopSharingEventTypes":95,"events":98}],37:[function(require,module,exports){
  8231. //maps keycode to character, id of popover for given function and function
  8232. var shortcuts = {
  8233. 67: {
  8234. character: "C",
  8235. id: "toggleChatPopover",
  8236. function: APP.UI.toggleChat
  8237. },
  8238. 70: {
  8239. character: "F",
  8240. id: "filmstripPopover",
  8241. function: APP.UI.toggleFilmStrip
  8242. },
  8243. 77: {
  8244. character: "M",
  8245. id: "mutePopover",
  8246. function: APP.UI.toggleAudio
  8247. },
  8248. 84: {
  8249. character: "T",
  8250. function: function() {
  8251. if(!APP.RTC.localAudio.isMuted()) {
  8252. APP.UI.toggleAudio();
  8253. }
  8254. }
  8255. },
  8256. 86: {
  8257. character: "V",
  8258. id: "toggleVideoPopover",
  8259. function: APP.UI.toggleVideo
  8260. }
  8261. };
  8262. var KeyboardShortcut = {
  8263. init: function () {
  8264. window.onkeyup = function(e) {
  8265. var keycode = e.which;
  8266. if(!($(":focus").is("input[type=text]") ||
  8267. $(":focus").is("input[type=password]") ||
  8268. $(":focus").is("textarea"))) {
  8269. if (typeof shortcuts[keycode] === "object") {
  8270. shortcuts[keycode].function();
  8271. }
  8272. else if (keycode >= "0".charCodeAt(0) &&
  8273. keycode <= "9".charCodeAt(0)) {
  8274. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  8275. }
  8276. //esc while the smileys are visible hides them
  8277. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  8278. APP.UI.toggleSmileys();
  8279. }
  8280. };
  8281. window.onkeydown = function(e) {
  8282. if(!($(":focus").is("input[type=text]") ||
  8283. $(":focus").is("input[type=password]") ||
  8284. $(":focus").is("textarea"))) {
  8285. if(e.which === "T".charCodeAt(0)) {
  8286. if(APP.RTC.localAudio.isMuted()) {
  8287. APP.UI.toggleAudio();
  8288. }
  8289. }
  8290. }
  8291. };
  8292. var self = this;
  8293. $('body').popover({ selector: '[data-toggle=popover]',
  8294. trigger: 'click hover',
  8295. content: function() {
  8296. return this.getAttribute("content") +
  8297. self.getShortcut(this.getAttribute("shortcut"));
  8298. }
  8299. });
  8300. },
  8301. /**
  8302. *
  8303. * @param id indicates the popover associated with the shortcut
  8304. * @returns {string} the keyboard shortcut used for the id given
  8305. */
  8306. getShortcut: function (id) {
  8307. for (var keycode in shortcuts) {
  8308. if (shortcuts.hasOwnProperty(keycode)) {
  8309. if (shortcuts[keycode].id === id) {
  8310. return " (" + shortcuts[keycode].character + ")";
  8311. }
  8312. }
  8313. }
  8314. return "";
  8315. }
  8316. };
  8317. module.exports = KeyboardShortcut;
  8318. },{}],38:[function(require,module,exports){
  8319. var email = '';
  8320. var displayName = '';
  8321. var userId;
  8322. var language = null;
  8323. function supportsLocalStorage() {
  8324. try {
  8325. return 'localStorage' in window && window.localStorage !== null;
  8326. } catch (e) {
  8327. console.log("localstorage is not supported");
  8328. return false;
  8329. }
  8330. }
  8331. function generateUniqueId() {
  8332. function _p8() {
  8333. return (Math.random().toString(16) + "000000000").substr(2, 8);
  8334. }
  8335. return _p8() + _p8() + _p8() + _p8();
  8336. }
  8337. if (supportsLocalStorage()) {
  8338. if (!window.localStorage.jitsiMeetId) {
  8339. window.localStorage.jitsiMeetId = generateUniqueId();
  8340. console.log("generated id", window.localStorage.jitsiMeetId);
  8341. }
  8342. userId = window.localStorage.jitsiMeetId || '';
  8343. email = window.localStorage.email || '';
  8344. displayName = window.localStorage.displayname || '';
  8345. language = window.localStorage.language;
  8346. } else {
  8347. console.log("local storage is not supported");
  8348. userId = generateUniqueId();
  8349. }
  8350. var Settings =
  8351. {
  8352. setDisplayName: function (newDisplayName) {
  8353. displayName = newDisplayName;
  8354. window.localStorage.displayname = displayName;
  8355. return displayName;
  8356. },
  8357. setEmail: function (newEmail)
  8358. {
  8359. email = newEmail;
  8360. window.localStorage.email = newEmail;
  8361. return email;
  8362. },
  8363. getSettings: function () {
  8364. return {
  8365. email: email,
  8366. displayName: displayName,
  8367. uid: userId,
  8368. language: language
  8369. };
  8370. },
  8371. setLanguage: function (lang) {
  8372. language = lang;
  8373. window.localStorage.language = lang;
  8374. }
  8375. };
  8376. module.exports = Settings;
  8377. },{}],39:[function(require,module,exports){
  8378. /**
  8379. *
  8380. * @constructor
  8381. */
  8382. function SimulcastLogger(name, lvl) {
  8383. this.name = name;
  8384. this.lvl = lvl;
  8385. }
  8386. SimulcastLogger.prototype.log = function (text) {
  8387. if (this.lvl) {
  8388. console.log(text);
  8389. }
  8390. };
  8391. SimulcastLogger.prototype.info = function (text) {
  8392. if (this.lvl > 1) {
  8393. console.info(text);
  8394. }
  8395. };
  8396. SimulcastLogger.prototype.fine = function (text) {
  8397. if (this.lvl > 2) {
  8398. console.log(text);
  8399. }
  8400. };
  8401. SimulcastLogger.prototype.error = function (text) {
  8402. console.error(text);
  8403. };
  8404. module.exports = SimulcastLogger;
  8405. },{}],40:[function(require,module,exports){
  8406. var SimulcastLogger = require("./SimulcastLogger");
  8407. var SimulcastUtils = require("./SimulcastUtils");
  8408. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  8409. function SimulcastReceiver() {
  8410. this.simulcastUtils = new SimulcastUtils();
  8411. this.logger = new SimulcastLogger('SimulcastReceiver', 1);
  8412. }
  8413. SimulcastReceiver.prototype._remoteVideoSourceCache = '';
  8414. SimulcastReceiver.prototype._remoteMaps = {
  8415. msid2Quality: {},
  8416. ssrc2Msid: {},
  8417. msid2ssrc: {},
  8418. receivingVideoStreams: {}
  8419. };
  8420. SimulcastReceiver.prototype._cacheRemoteVideoSources = function (lines) {
  8421. this._remoteVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  8422. };
  8423. SimulcastReceiver.prototype._restoreRemoteVideoSources = function (lines) {
  8424. this.simulcastUtils._replaceVideoSources(lines, this._remoteVideoSourceCache);
  8425. };
  8426. SimulcastReceiver.prototype._ensureGoogConference = function (lines) {
  8427. var sb;
  8428. this.logger.info('Ensuring x-google-conference flag...')
  8429. if (this.simulcastUtils._indexOfArray('a=x-google-flag:conference', lines) === this.simulcastUtils._emptyCompoundIndex) {
  8430. // TODO(gp) do that for the audio as well as suggested by fippo.
  8431. // Add the google conference flag
  8432. sb = this.simulcastUtils._getVideoSources(lines);
  8433. sb = ['a=x-google-flag:conference'].concat(sb);
  8434. this.simulcastUtils._replaceVideoSources(lines, sb);
  8435. }
  8436. };
  8437. SimulcastReceiver.prototype._restoreSimulcastGroups = function (sb) {
  8438. this._restoreRemoteVideoSources(sb);
  8439. };
  8440. /**
  8441. * Restores the simulcast groups of the remote description. In
  8442. * transformRemoteDescription we remove those in order for the set remote
  8443. * description to succeed. The focus needs the signal the groups to new
  8444. * participants.
  8445. *
  8446. * @param desc
  8447. * @returns {*}
  8448. */
  8449. SimulcastReceiver.prototype.reverseTransformRemoteDescription = function (desc) {
  8450. var sb;
  8451. if (!this.simulcastUtils.isValidDescription(desc)) {
  8452. return desc;
  8453. }
  8454. if (config.enableSimulcast) {
  8455. sb = desc.sdp.split('\r\n');
  8456. this._restoreSimulcastGroups(sb);
  8457. desc = new RTCSessionDescription({
  8458. type: desc.type,
  8459. sdp: sb.join('\r\n')
  8460. });
  8461. }
  8462. return desc;
  8463. };
  8464. SimulcastUtils.prototype._ensureOrder = function (lines) {
  8465. var videoSources, sb;
  8466. videoSources = this.parseMedia(lines, ['video'])[0];
  8467. sb = this._compileVideoSources(videoSources);
  8468. this._replaceVideoSources(lines, sb);
  8469. };
  8470. SimulcastReceiver.prototype._updateRemoteMaps = function (lines) {
  8471. var remoteVideoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0],
  8472. videoSource, quality;
  8473. // (re) initialize the remote maps.
  8474. this._remoteMaps.msid2Quality = {};
  8475. this._remoteMaps.ssrc2Msid = {};
  8476. this._remoteMaps.msid2ssrc = {};
  8477. var self = this;
  8478. if (remoteVideoSources.groups && remoteVideoSources.groups.length !== 0) {
  8479. remoteVideoSources.groups.forEach(function (group) {
  8480. if (group.semantics === 'SIM' && group.ssrcs && group.ssrcs.length !== 0) {
  8481. quality = 0;
  8482. group.ssrcs.forEach(function (ssrc) {
  8483. videoSource = remoteVideoSources.sources[ssrc];
  8484. self._remoteMaps.msid2Quality[videoSource.msid] = quality++;
  8485. self._remoteMaps.ssrc2Msid[videoSource.ssrc] = videoSource.msid;
  8486. self._remoteMaps.msid2ssrc[videoSource.msid] = videoSource.ssrc;
  8487. });
  8488. }
  8489. });
  8490. }
  8491. };
  8492. SimulcastReceiver.prototype._setReceivingVideoStream = function (resource, ssrc) {
  8493. this._remoteMaps.receivingVideoStreams[resource] = ssrc;
  8494. };
  8495. /**
  8496. * Returns a stream with single video track, the one currently being
  8497. * received by this endpoint.
  8498. *
  8499. * @param stream the remote simulcast stream.
  8500. * @returns {webkitMediaStream}
  8501. */
  8502. SimulcastReceiver.prototype.getReceivingVideoStream = function (stream) {
  8503. var tracks, i, electedTrack, msid, quality = 0, receivingTrackId;
  8504. var self = this;
  8505. if (config.enableSimulcast) {
  8506. stream.getVideoTracks().some(function (track) {
  8507. return Object.keys(self._remoteMaps.receivingVideoStreams).some(function (resource) {
  8508. var ssrc = self._remoteMaps.receivingVideoStreams[resource];
  8509. var msid = self._remoteMaps.ssrc2Msid[ssrc];
  8510. if (msid == [stream.id, track.id].join(' ')) {
  8511. electedTrack = track;
  8512. return true;
  8513. }
  8514. });
  8515. });
  8516. if (!electedTrack) {
  8517. // we don't have an elected track, choose by initial quality.
  8518. tracks = stream.getVideoTracks();
  8519. for (i = 0; i < tracks.length; i++) {
  8520. msid = [stream.id, tracks[i].id].join(' ');
  8521. if (this._remoteMaps.msid2Quality[msid] === quality) {
  8522. electedTrack = tracks[i];
  8523. break;
  8524. }
  8525. }
  8526. // TODO(gp) if the initialQuality could not be satisfied, lower
  8527. // the requirement and try again.
  8528. }
  8529. }
  8530. return (electedTrack)
  8531. ? new webkitMediaStream([electedTrack])
  8532. : stream;
  8533. };
  8534. SimulcastReceiver.prototype.getReceivingSSRC = function (jid) {
  8535. var resource = Strophe.getResourceFromJid(jid);
  8536. var ssrc = this._remoteMaps.receivingVideoStreams[resource];
  8537. // If we haven't receiving a "changed" event yet, then we must be receiving
  8538. // low quality (that the sender always streams).
  8539. if(!ssrc)
  8540. {
  8541. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  8542. var remoteStream = remoteStreamObject.getOriginalStream();
  8543. var tracks = remoteStream.getVideoTracks();
  8544. if (tracks) {
  8545. for (var k = 0; k < tracks.length; k++) {
  8546. var track = tracks[k];
  8547. var msid = [remoteStream.id, track.id].join(' ');
  8548. var _ssrc = this._remoteMaps.msid2ssrc[msid];
  8549. var quality = this._remoteMaps.msid2Quality[msid];
  8550. if (quality == 0) {
  8551. ssrc = _ssrc;
  8552. }
  8553. }
  8554. }
  8555. }
  8556. return ssrc;
  8557. };
  8558. SimulcastReceiver.prototype.getReceivingVideoStreamBySSRC = function (ssrc)
  8559. {
  8560. var sid, electedStream;
  8561. var i, j, k;
  8562. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  8563. if(jid && APP.RTC.remoteStreams[jid])
  8564. {
  8565. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  8566. var remoteStream = remoteStreamObject.getOriginalStream();
  8567. var tracks = remoteStream.getVideoTracks();
  8568. if (tracks) {
  8569. for (k = 0; k < tracks.length; k++) {
  8570. var track = tracks[k];
  8571. var msid = [remoteStream.id, track.id].join(' ');
  8572. var tmp = this._remoteMaps.msid2ssrc[msid];
  8573. if (tmp == ssrc) {
  8574. electedStream = new webkitMediaStream([track]);
  8575. sid = remoteStreamObject.sid;
  8576. // stream found, stop.
  8577. break;
  8578. }
  8579. }
  8580. }
  8581. }
  8582. else
  8583. {
  8584. console.debug(APP.RTC.remoteStreams, jid, ssrc);
  8585. }
  8586. return {
  8587. sid: sid,
  8588. stream: electedStream
  8589. };
  8590. };
  8591. /**
  8592. * Gets the fully qualified msid (stream.id + track.id) associated to the
  8593. * SSRC.
  8594. *
  8595. * @param ssrc
  8596. * @returns {*}
  8597. */
  8598. SimulcastReceiver.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  8599. return this._remoteMaps.ssrc2Msid[ssrc];
  8600. };
  8601. /**
  8602. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  8603. * either gets confused and thinks this is an FID group or, if an FID group
  8604. * is already present, it fails to set the remote description.
  8605. *
  8606. * @param desc
  8607. * @returns {*}
  8608. */
  8609. SimulcastReceiver.prototype.transformRemoteDescription = function (desc) {
  8610. if (desc && desc.sdp) {
  8611. var sb = desc.sdp.split('\r\n');
  8612. this._updateRemoteMaps(sb);
  8613. this._cacheRemoteVideoSources(sb);
  8614. // NOTE(gp) this needs to be called after updateRemoteMaps because we
  8615. // need the simulcast group in the _updateRemoteMaps() method.
  8616. this.simulcastUtils._removeSimulcastGroup(sb);
  8617. if (desc.sdp.indexOf('a=ssrc-group:SIM') !== -1) {
  8618. // We don't need the goog conference flag if we're not doing
  8619. // simulcast.
  8620. this._ensureGoogConference(sb);
  8621. }
  8622. desc = new RTCSessionDescription({
  8623. type: desc.type,
  8624. sdp: sb.join('\r\n')
  8625. });
  8626. this.logger.fine(['Transformed remote description', desc.sdp].join(' '));
  8627. }
  8628. return desc;
  8629. };
  8630. module.exports = SimulcastReceiver;
  8631. },{"../../service/RTC/MediaStreamTypes":87,"./SimulcastLogger":39,"./SimulcastUtils":42}],41:[function(require,module,exports){
  8632. var SimulcastLogger = require("./SimulcastLogger");
  8633. var SimulcastUtils = require("./SimulcastUtils");
  8634. function SimulcastSender() {
  8635. this.simulcastUtils = new SimulcastUtils();
  8636. this.logger = new SimulcastLogger('SimulcastSender', 1);
  8637. }
  8638. SimulcastSender.prototype.displayedLocalVideoStream = null;
  8639. SimulcastSender.prototype._generateGuid = (function () {
  8640. function s4() {
  8641. return Math.floor((1 + Math.random()) * 0x10000)
  8642. .toString(16)
  8643. .substring(1);
  8644. }
  8645. return function () {
  8646. return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
  8647. s4() + '-' + s4() + s4() + s4();
  8648. };
  8649. }());
  8650. // Returns a random integer between min (included) and max (excluded)
  8651. // Using Math.round() gives a non-uniform distribution!
  8652. SimulcastSender.prototype._generateRandomSSRC = function () {
  8653. var min = 0, max = 0xffffffff;
  8654. return Math.floor(Math.random() * (max - min)) + min;
  8655. };
  8656. SimulcastSender.prototype.getLocalVideoStream = function () {
  8657. return (this.displayedLocalVideoStream != null)
  8658. ? this.displayedLocalVideoStream
  8659. // in case we have no simulcast at all, i.e. we didn't perform the GUM
  8660. : APP.RTC.localVideo.getOriginalStream();
  8661. };
  8662. function NativeSimulcastSender() {
  8663. SimulcastSender.call(this); // call the super constructor.
  8664. }
  8665. NativeSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8666. NativeSimulcastSender.prototype._localExplosionMap = {};
  8667. NativeSimulcastSender.prototype._isUsingScreenStream = false;
  8668. NativeSimulcastSender.prototype._localVideoSourceCache = '';
  8669. NativeSimulcastSender.prototype.reset = function () {
  8670. this._localExplosionMap = {};
  8671. this._isUsingScreenStream = APP.desktopsharing.isUsingScreenStream();
  8672. };
  8673. NativeSimulcastSender.prototype._cacheLocalVideoSources = function (lines) {
  8674. this._localVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  8675. };
  8676. NativeSimulcastSender.prototype._restoreLocalVideoSources = function (lines) {
  8677. this.simulcastUtils._replaceVideoSources(lines, this._localVideoSourceCache);
  8678. };
  8679. NativeSimulcastSender.prototype._appendSimulcastGroup = function (lines) {
  8680. var videoSources, ssrcGroup, simSSRC, numOfSubs = 2, i, sb, msid;
  8681. this.logger.info('Appending simulcast group...');
  8682. // Get the primary SSRC information.
  8683. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8684. // Start building the SIM SSRC group.
  8685. ssrcGroup = ['a=ssrc-group:SIM'];
  8686. // The video source buffer.
  8687. sb = [];
  8688. // Create the simulcast sub-streams.
  8689. for (i = 0; i < numOfSubs; i++) {
  8690. // TODO(gp) prevent SSRC collision.
  8691. simSSRC = this._generateRandomSSRC();
  8692. ssrcGroup.push(simSSRC);
  8693. if (videoSources.base) {
  8694. sb.splice.apply(sb, [sb.length, 0].concat(
  8695. [["a=ssrc:", simSSRC, " cname:", videoSources.base.cname].join(''),
  8696. ["a=ssrc:", simSSRC, " msid:", videoSources.base.msid].join('')]
  8697. ));
  8698. }
  8699. this.logger.info(['Generated substream ', i, ' with SSRC ', simSSRC, '.'].join(''));
  8700. }
  8701. // Add the group sim layers.
  8702. sb.splice(0, 0, ssrcGroup.join(' '))
  8703. this.simulcastUtils._replaceVideoSources(lines, sb);
  8704. };
  8705. // Does the actual patching.
  8706. NativeSimulcastSender.prototype._ensureSimulcastGroup = function (lines) {
  8707. this.logger.info('Ensuring simulcast group...');
  8708. if (this.simulcastUtils._indexOfArray('a=ssrc-group:SIM', lines) === this.simulcastUtils._emptyCompoundIndex) {
  8709. this._appendSimulcastGroup(lines);
  8710. this._cacheLocalVideoSources(lines);
  8711. } else {
  8712. // verify that the ssrcs participating in the SIM group are present
  8713. // in the SDP (needed for presence).
  8714. this._restoreLocalVideoSources(lines);
  8715. }
  8716. };
  8717. /**
  8718. * Produces a single stream with multiple tracks for local video sources.
  8719. *
  8720. * @param lines
  8721. * @private
  8722. */
  8723. NativeSimulcastSender.prototype._explodeSimulcastSenderSources = function (lines) {
  8724. var sb, msid, sid, tid, videoSources, self;
  8725. this.logger.info('Exploding local video sources...');
  8726. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8727. self = this;
  8728. if (videoSources.groups && videoSources.groups.length !== 0) {
  8729. videoSources.groups.forEach(function (group) {
  8730. if (group.semantics === 'SIM') {
  8731. group.ssrcs.forEach(function (ssrc) {
  8732. // Get the msid for this ssrc..
  8733. if (self._localExplosionMap[ssrc]) {
  8734. // .. either from the explosion map..
  8735. msid = self._localExplosionMap[ssrc];
  8736. } else {
  8737. // .. or generate a new one (msid).
  8738. sid = videoSources.sources[ssrc].msid
  8739. .substring(0, videoSources.sources[ssrc].msid.indexOf(' '));
  8740. tid = self._generateGuid();
  8741. msid = [sid, tid].join(' ');
  8742. self._localExplosionMap[ssrc] = msid;
  8743. }
  8744. // Assign it to the source object.
  8745. videoSources.sources[ssrc].msid = msid;
  8746. // TODO(gp) Change the msid of associated sources.
  8747. });
  8748. }
  8749. });
  8750. }
  8751. sb = this.simulcastUtils._compileVideoSources(videoSources);
  8752. this.simulcastUtils._replaceVideoSources(lines, sb);
  8753. };
  8754. /**
  8755. * GUM for simulcast.
  8756. *
  8757. * @param constraints
  8758. * @param success
  8759. * @param err
  8760. */
  8761. NativeSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8762. // There's nothing special to do for native simulcast, so just do a normal GUM.
  8763. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8764. success(hqStream);
  8765. }, err);
  8766. };
  8767. /**
  8768. * Prepares the local description for public usage (i.e. to be signaled
  8769. * through Jingle to the focus).
  8770. *
  8771. * @param desc
  8772. * @returns {RTCSessionDescription}
  8773. */
  8774. NativeSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8775. var sb;
  8776. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  8777. return desc;
  8778. }
  8779. sb = desc.sdp.split('\r\n');
  8780. this._explodeSimulcastSenderSources(sb);
  8781. desc = new RTCSessionDescription({
  8782. type: desc.type,
  8783. sdp: sb.join('\r\n')
  8784. });
  8785. this.logger.fine(['Exploded local video sources', desc.sdp].join(' '));
  8786. return desc;
  8787. };
  8788. /**
  8789. * Ensures that the simulcast group is present in the answer, _if_ native
  8790. * simulcast is enabled,
  8791. *
  8792. * @param desc
  8793. * @returns {*}
  8794. */
  8795. NativeSimulcastSender.prototype.transformAnswer = function (desc) {
  8796. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  8797. return desc;
  8798. }
  8799. var sb = desc.sdp.split('\r\n');
  8800. // Even if we have enabled native simulcasting previously
  8801. // (with a call to SLD with an appropriate SDP, for example),
  8802. // createAnswer seems to consistently generate incomplete SDP
  8803. // with missing SSRCS.
  8804. //
  8805. // So, subsequent calls to SLD will have missing SSRCS and presence
  8806. // won't have the complete list of SRCs.
  8807. this._ensureSimulcastGroup(sb);
  8808. desc = new RTCSessionDescription({
  8809. type: desc.type,
  8810. sdp: sb.join('\r\n')
  8811. });
  8812. this.logger.fine(['Transformed answer', desc.sdp].join(' '));
  8813. return desc;
  8814. };
  8815. /**
  8816. *
  8817. *
  8818. * @param desc
  8819. * @returns {*}
  8820. */
  8821. NativeSimulcastSender.prototype.transformLocalDescription = function (desc) {
  8822. return desc;
  8823. };
  8824. NativeSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  8825. // Nothing to do here, native simulcast does that auto-magically.
  8826. };
  8827. NativeSimulcastSender.prototype.constructor = NativeSimulcastSender;
  8828. function SimpleSimulcastSender() {
  8829. SimulcastSender.call(this);
  8830. }
  8831. SimpleSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8832. SimpleSimulcastSender.prototype.localStream = null;
  8833. SimpleSimulcastSender.prototype._localMaps = {
  8834. msids: [],
  8835. msid2ssrc: {}
  8836. };
  8837. /**
  8838. * Groups local video sources together in the ssrc-group:SIM group.
  8839. *
  8840. * @param lines
  8841. * @private
  8842. */
  8843. SimpleSimulcastSender.prototype._groupLocalVideoSources = function (lines) {
  8844. var sb, videoSources, ssrcs = [], ssrc;
  8845. this.logger.info('Grouping local video sources...');
  8846. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8847. for (ssrc in videoSources.sources) {
  8848. // jitsi-meet destroys/creates streams at various places causing
  8849. // the original local stream ids to change. The only thing that
  8850. // remains unchanged is the trackid.
  8851. this._localMaps.msid2ssrc[videoSources.sources[ssrc].msid.split(' ')[1]] = ssrc;
  8852. }
  8853. var self = this;
  8854. // TODO(gp) add only "free" sources.
  8855. this._localMaps.msids.forEach(function (msid) {
  8856. ssrcs.push(self._localMaps.msid2ssrc[msid]);
  8857. });
  8858. if (!videoSources.groups) {
  8859. videoSources.groups = [];
  8860. }
  8861. videoSources.groups.push({
  8862. 'semantics': 'SIM',
  8863. 'ssrcs': ssrcs
  8864. });
  8865. sb = this.simulcastUtils._compileVideoSources(videoSources);
  8866. this.simulcastUtils._replaceVideoSources(lines, sb);
  8867. };
  8868. /**
  8869. * GUM for simulcast.
  8870. *
  8871. * @param constraints
  8872. * @param success
  8873. * @param err
  8874. */
  8875. SimpleSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8876. // TODO(gp) what if we request a resolution not supported by the hardware?
  8877. // TODO(gp) make the lq stream configurable; although this wouldn't work with native simulcast
  8878. var lqConstraints = {
  8879. audio: false,
  8880. video: {
  8881. mandatory: {
  8882. maxWidth: 320,
  8883. maxHeight: 180,
  8884. maxFrameRate: 15
  8885. }
  8886. }
  8887. };
  8888. this.logger.info('HQ constraints: ', constraints);
  8889. this.logger.info('LQ constraints: ', lqConstraints);
  8890. // NOTE(gp) if we request the lq stream first webkitGetUserMedia
  8891. // fails randomly. Tested with Chrome 37. As fippo suggested, the
  8892. // reason appears to be that Chrome only acquires the cam once and
  8893. // then downscales the picture (https://code.google.com/p/chromium/issues/detail?id=346616#c11)
  8894. var self = this;
  8895. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8896. self.localStream = hqStream;
  8897. // reset local maps.
  8898. self._localMaps.msids = [];
  8899. self._localMaps.msid2ssrc = {};
  8900. // add hq trackid to local map
  8901. self._localMaps.msids.push(hqStream.getVideoTracks()[0].id);
  8902. navigator.webkitGetUserMedia(lqConstraints, function (lqStream) {
  8903. self.displayedLocalVideoStream = lqStream;
  8904. // NOTE(gp) The specification says Array.forEach() will visit
  8905. // the array elements in numeric order, and that it doesn't
  8906. // visit elements that don't exist.
  8907. // add lq trackid to local map
  8908. self._localMaps.msids.splice(0, 0, lqStream.getVideoTracks()[0].id);
  8909. self.localStream.addTrack(lqStream.getVideoTracks()[0]);
  8910. success(self.localStream);
  8911. }, err);
  8912. }, err);
  8913. };
  8914. /**
  8915. * Prepares the local description for public usage (i.e. to be signaled
  8916. * through Jingle to the focus).
  8917. *
  8918. * @param desc
  8919. * @returns {RTCSessionDescription}
  8920. */
  8921. SimpleSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8922. var sb;
  8923. if (!this.simulcastUtils.isValidDescription(desc)) {
  8924. return desc;
  8925. }
  8926. sb = desc.sdp.split('\r\n');
  8927. this._groupLocalVideoSources(sb);
  8928. desc = new RTCSessionDescription({
  8929. type: desc.type,
  8930. sdp: sb.join('\r\n')
  8931. });
  8932. this.logger.fine('Grouped local video sources');
  8933. this.logger.fine(desc.sdp);
  8934. return desc;
  8935. };
  8936. /**
  8937. * Ensures that the simulcast group is present in the answer, _if_ native
  8938. * simulcast is enabled,
  8939. *
  8940. * @param desc
  8941. * @returns {*}
  8942. */
  8943. SimpleSimulcastSender.prototype.transformAnswer = function (desc) {
  8944. return desc;
  8945. };
  8946. /**
  8947. *
  8948. *
  8949. * @param desc
  8950. * @returns {*}
  8951. */
  8952. SimpleSimulcastSender.prototype.transformLocalDescription = function (desc) {
  8953. var sb = desc.sdp.split('\r\n');
  8954. this.simulcastUtils._removeSimulcastGroup(sb);
  8955. desc = new RTCSessionDescription({
  8956. type: desc.type,
  8957. sdp: sb.join('\r\n')
  8958. });
  8959. this.logger.fine('Transformed local description');
  8960. this.logger.fine(desc.sdp);
  8961. return desc;
  8962. };
  8963. SimpleSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  8964. var trackid;
  8965. var self = this;
  8966. this.logger.log(['Requested to', enabled ? 'enable' : 'disable', ssrc].join(' '));
  8967. if (Object.keys(this._localMaps.msid2ssrc).some(function (tid) {
  8968. // Search for the track id that corresponds to the ssrc
  8969. if (self._localMaps.msid2ssrc[tid] == ssrc) {
  8970. trackid = tid;
  8971. return true;
  8972. }
  8973. }) && self.localStream.getVideoTracks().some(function (track) {
  8974. // Start/stop the track that corresponds to the track id
  8975. if (track.id === trackid) {
  8976. track.enabled = enabled;
  8977. return true;
  8978. }
  8979. })) {
  8980. this.logger.log([trackid, enabled ? 'enabled' : 'disabled'].join(' '));
  8981. $(document).trigger(enabled
  8982. ? 'simulcastlayerstarted'
  8983. : 'simulcastlayerstopped');
  8984. } else {
  8985. this.logger.error("I don't have a local stream with SSRC " + ssrc);
  8986. }
  8987. };
  8988. SimpleSimulcastSender.prototype.constructor = SimpleSimulcastSender;
  8989. function NoSimulcastSender() {
  8990. SimulcastSender.call(this);
  8991. }
  8992. NoSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8993. /**
  8994. * GUM for simulcast.
  8995. *
  8996. * @param constraints
  8997. * @param success
  8998. * @param err
  8999. */
  9000. NoSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  9001. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  9002. success(hqStream);
  9003. }, err);
  9004. };
  9005. /**
  9006. * Prepares the local description for public usage (i.e. to be signaled
  9007. * through Jingle to the focus).
  9008. *
  9009. * @param desc
  9010. * @returns {RTCSessionDescription}
  9011. */
  9012. NoSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  9013. return desc;
  9014. };
  9015. /**
  9016. * Ensures that the simulcast group is present in the answer, _if_ native
  9017. * simulcast is enabled,
  9018. *
  9019. * @param desc
  9020. * @returns {*}
  9021. */
  9022. NoSimulcastSender.prototype.transformAnswer = function (desc) {
  9023. return desc;
  9024. };
  9025. /**
  9026. *
  9027. *
  9028. * @param desc
  9029. * @returns {*}
  9030. */
  9031. NoSimulcastSender.prototype.transformLocalDescription = function (desc) {
  9032. return desc;
  9033. };
  9034. NoSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  9035. };
  9036. NoSimulcastSender.prototype.constructor = NoSimulcastSender;
  9037. module.exports = {
  9038. "native": NativeSimulcastSender,
  9039. "no": NoSimulcastSender
  9040. }
  9041. },{"./SimulcastLogger":39,"./SimulcastUtils":42}],42:[function(require,module,exports){
  9042. var SimulcastLogger = require("./SimulcastLogger");
  9043. /**
  9044. *
  9045. * @constructor
  9046. */
  9047. function SimulcastUtils() {
  9048. this.logger = new SimulcastLogger("SimulcastUtils", 1);
  9049. }
  9050. /**
  9051. *
  9052. * @type {{}}
  9053. * @private
  9054. */
  9055. SimulcastUtils.prototype._emptyCompoundIndex = {};
  9056. /**
  9057. *
  9058. * @param lines
  9059. * @param videoSources
  9060. * @private
  9061. */
  9062. SimulcastUtils.prototype._replaceVideoSources = function (lines, videoSources) {
  9063. var i, inVideo = false, index = -1, howMany = 0;
  9064. this.logger.info('Replacing video sources...');
  9065. for (i = 0; i < lines.length; i++) {
  9066. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  9067. // Out of video.
  9068. break;
  9069. }
  9070. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  9071. // In video.
  9072. inVideo = true;
  9073. }
  9074. if (inVideo && (lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:'
  9075. || lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:')) {
  9076. if (index === -1) {
  9077. index = i;
  9078. }
  9079. howMany++;
  9080. }
  9081. }
  9082. // efficiency baby ;)
  9083. lines.splice.apply(lines,
  9084. [index, howMany].concat(videoSources));
  9085. };
  9086. SimulcastUtils.prototype.isValidDescription = function (desc)
  9087. {
  9088. return desc && desc != null
  9089. && desc.type && desc.type != ''
  9090. && desc.sdp && desc.sdp != '';
  9091. };
  9092. SimulcastUtils.prototype._getVideoSources = function (lines) {
  9093. var i, inVideo = false, sb = [];
  9094. this.logger.info('Getting video sources...');
  9095. for (i = 0; i < lines.length; i++) {
  9096. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  9097. // Out of video.
  9098. break;
  9099. }
  9100. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  9101. // In video.
  9102. inVideo = true;
  9103. }
  9104. if (inVideo && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  9105. // In SSRC.
  9106. sb.push(lines[i]);
  9107. }
  9108. if (inVideo && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  9109. sb.push(lines[i]);
  9110. }
  9111. }
  9112. return sb;
  9113. };
  9114. SimulcastUtils.prototype.parseMedia = function (lines, mediatypes) {
  9115. var i, res = [], type, cur_media, idx, ssrcs, cur_ssrc, ssrc,
  9116. ssrc_attribute, group, semantics, skip = true;
  9117. this.logger.info('Parsing media sources...');
  9118. for (i = 0; i < lines.length; i++) {
  9119. if (lines[i].substring(0, 'm='.length) === 'm=') {
  9120. type = lines[i]
  9121. .substr('m='.length, lines[i].indexOf(' ') - 'm='.length);
  9122. skip = mediatypes !== undefined && mediatypes.indexOf(type) === -1;
  9123. if (!skip) {
  9124. cur_media = {
  9125. 'type': type,
  9126. 'sources': {},
  9127. 'groups': []
  9128. };
  9129. res.push(cur_media);
  9130. }
  9131. } else if (!skip && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  9132. idx = lines[i].indexOf(' ');
  9133. ssrc = lines[i].substring('a=ssrc:'.length, idx);
  9134. if (cur_media.sources[ssrc] === undefined) {
  9135. cur_ssrc = {'ssrc': ssrc};
  9136. cur_media.sources[ssrc] = cur_ssrc;
  9137. }
  9138. ssrc_attribute = lines[i].substr(idx + 1).split(':', 2)[0];
  9139. cur_ssrc[ssrc_attribute] = lines[i].substr(idx + 1).split(':', 2)[1];
  9140. if (cur_media.base === undefined) {
  9141. cur_media.base = cur_ssrc;
  9142. }
  9143. } else if (!skip && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  9144. idx = lines[i].indexOf(' ');
  9145. semantics = lines[i].substr(0, idx).substr('a=ssrc-group:'.length);
  9146. ssrcs = lines[i].substr(idx).trim().split(' ');
  9147. group = {
  9148. 'semantics': semantics,
  9149. 'ssrcs': ssrcs
  9150. };
  9151. cur_media.groups.push(group);
  9152. } else if (!skip && (lines[i].substring(0, 'a=sendrecv'.length) === 'a=sendrecv' ||
  9153. lines[i].substring(0, 'a=recvonly'.length) === 'a=recvonly' ||
  9154. lines[i].substring(0, 'a=sendonly'.length) === 'a=sendonly' ||
  9155. lines[i].substring(0, 'a=inactive'.length) === 'a=inactive')) {
  9156. cur_media.direction = lines[i].substring('a='.length);
  9157. }
  9158. }
  9159. return res;
  9160. };
  9161. /**
  9162. * The _indexOfArray() method returns the first a CompoundIndex at which a
  9163. * given element can be found in the array, or _emptyCompoundIndex if it is
  9164. * not present.
  9165. *
  9166. * Example:
  9167. *
  9168. * _indexOfArray('3', [ 'this is line 1', 'this is line 2', 'this is line 3' ])
  9169. *
  9170. * returns {row: 2, column: 14}
  9171. *
  9172. * @param needle
  9173. * @param haystack
  9174. * @param start
  9175. * @returns {}
  9176. * @private
  9177. */
  9178. SimulcastUtils.prototype._indexOfArray = function (needle, haystack, start) {
  9179. var length = haystack.length, idx, i;
  9180. if (!start) {
  9181. start = 0;
  9182. }
  9183. for (i = start; i < length; i++) {
  9184. idx = haystack[i].indexOf(needle);
  9185. if (idx !== -1) {
  9186. return {row: i, column: idx};
  9187. }
  9188. }
  9189. return this._emptyCompoundIndex;
  9190. };
  9191. SimulcastUtils.prototype._removeSimulcastGroup = function (lines) {
  9192. var i;
  9193. for (i = lines.length - 1; i >= 0; i--) {
  9194. if (lines[i].indexOf('a=ssrc-group:SIM') !== -1) {
  9195. lines.splice(i, 1);
  9196. }
  9197. }
  9198. };
  9199. SimulcastUtils.prototype._compileVideoSources = function (videoSources) {
  9200. var sb = [], ssrc, addedSSRCs = [];
  9201. this.logger.info('Compiling video sources...');
  9202. // Add the groups
  9203. if (videoSources.groups && videoSources.groups.length !== 0) {
  9204. videoSources.groups.forEach(function (group) {
  9205. if (group.ssrcs && group.ssrcs.length !== 0) {
  9206. sb.push([['a=ssrc-group:', group.semantics].join(''), group.ssrcs.join(' ')].join(' '));
  9207. // if (group.semantics !== 'SIM') {
  9208. group.ssrcs.forEach(function (ssrc) {
  9209. addedSSRCs.push(ssrc);
  9210. sb.splice.apply(sb, [sb.length, 0].concat([
  9211. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  9212. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  9213. });
  9214. //}
  9215. }
  9216. });
  9217. }
  9218. // Then add any free sources.
  9219. if (videoSources.sources) {
  9220. for (ssrc in videoSources.sources) {
  9221. if (addedSSRCs.indexOf(ssrc) === -1) {
  9222. sb.splice.apply(sb, [sb.length, 0].concat([
  9223. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  9224. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  9225. }
  9226. }
  9227. }
  9228. return sb;
  9229. };
  9230. module.exports = SimulcastUtils;
  9231. },{"./SimulcastLogger":39}],43:[function(require,module,exports){
  9232. /*jslint plusplus: true */
  9233. /*jslint nomen: true*/
  9234. var SimulcastSender = require("./SimulcastSender");
  9235. var NoSimulcastSender = SimulcastSender["no"];
  9236. var NativeSimulcastSender = SimulcastSender["native"];
  9237. var SimulcastReceiver = require("./SimulcastReceiver");
  9238. var SimulcastUtils = require("./SimulcastUtils");
  9239. var RTCEvents = require("../../service/RTC/RTCEvents");
  9240. /**
  9241. *
  9242. * @constructor
  9243. */
  9244. function SimulcastManager() {
  9245. // Create the simulcast utilities.
  9246. this.simulcastUtils = new SimulcastUtils();
  9247. // Create remote simulcast.
  9248. this.simulcastReceiver = new SimulcastReceiver();
  9249. // Initialize local simulcast.
  9250. // TODO(gp) move into SimulcastManager.prototype.getUserMedia and take into
  9251. // account constraints.
  9252. if (!config.enableSimulcast) {
  9253. this.simulcastSender = new NoSimulcastSender();
  9254. } else {
  9255. var isChromium = window.chrome,
  9256. vendorName = window.navigator.vendor;
  9257. if(isChromium !== null && isChromium !== undefined
  9258. /* skip opera */
  9259. && vendorName === "Google Inc."
  9260. /* skip Chromium as suggested by fippo */
  9261. && !window.navigator.appVersion.match(/Chromium\//) ) {
  9262. var ver = parseInt(window.navigator.appVersion.match(/Chrome\/(\d+)\./)[1], 10);
  9263. if (ver > 37) {
  9264. this.simulcastSender = new NativeSimulcastSender();
  9265. } else {
  9266. this.simulcastSender = new NoSimulcastSender();
  9267. }
  9268. } else {
  9269. this.simulcastSender = new NoSimulcastSender();
  9270. }
  9271. }
  9272. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  9273. function (endpointSimulcastLayers) {
  9274. endpointSimulcastLayers.forEach(function (esl) {
  9275. var ssrc = esl.simulcastLayer.primarySSRC;
  9276. simulcast._setReceivingVideoStream(esl.endpoint, ssrc);
  9277. });
  9278. });
  9279. APP.RTC.addListener(RTCEvents.SIMULCAST_START, function (simulcastLayer) {
  9280. var ssrc = simulcastLayer.primarySSRC;
  9281. simulcast._setLocalVideoStreamEnabled(ssrc, true);
  9282. });
  9283. APP.RTC.addListener(RTCEvents.SIMULCAST_STOP, function (simulcastLayer) {
  9284. var ssrc = simulcastLayer.primarySSRC;
  9285. simulcast._setLocalVideoStreamEnabled(ssrc, false);
  9286. });
  9287. }
  9288. /**
  9289. * Restores the simulcast groups of the remote description. In
  9290. * transformRemoteDescription we remove those in order for the set remote
  9291. * description to succeed. The focus needs the signal the groups to new
  9292. * participants.
  9293. *
  9294. * @param desc
  9295. * @returns {*}
  9296. */
  9297. SimulcastManager.prototype.reverseTransformRemoteDescription = function (desc) {
  9298. return this.simulcastReceiver.reverseTransformRemoteDescription(desc);
  9299. };
  9300. /**
  9301. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  9302. * either gets confused and thinks this is an FID group or, if an FID group
  9303. * is already present, it fails to set the remote description.
  9304. *
  9305. * @param desc
  9306. * @returns {*}
  9307. */
  9308. SimulcastManager.prototype.transformRemoteDescription = function (desc) {
  9309. return this.simulcastReceiver.transformRemoteDescription(desc);
  9310. };
  9311. /**
  9312. * Gets the fully qualified msid (stream.id + track.id) associated to the
  9313. * SSRC.
  9314. *
  9315. * @param ssrc
  9316. * @returns {*}
  9317. */
  9318. SimulcastManager.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  9319. return this.simulcastReceiver.getRemoteVideoStreamIdBySSRC(ssrc);
  9320. };
  9321. /**
  9322. * Returns a stream with single video track, the one currently being
  9323. * received by this endpoint.
  9324. *
  9325. * @param stream the remote simulcast stream.
  9326. * @returns {webkitMediaStream}
  9327. */
  9328. SimulcastManager.prototype.getReceivingVideoStream = function (stream) {
  9329. return this.simulcastReceiver.getReceivingVideoStream(stream);
  9330. };
  9331. /**
  9332. *
  9333. *
  9334. * @param desc
  9335. * @returns {*}
  9336. */
  9337. SimulcastManager.prototype.transformLocalDescription = function (desc) {
  9338. return this.simulcastSender.transformLocalDescription(desc);
  9339. };
  9340. /**
  9341. *
  9342. * @returns {*}
  9343. */
  9344. SimulcastManager.prototype.getLocalVideoStream = function() {
  9345. return this.simulcastSender.getLocalVideoStream();
  9346. };
  9347. /**
  9348. * GUM for simulcast.
  9349. *
  9350. * @param constraints
  9351. * @param success
  9352. * @param err
  9353. */
  9354. SimulcastManager.prototype.getUserMedia = function (constraints, success, err) {
  9355. this.simulcastSender.getUserMedia(constraints, success, err);
  9356. };
  9357. /**
  9358. * Prepares the local description for public usage (i.e. to be signaled
  9359. * through Jingle to the focus).
  9360. *
  9361. * @param desc
  9362. * @returns {RTCSessionDescription}
  9363. */
  9364. SimulcastManager.prototype.reverseTransformLocalDescription = function (desc) {
  9365. return this.simulcastSender.reverseTransformLocalDescription(desc);
  9366. };
  9367. /**
  9368. * Ensures that the simulcast group is present in the answer, _if_ native
  9369. * simulcast is enabled,
  9370. *
  9371. * @param desc
  9372. * @returns {*}
  9373. */
  9374. SimulcastManager.prototype.transformAnswer = function (desc) {
  9375. return this.simulcastSender.transformAnswer(desc);
  9376. };
  9377. SimulcastManager.prototype.getReceivingSSRC = function (jid) {
  9378. return this.simulcastReceiver.getReceivingSSRC(jid);
  9379. };
  9380. SimulcastManager.prototype.getReceivingVideoStreamBySSRC = function (msid) {
  9381. return this.simulcastReceiver.getReceivingVideoStreamBySSRC(msid);
  9382. };
  9383. /**
  9384. *
  9385. * @param lines
  9386. * @param mediatypes
  9387. * @returns {*}
  9388. */
  9389. SimulcastManager.prototype.parseMedia = function(lines, mediatypes) {
  9390. var sb = lines.sdp.split('\r\n');
  9391. return this.simulcastUtils.parseMedia(sb, mediatypes);
  9392. };
  9393. SimulcastManager.prototype._setReceivingVideoStream = function(resource, ssrc) {
  9394. this.simulcastReceiver._setReceivingVideoStream(resource, ssrc);
  9395. };
  9396. SimulcastManager.prototype._setLocalVideoStreamEnabled = function(ssrc, enabled) {
  9397. this.simulcastSender._setLocalVideoStreamEnabled(ssrc, enabled);
  9398. };
  9399. SimulcastManager.prototype.resetSender = function() {
  9400. if (typeof this.simulcastSender.reset === 'function'){
  9401. this.simulcastSender.reset();
  9402. }
  9403. };
  9404. var simulcast = new SimulcastManager();
  9405. module.exports = simulcast;
  9406. },{"../../service/RTC/RTCEvents":89,"./SimulcastReceiver":40,"./SimulcastSender":41,"./SimulcastUtils":42}],44:[function(require,module,exports){
  9407. /**
  9408. * Provides statistics for the local stream.
  9409. */
  9410. /**
  9411. * Size of the webaudio analizer buffer.
  9412. * @type {number}
  9413. */
  9414. var WEBAUDIO_ANALIZER_FFT_SIZE = 2048;
  9415. /**
  9416. * Value of the webaudio analizer smoothing time parameter.
  9417. * @type {number}
  9418. */
  9419. var WEBAUDIO_ANALIZER_SMOOTING_TIME = 0.8;
  9420. /**
  9421. * Converts time domain data array to audio level.
  9422. * @param array the time domain data array.
  9423. * @returns {number} the audio level
  9424. */
  9425. function timeDomainDataToAudioLevel(samples) {
  9426. var maxVolume = 0;
  9427. var length = samples.length;
  9428. for (var i = 0; i < length; i++) {
  9429. if (maxVolume < samples[i])
  9430. maxVolume = samples[i];
  9431. }
  9432. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  9433. };
  9434. /**
  9435. * Animates audio level change
  9436. * @param newLevel the new audio level
  9437. * @param lastLevel the last audio level
  9438. * @returns {Number} the audio level to be set
  9439. */
  9440. function animateLevel(newLevel, lastLevel)
  9441. {
  9442. var value = 0;
  9443. var diff = lastLevel - newLevel;
  9444. if(diff > 0.2)
  9445. {
  9446. value = lastLevel - 0.2;
  9447. }
  9448. else if(diff < -0.4)
  9449. {
  9450. value = lastLevel + 0.4;
  9451. }
  9452. else
  9453. {
  9454. value = newLevel;
  9455. }
  9456. return parseFloat(value.toFixed(3));
  9457. }
  9458. /**
  9459. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  9460. *
  9461. * @param stream the local stream
  9462. * @param interval stats refresh interval given in ms.
  9463. * @param {function(LocalStatsCollector)} updateCallback the callback called on stats
  9464. * update.
  9465. * @constructor
  9466. */
  9467. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  9468. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  9469. this.stream = stream;
  9470. this.intervalId = null;
  9471. this.intervalMilis = interval;
  9472. this.eventEmitter = eventEmitter;
  9473. this.audioLevel = 0;
  9474. this.statisticsService = statisticsService;
  9475. }
  9476. /**
  9477. * Starts the collecting the statistics.
  9478. */
  9479. LocalStatsCollector.prototype.start = function () {
  9480. if (config.disableAudioLevels || !window.AudioContext)
  9481. return;
  9482. var context = new AudioContext();
  9483. var analyser = context.createAnalyser();
  9484. analyser.smoothingTimeConstant = WEBAUDIO_ANALIZER_SMOOTING_TIME;
  9485. analyser.fftSize = WEBAUDIO_ANALIZER_FFT_SIZE;
  9486. var source = context.createMediaStreamSource(this.stream);
  9487. source.connect(analyser);
  9488. var self = this;
  9489. this.intervalId = setInterval(
  9490. function () {
  9491. var array = new Uint8Array(analyser.frequencyBinCount);
  9492. analyser.getByteTimeDomainData(array);
  9493. var audioLevel = timeDomainDataToAudioLevel(array);
  9494. if(audioLevel != self.audioLevel) {
  9495. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  9496. self.eventEmitter.emit(
  9497. "statistics.audioLevel",
  9498. self.statisticsService.LOCAL_JID,
  9499. self.audioLevel);
  9500. }
  9501. },
  9502. this.intervalMilis
  9503. );
  9504. };
  9505. /**
  9506. * Stops collecting the statistics.
  9507. */
  9508. LocalStatsCollector.prototype.stop = function () {
  9509. if (this.intervalId) {
  9510. clearInterval(this.intervalId);
  9511. this.intervalId = null;
  9512. }
  9513. };
  9514. module.exports = LocalStatsCollector;
  9515. },{}],45:[function(require,module,exports){
  9516. /* global ssrc2jid */
  9517. /* jshint -W117 */
  9518. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  9519. /**
  9520. * Calculates packet lost percent using the number of lost packets and the
  9521. * number of all packet.
  9522. * @param lostPackets the number of lost packets
  9523. * @param totalPackets the number of all packets.
  9524. * @returns {number} packet loss percent
  9525. */
  9526. function calculatePacketLoss(lostPackets, totalPackets) {
  9527. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  9528. return 0;
  9529. return Math.round((lostPackets/totalPackets)*100);
  9530. }
  9531. function getStatValue(item, name) {
  9532. if(!keyMap[APP.RTC.getBrowserType()][name])
  9533. throw "The property isn't supported!";
  9534. var key = keyMap[APP.RTC.getBrowserType()][name];
  9535. return APP.RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_CHROME? item.stat(key) : item[key];
  9536. }
  9537. /**
  9538. * Peer statistics data holder.
  9539. * @constructor
  9540. */
  9541. function PeerStats()
  9542. {
  9543. this.ssrc2Loss = {};
  9544. this.ssrc2AudioLevel = {};
  9545. this.ssrc2bitrate = {};
  9546. this.ssrc2resolution = {};
  9547. }
  9548. /**
  9549. * The bandwidth
  9550. * @type {{}}
  9551. */
  9552. PeerStats.bandwidth = {};
  9553. /**
  9554. * The bit rate
  9555. * @type {{}}
  9556. */
  9557. PeerStats.bitrate = {};
  9558. /**
  9559. * The packet loss rate
  9560. * @type {{}}
  9561. */
  9562. PeerStats.packetLoss = null;
  9563. /**
  9564. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  9565. * represented by this instance.
  9566. * @param ssrc audio or video RTP stream SSRC.
  9567. * @param lossRate new packet loss rate value to be set.
  9568. */
  9569. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  9570. {
  9571. this.ssrc2Loss[ssrc] = lossRate;
  9572. };
  9573. /**
  9574. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  9575. * represented by this instance.
  9576. * @param ssrc audio or video RTP stream SSRC.
  9577. * @param resolution new resolution value to be set.
  9578. */
  9579. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  9580. {
  9581. if(resolution === null && this.ssrc2resolution[ssrc])
  9582. {
  9583. delete this.ssrc2resolution[ssrc];
  9584. }
  9585. else if(resolution !== null)
  9586. this.ssrc2resolution[ssrc] = resolution;
  9587. };
  9588. /**
  9589. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  9590. * represented by this instance.
  9591. * @param ssrc audio or video RTP stream SSRC.
  9592. * @param bitrate new bitrate value to be set.
  9593. */
  9594. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  9595. {
  9596. if(this.ssrc2bitrate[ssrc])
  9597. {
  9598. this.ssrc2bitrate[ssrc].download += bitrate.download;
  9599. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  9600. }
  9601. else {
  9602. this.ssrc2bitrate[ssrc] = bitrate;
  9603. }
  9604. };
  9605. /**
  9606. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  9607. * the stream which belongs to the peer represented by this instance.
  9608. * @param ssrc RTP stream SSRC for which current audio level value will be
  9609. * updated.
  9610. * @param audioLevel the new audio level value to be set. Value is truncated to
  9611. * fit the range from 0 to 1.
  9612. */
  9613. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  9614. {
  9615. // Range limit 0 - 1
  9616. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  9617. };
  9618. function formatAudioLevel(audioLevel) {
  9619. return Math.min(Math.max(audioLevel, 0), 1);
  9620. }
  9621. /**
  9622. * Array with the transport information.
  9623. * @type {Array}
  9624. */
  9625. PeerStats.transport = [];
  9626. /**
  9627. * <tt>StatsCollector</tt> registers for stats updates of given
  9628. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  9629. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  9630. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  9631. * instance as an event source.
  9632. *
  9633. * @param peerconnection webRTC peer connection object.
  9634. * @param interval stats refresh interval given in ms.
  9635. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  9636. * called on stats update.
  9637. * @constructor
  9638. */
  9639. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  9640. {
  9641. this.peerconnection = peerconnection;
  9642. this.baselineAudioLevelsReport = null;
  9643. this.currentAudioLevelsReport = null;
  9644. this.currentStatsReport = null;
  9645. this.baselineStatsReport = null;
  9646. this.audioLevelsIntervalId = null;
  9647. this.eventEmitter = eventEmitter;
  9648. /**
  9649. * Gather PeerConnection stats once every this many milliseconds.
  9650. */
  9651. this.GATHER_INTERVAL = 15000;
  9652. /**
  9653. * Log stats via the focus once every this many milliseconds.
  9654. */
  9655. this.LOG_INTERVAL = 60000;
  9656. /**
  9657. * Gather stats and store them in this.statsToBeLogged.
  9658. */
  9659. this.gatherStatsIntervalId = null;
  9660. /**
  9661. * Send the stats already saved in this.statsToBeLogged to be logged via
  9662. * the focus.
  9663. */
  9664. this.logStatsIntervalId = null;
  9665. /**
  9666. * Stores the statistics which will be send to the focus to be logged.
  9667. */
  9668. this.statsToBeLogged =
  9669. {
  9670. timestamps: [],
  9671. stats: {}
  9672. };
  9673. // Updates stats interval
  9674. this.audioLevelsIntervalMilis = audioLevelsInterval;
  9675. this.statsIntervalId = null;
  9676. this.statsIntervalMilis = statsInterval;
  9677. // Map of jids to PeerStats
  9678. this.jid2stats = {};
  9679. }
  9680. module.exports = StatsCollector;
  9681. /**
  9682. * Stops stats updates.
  9683. */
  9684. StatsCollector.prototype.stop = function () {
  9685. if (this.audioLevelsIntervalId) {
  9686. clearInterval(this.audioLevelsIntervalId);
  9687. this.audioLevelsIntervalId = null;
  9688. }
  9689. if (this.statsIntervalId)
  9690. {
  9691. clearInterval(this.statsIntervalId);
  9692. this.statsIntervalId = null;
  9693. }
  9694. if(this.logStatsIntervalId)
  9695. {
  9696. clearInterval(this.logStatsIntervalId);
  9697. this.logStatsIntervalId = null;
  9698. }
  9699. if(this.gatherStatsIntervalId)
  9700. {
  9701. clearInterval(this.gatherStatsIntervalId);
  9702. this.gatherStatsIntervalId = null;
  9703. }
  9704. };
  9705. /**
  9706. * Callback passed to <tt>getStats</tt> method.
  9707. * @param error an error that occurred on <tt>getStats</tt> call.
  9708. */
  9709. StatsCollector.prototype.errorCallback = function (error)
  9710. {
  9711. console.error("Get stats error", error);
  9712. this.stop();
  9713. };
  9714. /**
  9715. * Starts stats updates.
  9716. */
  9717. StatsCollector.prototype.start = function ()
  9718. {
  9719. var self = this;
  9720. if(!config.disableAudioLevels) {
  9721. this.audioLevelsIntervalId = setInterval(
  9722. function () {
  9723. // Interval updates
  9724. self.peerconnection.getStats(
  9725. function (report) {
  9726. var results = null;
  9727. if (!report || !report.result ||
  9728. typeof report.result != 'function') {
  9729. results = report;
  9730. }
  9731. else {
  9732. results = report.result();
  9733. }
  9734. //console.error("Got interval report", results);
  9735. self.currentAudioLevelsReport = results;
  9736. self.processAudioLevelReport();
  9737. self.baselineAudioLevelsReport =
  9738. self.currentAudioLevelsReport;
  9739. },
  9740. self.errorCallback
  9741. );
  9742. },
  9743. self.audioLevelsIntervalMilis
  9744. );
  9745. }
  9746. if(!config.disableStats) {
  9747. this.statsIntervalId = setInterval(
  9748. function () {
  9749. // Interval updates
  9750. self.peerconnection.getStats(
  9751. function (report) {
  9752. var results = null;
  9753. if (!report || !report.result ||
  9754. typeof report.result != 'function') {
  9755. //firefox
  9756. results = report;
  9757. }
  9758. else {
  9759. //chrome
  9760. results = report.result();
  9761. }
  9762. //console.error("Got interval report", results);
  9763. self.currentStatsReport = results;
  9764. try {
  9765. self.processStatsReport();
  9766. }
  9767. catch (e) {
  9768. console.error("Unsupported key:" + e, e);
  9769. }
  9770. self.baselineStatsReport = self.currentStatsReport;
  9771. },
  9772. self.errorCallback
  9773. );
  9774. },
  9775. self.statsIntervalMilis
  9776. );
  9777. }
  9778. if (config.logStats) {
  9779. this.gatherStatsIntervalId = setInterval(
  9780. function () {
  9781. self.peerconnection.getStats(
  9782. function (report) {
  9783. self.addStatsToBeLogged(report.result());
  9784. },
  9785. function () {
  9786. }
  9787. );
  9788. },
  9789. this.GATHER_INTERVAL
  9790. );
  9791. this.logStatsIntervalId = setInterval(
  9792. function() { self.logStats(); },
  9793. this.LOG_INTERVAL);
  9794. }
  9795. };
  9796. /**
  9797. * Checks whether a certain record should be included in the logged statistics.
  9798. */
  9799. function acceptStat(reportId, reportType, statName) {
  9800. if (reportType == "googCandidatePair" && statName == "googChannelId")
  9801. return false;
  9802. if (reportType == "ssrc") {
  9803. if (statName == "googTrackId" ||
  9804. statName == "transportId" ||
  9805. statName == "ssrc")
  9806. return false;
  9807. }
  9808. return true;
  9809. }
  9810. /**
  9811. * Checks whether a certain record should be included in the logged statistics.
  9812. */
  9813. function acceptReport(id, type) {
  9814. if (id.substring(0, 15) == "googCertificate" ||
  9815. id.substring(0, 9) == "googTrack" ||
  9816. id.substring(0, 20) == "googLibjingleSession")
  9817. return false;
  9818. if (type == "googComponent")
  9819. return false;
  9820. return true;
  9821. }
  9822. /**
  9823. * Converts the stats to the format used for logging, and saves the data in
  9824. * this.statsToBeLogged.
  9825. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  9826. */
  9827. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  9828. var self = this;
  9829. var num_records = this.statsToBeLogged.timestamps.length;
  9830. this.statsToBeLogged.timestamps.push(new Date().getTime());
  9831. reports.map(function (report) {
  9832. if (!acceptReport(report.id, report.type))
  9833. return;
  9834. var stat = self.statsToBeLogged.stats[report.id];
  9835. if (!stat) {
  9836. stat = self.statsToBeLogged.stats[report.id] = {};
  9837. }
  9838. stat.type = report.type;
  9839. report.names().map(function (name) {
  9840. if (!acceptStat(report.id, report.type, name))
  9841. return;
  9842. var values = stat[name];
  9843. if (!values) {
  9844. values = stat[name] = [];
  9845. }
  9846. while (values.length < num_records) {
  9847. values.push(null);
  9848. }
  9849. values.push(report.stat(name));
  9850. });
  9851. });
  9852. };
  9853. StatsCollector.prototype.logStats = function () {
  9854. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  9855. return;
  9856. // Reset the stats
  9857. this.statsToBeLogged.stats = {};
  9858. this.statsToBeLogged.timestamps = [];
  9859. };
  9860. var keyMap = {};
  9861. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  9862. "ssrc": "ssrc",
  9863. "packetsReceived": "packetsReceived",
  9864. "packetsLost": "packetsLost",
  9865. "packetsSent": "packetsSent",
  9866. "bytesReceived": "bytesReceived",
  9867. "bytesSent": "bytesSent"
  9868. };
  9869. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  9870. "receiveBandwidth": "googAvailableReceiveBandwidth",
  9871. "sendBandwidth": "googAvailableSendBandwidth",
  9872. "remoteAddress": "googRemoteAddress",
  9873. "transportType": "googTransportType",
  9874. "localAddress": "googLocalAddress",
  9875. "activeConnection": "googActiveConnection",
  9876. "ssrc": "ssrc",
  9877. "packetsReceived": "packetsReceived",
  9878. "packetsSent": "packetsSent",
  9879. "packetsLost": "packetsLost",
  9880. "bytesReceived": "bytesReceived",
  9881. "bytesSent": "bytesSent",
  9882. "googFrameHeightReceived": "googFrameHeightReceived",
  9883. "googFrameWidthReceived": "googFrameWidthReceived",
  9884. "googFrameHeightSent": "googFrameHeightSent",
  9885. "googFrameWidthSent": "googFrameWidthSent",
  9886. "audioInputLevel": "audioInputLevel",
  9887. "audioOutputLevel": "audioOutputLevel"
  9888. };
  9889. /**
  9890. * Stats processing logic.
  9891. */
  9892. StatsCollector.prototype.processStatsReport = function () {
  9893. if (!this.baselineStatsReport) {
  9894. return;
  9895. }
  9896. for (var idx in this.currentStatsReport) {
  9897. var now = this.currentStatsReport[idx];
  9898. try {
  9899. if (getStatValue(now, 'receiveBandwidth') ||
  9900. getStatValue(now, 'sendBandwidth')) {
  9901. PeerStats.bandwidth = {
  9902. "download": Math.round(
  9903. (getStatValue(now, 'receiveBandwidth')) / 1000),
  9904. "upload": Math.round(
  9905. (getStatValue(now, 'sendBandwidth')) / 1000)
  9906. };
  9907. }
  9908. }
  9909. catch(e){/*not supported*/}
  9910. if(now.type == 'googCandidatePair')
  9911. {
  9912. var ip, type, localIP, active;
  9913. try {
  9914. ip = getStatValue(now, 'remoteAddress');
  9915. type = getStatValue(now, "transportType");
  9916. localIP = getStatValue(now, "localAddress");
  9917. active = getStatValue(now, "activeConnection");
  9918. }
  9919. catch(e){/*not supported*/}
  9920. if(!ip || !type || !localIP || active != "true")
  9921. continue;
  9922. var addressSaved = false;
  9923. for(var i = 0; i < PeerStats.transport.length; i++)
  9924. {
  9925. if(PeerStats.transport[i].ip == ip &&
  9926. PeerStats.transport[i].type == type &&
  9927. PeerStats.transport[i].localip == localIP)
  9928. {
  9929. addressSaved = true;
  9930. }
  9931. }
  9932. if(addressSaved)
  9933. continue;
  9934. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  9935. continue;
  9936. }
  9937. if(now.type == "candidatepair")
  9938. {
  9939. if(now.state == "succeeded")
  9940. continue;
  9941. var local = this.currentStatsReport[now.localCandidateId];
  9942. var remote = this.currentStatsReport[now.remoteCandidateId];
  9943. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  9944. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  9945. }
  9946. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  9947. now.type != "inboundrtp") {
  9948. continue;
  9949. }
  9950. var before = this.baselineStatsReport[idx];
  9951. if (!before) {
  9952. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  9953. continue;
  9954. }
  9955. var ssrc = getStatValue(now, 'ssrc');
  9956. if(!ssrc)
  9957. continue;
  9958. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  9959. if (!jid && (Date.now() - now.timestamp) < 3000) {
  9960. console.warn("No jid for ssrc: " + ssrc);
  9961. continue;
  9962. }
  9963. var jidStats = this.jid2stats[jid];
  9964. if (!jidStats) {
  9965. jidStats = new PeerStats();
  9966. this.jid2stats[jid] = jidStats;
  9967. }
  9968. var isDownloadStream = true;
  9969. var key = 'packetsReceived';
  9970. if (!getStatValue(now, key))
  9971. {
  9972. isDownloadStream = false;
  9973. key = 'packetsSent';
  9974. if (!getStatValue(now, key))
  9975. {
  9976. console.warn("No packetsReceived nor packetSent stat found");
  9977. continue;
  9978. }
  9979. }
  9980. var packetsNow = getStatValue(now, key);
  9981. if(!packetsNow || packetsNow < 0)
  9982. packetsNow = 0;
  9983. var packetsBefore = getStatValue(before, key);
  9984. if(!packetsBefore || packetsBefore < 0)
  9985. packetsBefore = 0;
  9986. var packetRate = packetsNow - packetsBefore;
  9987. if(!packetRate || packetRate < 0)
  9988. packetRate = 0;
  9989. var currentLoss = getStatValue(now, 'packetsLost');
  9990. if(!currentLoss || currentLoss < 0)
  9991. currentLoss = 0;
  9992. var previousLoss = getStatValue(before, 'packetsLost');
  9993. if(!previousLoss || previousLoss < 0)
  9994. previousLoss = 0;
  9995. var lossRate = currentLoss - previousLoss;
  9996. if(!lossRate || lossRate < 0)
  9997. lossRate = 0;
  9998. var packetsTotal = (packetRate + lossRate);
  9999. jidStats.setSsrcLoss(ssrc,
  10000. {"packetsTotal": packetsTotal,
  10001. "packetsLost": lossRate,
  10002. "isDownloadStream": isDownloadStream});
  10003. var bytesReceived = 0, bytesSent = 0;
  10004. if(getStatValue(now, "bytesReceived"))
  10005. {
  10006. bytesReceived = getStatValue(now, "bytesReceived") -
  10007. getStatValue(before, "bytesReceived");
  10008. }
  10009. if(getStatValue(now, "bytesSent"))
  10010. {
  10011. bytesSent = getStatValue(now, "bytesSent") -
  10012. getStatValue(before, "bytesSent");
  10013. }
  10014. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  10015. if(bytesReceived <= 0 || time <= 0)
  10016. {
  10017. bytesReceived = 0;
  10018. }
  10019. else
  10020. {
  10021. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  10022. }
  10023. if(bytesSent <= 0 || time <= 0)
  10024. {
  10025. bytesSent = 0;
  10026. }
  10027. else
  10028. {
  10029. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  10030. }
  10031. jidStats.setSsrcBitrate(ssrc, {
  10032. "download": bytesReceived,
  10033. "upload": bytesSent});
  10034. var resolution = {height: null, width: null};
  10035. try {
  10036. if (getStatValue(now, "googFrameHeightReceived") &&
  10037. getStatValue(now, "googFrameWidthReceived")) {
  10038. resolution.height = getStatValue(now, "googFrameHeightReceived");
  10039. resolution.width = getStatValue(now, "googFrameWidthReceived");
  10040. }
  10041. else if (getStatValue(now, "googFrameHeightSent") &&
  10042. getStatValue(now, "googFrameWidthSent")) {
  10043. resolution.height = getStatValue(now, "googFrameHeightSent");
  10044. resolution.width = getStatValue(now, "googFrameWidthSent");
  10045. }
  10046. }
  10047. catch(e){/*not supported*/}
  10048. if(resolution.height && resolution.width)
  10049. {
  10050. jidStats.setSsrcResolution(ssrc, resolution);
  10051. }
  10052. else
  10053. {
  10054. jidStats.setSsrcResolution(ssrc, null);
  10055. }
  10056. }
  10057. var self = this;
  10058. // Jid stats
  10059. var totalPackets = {download: 0, upload: 0};
  10060. var lostPackets = {download: 0, upload: 0};
  10061. var bitrateDownload = 0;
  10062. var bitrateUpload = 0;
  10063. var resolutions = {};
  10064. Object.keys(this.jid2stats).forEach(
  10065. function (jid)
  10066. {
  10067. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  10068. function (ssrc)
  10069. {
  10070. var type = "upload";
  10071. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  10072. type = "download";
  10073. totalPackets[type] +=
  10074. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  10075. lostPackets[type] +=
  10076. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  10077. }
  10078. );
  10079. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  10080. function (ssrc) {
  10081. bitrateDownload +=
  10082. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  10083. bitrateUpload +=
  10084. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  10085. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  10086. }
  10087. );
  10088. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  10089. }
  10090. );
  10091. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  10092. PeerStats.packetLoss = {
  10093. total:
  10094. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  10095. totalPackets.download + totalPackets.upload),
  10096. download:
  10097. calculatePacketLoss(lostPackets.download, totalPackets.download),
  10098. upload:
  10099. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  10100. };
  10101. this.eventEmitter.emit("statistics.connectionstats",
  10102. {
  10103. "bitrate": PeerStats.bitrate,
  10104. "packetLoss": PeerStats.packetLoss,
  10105. "bandwidth": PeerStats.bandwidth,
  10106. "resolution": resolutions,
  10107. "transport": PeerStats.transport
  10108. });
  10109. PeerStats.transport = [];
  10110. };
  10111. /**
  10112. * Stats processing logic.
  10113. */
  10114. StatsCollector.prototype.processAudioLevelReport = function ()
  10115. {
  10116. if (!this.baselineAudioLevelsReport)
  10117. {
  10118. return;
  10119. }
  10120. for (var idx in this.currentAudioLevelsReport)
  10121. {
  10122. var now = this.currentAudioLevelsReport[idx];
  10123. if (now.type != 'ssrc')
  10124. {
  10125. continue;
  10126. }
  10127. var before = this.baselineAudioLevelsReport[idx];
  10128. if (!before)
  10129. {
  10130. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  10131. continue;
  10132. }
  10133. var ssrc = getStatValue(now, 'ssrc');
  10134. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  10135. if (!jid && (Date.now() - now.timestamp) < 3000)
  10136. {
  10137. console.warn("No jid for ssrc: " + ssrc);
  10138. continue;
  10139. }
  10140. var jidStats = this.jid2stats[jid];
  10141. if (!jidStats)
  10142. {
  10143. jidStats = new PeerStats();
  10144. this.jid2stats[jid] = jidStats;
  10145. }
  10146. // Audio level
  10147. var audioLevel = null;
  10148. try {
  10149. audioLevel = getStatValue(now, 'audioInputLevel');
  10150. if (!audioLevel)
  10151. audioLevel = getStatValue(now, 'audioOutputLevel');
  10152. }
  10153. catch(e) {/*not supported*/
  10154. console.warn("Audio Levels are not available in the statistics.");
  10155. clearInterval(this.audioLevelsIntervalId);
  10156. return;
  10157. }
  10158. if (audioLevel)
  10159. {
  10160. // TODO: can't find specs about what this value really is,
  10161. // but it seems to vary between 0 and around 32k.
  10162. audioLevel = audioLevel / 32767;
  10163. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  10164. if(jid != APP.xmpp.myJid())
  10165. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  10166. }
  10167. }
  10168. };
  10169. },{"../../service/RTC/RTCBrowserType":88}],46:[function(require,module,exports){
  10170. /**
  10171. * Created by hristo on 8/4/14.
  10172. */
  10173. var LocalStats = require("./LocalStatsCollector.js");
  10174. var RTPStats = require("./RTPStatsCollector.js");
  10175. var EventEmitter = require("events");
  10176. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  10177. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10178. var eventEmitter = new EventEmitter();
  10179. var localStats = null;
  10180. var rtpStats = null;
  10181. function stopLocal()
  10182. {
  10183. if(localStats)
  10184. {
  10185. localStats.stop();
  10186. localStats = null;
  10187. }
  10188. }
  10189. function stopRemote()
  10190. {
  10191. if(rtpStats)
  10192. {
  10193. rtpStats.stop();
  10194. eventEmitter.emit("statistics.stop");
  10195. rtpStats = null;
  10196. }
  10197. }
  10198. function startRemoteStats (peerconnection) {
  10199. if(rtpStats)
  10200. {
  10201. rtpStats.stop();
  10202. rtpStats = null;
  10203. }
  10204. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  10205. rtpStats.start();
  10206. }
  10207. function onStreamCreated(stream)
  10208. {
  10209. if(stream.getOriginalStream().getAudioTracks().length === 0)
  10210. return;
  10211. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  10212. eventEmitter);
  10213. localStats.start();
  10214. }
  10215. function onDisposeConference(onUnload) {
  10216. stopRemote();
  10217. if(onUnload) {
  10218. stopLocal();
  10219. eventEmitter.removeAllListeners();
  10220. }
  10221. }
  10222. var statistics =
  10223. {
  10224. /**
  10225. * Indicates that this audio level is for local jid.
  10226. * @type {string}
  10227. */
  10228. LOCAL_JID: 'local',
  10229. addAudioLevelListener: function(listener)
  10230. {
  10231. eventEmitter.on("statistics.audioLevel", listener);
  10232. },
  10233. removeAudioLevelListener: function(listener)
  10234. {
  10235. eventEmitter.removeListener("statistics.audioLevel", listener);
  10236. },
  10237. addConnectionStatsListener: function(listener)
  10238. {
  10239. eventEmitter.on("statistics.connectionstats", listener);
  10240. },
  10241. removeConnectionStatsListener: function(listener)
  10242. {
  10243. eventEmitter.removeListener("statistics.connectionstats", listener);
  10244. },
  10245. addRemoteStatsStopListener: function(listener)
  10246. {
  10247. eventEmitter.on("statistics.stop", listener);
  10248. },
  10249. removeRemoteStatsStopListener: function(listener)
  10250. {
  10251. eventEmitter.removeListener("statistics.stop", listener);
  10252. },
  10253. stop: function () {
  10254. stopLocal();
  10255. stopRemote();
  10256. if(eventEmitter)
  10257. {
  10258. eventEmitter.removeAllListeners();
  10259. }
  10260. },
  10261. stopRemoteStatistics: function()
  10262. {
  10263. stopRemote();
  10264. },
  10265. start: function () {
  10266. APP.RTC.addStreamListener(onStreamCreated,
  10267. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  10268. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  10269. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  10270. startRemoteStats(event.peerconnection);
  10271. });
  10272. }
  10273. };
  10274. module.exports = statistics;
  10275. },{"../../service/RTC/StreamEventTypes.js":91,"../../service/xmpp/XMPPEvents":97,"./LocalStatsCollector.js":44,"./RTPStatsCollector.js":45,"events":98}],47:[function(require,module,exports){
  10276. var i18n = require("i18next-client");
  10277. var languages = require("../../service/translation/languages");
  10278. var Settings = require("../settings/Settings");
  10279. var DEFAULT_LANG = languages.EN;
  10280. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  10281. return value.replace("__app__", interfaceConfig.APP_NAME);
  10282. });
  10283. var defaultOptions = {
  10284. detectLngQS: "lang",
  10285. useCookie: false,
  10286. fallbackLng: DEFAULT_LANG,
  10287. load: "unspecific",
  10288. resGetPath: 'lang/__ns__-__lng__.json',
  10289. ns: {
  10290. namespaces: ['main', 'languages'],
  10291. defaultNs: 'main'
  10292. },
  10293. lngWhitelist : languages.getLanguages(),
  10294. fallbackOnNull: true,
  10295. fallbackOnEmpty: true,
  10296. useDataAttrOptions: true,
  10297. defaultValueFromContent: false,
  10298. app: interfaceConfig.APP_NAME,
  10299. getAsync: false,
  10300. defaultValueFromContent: false,
  10301. customLoad: function(lng, ns, options, done) {
  10302. var resPath = "lang/__ns__-__lng__.json";
  10303. if(lng === languages.EN)
  10304. resPath = "lang/__ns__.json";
  10305. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  10306. i18n.functions.ajax({
  10307. url: url,
  10308. success: function(data, status, xhr) {
  10309. i18n.functions.log('loaded: ' + url);
  10310. done(null, data);
  10311. },
  10312. error : function(xhr, status, error) {
  10313. if ((status && status == 200) ||
  10314. (xhr && xhr.status && xhr.status == 200)) {
  10315. // file loaded but invalid json, stop waste time !
  10316. i18n.functions.error('There is a typo in: ' + url);
  10317. } else if ((status && status == 404) ||
  10318. (xhr && xhr.status && xhr.status == 404)) {
  10319. i18n.functions.log('Does not exist: ' + url);
  10320. } else {
  10321. var theStatus = status ? status :
  10322. ((xhr && xhr.status) ? xhr.status : null);
  10323. i18n.functions.log(theStatus + ' when loading ' + url);
  10324. }
  10325. done(error, {});
  10326. },
  10327. dataType: "json",
  10328. async : options.getAsync
  10329. });
  10330. }
  10331. // options for caching
  10332. // useLocalStorage: true,
  10333. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  10334. };
  10335. function initCompleted(t)
  10336. {
  10337. $("[data-i18n]").i18n();
  10338. }
  10339. function checkForParameter() {
  10340. var query = window.location.search.substring(1);
  10341. var vars = query.split("&");
  10342. for (var i=0;i<vars.length;i++) {
  10343. var pair = vars[i].split("=");
  10344. if(pair[0] == "lang")
  10345. {
  10346. return pair[1];
  10347. }
  10348. }
  10349. return null;
  10350. }
  10351. module.exports = {
  10352. init: function (lang) {
  10353. var options = defaultOptions;
  10354. if(!lang)
  10355. {
  10356. lang = checkForParameter();
  10357. if(!lang)
  10358. {
  10359. var settings = Settings.getSettings();
  10360. if(settings)
  10361. lang = settings.language;
  10362. }
  10363. }
  10364. if(lang) {
  10365. options.lng = lang;
  10366. }
  10367. i18n.init(options, initCompleted);
  10368. },
  10369. translateString: function (key, options) {
  10370. return i18n.t(key, options);
  10371. },
  10372. setLanguage: function (lang) {
  10373. if(!lang)
  10374. lang = DEFAULT_LANG;
  10375. i18n.setLng(lang, defaultOptions, initCompleted);
  10376. },
  10377. getCurrentLanguage: function () {
  10378. return i18n.lng();
  10379. },
  10380. translateElement: function (selector) {
  10381. selector.i18n();
  10382. },
  10383. generateTranslatonHTML: function (key, options) {
  10384. var str = "<span data-i18n=\"" + key + "\"";
  10385. if(options)
  10386. {
  10387. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  10388. }
  10389. str += ">";
  10390. str += this.translateString(key, options);
  10391. str += "</span>";
  10392. return str;
  10393. }
  10394. };
  10395. },{"../../service/translation/languages":96,"../settings/Settings":38,"i18next-client":62}],48:[function(require,module,exports){
  10396. /* jshint -W117 */
  10397. var TraceablePeerConnection = require("./TraceablePeerConnection");
  10398. var SDPDiffer = require("./SDPDiffer");
  10399. var SDPUtil = require("./SDPUtil");
  10400. var SDP = require("./SDP");
  10401. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  10402. // Jingle stuff
  10403. function JingleSession(me, sid, connection, service) {
  10404. this.me = me;
  10405. this.sid = sid;
  10406. this.connection = connection;
  10407. this.initiator = null;
  10408. this.responder = null;
  10409. this.isInitiator = null;
  10410. this.peerjid = null;
  10411. this.state = null;
  10412. this.localSDP = null;
  10413. this.remoteSDP = null;
  10414. this.relayedStreams = [];
  10415. this.startTime = null;
  10416. this.stopTime = null;
  10417. this.media_constraints = null;
  10418. this.pc_constraints = null;
  10419. this.ice_config = {};
  10420. this.drip_container = [];
  10421. this.service = service;
  10422. this.usetrickle = true;
  10423. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  10424. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  10425. this.hadstuncandidate = false;
  10426. this.hadturncandidate = false;
  10427. this.lasticecandidate = false;
  10428. this.statsinterval = null;
  10429. this.reason = null;
  10430. this.addssrc = [];
  10431. this.removessrc = [];
  10432. this.pendingop = null;
  10433. this.switchstreams = false;
  10434. this.wait = true;
  10435. this.localStreamsSSRC = null;
  10436. /**
  10437. * The indicator which determines whether the (local) video has been muted
  10438. * in response to a user command in contrast to an automatic decision made
  10439. * by the application logic.
  10440. */
  10441. this.videoMuteByUser = false;
  10442. }
  10443. //TODO: this array must be removed when firefox implement multistream support
  10444. JingleSession.notReceivedSSRCs = [];
  10445. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  10446. var self = this;
  10447. if (this.state !== null) {
  10448. console.error('attempt to initiate on session ' + this.sid +
  10449. 'in state ' + this.state);
  10450. return;
  10451. }
  10452. this.isInitiator = isInitiator;
  10453. this.state = 'pending';
  10454. this.initiator = isInitiator ? this.me : peerjid;
  10455. this.responder = !isInitiator ? this.me : peerjid;
  10456. this.peerjid = peerjid;
  10457. this.hadstuncandidate = false;
  10458. this.hadturncandidate = false;
  10459. this.lasticecandidate = false;
  10460. this.peerconnection
  10461. = new TraceablePeerConnection(
  10462. this.connection.jingle.ice_config,
  10463. this.connection.jingle.pc_constraints );
  10464. this.peerconnection.onicecandidate = function (event) {
  10465. self.sendIceCandidate(event.candidate);
  10466. };
  10467. this.peerconnection.onaddstream = function (event) {
  10468. console.log("REMOTE STREAM ADDED: " + event.stream + " - " + event.stream.id);
  10469. self.remoteStreamAdded(event);
  10470. };
  10471. this.peerconnection.onremovestream = function (event) {
  10472. // Remove the stream from remoteStreams
  10473. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  10474. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  10475. };
  10476. this.peerconnection.onsignalingstatechange = function (event) {
  10477. if (!(self && self.peerconnection)) return;
  10478. };
  10479. this.peerconnection.oniceconnectionstatechange = function (event) {
  10480. if (!(self && self.peerconnection)) return;
  10481. switch (self.peerconnection.iceConnectionState) {
  10482. case 'connected':
  10483. this.startTime = new Date();
  10484. break;
  10485. case 'disconnected':
  10486. this.stopTime = new Date();
  10487. break;
  10488. }
  10489. onIceConnectionStateChange(self.sid, self);
  10490. };
  10491. // add any local and relayed stream
  10492. APP.RTC.localStreams.forEach(function(stream) {
  10493. self.peerconnection.addStream(stream.getOriginalStream());
  10494. });
  10495. this.relayedStreams.forEach(function(stream) {
  10496. self.peerconnection.addStream(stream);
  10497. });
  10498. };
  10499. function onIceConnectionStateChange(sid, session) {
  10500. switch (session.peerconnection.iceConnectionState) {
  10501. case 'checking':
  10502. session.timeChecking = (new Date()).getTime();
  10503. session.firstconnect = true;
  10504. break;
  10505. case 'completed': // on caller side
  10506. case 'connected':
  10507. if (session.firstconnect) {
  10508. session.firstconnect = false;
  10509. var metadata = {};
  10510. metadata.setupTime
  10511. = (new Date()).getTime() - session.timeChecking;
  10512. session.peerconnection.getStats(function (res) {
  10513. if(res && res.result) {
  10514. res.result().forEach(function (report) {
  10515. if (report.type == 'googCandidatePair' &&
  10516. report.stat('googActiveConnection') == 'true') {
  10517. metadata.localCandidateType
  10518. = report.stat('googLocalCandidateType');
  10519. metadata.remoteCandidateType
  10520. = report.stat('googRemoteCandidateType');
  10521. // log pair as well so we can get nice pie
  10522. // charts
  10523. metadata.candidatePair
  10524. = report.stat('googLocalCandidateType') +
  10525. ';' +
  10526. report.stat('googRemoteCandidateType');
  10527. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  10528. {
  10529. metadata.ipv6 = true;
  10530. }
  10531. }
  10532. });
  10533. }
  10534. });
  10535. }
  10536. break;
  10537. }
  10538. }
  10539. JingleSession.prototype.accept = function () {
  10540. var self = this;
  10541. this.state = 'active';
  10542. var pranswer = this.peerconnection.localDescription;
  10543. if (!pranswer || pranswer.type != 'pranswer') {
  10544. return;
  10545. }
  10546. console.log('going from pranswer to answer');
  10547. if (this.usetrickle) {
  10548. // remove candidates already sent from session-accept
  10549. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  10550. for (var i = 0; i < lines.length; i++) {
  10551. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  10552. }
  10553. }
  10554. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  10555. // FIXME: change any inactive to sendrecv or whatever they were originally
  10556. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  10557. }
  10558. pranswer = APP.simulcast.reverseTransformLocalDescription(pranswer);
  10559. var prsdp = new SDP(pranswer.sdp);
  10560. var accept = $iq({to: this.peerjid,
  10561. type: 'set'})
  10562. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10563. action: 'session-accept',
  10564. initiator: this.initiator,
  10565. responder: this.responder,
  10566. sid: this.sid });
  10567. prsdp.toJingle(accept, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10568. var sdp = this.peerconnection.localDescription.sdp;
  10569. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  10570. // FIXME: change any inactive to sendrecv or whatever they were originally
  10571. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  10572. }
  10573. var self = this;
  10574. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  10575. function () {
  10576. //console.log('setLocalDescription success');
  10577. self.setLocalDescription();
  10578. self.connection.sendIQ(accept,
  10579. function () {
  10580. var ack = {};
  10581. ack.source = 'answer';
  10582. $(document).trigger('ack.jingle', [self.sid, ack]);
  10583. },
  10584. function (stanza) {
  10585. var error = ($(stanza).find('error').length) ? {
  10586. code: $(stanza).find('error').attr('code'),
  10587. reason: $(stanza).find('error :first')[0].tagName
  10588. }:{};
  10589. error.source = 'answer';
  10590. JingleSession.onJingleError(self.sid, error);
  10591. },
  10592. 10000);
  10593. },
  10594. function (e) {
  10595. console.error('setLocalDescription failed', e);
  10596. }
  10597. );
  10598. };
  10599. JingleSession.prototype.terminate = function (reason) {
  10600. this.state = 'ended';
  10601. this.reason = reason;
  10602. this.peerconnection.close();
  10603. if (this.statsinterval !== null) {
  10604. window.clearInterval(this.statsinterval);
  10605. this.statsinterval = null;
  10606. }
  10607. };
  10608. JingleSession.prototype.active = function () {
  10609. return this.state == 'active';
  10610. };
  10611. JingleSession.prototype.sendIceCandidate = function (candidate) {
  10612. var self = this;
  10613. if (candidate && !this.lasticecandidate) {
  10614. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  10615. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  10616. if (!(ice && jcand)) {
  10617. console.error('failed to get ice && jcand');
  10618. return;
  10619. }
  10620. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10621. if (jcand.type === 'srflx') {
  10622. this.hadstuncandidate = true;
  10623. } else if (jcand.type === 'relay') {
  10624. this.hadturncandidate = true;
  10625. }
  10626. if (this.usetrickle) {
  10627. if (this.usedrip) {
  10628. if (this.drip_container.length === 0) {
  10629. // start 20ms callout
  10630. window.setTimeout(function () {
  10631. if (self.drip_container.length === 0) return;
  10632. self.sendIceCandidates(self.drip_container);
  10633. self.drip_container = [];
  10634. }, 20);
  10635. }
  10636. this.drip_container.push(candidate);
  10637. return;
  10638. } else {
  10639. self.sendIceCandidate([candidate]);
  10640. }
  10641. }
  10642. } else {
  10643. //console.log('sendIceCandidate: last candidate.');
  10644. if (!this.usetrickle) {
  10645. //console.log('should send full offer now...');
  10646. var init = $iq({to: this.peerjid,
  10647. type: 'set'})
  10648. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10649. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  10650. initiator: this.initiator,
  10651. sid: this.sid});
  10652. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  10653. var self = this;
  10654. var sendJingle = function (ssrc) {
  10655. if(!ssrc)
  10656. ssrc = {};
  10657. self.localSDP.toJingle(init, self.initiator == self.me ? 'initiator' : 'responder', ssrc);
  10658. self.connection.sendIQ(init,
  10659. function () {
  10660. //console.log('session initiate ack');
  10661. var ack = {};
  10662. ack.source = 'offer';
  10663. $(document).trigger('ack.jingle', [self.sid, ack]);
  10664. },
  10665. function (stanza) {
  10666. self.state = 'error';
  10667. self.peerconnection.close();
  10668. var error = ($(stanza).find('error').length) ? {
  10669. code: $(stanza).find('error').attr('code'),
  10670. reason: $(stanza).find('error :first')[0].tagName,
  10671. }:{};
  10672. error.source = 'offer';
  10673. JingleSession.onJingleError(self.sid, error);
  10674. },
  10675. 10000);
  10676. }
  10677. sendJingle();
  10678. }
  10679. this.lasticecandidate = true;
  10680. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  10681. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  10682. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  10683. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  10684. }
  10685. }
  10686. };
  10687. JingleSession.prototype.sendIceCandidates = function (candidates) {
  10688. console.log('sendIceCandidates', candidates);
  10689. var cand = $iq({to: this.peerjid, type: 'set'})
  10690. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10691. action: 'transport-info',
  10692. initiator: this.initiator,
  10693. sid: this.sid});
  10694. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  10695. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  10696. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  10697. if (cands.length > 0) {
  10698. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  10699. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10700. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  10701. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  10702. }).c('transport', ice);
  10703. for (var i = 0; i < cands.length; i++) {
  10704. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  10705. }
  10706. // add fingerprint
  10707. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  10708. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  10709. tmp.required = true;
  10710. cand.c(
  10711. 'fingerprint',
  10712. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  10713. .t(tmp.fingerprint);
  10714. delete tmp.fingerprint;
  10715. cand.attrs(tmp);
  10716. cand.up();
  10717. }
  10718. cand.up(); // transport
  10719. cand.up(); // content
  10720. }
  10721. }
  10722. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  10723. //console.log('was this the last candidate', this.lasticecandidate);
  10724. this.connection.sendIQ(cand,
  10725. function () {
  10726. var ack = {};
  10727. ack.source = 'transportinfo';
  10728. $(document).trigger('ack.jingle', [this.sid, ack]);
  10729. },
  10730. function (stanza) {
  10731. var error = ($(stanza).find('error').length) ? {
  10732. code: $(stanza).find('error').attr('code'),
  10733. reason: $(stanza).find('error :first')[0].tagName,
  10734. }:{};
  10735. error.source = 'transportinfo';
  10736. JingleSession.onJingleError(this.sid, error);
  10737. },
  10738. 10000);
  10739. };
  10740. JingleSession.prototype.sendOffer = function () {
  10741. //console.log('sendOffer...');
  10742. var self = this;
  10743. this.peerconnection.createOffer(function (sdp) {
  10744. self.createdOffer(sdp);
  10745. },
  10746. function (e) {
  10747. console.error('createOffer failed', e);
  10748. },
  10749. this.media_constraints
  10750. );
  10751. };
  10752. JingleSession.prototype.createdOffer = function (sdp) {
  10753. //console.log('createdOffer', sdp);
  10754. var self = this;
  10755. this.localSDP = new SDP(sdp.sdp);
  10756. //this.localSDP.mangle();
  10757. var sendJingle = function () {
  10758. var init = $iq({to: this.peerjid,
  10759. type: 'set'})
  10760. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10761. action: 'session-initiate',
  10762. initiator: this.initiator,
  10763. sid: this.sid});
  10764. self.localSDP.toJingle(init, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10765. self.connection.sendIQ(init,
  10766. function () {
  10767. var ack = {};
  10768. ack.source = 'offer';
  10769. $(document).trigger('ack.jingle', [self.sid, ack]);
  10770. },
  10771. function (stanza) {
  10772. self.state = 'error';
  10773. self.peerconnection.close();
  10774. var error = ($(stanza).find('error').length) ? {
  10775. code: $(stanza).find('error').attr('code'),
  10776. reason: $(stanza).find('error :first')[0].tagName,
  10777. }:{};
  10778. error.source = 'offer';
  10779. JingleSession.onJingleError(self.sid, error);
  10780. },
  10781. 10000);
  10782. }
  10783. sdp.sdp = this.localSDP.raw;
  10784. this.peerconnection.setLocalDescription(sdp,
  10785. function () {
  10786. if(self.usetrickle)
  10787. {
  10788. sendJingle();
  10789. }
  10790. self.setLocalDescription();
  10791. //console.log('setLocalDescription success');
  10792. },
  10793. function (e) {
  10794. console.error('setLocalDescription failed', e);
  10795. }
  10796. );
  10797. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  10798. for (var i = 0; i < cands.length; i++) {
  10799. var cand = SDPUtil.parse_icecandidate(cands[i]);
  10800. if (cand.type == 'srflx') {
  10801. this.hadstuncandidate = true;
  10802. } else if (cand.type == 'relay') {
  10803. this.hadturncandidate = true;
  10804. }
  10805. }
  10806. };
  10807. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  10808. //console.log('setting remote description... ', desctype);
  10809. this.remoteSDP = new SDP('');
  10810. this.remoteSDP.fromJingle(elem);
  10811. if (this.peerconnection.remoteDescription !== null) {
  10812. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  10813. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  10814. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  10815. for (var i = 0; i < pranswer.media.length; i++) {
  10816. // make sure we have ice ufrag and pwd
  10817. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  10818. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  10819. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  10820. } else {
  10821. console.warn('no ice ufrag?');
  10822. }
  10823. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  10824. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  10825. } else {
  10826. console.warn('no ice pwd?');
  10827. }
  10828. }
  10829. // copy over candidates
  10830. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  10831. for (var j = 0; j < lines.length; j++) {
  10832. this.remoteSDP.media[i] += lines[j] + '\r\n';
  10833. }
  10834. }
  10835. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  10836. }
  10837. }
  10838. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  10839. this.peerconnection.setRemoteDescription(remotedesc,
  10840. function () {
  10841. //console.log('setRemoteDescription success');
  10842. },
  10843. function (e) {
  10844. console.error('setRemoteDescription error', e);
  10845. JingleSession.onJingleFatalError(self, e);
  10846. }
  10847. );
  10848. };
  10849. JingleSession.prototype.addIceCandidate = function (elem) {
  10850. var self = this;
  10851. if (this.peerconnection.signalingState == 'closed') {
  10852. return;
  10853. }
  10854. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  10855. console.log('trickle ice candidate arriving before session accept...');
  10856. // create a PRANSWER for setRemoteDescription
  10857. if (!this.remoteSDP) {
  10858. var cobbled = 'v=0\r\n' +
  10859. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  10860. 's=-\r\n' +
  10861. 't=0 0\r\n';
  10862. // first, take some things from the local description
  10863. for (var i = 0; i < this.localSDP.media.length; i++) {
  10864. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  10865. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  10866. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  10867. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  10868. }
  10869. cobbled += 'a=inactive\r\n';
  10870. }
  10871. this.remoteSDP = new SDP(cobbled);
  10872. }
  10873. // then add things like ice and dtls from remote candidate
  10874. elem.each(function () {
  10875. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  10876. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10877. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10878. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  10879. var tmp = $(this).find('transport');
  10880. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  10881. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  10882. tmp = $(this).find('transport>fingerprint');
  10883. if (tmp.length) {
  10884. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  10885. } else {
  10886. console.log('no dtls fingerprint (webrtc issue #1718?)');
  10887. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  10888. }
  10889. break;
  10890. }
  10891. }
  10892. }
  10893. });
  10894. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  10895. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  10896. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  10897. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  10898. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  10899. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  10900. }).length == this.remoteSDP.media.length;
  10901. if (iscomplete) {
  10902. console.log('setting pranswer');
  10903. try {
  10904. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  10905. function() {
  10906. },
  10907. function(e) {
  10908. console.log('setRemoteDescription pranswer failed', e.toString());
  10909. });
  10910. } catch (e) {
  10911. console.error('setting pranswer failed', e);
  10912. }
  10913. } else {
  10914. //console.log('not yet setting pranswer');
  10915. }
  10916. }
  10917. // operate on each content element
  10918. elem.each(function () {
  10919. // would love to deactivate this, but firefox still requires it
  10920. var idx = -1;
  10921. var i;
  10922. for (i = 0; i < self.remoteSDP.media.length; i++) {
  10923. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10924. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10925. idx = i;
  10926. break;
  10927. }
  10928. }
  10929. if (idx == -1) { // fall back to localdescription
  10930. for (i = 0; i < self.localSDP.media.length; i++) {
  10931. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10932. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10933. idx = i;
  10934. break;
  10935. }
  10936. }
  10937. }
  10938. var name = $(this).attr('name');
  10939. // TODO: check ice-pwd and ice-ufrag?
  10940. $(this).find('transport>candidate').each(function () {
  10941. var line, candidate;
  10942. line = SDPUtil.candidateFromJingle(this);
  10943. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  10944. sdpMid: name,
  10945. candidate: line});
  10946. try {
  10947. self.peerconnection.addIceCandidate(candidate);
  10948. } catch (e) {
  10949. console.error('addIceCandidate failed', e.toString(), line);
  10950. }
  10951. });
  10952. });
  10953. };
  10954. JingleSession.prototype.sendAnswer = function (provisional) {
  10955. //console.log('createAnswer', provisional);
  10956. var self = this;
  10957. this.peerconnection.createAnswer(
  10958. function (sdp) {
  10959. self.createdAnswer(sdp, provisional);
  10960. },
  10961. function (e) {
  10962. console.error('createAnswer failed', e);
  10963. },
  10964. this.media_constraints
  10965. );
  10966. };
  10967. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  10968. //console.log('createAnswer callback');
  10969. var self = this;
  10970. this.localSDP = new SDP(sdp.sdp);
  10971. //this.localSDP.mangle();
  10972. this.usepranswer = provisional === true;
  10973. if (this.usetrickle) {
  10974. if (this.usepranswer) {
  10975. sdp.type = 'pranswer';
  10976. for (var i = 0; i < this.localSDP.media.length; i++) {
  10977. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  10978. }
  10979. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  10980. }
  10981. }
  10982. var self = this;
  10983. var sendJingle = function (ssrcs) {
  10984. var accept = $iq({to: self.peerjid,
  10985. type: 'set'})
  10986. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10987. action: 'session-accept',
  10988. initiator: self.initiator,
  10989. responder: self.responder,
  10990. sid: self.sid });
  10991. var publicLocalDesc = APP.simulcast.reverseTransformLocalDescription(sdp);
  10992. var publicLocalSDP = new SDP(publicLocalDesc.sdp);
  10993. publicLocalSDP.toJingle(accept, self.initiator == self.me ? 'initiator' : 'responder', ssrcs);
  10994. self.connection.sendIQ(accept,
  10995. function () {
  10996. var ack = {};
  10997. ack.source = 'answer';
  10998. $(document).trigger('ack.jingle', [self.sid, ack]);
  10999. },
  11000. function (stanza) {
  11001. var error = ($(stanza).find('error').length) ? {
  11002. code: $(stanza).find('error').attr('code'),
  11003. reason: $(stanza).find('error :first')[0].tagName,
  11004. }:{};
  11005. error.source = 'answer';
  11006. JingleSession.onJingleError(self.sid, error);
  11007. },
  11008. 10000);
  11009. }
  11010. sdp.sdp = this.localSDP.raw;
  11011. this.peerconnection.setLocalDescription(sdp,
  11012. function () {
  11013. //console.log('setLocalDescription success');
  11014. if (self.usetrickle && !self.usepranswer) {
  11015. sendJingle();
  11016. }
  11017. self.setLocalDescription();
  11018. },
  11019. function (e) {
  11020. console.error('setLocalDescription failed', e);
  11021. }
  11022. );
  11023. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  11024. for (var j = 0; j < cands.length; j++) {
  11025. var cand = SDPUtil.parse_icecandidate(cands[j]);
  11026. if (cand.type == 'srflx') {
  11027. this.hadstuncandidate = true;
  11028. } else if (cand.type == 'relay') {
  11029. this.hadturncandidate = true;
  11030. }
  11031. }
  11032. };
  11033. JingleSession.prototype.sendTerminate = function (reason, text) {
  11034. var self = this,
  11035. term = $iq({to: this.peerjid,
  11036. type: 'set'})
  11037. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11038. action: 'session-terminate',
  11039. initiator: this.initiator,
  11040. sid: this.sid})
  11041. .c('reason')
  11042. .c(reason || 'success');
  11043. if (text) {
  11044. term.up().c('text').t(text);
  11045. }
  11046. this.connection.sendIQ(term,
  11047. function () {
  11048. self.peerconnection.close();
  11049. self.peerconnection = null;
  11050. self.terminate();
  11051. var ack = {};
  11052. ack.source = 'terminate';
  11053. $(document).trigger('ack.jingle', [self.sid, ack]);
  11054. },
  11055. function (stanza) {
  11056. var error = ($(stanza).find('error').length) ? {
  11057. code: $(stanza).find('error').attr('code'),
  11058. reason: $(stanza).find('error :first')[0].tagName,
  11059. }:{};
  11060. $(document).trigger('ack.jingle', [self.sid, error]);
  11061. },
  11062. 10000);
  11063. if (this.statsinterval !== null) {
  11064. window.clearInterval(this.statsinterval);
  11065. this.statsinterval = null;
  11066. }
  11067. };
  11068. JingleSession.prototype.addSource = function (elem, fromJid) {
  11069. var self = this;
  11070. // FIXME: dirty waiting
  11071. if (!this.peerconnection.localDescription)
  11072. {
  11073. console.warn("addSource - localDescription not ready yet")
  11074. setTimeout(function()
  11075. {
  11076. self.addSource(elem, fromJid);
  11077. },
  11078. 200
  11079. );
  11080. return;
  11081. }
  11082. console.log('addssrc', new Date().getTime());
  11083. console.log('ice', this.peerconnection.iceConnectionState);
  11084. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11085. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  11086. $(elem).each(function (idx, content) {
  11087. var name = $(content).attr('name');
  11088. var lines = '';
  11089. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  11090. var semantics = this.getAttribute('semantics');
  11091. var ssrcs = $(this).find('>source').map(function () {
  11092. return this.getAttribute('ssrc');
  11093. }).get();
  11094. if (ssrcs.length != 0) {
  11095. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  11096. }
  11097. });
  11098. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  11099. tmp.each(function () {
  11100. var ssrc = $(this).attr('ssrc');
  11101. if(mySdp.containsSSRC(ssrc)){
  11102. /**
  11103. * This happens when multiple participants change their streams at the same time and
  11104. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  11105. * addssrc are scheduled for update IQ. See
  11106. */
  11107. console.warn("Got add stream request for my own ssrc: "+ssrc);
  11108. return;
  11109. }
  11110. $(this).find('>parameter').each(function () {
  11111. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  11112. if ($(this).attr('value') && $(this).attr('value').length)
  11113. lines += ':' + $(this).attr('value');
  11114. lines += '\r\n';
  11115. });
  11116. });
  11117. sdp.media.forEach(function(media, idx) {
  11118. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  11119. return;
  11120. sdp.media[idx] += lines;
  11121. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  11122. self.addssrc[idx] += lines;
  11123. });
  11124. sdp.raw = sdp.session + sdp.media.join('');
  11125. });
  11126. this.modifySources();
  11127. };
  11128. JingleSession.prototype.removeSource = function (elem, fromJid) {
  11129. var self = this;
  11130. // FIXME: dirty waiting
  11131. if (!this.peerconnection.localDescription)
  11132. {
  11133. console.warn("removeSource - localDescription not ready yet")
  11134. setTimeout(function()
  11135. {
  11136. self.removeSource(elem, fromJid);
  11137. },
  11138. 200
  11139. );
  11140. return;
  11141. }
  11142. console.log('removessrc', new Date().getTime());
  11143. console.log('ice', this.peerconnection.iceConnectionState);
  11144. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11145. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  11146. $(elem).each(function (idx, content) {
  11147. var name = $(content).attr('name');
  11148. var lines = '';
  11149. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  11150. var semantics = this.getAttribute('semantics');
  11151. var ssrcs = $(this).find('>source').map(function () {
  11152. return this.getAttribute('ssrc');
  11153. }).get();
  11154. if (ssrcs.length != 0) {
  11155. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  11156. }
  11157. });
  11158. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  11159. tmp.each(function () {
  11160. var ssrc = $(this).attr('ssrc');
  11161. // This should never happen, but can be useful for bug detection
  11162. if(mySdp.containsSSRC(ssrc)){
  11163. console.error("Got remove stream request for my own ssrc: "+ssrc);
  11164. return;
  11165. }
  11166. $(this).find('>parameter').each(function () {
  11167. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  11168. if ($(this).attr('value') && $(this).attr('value').length)
  11169. lines += ':' + $(this).attr('value');
  11170. lines += '\r\n';
  11171. });
  11172. });
  11173. sdp.media.forEach(function(media, idx) {
  11174. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  11175. return;
  11176. sdp.media[idx] += lines;
  11177. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  11178. self.removessrc[idx] += lines;
  11179. });
  11180. sdp.raw = sdp.session + sdp.media.join('');
  11181. });
  11182. this.modifySources();
  11183. };
  11184. JingleSession.prototype.modifySources = function (successCallback) {
  11185. var self = this;
  11186. if (this.peerconnection.signalingState == 'closed') return;
  11187. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  11188. // There is nothing to do since scheduled job might have been executed by another succeeding call
  11189. this.setLocalDescription();
  11190. if(successCallback){
  11191. successCallback();
  11192. }
  11193. return;
  11194. }
  11195. // FIXME: this is a big hack
  11196. // https://code.google.com/p/webrtc/issues/detail?id=2688
  11197. // ^ has been fixed.
  11198. if (!(this.peerconnection.signalingState == 'stable' && this.peerconnection.iceConnectionState == 'connected')) {
  11199. console.warn('modifySources not yet', this.peerconnection.signalingState, this.peerconnection.iceConnectionState);
  11200. this.wait = true;
  11201. window.setTimeout(function() { self.modifySources(successCallback); }, 250);
  11202. return;
  11203. }
  11204. if (this.wait) {
  11205. window.setTimeout(function() { self.modifySources(successCallback); }, 2500);
  11206. this.wait = false;
  11207. return;
  11208. }
  11209. // Reset switch streams flag
  11210. this.switchstreams = false;
  11211. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11212. // add sources
  11213. this.addssrc.forEach(function(lines, idx) {
  11214. sdp.media[idx] += lines;
  11215. });
  11216. this.addssrc = [];
  11217. // remove sources
  11218. this.removessrc.forEach(function(lines, idx) {
  11219. lines = lines.split('\r\n');
  11220. lines.pop(); // remove empty last element;
  11221. lines.forEach(function(line) {
  11222. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  11223. });
  11224. });
  11225. this.removessrc = [];
  11226. // FIXME:
  11227. // this was a hack for the situation when only one peer exists
  11228. // in the conference.
  11229. // check if still required and remove
  11230. if (sdp.media[0])
  11231. sdp.media[0] = sdp.media[0].replace('a=recvonly', 'a=sendrecv');
  11232. if (sdp.media[1])
  11233. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11234. sdp.raw = sdp.session + sdp.media.join('');
  11235. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  11236. function() {
  11237. if(self.signalingState == 'closed') {
  11238. console.error("createAnswer attempt on closed state");
  11239. return;
  11240. }
  11241. self.peerconnection.createAnswer(
  11242. function(modifiedAnswer) {
  11243. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  11244. if (self.pendingop !== null) {
  11245. var sdp = new SDP(modifiedAnswer.sdp);
  11246. if (sdp.media.length > 1) {
  11247. switch(self.pendingop) {
  11248. case 'mute':
  11249. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  11250. break;
  11251. case 'unmute':
  11252. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11253. break;
  11254. }
  11255. sdp.raw = sdp.session + sdp.media.join('');
  11256. modifiedAnswer.sdp = sdp.raw;
  11257. }
  11258. self.pendingop = null;
  11259. }
  11260. // FIXME: pushing down an answer while ice connection state
  11261. // is still checking is bad...
  11262. //console.log(self.peerconnection.iceConnectionState);
  11263. // trying to work around another chrome bug
  11264. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  11265. self.peerconnection.setLocalDescription(modifiedAnswer,
  11266. function() {
  11267. //console.log('modified setLocalDescription ok');
  11268. self.setLocalDescription();
  11269. if(successCallback){
  11270. successCallback();
  11271. }
  11272. },
  11273. function(error) {
  11274. console.error('modified setLocalDescription failed', error);
  11275. }
  11276. );
  11277. },
  11278. function(error) {
  11279. console.error('modified answer failed', error);
  11280. }
  11281. );
  11282. },
  11283. function(error) {
  11284. console.error('modify failed', error);
  11285. }
  11286. );
  11287. };
  11288. /**
  11289. * Switches video streams.
  11290. * @param new_stream new stream that will be used as video of this session.
  11291. * @param oldStream old video stream of this session.
  11292. * @param success_callback callback executed after successful stream switch.
  11293. */
  11294. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback) {
  11295. var self = this;
  11296. // Remember SDP to figure out added/removed SSRCs
  11297. var oldSdp = null;
  11298. if(self.peerconnection) {
  11299. if(self.peerconnection.localDescription) {
  11300. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  11301. }
  11302. self.peerconnection.removeStream(oldStream, true);
  11303. self.peerconnection.addStream(new_stream);
  11304. }
  11305. APP.RTC.switchVideoStreams(new_stream, oldStream);
  11306. // Conference is not active
  11307. if(!oldSdp || !self.peerconnection) {
  11308. success_callback();
  11309. return;
  11310. }
  11311. self.switchstreams = true;
  11312. self.modifySources(function() {
  11313. console.log('modify sources done');
  11314. success_callback();
  11315. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  11316. console.log("SDPs", oldSdp, newSdp);
  11317. self.notifyMySSRCUpdate(oldSdp, newSdp);
  11318. });
  11319. };
  11320. /**
  11321. * Figures out added/removed ssrcs and send update IQs.
  11322. * @param old_sdp SDP object for old description.
  11323. * @param new_sdp SDP object for new description.
  11324. */
  11325. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  11326. if (!(this.peerconnection.signalingState == 'stable' &&
  11327. this.peerconnection.iceConnectionState == 'connected')){
  11328. console.log("Too early to send updates");
  11329. return;
  11330. }
  11331. // send source-remove IQ.
  11332. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  11333. var remove = $iq({to: this.peerjid, type: 'set'})
  11334. .c('jingle', {
  11335. xmlns: 'urn:xmpp:jingle:1',
  11336. action: 'source-remove',
  11337. initiator: this.initiator,
  11338. sid: this.sid
  11339. }
  11340. );
  11341. var removed = sdpDiffer.toJingle(remove);
  11342. if (removed) {
  11343. this.connection.sendIQ(remove,
  11344. function (res) {
  11345. console.info('got remove result', res);
  11346. },
  11347. function (err) {
  11348. console.error('got remove error', err);
  11349. }
  11350. );
  11351. } else {
  11352. console.log('removal not necessary');
  11353. }
  11354. // send source-add IQ.
  11355. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  11356. var add = $iq({to: this.peerjid, type: 'set'})
  11357. .c('jingle', {
  11358. xmlns: 'urn:xmpp:jingle:1',
  11359. action: 'source-add',
  11360. initiator: this.initiator,
  11361. sid: this.sid
  11362. }
  11363. );
  11364. var added = sdpDiffer.toJingle(add);
  11365. if (added) {
  11366. this.connection.sendIQ(add,
  11367. function (res) {
  11368. console.info('got add result', res);
  11369. },
  11370. function (err) {
  11371. console.error('got add error', err);
  11372. }
  11373. );
  11374. } else {
  11375. console.log('addition not necessary');
  11376. }
  11377. };
  11378. /**
  11379. * Determines whether the (local) video is mute i.e. all video tracks are
  11380. * disabled.
  11381. *
  11382. * @return <tt>true</tt> if the (local) video is mute i.e. all video tracks are
  11383. * disabled; otherwise, <tt>false</tt>
  11384. */
  11385. JingleSession.prototype.isVideoMute = function () {
  11386. var tracks = APP.RTC.localVideo.getVideoTracks();
  11387. var mute = true;
  11388. for (var i = 0; i < tracks.length; ++i) {
  11389. if (tracks[i].enabled) {
  11390. mute = false;
  11391. break;
  11392. }
  11393. }
  11394. return mute;
  11395. };
  11396. /**
  11397. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  11398. *
  11399. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  11400. * tracks; otherwise, <tt>false</tt>
  11401. * @param callback a function to be invoked with <tt>mute</tt> after all video
  11402. * tracks have been enabled/disabled. The function may, optionally, return
  11403. * another function which is to be invoked after the whole mute/unmute operation
  11404. * has completed successfully.
  11405. * @param options an object which specifies optional arguments such as the
  11406. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  11407. * specifies whether the method was initiated in response to a user command (in
  11408. * contrast to an automatic decision made by the application logic)
  11409. */
  11410. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  11411. var byUser;
  11412. if (options) {
  11413. byUser = options.byUser;
  11414. if (typeof byUser === 'undefined') {
  11415. byUser = true;
  11416. }
  11417. } else {
  11418. byUser = true;
  11419. }
  11420. // The user's command to mute the (local) video takes precedence over any
  11421. // automatic decision made by the application logic.
  11422. if (byUser) {
  11423. this.videoMuteByUser = mute;
  11424. } else if (this.videoMuteByUser) {
  11425. return;
  11426. }
  11427. this.hardMuteVideo(mute);
  11428. this.modifySources(callback(mute));
  11429. };
  11430. // SDP-based mute by going recvonly/sendrecv
  11431. // FIXME: should probably black out the screen as well
  11432. JingleSession.prototype.toggleVideoMute = function (callback) {
  11433. this.service.setVideoMute(APP.RTC.localVideo.isMuted(), callback);
  11434. };
  11435. JingleSession.prototype.hardMuteVideo = function (muted) {
  11436. this.pendingop = muted ? 'mute' : 'unmute';
  11437. };
  11438. JingleSession.prototype.sendMute = function (muted, content) {
  11439. var info = $iq({to: this.peerjid,
  11440. type: 'set'})
  11441. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11442. action: 'session-info',
  11443. initiator: this.initiator,
  11444. sid: this.sid });
  11445. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11446. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  11447. if (content) {
  11448. info.attrs({'name': content});
  11449. }
  11450. this.connection.send(info);
  11451. };
  11452. JingleSession.prototype.sendRinging = function () {
  11453. var info = $iq({to: this.peerjid,
  11454. type: 'set'})
  11455. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11456. action: 'session-info',
  11457. initiator: this.initiator,
  11458. sid: this.sid });
  11459. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11460. this.connection.send(info);
  11461. };
  11462. JingleSession.prototype.getStats = function (interval) {
  11463. var self = this;
  11464. var recv = {audio: 0, video: 0};
  11465. var lost = {audio: 0, video: 0};
  11466. var lastrecv = {audio: 0, video: 0};
  11467. var lastlost = {audio: 0, video: 0};
  11468. var loss = {audio: 0, video: 0};
  11469. var delta = {audio: 0, video: 0};
  11470. this.statsinterval = window.setInterval(function () {
  11471. if (self && self.peerconnection && self.peerconnection.getStats) {
  11472. self.peerconnection.getStats(function (stats) {
  11473. var results = stats.result();
  11474. // TODO: there are so much statistics you can get from this..
  11475. for (var i = 0; i < results.length; ++i) {
  11476. if (results[i].type == 'ssrc') {
  11477. var packetsrecv = results[i].stat('packetsReceived');
  11478. var packetslost = results[i].stat('packetsLost');
  11479. if (packetsrecv && packetslost) {
  11480. packetsrecv = parseInt(packetsrecv, 10);
  11481. packetslost = parseInt(packetslost, 10);
  11482. if (results[i].stat('googFrameRateReceived')) {
  11483. lastlost.video = lost.video;
  11484. lastrecv.video = recv.video;
  11485. recv.video = packetsrecv;
  11486. lost.video = packetslost;
  11487. } else {
  11488. lastlost.audio = lost.audio;
  11489. lastrecv.audio = recv.audio;
  11490. recv.audio = packetsrecv;
  11491. lost.audio = packetslost;
  11492. }
  11493. }
  11494. }
  11495. }
  11496. delta.audio = recv.audio - lastrecv.audio;
  11497. delta.video = recv.video - lastrecv.video;
  11498. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  11499. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  11500. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  11501. });
  11502. }
  11503. }, interval || 3000);
  11504. return this.statsinterval;
  11505. };
  11506. JingleSession.onJingleError = function (session, error)
  11507. {
  11508. console.error("Jingle error", error);
  11509. }
  11510. JingleSession.onJingleFatalError = function (session, error)
  11511. {
  11512. this.service.sessionTerminated = true;
  11513. this.connection.emuc.doLeave();
  11514. APP.UI.messageHandler.showError("dialog.sorry",
  11515. "dialog.internalError");
  11516. }
  11517. JingleSession.prototype.setLocalDescription = function () {
  11518. // put our ssrcs into presence so other clients can identify our stream
  11519. var newssrcs = [];
  11520. var media = APP.simulcast.parseMedia(this.peerconnection.localDescription);
  11521. media.forEach(function (media) {
  11522. if(Object.keys(media.sources).length > 0) {
  11523. // TODO(gp) maybe exclude FID streams?
  11524. Object.keys(media.sources).forEach(function (ssrc) {
  11525. newssrcs.push({
  11526. 'ssrc': ssrc,
  11527. 'type': media.type,
  11528. 'direction': media.direction
  11529. });
  11530. });
  11531. }
  11532. else if(this.localStreamsSSRC && this.localStreamsSSRC[media.type])
  11533. {
  11534. newssrcs.push({
  11535. 'ssrc': this.localStreamsSSRC[media.type],
  11536. 'type': media.type,
  11537. 'direction': media.direction
  11538. });
  11539. }
  11540. });
  11541. console.log('new ssrcs', newssrcs);
  11542. // Have to clear presence map to get rid of removed streams
  11543. this.connection.emuc.clearPresenceMedia();
  11544. if (newssrcs.length > 0) {
  11545. for (var i = 1; i <= newssrcs.length; i ++) {
  11546. // Change video type to screen
  11547. if (newssrcs[i-1].type === 'video' && APP.desktopsharing.isUsingScreenStream()) {
  11548. newssrcs[i-1].type = 'screen';
  11549. }
  11550. this.connection.emuc.addMediaToPresence(i,
  11551. newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
  11552. }
  11553. this.connection.emuc.sendPresence();
  11554. }
  11555. }
  11556. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11557. function sendKeyframe(pc) {
  11558. console.log('sendkeyframe', pc.iceConnectionState);
  11559. if (pc.iceConnectionState !== 'connected') return; // safe...
  11560. pc.setRemoteDescription(
  11561. pc.remoteDescription,
  11562. function () {
  11563. pc.createAnswer(
  11564. function (modifiedAnswer) {
  11565. pc.setLocalDescription(
  11566. modifiedAnswer,
  11567. function () {
  11568. // noop
  11569. },
  11570. function (error) {
  11571. console.log('triggerKeyframe setLocalDescription failed', error);
  11572. APP.UI.messageHandler.showError();
  11573. }
  11574. );
  11575. },
  11576. function (error) {
  11577. console.log('triggerKeyframe createAnswer failed', error);
  11578. APP.UI.messageHandler.showError();
  11579. }
  11580. );
  11581. },
  11582. function (error) {
  11583. console.log('triggerKeyframe setRemoteDescription failed', error);
  11584. APP.UI.messageHandler.showError();
  11585. }
  11586. );
  11587. }
  11588. JingleSession.prototype.remoteStreamAdded = function (data, times) {
  11589. var self = this;
  11590. var thessrc;
  11591. var ssrc2jid = this.connection.emuc.ssrc2jid;
  11592. // look up an associated JID for a stream id
  11593. if (data.stream.id && data.stream.id.indexOf('mixedmslabel') === -1) {
  11594. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  11595. var ssrclines
  11596. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  11597. ssrclines = ssrclines.filter(function (line) {
  11598. // NOTE(gp) previously we filtered on the mslabel, but that property
  11599. // is not always present.
  11600. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  11601. return ((line.indexOf('msid:' + data.stream.id) !== -1));
  11602. });
  11603. if (ssrclines.length) {
  11604. thessrc = ssrclines[0].substring(7).split(' ')[0];
  11605. // We signal our streams (through Jingle to the focus) before we set
  11606. // our presence (through which peers associate remote streams to
  11607. // jids). So, it might arrive that a remote stream is added but
  11608. // ssrc2jid is not yet updated and thus data.peerjid cannot be
  11609. // successfully set. Here we wait for up to a second for the
  11610. // presence to arrive.
  11611. if (!ssrc2jid[thessrc]) {
  11612. if (typeof times === 'undefined')
  11613. {
  11614. times = 0;
  11615. }
  11616. if (times > 10)
  11617. {
  11618. console.warning('Waiting for jid timed out', thessrc);
  11619. }
  11620. else
  11621. {
  11622. setTimeout(function(d) {
  11623. return function() {
  11624. self.remoteStreamAdded(d, times++);
  11625. }
  11626. }(data), 250);
  11627. }
  11628. return;
  11629. }
  11630. // ok to overwrite the one from focus? might save work in colibri.js
  11631. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  11632. if (ssrc2jid[thessrc]) {
  11633. data.peerjid = ssrc2jid[thessrc];
  11634. }
  11635. }
  11636. }
  11637. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  11638. var isVideo = data.stream.getVideoTracks().length > 0;
  11639. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11640. if (isVideo &&
  11641. data.peerjid && this.peerjid === data.peerjid &&
  11642. data.stream.getVideoTracks().length === 0 &&
  11643. APP.RTC.localVideo.getTracks().length > 0) {
  11644. window.setTimeout(function () {
  11645. sendKeyframe(self.peerconnection);
  11646. }, 3000);
  11647. }
  11648. }
  11649. module.exports = JingleSession;
  11650. },{"../../service/RTC/RTCBrowserType":88,"./SDP":49,"./SDPDiffer":50,"./SDPUtil":51,"./TraceablePeerConnection":52}],49:[function(require,module,exports){
  11651. /* jshint -W117 */
  11652. var SDPUtil = require("./SDPUtil");
  11653. // SDP STUFF
  11654. function SDP(sdp) {
  11655. this.media = sdp.split('\r\nm=');
  11656. for (var i = 1; i < this.media.length; i++) {
  11657. this.media[i] = 'm=' + this.media[i];
  11658. if (i != this.media.length - 1) {
  11659. this.media[i] += '\r\n';
  11660. }
  11661. }
  11662. this.session = this.media.shift() + '\r\n';
  11663. this.raw = this.session + this.media.join('');
  11664. }
  11665. /**
  11666. * Returns map of MediaChannel mapped per channel idx.
  11667. */
  11668. SDP.prototype.getMediaSsrcMap = function() {
  11669. var self = this;
  11670. var media_ssrcs = {};
  11671. var tmp;
  11672. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  11673. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  11674. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  11675. var media = {
  11676. mediaindex: mediaindex,
  11677. mid: mid,
  11678. ssrcs: {},
  11679. ssrcGroups: []
  11680. };
  11681. media_ssrcs[mediaindex] = media;
  11682. tmp.forEach(function (line) {
  11683. var linessrc = line.substring(7).split(' ')[0];
  11684. // allocate new ChannelSsrc
  11685. if(!media.ssrcs[linessrc]) {
  11686. media.ssrcs[linessrc] = {
  11687. ssrc: linessrc,
  11688. lines: []
  11689. };
  11690. }
  11691. media.ssrcs[linessrc].lines.push(line);
  11692. });
  11693. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  11694. tmp.forEach(function(line){
  11695. var semantics = line.substr(0, idx).substr(13);
  11696. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11697. if (ssrcs.length != 0) {
  11698. media.ssrcGroups.push({
  11699. semantics: semantics,
  11700. ssrcs: ssrcs
  11701. });
  11702. }
  11703. });
  11704. }
  11705. return media_ssrcs;
  11706. };
  11707. /**
  11708. * Returns <tt>true</tt> if this SDP contains given SSRC.
  11709. * @param ssrc the ssrc to check.
  11710. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  11711. */
  11712. SDP.prototype.containsSSRC = function(ssrc) {
  11713. var medias = this.getMediaSsrcMap();
  11714. var contains = false;
  11715. Object.keys(medias).forEach(function(mediaindex){
  11716. var media = medias[mediaindex];
  11717. //console.log("Check", channel, ssrc);
  11718. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  11719. contains = true;
  11720. }
  11721. });
  11722. return contains;
  11723. };
  11724. // remove iSAC and CN from SDP
  11725. SDP.prototype.mangle = function () {
  11726. var i, j, mline, lines, rtpmap, newdesc;
  11727. for (i = 0; i < this.media.length; i++) {
  11728. lines = this.media[i].split('\r\n');
  11729. lines.pop(); // remove empty last element
  11730. mline = SDPUtil.parse_mline(lines.shift());
  11731. if (mline.media != 'audio')
  11732. continue;
  11733. newdesc = '';
  11734. mline.fmt.length = 0;
  11735. for (j = 0; j < lines.length; j++) {
  11736. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  11737. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  11738. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  11739. continue;
  11740. mline.fmt.push(rtpmap.id);
  11741. newdesc += lines[j] + '\r\n';
  11742. } else {
  11743. newdesc += lines[j] + '\r\n';
  11744. }
  11745. }
  11746. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  11747. this.media[i] += newdesc;
  11748. }
  11749. this.raw = this.session + this.media.join('');
  11750. };
  11751. // remove lines matching prefix from session section
  11752. SDP.prototype.removeSessionLines = function(prefix) {
  11753. var self = this;
  11754. var lines = SDPUtil.find_lines(this.session, prefix);
  11755. lines.forEach(function(line) {
  11756. self.session = self.session.replace(line + '\r\n', '');
  11757. });
  11758. this.raw = this.session + this.media.join('');
  11759. return lines;
  11760. }
  11761. // remove lines matching prefix from a media section specified by mediaindex
  11762. // TODO: non-numeric mediaindex could match mid
  11763. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  11764. var self = this;
  11765. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  11766. lines.forEach(function(line) {
  11767. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  11768. });
  11769. this.raw = this.session + this.media.join('');
  11770. return lines;
  11771. }
  11772. // add content's to a jingle element
  11773. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  11774. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  11775. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  11776. var self = this;
  11777. // new bundle plan
  11778. if (SDPUtil.find_line(this.session, 'a=group:')) {
  11779. lines = SDPUtil.find_lines(this.session, 'a=group:');
  11780. for (i = 0; i < lines.length; i++) {
  11781. tmp = lines[i].split(' ');
  11782. var semantics = tmp.shift().substr(8);
  11783. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  11784. for (j = 0; j < tmp.length; j++) {
  11785. elem.c('content', {name: tmp[j]}).up();
  11786. }
  11787. elem.up();
  11788. }
  11789. }
  11790. for (i = 0; i < this.media.length; i++) {
  11791. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  11792. if (!(mline.media === 'audio' ||
  11793. mline.media === 'video' ||
  11794. mline.media === 'application'))
  11795. {
  11796. continue;
  11797. }
  11798. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  11799. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  11800. } else {
  11801. if(ssrcs && ssrcs[mline.media])
  11802. {
  11803. ssrc = ssrcs[mline.media];
  11804. }
  11805. else
  11806. ssrc = false;
  11807. }
  11808. elem.c('content', {creator: thecreator, name: mline.media});
  11809. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  11810. // prefer identifier from a=mid if present
  11811. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  11812. elem.attrs({ name: mid });
  11813. }
  11814. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  11815. {
  11816. elem.c('description',
  11817. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  11818. media: mline.media });
  11819. if (ssrc) {
  11820. elem.attrs({ssrc: ssrc});
  11821. }
  11822. for (j = 0; j < mline.fmt.length; j++) {
  11823. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  11824. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  11825. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  11826. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  11827. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  11828. for (k = 0; k < tmp.length; k++) {
  11829. elem.c('parameter', tmp[k]).up();
  11830. }
  11831. }
  11832. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  11833. elem.up();
  11834. }
  11835. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  11836. elem.c('encryption', {required: 1});
  11837. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  11838. crypto.forEach(function(line) {
  11839. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  11840. });
  11841. elem.up(); // end of encryption
  11842. }
  11843. if (ssrc) {
  11844. // new style mapping
  11845. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11846. // FIXME: group by ssrc and support multiple different ssrcs
  11847. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  11848. if(ssrclines.length > 0) {
  11849. ssrclines.forEach(function (line) {
  11850. idx = line.indexOf(' ');
  11851. var linessrc = line.substr(0, idx).substr(7);
  11852. if (linessrc != ssrc) {
  11853. elem.up();
  11854. ssrc = linessrc;
  11855. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11856. }
  11857. var kv = line.substr(idx + 1);
  11858. elem.c('parameter');
  11859. if (kv.indexOf(':') == -1) {
  11860. elem.attrs({ name: kv });
  11861. } else {
  11862. elem.attrs({ name: kv.split(':', 2)[0] });
  11863. elem.attrs({ value: kv.split(':', 2)[1] });
  11864. }
  11865. elem.up();
  11866. });
  11867. elem.up();
  11868. }
  11869. else
  11870. {
  11871. elem.up();
  11872. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11873. elem.c('parameter');
  11874. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  11875. elem.up();
  11876. var msid = null;
  11877. if(mline.media == "audio")
  11878. {
  11879. msid = APP.RTC.localAudio.getId();
  11880. }
  11881. else
  11882. {
  11883. msid = APP.RTC.localVideo.getId();
  11884. }
  11885. if(msid != null)
  11886. {
  11887. msid = msid.replace(/[\{,\}]/g,"");
  11888. elem.c('parameter');
  11889. elem.attrs({name: "msid", value:msid});
  11890. elem.up();
  11891. elem.c('parameter');
  11892. elem.attrs({name: "mslabel", value:msid});
  11893. elem.up();
  11894. elem.c('parameter');
  11895. elem.attrs({name: "label", value:msid});
  11896. elem.up();
  11897. elem.up();
  11898. }
  11899. }
  11900. // XEP-0339 handle ssrc-group attributes
  11901. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  11902. ssrc_group_lines.forEach(function(line) {
  11903. idx = line.indexOf(' ');
  11904. var semantics = line.substr(0, idx).substr(13);
  11905. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11906. if (ssrcs.length != 0) {
  11907. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11908. ssrcs.forEach(function(ssrc) {
  11909. elem.c('source', { ssrc: ssrc })
  11910. .up();
  11911. });
  11912. elem.up();
  11913. }
  11914. });
  11915. }
  11916. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  11917. elem.c('rtcp-mux').up();
  11918. }
  11919. // XEP-0293 -- map a=rtcp-fb:*
  11920. this.RtcpFbToJingle(i, elem, '*');
  11921. // XEP-0294
  11922. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  11923. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  11924. for (j = 0; j < lines.length; j++) {
  11925. tmp = SDPUtil.parse_extmap(lines[j]);
  11926. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  11927. uri: tmp.uri,
  11928. id: tmp.value });
  11929. if (tmp.hasOwnProperty('direction')) {
  11930. switch (tmp.direction) {
  11931. case 'sendonly':
  11932. elem.attrs({senders: 'responder'});
  11933. break;
  11934. case 'recvonly':
  11935. elem.attrs({senders: 'initiator'});
  11936. break;
  11937. case 'sendrecv':
  11938. elem.attrs({senders: 'both'});
  11939. break;
  11940. case 'inactive':
  11941. elem.attrs({senders: 'none'});
  11942. break;
  11943. }
  11944. }
  11945. // TODO: handle params
  11946. elem.up();
  11947. }
  11948. }
  11949. elem.up(); // end of description
  11950. }
  11951. // map ice-ufrag/pwd, dtls fingerprint, candidates
  11952. this.TransportToJingle(i, elem);
  11953. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  11954. elem.attrs({senders: 'both'});
  11955. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  11956. elem.attrs({senders: 'initiator'});
  11957. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  11958. elem.attrs({senders: 'responder'});
  11959. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  11960. elem.attrs({senders: 'none'});
  11961. }
  11962. if (mline.port == '0') {
  11963. // estos hack to reject an m-line
  11964. elem.attrs({senders: 'rejected'});
  11965. }
  11966. elem.up(); // end of content
  11967. }
  11968. elem.up();
  11969. return elem;
  11970. };
  11971. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  11972. var i = mediaindex;
  11973. var tmp;
  11974. var self = this;
  11975. elem.c('transport');
  11976. // XEP-0343 DTLS/SCTP
  11977. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  11978. {
  11979. var sctpmap = SDPUtil.find_line(
  11980. this.media[i], 'a=sctpmap:', self.session);
  11981. if (sctpmap)
  11982. {
  11983. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  11984. elem.c('sctpmap',
  11985. {
  11986. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  11987. number: sctpAttrs[0], /* SCTP port */
  11988. protocol: sctpAttrs[1], /* protocol */
  11989. });
  11990. // Optional stream count attribute
  11991. if (sctpAttrs.length > 2)
  11992. elem.attrs({ streams: sctpAttrs[2]});
  11993. elem.up();
  11994. }
  11995. }
  11996. // XEP-0320
  11997. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  11998. fingerprints.forEach(function(line) {
  11999. tmp = SDPUtil.parse_fingerprint(line);
  12000. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  12001. elem.c('fingerprint').t(tmp.fingerprint);
  12002. delete tmp.fingerprint;
  12003. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  12004. if (line) {
  12005. tmp.setup = line.substr(8);
  12006. }
  12007. elem.attrs(tmp);
  12008. elem.up(); // end of fingerprint
  12009. });
  12010. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  12011. if (tmp) {
  12012. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  12013. elem.attrs(tmp);
  12014. // XEP-0176
  12015. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  12016. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  12017. lines.forEach(function (line) {
  12018. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  12019. });
  12020. }
  12021. }
  12022. elem.up(); // end of transport
  12023. }
  12024. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  12025. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  12026. lines.forEach(function (line) {
  12027. var tmp = SDPUtil.parse_rtcpfb(line);
  12028. if (tmp.type == 'trr-int') {
  12029. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  12030. elem.up();
  12031. } else {
  12032. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  12033. if (tmp.params.length > 0) {
  12034. elem.attrs({'subtype': tmp.params[0]});
  12035. }
  12036. elem.up();
  12037. }
  12038. });
  12039. };
  12040. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  12041. var media = '';
  12042. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  12043. if (tmp.length) {
  12044. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  12045. if (tmp.attr('value')) {
  12046. media += tmp.attr('value');
  12047. } else {
  12048. media += '0';
  12049. }
  12050. media += '\r\n';
  12051. }
  12052. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  12053. tmp.each(function () {
  12054. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  12055. if ($(this).attr('subtype')) {
  12056. media += ' ' + $(this).attr('subtype');
  12057. }
  12058. media += '\r\n';
  12059. });
  12060. return media;
  12061. };
  12062. // construct an SDP from a jingle stanza
  12063. SDP.prototype.fromJingle = function (jingle) {
  12064. var self = this;
  12065. this.raw = 'v=0\r\n' +
  12066. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  12067. 's=-\r\n' +
  12068. 't=0 0\r\n';
  12069. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  12070. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  12071. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  12072. var contents = $(group).find('>content').map(function (idx, content) {
  12073. return content.getAttribute('name');
  12074. }).get();
  12075. if (contents.length > 0) {
  12076. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  12077. }
  12078. });
  12079. }
  12080. this.session = this.raw;
  12081. jingle.find('>content').each(function () {
  12082. var m = self.jingle2media($(this));
  12083. self.media.push(m);
  12084. });
  12085. // reconstruct msid-semantic -- apparently not necessary
  12086. /*
  12087. var msid = SDPUtil.parse_ssrc(this.raw);
  12088. if (msid.hasOwnProperty('mslabel')) {
  12089. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  12090. }
  12091. */
  12092. this.raw = this.session + this.media.join('');
  12093. };
  12094. // translate a jingle content element into an an SDP media part
  12095. SDP.prototype.jingle2media = function (content) {
  12096. var media = '',
  12097. desc = content.find('description'),
  12098. ssrc = desc.attr('ssrc'),
  12099. self = this,
  12100. tmp;
  12101. var sctp = content.find(
  12102. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  12103. tmp = { media: desc.attr('media') };
  12104. tmp.port = '1';
  12105. if (content.attr('senders') == 'rejected') {
  12106. // estos hack to reject an m-line.
  12107. tmp.port = '0';
  12108. }
  12109. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  12110. if (sctp.length)
  12111. tmp.proto = 'DTLS/SCTP';
  12112. else
  12113. tmp.proto = 'RTP/SAVPF';
  12114. } else {
  12115. tmp.proto = 'RTP/AVPF';
  12116. }
  12117. if (!sctp.length)
  12118. {
  12119. tmp.fmt = desc.find('payload-type').map(
  12120. function () { return this.getAttribute('id'); }).get();
  12121. media += SDPUtil.build_mline(tmp) + '\r\n';
  12122. }
  12123. else
  12124. {
  12125. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  12126. media += 'a=sctpmap:' + sctp.attr('number') +
  12127. ' ' + sctp.attr('protocol');
  12128. var streamCount = sctp.attr('streams');
  12129. if (streamCount)
  12130. media += ' ' + streamCount + '\r\n';
  12131. else
  12132. media += '\r\n';
  12133. }
  12134. media += 'c=IN IP4 0.0.0.0\r\n';
  12135. if (!sctp.length)
  12136. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  12137. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  12138. if (tmp.length) {
  12139. if (tmp.attr('ufrag')) {
  12140. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  12141. }
  12142. if (tmp.attr('pwd')) {
  12143. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  12144. }
  12145. tmp.find('>fingerprint').each(function () {
  12146. // FIXME: check namespace at some point
  12147. media += 'a=fingerprint:' + this.getAttribute('hash');
  12148. media += ' ' + $(this).text();
  12149. media += '\r\n';
  12150. if (this.getAttribute('setup')) {
  12151. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  12152. }
  12153. });
  12154. }
  12155. switch (content.attr('senders')) {
  12156. case 'initiator':
  12157. media += 'a=sendonly\r\n';
  12158. break;
  12159. case 'responder':
  12160. media += 'a=recvonly\r\n';
  12161. break;
  12162. case 'none':
  12163. media += 'a=inactive\r\n';
  12164. break;
  12165. case 'both':
  12166. media += 'a=sendrecv\r\n';
  12167. break;
  12168. }
  12169. media += 'a=mid:' + content.attr('name') + '\r\n';
  12170. // <description><rtcp-mux/></description>
  12171. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  12172. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  12173. if (desc.find('rtcp-mux').length) {
  12174. media += 'a=rtcp-mux\r\n';
  12175. }
  12176. if (desc.find('encryption').length) {
  12177. desc.find('encryption>crypto').each(function () {
  12178. media += 'a=crypto:' + this.getAttribute('tag');
  12179. media += ' ' + this.getAttribute('crypto-suite');
  12180. media += ' ' + this.getAttribute('key-params');
  12181. if (this.getAttribute('session-params')) {
  12182. media += ' ' + this.getAttribute('session-params');
  12183. }
  12184. media += '\r\n';
  12185. });
  12186. }
  12187. desc.find('payload-type').each(function () {
  12188. media += SDPUtil.build_rtpmap(this) + '\r\n';
  12189. if ($(this).find('>parameter').length) {
  12190. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  12191. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  12192. media += '\r\n';
  12193. }
  12194. // xep-0293
  12195. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  12196. });
  12197. // xep-0293
  12198. media += self.RtcpFbFromJingle(desc, '*');
  12199. // xep-0294
  12200. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  12201. tmp.each(function () {
  12202. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  12203. });
  12204. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  12205. media += SDPUtil.candidateFromJingle(this);
  12206. });
  12207. // XEP-0339 handle ssrc-group attributes
  12208. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12209. var semantics = this.getAttribute('semantics');
  12210. var ssrcs = $(this).find('>source').map(function() {
  12211. return this.getAttribute('ssrc');
  12212. }).get();
  12213. if (ssrcs.length != 0) {
  12214. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12215. }
  12216. });
  12217. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  12218. tmp.each(function () {
  12219. var ssrc = this.getAttribute('ssrc');
  12220. $(this).find('>parameter').each(function () {
  12221. media += 'a=ssrc:' + ssrc + ' ' + this.getAttribute('name');
  12222. if (this.getAttribute('value') && this.getAttribute('value').length)
  12223. media += ':' + this.getAttribute('value');
  12224. media += '\r\n';
  12225. });
  12226. });
  12227. return media;
  12228. };
  12229. module.exports = SDP;
  12230. },{"./SDPUtil":51}],50:[function(require,module,exports){
  12231. function SDPDiffer(mySDP, otherSDP) {
  12232. this.mySDP = mySDP;
  12233. this.otherSDP = otherSDP;
  12234. }
  12235. /**
  12236. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  12237. * @param otherSdp the other SDP to check ssrc with.
  12238. */
  12239. SDPDiffer.prototype.getNewMedia = function() {
  12240. // this could be useful in Array.prototype.
  12241. function arrayEquals(array) {
  12242. // if the other array is a falsy value, return
  12243. if (!array)
  12244. return false;
  12245. // compare lengths - can save a lot of time
  12246. if (this.length != array.length)
  12247. return false;
  12248. for (var i = 0, l=this.length; i < l; i++) {
  12249. // Check if we have nested arrays
  12250. if (this[i] instanceof Array && array[i] instanceof Array) {
  12251. // recurse into the nested arrays
  12252. if (!this[i].equals(array[i]))
  12253. return false;
  12254. }
  12255. else if (this[i] != array[i]) {
  12256. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  12257. return false;
  12258. }
  12259. }
  12260. return true;
  12261. }
  12262. var myMedias = this.mySDP.getMediaSsrcMap();
  12263. var othersMedias = this.otherSDP.getMediaSsrcMap();
  12264. var newMedia = {};
  12265. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  12266. var myMedia = myMedias[othersMediaIdx];
  12267. var othersMedia = othersMedias[othersMediaIdx];
  12268. if(!myMedia && othersMedia) {
  12269. // Add whole channel
  12270. newMedia[othersMediaIdx] = othersMedia;
  12271. return;
  12272. }
  12273. // Look for new ssrcs accross the channel
  12274. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  12275. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  12276. // Allocate channel if we've found ssrc that doesn't exist in our channel
  12277. if(!newMedia[othersMediaIdx]){
  12278. newMedia[othersMediaIdx] = {
  12279. mediaindex: othersMedia.mediaindex,
  12280. mid: othersMedia.mid,
  12281. ssrcs: {},
  12282. ssrcGroups: []
  12283. };
  12284. }
  12285. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  12286. }
  12287. });
  12288. // Look for new ssrc groups across the channels
  12289. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  12290. // try to match the other ssrc-group with an ssrc-group of ours
  12291. var matched = false;
  12292. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  12293. var mySsrcGroup = myMedia.ssrcGroups[i];
  12294. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  12295. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  12296. matched = true;
  12297. break;
  12298. }
  12299. }
  12300. if (!matched) {
  12301. // Allocate channel if we've found an ssrc-group that doesn't
  12302. // exist in our channel
  12303. if(!newMedia[othersMediaIdx]){
  12304. newMedia[othersMediaIdx] = {
  12305. mediaindex: othersMedia.mediaindex,
  12306. mid: othersMedia.mid,
  12307. ssrcs: {},
  12308. ssrcGroups: []
  12309. };
  12310. }
  12311. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  12312. }
  12313. });
  12314. });
  12315. return newMedia;
  12316. };
  12317. /**
  12318. * Sends SSRC update IQ.
  12319. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  12320. * @param sid session identifier that will be put into the IQ.
  12321. * @param initiator initiator identifier.
  12322. * @param toJid destination Jid
  12323. * @param isAdd indicates if this is remove or add operation.
  12324. */
  12325. SDPDiffer.prototype.toJingle = function(modify) {
  12326. var sdpMediaSsrcs = this.getNewMedia();
  12327. var self = this;
  12328. // FIXME: only announce video ssrcs since we mix audio and dont need
  12329. // the audio ssrcs therefore
  12330. var modified = false;
  12331. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  12332. modified = true;
  12333. var media = sdpMediaSsrcs[mediaindex];
  12334. modify.c('content', {name: media.mid});
  12335. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  12336. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  12337. // generate sources from lines
  12338. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  12339. var mediaSsrc = media.ssrcs[ssrcNum];
  12340. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12341. modify.attrs({ssrc: mediaSsrc.ssrc});
  12342. // iterate over ssrc lines
  12343. mediaSsrc.lines.forEach(function (line) {
  12344. var idx = line.indexOf(' ');
  12345. var kv = line.substr(idx + 1);
  12346. modify.c('parameter');
  12347. if (kv.indexOf(':') == -1) {
  12348. modify.attrs({ name: kv });
  12349. } else {
  12350. modify.attrs({ name: kv.split(':', 2)[0] });
  12351. modify.attrs({ value: kv.split(':', 2)[1] });
  12352. }
  12353. modify.up(); // end of parameter
  12354. });
  12355. modify.up(); // end of source
  12356. });
  12357. // generate source groups from lines
  12358. media.ssrcGroups.forEach(function(ssrcGroup) {
  12359. if (ssrcGroup.ssrcs.length != 0) {
  12360. modify.c('ssrc-group', {
  12361. semantics: ssrcGroup.semantics,
  12362. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  12363. });
  12364. ssrcGroup.ssrcs.forEach(function (ssrc) {
  12365. modify.c('source', { ssrc: ssrc })
  12366. .up(); // end of source
  12367. });
  12368. modify.up(); // end of ssrc-group
  12369. }
  12370. });
  12371. modify.up(); // end of description
  12372. modify.up(); // end of content
  12373. });
  12374. return modified;
  12375. };
  12376. module.exports = SDPDiffer;
  12377. },{}],51:[function(require,module,exports){
  12378. SDPUtil = {
  12379. iceparams: function (mediadesc, sessiondesc) {
  12380. var data = null;
  12381. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  12382. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  12383. data = {
  12384. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  12385. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  12386. };
  12387. }
  12388. return data;
  12389. },
  12390. parse_iceufrag: function (line) {
  12391. return line.substring(12);
  12392. },
  12393. build_iceufrag: function (frag) {
  12394. return 'a=ice-ufrag:' + frag;
  12395. },
  12396. parse_icepwd: function (line) {
  12397. return line.substring(10);
  12398. },
  12399. build_icepwd: function (pwd) {
  12400. return 'a=ice-pwd:' + pwd;
  12401. },
  12402. parse_mid: function (line) {
  12403. return line.substring(6);
  12404. },
  12405. parse_mline: function (line) {
  12406. var parts = line.substring(2).split(' '),
  12407. data = {};
  12408. data.media = parts.shift();
  12409. data.port = parts.shift();
  12410. data.proto = parts.shift();
  12411. if (parts[parts.length - 1] === '') { // trailing whitespace
  12412. parts.pop();
  12413. }
  12414. data.fmt = parts;
  12415. return data;
  12416. },
  12417. build_mline: function (mline) {
  12418. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  12419. },
  12420. parse_rtpmap: function (line) {
  12421. var parts = line.substring(9).split(' '),
  12422. data = {};
  12423. data.id = parts.shift();
  12424. parts = parts[0].split('/');
  12425. data.name = parts.shift();
  12426. data.clockrate = parts.shift();
  12427. data.channels = parts.length ? parts.shift() : '1';
  12428. return data;
  12429. },
  12430. /**
  12431. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  12432. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  12433. * @returns [SCTP port number, protocol, streams]
  12434. */
  12435. parse_sctpmap: function (line)
  12436. {
  12437. var parts = line.substring(10).split(' ');
  12438. var sctpPort = parts[0];
  12439. var protocol = parts[1];
  12440. // Stream count is optional
  12441. var streamCount = parts.length > 2 ? parts[2] : null;
  12442. return [sctpPort, protocol, streamCount];// SCTP port
  12443. },
  12444. build_rtpmap: function (el) {
  12445. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  12446. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  12447. line += '/' + el.getAttribute('channels');
  12448. }
  12449. return line;
  12450. },
  12451. parse_crypto: function (line) {
  12452. var parts = line.substring(9).split(' '),
  12453. data = {};
  12454. data.tag = parts.shift();
  12455. data['crypto-suite'] = parts.shift();
  12456. data['key-params'] = parts.shift();
  12457. if (parts.length) {
  12458. data['session-params'] = parts.join(' ');
  12459. }
  12460. return data;
  12461. },
  12462. parse_fingerprint: function (line) { // RFC 4572
  12463. var parts = line.substring(14).split(' '),
  12464. data = {};
  12465. data.hash = parts.shift();
  12466. data.fingerprint = parts.shift();
  12467. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  12468. return data;
  12469. },
  12470. parse_fmtp: function (line) {
  12471. var parts = line.split(' '),
  12472. i, key, value,
  12473. data = [];
  12474. parts.shift();
  12475. parts = parts.join(' ').split(';');
  12476. for (i = 0; i < parts.length; i++) {
  12477. key = parts[i].split('=')[0];
  12478. while (key.length && key[0] == ' ') {
  12479. key = key.substring(1);
  12480. }
  12481. value = parts[i].split('=')[1];
  12482. if (key && value) {
  12483. data.push({name: key, value: value});
  12484. } else if (key) {
  12485. // rfc 4733 (DTMF) style stuff
  12486. data.push({name: '', value: key});
  12487. }
  12488. }
  12489. return data;
  12490. },
  12491. parse_icecandidate: function (line) {
  12492. var candidate = {},
  12493. elems = line.split(' ');
  12494. candidate.foundation = elems[0].substring(12);
  12495. candidate.component = elems[1];
  12496. candidate.protocol = elems[2].toLowerCase();
  12497. candidate.priority = elems[3];
  12498. candidate.ip = elems[4];
  12499. candidate.port = elems[5];
  12500. // elems[6] => "typ"
  12501. candidate.type = elems[7];
  12502. candidate.generation = 0; // default value, may be overwritten below
  12503. for (var i = 8; i < elems.length; i += 2) {
  12504. switch (elems[i]) {
  12505. case 'raddr':
  12506. candidate['rel-addr'] = elems[i + 1];
  12507. break;
  12508. case 'rport':
  12509. candidate['rel-port'] = elems[i + 1];
  12510. break;
  12511. case 'generation':
  12512. candidate.generation = elems[i + 1];
  12513. break;
  12514. case 'tcptype':
  12515. candidate.tcptype = elems[i + 1];
  12516. break;
  12517. default: // TODO
  12518. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12519. }
  12520. }
  12521. candidate.network = '1';
  12522. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12523. return candidate;
  12524. },
  12525. build_icecandidate: function (cand) {
  12526. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  12527. line += ' ';
  12528. switch (cand.type) {
  12529. case 'srflx':
  12530. case 'prflx':
  12531. case 'relay':
  12532. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  12533. line += 'raddr';
  12534. line += ' ';
  12535. line += cand['rel-addr'];
  12536. line += ' ';
  12537. line += 'rport';
  12538. line += ' ';
  12539. line += cand['rel-port'];
  12540. line += ' ';
  12541. }
  12542. break;
  12543. }
  12544. if (cand.hasOwnAttribute('tcptype')) {
  12545. line += 'tcptype';
  12546. line += ' ';
  12547. line += cand.tcptype;
  12548. line += ' ';
  12549. }
  12550. line += 'generation';
  12551. line += ' ';
  12552. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  12553. return line;
  12554. },
  12555. parse_ssrc: function (desc) {
  12556. // proprietary mapping of a=ssrc lines
  12557. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  12558. // and parse according to that
  12559. var lines = desc.split('\r\n'),
  12560. data = {};
  12561. for (var i = 0; i < lines.length; i++) {
  12562. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  12563. var idx = lines[i].indexOf(' ');
  12564. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  12565. }
  12566. }
  12567. return data;
  12568. },
  12569. parse_rtcpfb: function (line) {
  12570. var parts = line.substr(10).split(' ');
  12571. var data = {};
  12572. data.pt = parts.shift();
  12573. data.type = parts.shift();
  12574. data.params = parts;
  12575. return data;
  12576. },
  12577. parse_extmap: function (line) {
  12578. var parts = line.substr(9).split(' ');
  12579. var data = {};
  12580. data.value = parts.shift();
  12581. if (data.value.indexOf('/') != -1) {
  12582. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  12583. data.value = data.value.substr(0, data.value.indexOf('/'));
  12584. } else {
  12585. data.direction = 'both';
  12586. }
  12587. data.uri = parts.shift();
  12588. data.params = parts;
  12589. return data;
  12590. },
  12591. find_line: function (haystack, needle, sessionpart) {
  12592. var lines = haystack.split('\r\n');
  12593. for (var i = 0; i < lines.length; i++) {
  12594. if (lines[i].substring(0, needle.length) == needle) {
  12595. return lines[i];
  12596. }
  12597. }
  12598. if (!sessionpart) {
  12599. return false;
  12600. }
  12601. // search session part
  12602. lines = sessionpart.split('\r\n');
  12603. for (var j = 0; j < lines.length; j++) {
  12604. if (lines[j].substring(0, needle.length) == needle) {
  12605. return lines[j];
  12606. }
  12607. }
  12608. return false;
  12609. },
  12610. find_lines: function (haystack, needle, sessionpart) {
  12611. var lines = haystack.split('\r\n'),
  12612. needles = [];
  12613. for (var i = 0; i < lines.length; i++) {
  12614. if (lines[i].substring(0, needle.length) == needle)
  12615. needles.push(lines[i]);
  12616. }
  12617. if (needles.length || !sessionpart) {
  12618. return needles;
  12619. }
  12620. // search session part
  12621. lines = sessionpart.split('\r\n');
  12622. for (var j = 0; j < lines.length; j++) {
  12623. if (lines[j].substring(0, needle.length) == needle) {
  12624. needles.push(lines[j]);
  12625. }
  12626. }
  12627. return needles;
  12628. },
  12629. candidateToJingle: function (line) {
  12630. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  12631. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  12632. if (line.indexOf('candidate:') === 0) {
  12633. line = 'a=' + line;
  12634. } else if (line.substring(0, 12) != 'a=candidate:') {
  12635. console.log('parseCandidate called with a line that is not a candidate line');
  12636. console.log(line);
  12637. return null;
  12638. }
  12639. if (line.substring(line.length - 2) == '\r\n') // chomp it
  12640. line = line.substring(0, line.length - 2);
  12641. var candidate = {},
  12642. elems = line.split(' '),
  12643. i;
  12644. if (elems[6] != 'typ') {
  12645. console.log('did not find typ in the right place');
  12646. console.log(line);
  12647. return null;
  12648. }
  12649. candidate.foundation = elems[0].substring(12);
  12650. candidate.component = elems[1];
  12651. candidate.protocol = elems[2].toLowerCase();
  12652. candidate.priority = elems[3];
  12653. candidate.ip = elems[4];
  12654. candidate.port = elems[5];
  12655. // elems[6] => "typ"
  12656. candidate.type = elems[7];
  12657. candidate.generation = '0'; // default, may be overwritten below
  12658. for (i = 8; i < elems.length; i += 2) {
  12659. switch (elems[i]) {
  12660. case 'raddr':
  12661. candidate['rel-addr'] = elems[i + 1];
  12662. break;
  12663. case 'rport':
  12664. candidate['rel-port'] = elems[i + 1];
  12665. break;
  12666. case 'generation':
  12667. candidate.generation = elems[i + 1];
  12668. break;
  12669. case 'tcptype':
  12670. candidate.tcptype = elems[i + 1];
  12671. break;
  12672. default: // TODO
  12673. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12674. }
  12675. }
  12676. candidate.network = '1';
  12677. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12678. return candidate;
  12679. },
  12680. candidateFromJingle: function (cand) {
  12681. var line = 'a=candidate:';
  12682. line += cand.getAttribute('foundation');
  12683. line += ' ';
  12684. line += cand.getAttribute('component');
  12685. line += ' ';
  12686. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  12687. line += ' ';
  12688. line += cand.getAttribute('priority');
  12689. line += ' ';
  12690. line += cand.getAttribute('ip');
  12691. line += ' ';
  12692. line += cand.getAttribute('port');
  12693. line += ' ';
  12694. line += 'typ';
  12695. line += ' ' + cand.getAttribute('type');
  12696. line += ' ';
  12697. switch (cand.getAttribute('type')) {
  12698. case 'srflx':
  12699. case 'prflx':
  12700. case 'relay':
  12701. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  12702. line += 'raddr';
  12703. line += ' ';
  12704. line += cand.getAttribute('rel-addr');
  12705. line += ' ';
  12706. line += 'rport';
  12707. line += ' ';
  12708. line += cand.getAttribute('rel-port');
  12709. line += ' ';
  12710. }
  12711. break;
  12712. }
  12713. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  12714. line += 'tcptype';
  12715. line += ' ';
  12716. line += cand.getAttribute('tcptype');
  12717. line += ' ';
  12718. }
  12719. line += 'generation';
  12720. line += ' ';
  12721. line += cand.getAttribute('generation') || '0';
  12722. return line + '\r\n';
  12723. }
  12724. };
  12725. module.exports = SDPUtil;
  12726. },{}],52:[function(require,module,exports){
  12727. function TraceablePeerConnection(ice_config, constraints) {
  12728. var self = this;
  12729. var RTCPeerconnection = navigator.mozGetUserMedia ? mozRTCPeerConnection : webkitRTCPeerConnection;
  12730. this.peerconnection = new RTCPeerconnection(ice_config, constraints);
  12731. this.updateLog = [];
  12732. this.stats = {};
  12733. this.statsinterval = null;
  12734. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  12735. var Interop = require('sdp-interop').Interop;
  12736. this.interop = new Interop();
  12737. // override as desired
  12738. this.trace = function (what, info) {
  12739. //console.warn('WTRACE', what, info);
  12740. self.updateLog.push({
  12741. time: new Date(),
  12742. type: what,
  12743. value: info || ""
  12744. });
  12745. };
  12746. this.onicecandidate = null;
  12747. this.peerconnection.onicecandidate = function (event) {
  12748. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  12749. if (self.onicecandidate !== null) {
  12750. self.onicecandidate(event);
  12751. }
  12752. };
  12753. this.onaddstream = null;
  12754. this.peerconnection.onaddstream = function (event) {
  12755. self.trace('onaddstream', event.stream.id);
  12756. if (self.onaddstream !== null) {
  12757. self.onaddstream(event);
  12758. }
  12759. };
  12760. this.onremovestream = null;
  12761. this.peerconnection.onremovestream = function (event) {
  12762. self.trace('onremovestream', event.stream.id);
  12763. if (self.onremovestream !== null) {
  12764. self.onremovestream(event);
  12765. }
  12766. };
  12767. this.onsignalingstatechange = null;
  12768. this.peerconnection.onsignalingstatechange = function (event) {
  12769. self.trace('onsignalingstatechange', self.signalingState);
  12770. if (self.onsignalingstatechange !== null) {
  12771. self.onsignalingstatechange(event);
  12772. }
  12773. };
  12774. this.oniceconnectionstatechange = null;
  12775. this.peerconnection.oniceconnectionstatechange = function (event) {
  12776. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  12777. if (self.oniceconnectionstatechange !== null) {
  12778. self.oniceconnectionstatechange(event);
  12779. }
  12780. };
  12781. this.onnegotiationneeded = null;
  12782. this.peerconnection.onnegotiationneeded = function (event) {
  12783. self.trace('onnegotiationneeded');
  12784. if (self.onnegotiationneeded !== null) {
  12785. self.onnegotiationneeded(event);
  12786. }
  12787. };
  12788. self.ondatachannel = null;
  12789. this.peerconnection.ondatachannel = function (event) {
  12790. self.trace('ondatachannel', event);
  12791. if (self.ondatachannel !== null) {
  12792. self.ondatachannel(event);
  12793. }
  12794. };
  12795. if (!navigator.mozGetUserMedia && this.maxstats) {
  12796. this.statsinterval = window.setInterval(function() {
  12797. self.peerconnection.getStats(function(stats) {
  12798. var results = stats.result();
  12799. for (var i = 0; i < results.length; ++i) {
  12800. //console.log(results[i].type, results[i].id, results[i].names())
  12801. var now = new Date();
  12802. results[i].names().forEach(function (name) {
  12803. var id = results[i].id + '-' + name;
  12804. if (!self.stats[id]) {
  12805. self.stats[id] = {
  12806. startTime: now,
  12807. endTime: now,
  12808. values: [],
  12809. times: []
  12810. };
  12811. }
  12812. self.stats[id].values.push(results[i].stat(name));
  12813. self.stats[id].times.push(now.getTime());
  12814. if (self.stats[id].values.length > self.maxstats) {
  12815. self.stats[id].values.shift();
  12816. self.stats[id].times.shift();
  12817. }
  12818. self.stats[id].endTime = now;
  12819. });
  12820. }
  12821. });
  12822. }, 1000);
  12823. }
  12824. };
  12825. dumpSDP = function(description) {
  12826. if (typeof description === 'undefined' || description == null) {
  12827. return '';
  12828. }
  12829. return 'type: ' + description.type + '\r\n' + description.sdp;
  12830. };
  12831. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  12832. TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
  12833. TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
  12834. TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() {
  12835. this.trace('getLocalDescription::preTransform (Plan A)', dumpSDP(this.peerconnection.localDescription));
  12836. // if we're running on FF, transform to Plan B first.
  12837. var desc = this.peerconnection.localDescription;
  12838. if (navigator.mozGetUserMedia) {
  12839. desc = this.interop.toPlanB(desc);
  12840. } else {
  12841. desc = APP.simulcast.reverseTransformLocalDescription(this.peerconnection.localDescription);
  12842. }
  12843. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  12844. return desc;
  12845. });
  12846. TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() {
  12847. this.trace('getRemoteDescription::preTransform (Plan A)', dumpSDP(this.peerconnection.remoteDescription));
  12848. // if we're running on FF, transform to Plan B first.
  12849. var desc = this.peerconnection.remoteDescription;
  12850. if (navigator.mozGetUserMedia) {
  12851. desc = this.interop.toPlanB(desc);
  12852. } else {
  12853. desc = APP.simulcast.reverseTransformRemoteDescription(this.peerconnection.remoteDescription);
  12854. }
  12855. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  12856. return desc;
  12857. });
  12858. }
  12859. TraceablePeerConnection.prototype.addStream = function (stream) {
  12860. this.trace('addStream', stream.id);
  12861. APP.simulcast.resetSender();
  12862. try
  12863. {
  12864. this.peerconnection.addStream(stream);
  12865. }
  12866. catch (e)
  12867. {
  12868. console.error(e);
  12869. return;
  12870. }
  12871. };
  12872. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  12873. this.trace('removeStream', stream.id);
  12874. APP.simulcast.resetSender();
  12875. if(stopStreams) {
  12876. stream.getAudioTracks().forEach(function (track) {
  12877. track.stop();
  12878. });
  12879. stream.getVideoTracks().forEach(function (track) {
  12880. track.stop();
  12881. });
  12882. }
  12883. try {
  12884. // FF doesn't support this yet.
  12885. this.peerconnection.removeStream(stream);
  12886. } catch (e) {
  12887. console.error(e);
  12888. }
  12889. };
  12890. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  12891. this.trace('createDataChannel', label, opts);
  12892. return this.peerconnection.createDataChannel(label, opts);
  12893. };
  12894. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  12895. this.trace('setLocalDescription::preTransform (Plan B)', dumpSDP(description));
  12896. // if we're running on FF, transform to Plan A first.
  12897. if (navigator.mozGetUserMedia) {
  12898. description = this.interop.toPlanA(description);
  12899. } else {
  12900. description = APP.simulcast.transformLocalDescription(description);
  12901. }
  12902. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  12903. var self = this;
  12904. this.peerconnection.setLocalDescription(description,
  12905. function () {
  12906. self.trace('setLocalDescriptionOnSuccess');
  12907. successCallback();
  12908. },
  12909. function (err) {
  12910. self.trace('setLocalDescriptionOnFailure', err);
  12911. failureCallback(err);
  12912. }
  12913. );
  12914. /*
  12915. if (this.statsinterval === null && this.maxstats > 0) {
  12916. // start gathering stats
  12917. }
  12918. */
  12919. };
  12920. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  12921. this.trace('setRemoteDescription::preTransform (Plan B)', dumpSDP(description));
  12922. // if we're running on FF, transform to Plan A first.
  12923. if (navigator.mozGetUserMedia) {
  12924. description = this.interop.toPlanA(description);
  12925. }
  12926. else {
  12927. description = APP.simulcast.transformRemoteDescription(description);
  12928. }
  12929. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  12930. var self = this;
  12931. this.peerconnection.setRemoteDescription(description,
  12932. function () {
  12933. self.trace('setRemoteDescriptionOnSuccess');
  12934. successCallback();
  12935. },
  12936. function (err) {
  12937. self.trace('setRemoteDescriptionOnFailure', err);
  12938. failureCallback(err);
  12939. }
  12940. );
  12941. /*
  12942. if (this.statsinterval === null && this.maxstats > 0) {
  12943. // start gathering stats
  12944. }
  12945. */
  12946. };
  12947. TraceablePeerConnection.prototype.close = function () {
  12948. this.trace('stop');
  12949. if (this.statsinterval !== null) {
  12950. window.clearInterval(this.statsinterval);
  12951. this.statsinterval = null;
  12952. }
  12953. this.peerconnection.close();
  12954. };
  12955. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  12956. var self = this;
  12957. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  12958. this.peerconnection.createOffer(
  12959. function (offer) {
  12960. self.trace('createOfferOnSuccess::preTransform (Plan A)', dumpSDP(offer));
  12961. // if we're running on FF, transform to Plan B first.
  12962. if (navigator.mozGetUserMedia) {
  12963. offer = self.interop.toPlanB(offer);
  12964. }
  12965. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  12966. successCallback(offer);
  12967. },
  12968. function(err) {
  12969. self.trace('createOfferOnFailure', err);
  12970. failureCallback(err);
  12971. },
  12972. constraints
  12973. );
  12974. };
  12975. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  12976. var self = this;
  12977. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  12978. this.peerconnection.createAnswer(
  12979. function (answer) {
  12980. self.trace('createAnswerOnSuccess::preTransfom (Plan A)', dumpSDP(answer));
  12981. // if we're running on FF, transform to Plan A first.
  12982. if (navigator.mozGetUserMedia) {
  12983. answer = self.interop.toPlanB(answer);
  12984. } else {
  12985. answer = APP.simulcast.transformAnswer(answer);
  12986. }
  12987. self.trace('createAnswerOnSuccess::postTransfom (Plan B)', dumpSDP(answer));
  12988. successCallback(answer);
  12989. },
  12990. function(err) {
  12991. self.trace('createAnswerOnFailure', err);
  12992. failureCallback(err);
  12993. },
  12994. constraints
  12995. );
  12996. };
  12997. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  12998. var self = this;
  12999. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  13000. this.peerconnection.addIceCandidate(candidate);
  13001. /* maybe later
  13002. this.peerconnection.addIceCandidate(candidate,
  13003. function () {
  13004. self.trace('addIceCandidateOnSuccess');
  13005. successCallback();
  13006. },
  13007. function (err) {
  13008. self.trace('addIceCandidateOnFailure', err);
  13009. failureCallback(err);
  13010. }
  13011. );
  13012. */
  13013. };
  13014. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  13015. if (navigator.mozGetUserMedia) {
  13016. // ignore for now...
  13017. if(!errback)
  13018. errback = function () {
  13019. }
  13020. this.peerconnection.getStats(null,callback,errback);
  13021. } else {
  13022. this.peerconnection.getStats(callback);
  13023. }
  13024. };
  13025. module.exports = TraceablePeerConnection;
  13026. },{"sdp-interop":80}],53:[function(require,module,exports){
  13027. /* global $, $iq, APP, config, connection, UI, messageHandler,
  13028. roomName, sessionTerminated, Strophe, Util */
  13029. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13030. var Settings = require("../settings/Settings");
  13031. var AuthenticationEvents
  13032. = require("../../service/authentication/AuthenticationEvents");
  13033. /**
  13034. * Contains logic responsible for enabling/disabling functionality available
  13035. * only to moderator users.
  13036. */
  13037. var connection = null;
  13038. var focusUserJid;
  13039. function createExpBackoffTimer(step) {
  13040. var count = 1;
  13041. return function (reset) {
  13042. // Reset call
  13043. if (reset) {
  13044. count = 1;
  13045. return;
  13046. }
  13047. // Calculate next timeout
  13048. var timeout = Math.pow(2, count - 1);
  13049. count += 1;
  13050. return timeout * step;
  13051. };
  13052. }
  13053. var getNextTimeout = createExpBackoffTimer(1000);
  13054. var getNextErrorTimeout = createExpBackoffTimer(1000);
  13055. // External authentication stuff
  13056. var externalAuthEnabled = false;
  13057. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  13058. // it will be enabled automatically if focus detects the component through
  13059. // service discovery.
  13060. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  13061. var eventEmitter = null;
  13062. var Moderator = {
  13063. isModerator: function () {
  13064. return connection && connection.emuc.isModerator();
  13065. },
  13066. isPeerModerator: function (peerJid) {
  13067. return connection &&
  13068. connection.emuc.getMemberRole(peerJid) === 'moderator';
  13069. },
  13070. isExternalAuthEnabled: function () {
  13071. return externalAuthEnabled;
  13072. },
  13073. isSipGatewayEnabled: function () {
  13074. return sipGatewayEnabled;
  13075. },
  13076. setConnection: function (con) {
  13077. connection = con;
  13078. },
  13079. init: function (xmpp, emitter) {
  13080. this.xmppService = xmpp;
  13081. eventEmitter = emitter;
  13082. // Message listener that talks to POPUP window
  13083. function listener(event) {
  13084. if (event.data && event.data.sessionId) {
  13085. if (event.origin !== window.location.origin) {
  13086. console.warn(
  13087. "Ignoring sessionId from different origin: " + event.origin);
  13088. return;
  13089. }
  13090. localStorage.setItem('sessionId', event.data.sessionId);
  13091. // After popup is closed we will authenticate
  13092. }
  13093. }
  13094. // Register
  13095. if (window.addEventListener) {
  13096. window.addEventListener("message", listener, false);
  13097. } else {
  13098. window.attachEvent("onmessage", listener);
  13099. }
  13100. },
  13101. onMucLeft: function (jid) {
  13102. console.info("Someone left is it focus ? " + jid);
  13103. var resource = Strophe.getResourceFromJid(jid);
  13104. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  13105. console.info(
  13106. "Focus has left the room - leaving conference");
  13107. //hangUp();
  13108. // We'd rather reload to have everything re-initialized
  13109. // FIXME: show some message before reload
  13110. location.reload();
  13111. }
  13112. },
  13113. setFocusUserJid: function (focusJid) {
  13114. if (!focusUserJid) {
  13115. focusUserJid = focusJid;
  13116. console.info("Focus jid set to: " + focusUserJid);
  13117. }
  13118. },
  13119. getFocusUserJid: function () {
  13120. return focusUserJid;
  13121. },
  13122. getFocusComponent: function () {
  13123. // Get focus component address
  13124. var focusComponent = config.hosts.focus;
  13125. // If not specified use default: 'focus.domain'
  13126. if (!focusComponent) {
  13127. focusComponent = 'focus.' + config.hosts.domain;
  13128. }
  13129. return focusComponent;
  13130. },
  13131. createConferenceIq: function (roomName) {
  13132. // Generate create conference IQ
  13133. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  13134. // Session Id used for authentication
  13135. var sessionId = localStorage.getItem('sessionId');
  13136. var machineUID = Settings.getSettings().uid;
  13137. console.info(
  13138. "Session ID: " + sessionId + " machine UID: " + machineUID);
  13139. elem.c('conference', {
  13140. xmlns: 'http://jitsi.org/protocol/focus',
  13141. room: roomName,
  13142. 'machine-uid': machineUID
  13143. });
  13144. if (sessionId) {
  13145. elem.attrs({ 'session-id': sessionId});
  13146. }
  13147. if (config.hosts.bridge !== undefined) {
  13148. elem.c(
  13149. 'property',
  13150. { name: 'bridge', value: config.hosts.bridge})
  13151. .up();
  13152. }
  13153. // Tell the focus we have Jigasi configured
  13154. if (config.hosts.call_control !== undefined) {
  13155. elem.c(
  13156. 'property',
  13157. { name: 'call_control', value: config.hosts.call_control})
  13158. .up();
  13159. }
  13160. if (config.channelLastN !== undefined) {
  13161. elem.c(
  13162. 'property',
  13163. { name: 'channelLastN', value: config.channelLastN})
  13164. .up();
  13165. }
  13166. if (config.adaptiveLastN !== undefined) {
  13167. elem.c(
  13168. 'property',
  13169. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  13170. .up();
  13171. }
  13172. if (config.adaptiveSimulcast !== undefined) {
  13173. elem.c(
  13174. 'property',
  13175. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  13176. .up();
  13177. }
  13178. if (config.openSctp !== undefined) {
  13179. elem.c(
  13180. 'property',
  13181. { name: 'openSctp', value: config.openSctp})
  13182. .up();
  13183. }
  13184. if (config.enableFirefoxSupport !== undefined) {
  13185. elem.c(
  13186. 'property',
  13187. { name: 'enableFirefoxHacks',
  13188. value: config.enableFirefoxSupport})
  13189. .up();
  13190. }
  13191. elem.up();
  13192. return elem;
  13193. },
  13194. parseSessionId: function (resultIq) {
  13195. var sessionId = $(resultIq).find('conference').attr('session-id');
  13196. if (sessionId) {
  13197. console.info('Received sessionId: ' + sessionId);
  13198. localStorage.setItem('sessionId', sessionId);
  13199. }
  13200. },
  13201. parseConfigOptions: function (resultIq) {
  13202. Moderator.setFocusUserJid(
  13203. $(resultIq).find('conference').attr('focusjid'));
  13204. var authenticationEnabled
  13205. = $(resultIq).find(
  13206. '>conference>property' +
  13207. '[name=\'authentication\'][value=\'true\']').length > 0;
  13208. console.info("Authentication enabled: " + authenticationEnabled);
  13209. externalAuthEnabled
  13210. = $(resultIq).find(
  13211. '>conference>property' +
  13212. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  13213. console.info('External authentication enabled: ' + externalAuthEnabled);
  13214. if (!externalAuthEnabled) {
  13215. // We expect to receive sessionId in 'internal' authentication mode
  13216. Moderator.parseSessionId(resultIq);
  13217. }
  13218. var authIdentity = $(resultIq).find('>conference').attr('identity');
  13219. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  13220. authenticationEnabled, authIdentity);
  13221. // Check if focus has auto-detected Jigasi component(this will be also
  13222. // included if we have passed our host from the config)
  13223. if ($(resultIq).find(
  13224. '>conference>property' +
  13225. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  13226. sipGatewayEnabled = true;
  13227. }
  13228. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  13229. },
  13230. // FIXME: we need to show the fact that we're waiting for the focus
  13231. // to the user(or that focus is not available)
  13232. allocateConferenceFocus: function (roomName, callback) {
  13233. // Try to use focus user JID from the config
  13234. Moderator.setFocusUserJid(config.focusUserJid);
  13235. // Send create conference IQ
  13236. var iq = Moderator.createConferenceIq(roomName);
  13237. var self = this;
  13238. connection.sendIQ(
  13239. iq,
  13240. function (result) {
  13241. // Setup config options
  13242. Moderator.parseConfigOptions(result);
  13243. if ('true' === $(result).find('conference').attr('ready')) {
  13244. // Reset both timers
  13245. getNextTimeout(true);
  13246. getNextErrorTimeout(true);
  13247. // Exec callback
  13248. callback();
  13249. } else {
  13250. var waitMs = getNextTimeout();
  13251. console.info("Waiting for the focus... " + waitMs);
  13252. // Reset error timeout
  13253. getNextErrorTimeout(true);
  13254. window.setTimeout(
  13255. function () {
  13256. Moderator.allocateConferenceFocus(
  13257. roomName, callback);
  13258. }, waitMs);
  13259. }
  13260. },
  13261. function (error) {
  13262. // Invalid session ? remove and try again
  13263. // without session ID to get a new one
  13264. var invalidSession
  13265. = $(error).find('>error>session-invalid').length;
  13266. if (invalidSession) {
  13267. console.info("Session expired! - removing");
  13268. localStorage.removeItem("sessionId");
  13269. }
  13270. if ($(error).find('>error>graceful-shutdown').length) {
  13271. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  13272. return;
  13273. }
  13274. // Check for error returned by the reservation system
  13275. var reservationErr = $(error).find('>error>reservation-error');
  13276. if (reservationErr.length) {
  13277. // Trigger error event
  13278. var errorCode = reservationErr.attr('error-code');
  13279. var errorMsg;
  13280. if ($(error).find('>error>text')) {
  13281. errorMsg = $(error).find('>error>text').text();
  13282. }
  13283. eventEmitter.emit(
  13284. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  13285. return;
  13286. }
  13287. // Not authorized to create new room
  13288. if ($(error).find('>error>not-authorized').length) {
  13289. console.warn("Unauthorized to start the conference", error);
  13290. var toDomain
  13291. = Strophe.getDomainFromJid(error.getAttribute('to'));
  13292. if (toDomain !== config.hosts.anonymousdomain) {
  13293. // FIXME: "is external" should come either from
  13294. // the focus or config.js
  13295. externalAuthEnabled = true;
  13296. }
  13297. eventEmitter.emit(
  13298. XMPPEvents.AUTHENTICATION_REQUIRED,
  13299. function () {
  13300. Moderator.allocateConferenceFocus(
  13301. roomName, callback);
  13302. });
  13303. return;
  13304. }
  13305. var waitMs = getNextErrorTimeout();
  13306. console.error("Focus error, retry after " + waitMs, error);
  13307. // Show message
  13308. var focusComponent = Moderator.getFocusComponent();
  13309. var retrySec = waitMs / 1000;
  13310. // FIXME: message is duplicated ?
  13311. // Do not show in case of session invalid
  13312. // which means just a retry
  13313. if (!invalidSession) {
  13314. APP.UI.messageHandler.notify(
  13315. null, "notify.focus",
  13316. 'disconnected', "notify.focusFail",
  13317. {component: focusComponent, ms: retrySec});
  13318. }
  13319. // Reset response timeout
  13320. getNextTimeout(true);
  13321. window.setTimeout(
  13322. function () {
  13323. Moderator.allocateConferenceFocus(roomName, callback);
  13324. }, waitMs);
  13325. }
  13326. );
  13327. },
  13328. getLoginUrl: function (roomName, urlCallback) {
  13329. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13330. iq.c('login-url', {
  13331. xmlns: 'http://jitsi.org/protocol/focus',
  13332. room: roomName,
  13333. 'machine-uid': Settings.getSettings().uid
  13334. });
  13335. connection.sendIQ(
  13336. iq,
  13337. function (result) {
  13338. var url = $(result).find('login-url').attr('url');
  13339. url = url = decodeURIComponent(url);
  13340. if (url) {
  13341. console.info("Got auth url: " + url);
  13342. urlCallback(url);
  13343. } else {
  13344. console.error(
  13345. "Failed to get auth url from the focus", result);
  13346. }
  13347. },
  13348. function (error) {
  13349. console.error("Get auth url error", error);
  13350. }
  13351. );
  13352. },
  13353. getPopupLoginUrl: function (roomName, urlCallback) {
  13354. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13355. iq.c('login-url', {
  13356. xmlns: 'http://jitsi.org/protocol/focus',
  13357. room: roomName,
  13358. 'machine-uid': Settings.getSettings().uid,
  13359. popup: true
  13360. });
  13361. connection.sendIQ(
  13362. iq,
  13363. function (result) {
  13364. var url = $(result).find('login-url').attr('url');
  13365. url = url = decodeURIComponent(url);
  13366. if (url) {
  13367. console.info("Got POPUP auth url: " + url);
  13368. urlCallback(url);
  13369. } else {
  13370. console.error(
  13371. "Failed to get POPUP auth url from the focus", result);
  13372. }
  13373. },
  13374. function (error) {
  13375. console.error('Get POPUP auth url error', error);
  13376. }
  13377. );
  13378. },
  13379. logout: function (callback) {
  13380. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  13381. var sessionId = localStorage.getItem('sessionId');
  13382. if (!sessionId) {
  13383. callback();
  13384. return;
  13385. }
  13386. iq.c('logout', {
  13387. xmlns: 'http://jitsi.org/protocol/focus',
  13388. 'session-id': sessionId
  13389. });
  13390. connection.sendIQ(
  13391. iq,
  13392. function (result) {
  13393. var logoutUrl = $(result).find('logout').attr('logout-url');
  13394. if (logoutUrl) {
  13395. logoutUrl = decodeURIComponent(logoutUrl);
  13396. }
  13397. console.info("Log out OK, url: " + logoutUrl, result);
  13398. localStorage.removeItem('sessionId');
  13399. callback(logoutUrl);
  13400. },
  13401. function (error) {
  13402. console.error("Logout error", error);
  13403. }
  13404. );
  13405. }
  13406. };
  13407. module.exports = Moderator;
  13408. },{"../../service/authentication/AuthenticationEvents":93,"../../service/xmpp/XMPPEvents":97,"../settings/Settings":38}],54:[function(require,module,exports){
  13409. /* global $, $iq, config, connection, focusMucJid, messageHandler, Moderator,
  13410. Toolbar, Util */
  13411. var Moderator = require("./moderator");
  13412. var recordingToken = null;
  13413. var recordingEnabled;
  13414. /**
  13415. * Whether to use a jirecon component for recording, or use the videobridge
  13416. * through COLIBRI.
  13417. */
  13418. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  13419. /**
  13420. * The ID of the jirecon recording session. Jirecon generates it when we
  13421. * initially start recording, and it needs to be used in subsequent requests
  13422. * to jirecon.
  13423. */
  13424. var jireconRid = null;
  13425. function setRecordingToken(token) {
  13426. recordingToken = token;
  13427. }
  13428. function setRecording(state, token, callback, connection) {
  13429. if (useJirecon){
  13430. setRecordingJirecon(state, token, callback, connection);
  13431. } else {
  13432. setRecordingColibri(state, token, callback, connection);
  13433. }
  13434. }
  13435. function setRecordingJirecon(state, token, callback, connection) {
  13436. if (state == recordingEnabled){
  13437. return;
  13438. }
  13439. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  13440. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  13441. action: state ? 'start' : 'stop',
  13442. mucjid: connection.emuc.roomjid});
  13443. if (!state){
  13444. iq.attrs({rid: jireconRid});
  13445. }
  13446. console.log('Start recording');
  13447. connection.sendIQ(
  13448. iq,
  13449. function (result) {
  13450. // TODO wait for an IQ with the real status, since this is
  13451. // provisional?
  13452. jireconRid = $(result).find('recording').attr('rid');
  13453. console.log('Recording ' + (state ? 'started' : 'stopped') +
  13454. '(jirecon)' + result);
  13455. recordingEnabled = state;
  13456. if (!state){
  13457. jireconRid = null;
  13458. }
  13459. callback(state);
  13460. },
  13461. function (error) {
  13462. console.log('Failed to start recording, error: ', error);
  13463. callback(recordingEnabled);
  13464. });
  13465. }
  13466. // Sends a COLIBRI message which enables or disables (according to 'state')
  13467. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  13468. // with the new recording state, according to the IQ.
  13469. function setRecordingColibri(state, token, callback, connection) {
  13470. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  13471. elem.c('conference', {
  13472. xmlns: 'http://jitsi.org/protocol/colibri'
  13473. });
  13474. elem.c('recording', {state: state, token: token});
  13475. connection.sendIQ(elem,
  13476. function (result) {
  13477. console.log('Set recording "', state, '". Result:', result);
  13478. var recordingElem = $(result).find('>conference>recording');
  13479. var newState = ('true' === recordingElem.attr('state'));
  13480. recordingEnabled = newState;
  13481. callback(newState);
  13482. },
  13483. function (error) {
  13484. console.warn(error);
  13485. callback(recordingEnabled);
  13486. }
  13487. );
  13488. }
  13489. var Recording = {
  13490. toggleRecording: function (tokenEmptyCallback,
  13491. startingCallback, startedCallback, connection) {
  13492. if (!Moderator.isModerator()) {
  13493. console.log(
  13494. 'non-focus, or conference not yet organized:' +
  13495. ' not enabling recording');
  13496. return;
  13497. }
  13498. var self = this;
  13499. // Jirecon does not (currently) support a token.
  13500. if (!recordingToken && !useJirecon) {
  13501. tokenEmptyCallback(function (value) {
  13502. setRecordingToken(value);
  13503. self.toggleRecording(tokenEmptyCallback,
  13504. startingCallback, startedCallback, connection);
  13505. });
  13506. return;
  13507. }
  13508. var oldState = recordingEnabled;
  13509. startingCallback(!oldState);
  13510. setRecording(!oldState,
  13511. recordingToken,
  13512. function (state) {
  13513. console.log("New recording state: ", state);
  13514. if (state === oldState) {
  13515. // FIXME: new focus:
  13516. // this will not work when moderator changes
  13517. // during active session. Then it will assume that
  13518. // recording status has changed to true, but it might have
  13519. // been already true(and we only received actual status from
  13520. // the focus).
  13521. //
  13522. // SO we start with status null, so that it is initialized
  13523. // here and will fail only after second click, so if invalid
  13524. // token was used we have to press the button twice before
  13525. // current status will be fetched and token will be reset.
  13526. //
  13527. // Reliable way would be to return authentication error.
  13528. // Or status update when moderator connects.
  13529. // Or we have to stop recording session when current
  13530. // moderator leaves the room.
  13531. // Failed to change, reset the token because it might
  13532. // have been wrong
  13533. setRecordingToken(null);
  13534. }
  13535. startedCallback(state);
  13536. },
  13537. connection
  13538. );
  13539. }
  13540. }
  13541. module.exports = Recording;
  13542. },{"./moderator":53}],55:[function(require,module,exports){
  13543. /* jshint -W117 */
  13544. /* a simple MUC connection plugin
  13545. * can only handle a single MUC room
  13546. */
  13547. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13548. var Moderator = require("./moderator");
  13549. var JingleSession = require("./JingleSession");
  13550. var bridgeIsDown = false;
  13551. module.exports = function(XMPP, eventEmitter) {
  13552. Strophe.addConnectionPlugin('emuc', {
  13553. connection: null,
  13554. roomjid: null,
  13555. myroomjid: null,
  13556. members: {},
  13557. list_members: [], // so we can elect a new focus
  13558. presMap: {},
  13559. preziMap: {},
  13560. joined: false,
  13561. isOwner: false,
  13562. role: null,
  13563. focusMucJid: null,
  13564. ssrc2jid: {},
  13565. init: function (conn) {
  13566. this.connection = conn;
  13567. },
  13568. initPresenceMap: function (myroomjid) {
  13569. this.presMap['to'] = myroomjid;
  13570. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  13571. },
  13572. doJoin: function (jid, password) {
  13573. this.myroomjid = jid;
  13574. console.info("Joined MUC as " + this.myroomjid);
  13575. this.initPresenceMap(this.myroomjid);
  13576. if (!this.roomjid) {
  13577. this.roomjid = Strophe.getBareJidFromJid(jid);
  13578. // add handlers (just once)
  13579. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  13580. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  13581. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  13582. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  13583. }
  13584. if (password !== undefined) {
  13585. this.presMap['password'] = password;
  13586. }
  13587. this.sendPresence();
  13588. },
  13589. doLeave: function () {
  13590. console.log("do leave", this.myroomjid);
  13591. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  13592. this.presMap.length = 0;
  13593. this.connection.send(pres);
  13594. },
  13595. createNonAnonymousRoom: function () {
  13596. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  13597. var getForm = $iq({type: 'get', to: this.roomjid})
  13598. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  13599. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13600. var self = this;
  13601. this.connection.sendIQ(getForm, function (form) {
  13602. if (!$(form).find(
  13603. '>query>x[xmlns="jabber:x:data"]' +
  13604. '>field[var="muc#roomconfig_whois"]').length) {
  13605. console.error('non-anonymous rooms not supported');
  13606. return;
  13607. }
  13608. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  13609. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  13610. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13611. formSubmit.c('field', {'var': 'FORM_TYPE'})
  13612. .c('value')
  13613. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  13614. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  13615. .c('value').t('anyone').up().up();
  13616. self.connection.sendIQ(formSubmit);
  13617. }, function (error) {
  13618. console.error("Error getting room configuration form");
  13619. });
  13620. },
  13621. onPresence: function (pres) {
  13622. var from = pres.getAttribute('from');
  13623. // What is this for? A workaround for something?
  13624. if (pres.getAttribute('type')) {
  13625. return true;
  13626. }
  13627. // Parse etherpad tag.
  13628. var etherpad = $(pres).find('>etherpad');
  13629. if (etherpad.length) {
  13630. if (config.etherpad_base && !Moderator.isModerator()) {
  13631. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  13632. }
  13633. }
  13634. // Parse prezi tag.
  13635. var presentation = $(pres).find('>prezi');
  13636. if (presentation.length) {
  13637. var url = presentation.attr('url');
  13638. var current = presentation.find('>current').text();
  13639. console.log('presentation info received from', from, url);
  13640. if (this.preziMap[from] == null) {
  13641. this.preziMap[from] = url;
  13642. $(document).trigger('presentationadded.muc', [from, url, current]);
  13643. }
  13644. else {
  13645. $(document).trigger('gotoslide.muc', [from, url, current]);
  13646. }
  13647. }
  13648. else if (this.preziMap[from] != null) {
  13649. var url = this.preziMap[from];
  13650. delete this.preziMap[from];
  13651. $(document).trigger('presentationremoved.muc', [from, url]);
  13652. }
  13653. // Parse audio info tag.
  13654. var audioMuted = $(pres).find('>audiomuted');
  13655. if (audioMuted.length) {
  13656. $(document).trigger('audiomuted.muc', [from, audioMuted.text()]);
  13657. }
  13658. // Parse video info tag.
  13659. var videoMuted = $(pres).find('>videomuted');
  13660. if (videoMuted.length) {
  13661. $(document).trigger('videomuted.muc', [from, videoMuted.text()]);
  13662. }
  13663. var stats = $(pres).find('>stats');
  13664. if (stats.length) {
  13665. var statsObj = {};
  13666. Strophe.forEachChild(stats[0], "stat", function (el) {
  13667. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  13668. });
  13669. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  13670. }
  13671. // Parse status.
  13672. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  13673. this.isOwner = true;
  13674. this.createNonAnonymousRoom();
  13675. }
  13676. // Parse roles.
  13677. var member = {};
  13678. member.show = $(pres).find('>show').text();
  13679. member.status = $(pres).find('>status').text();
  13680. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  13681. member.affiliation = tmp.attr('affiliation');
  13682. member.role = tmp.attr('role');
  13683. // Focus recognition
  13684. member.jid = tmp.attr('jid');
  13685. member.isFocus = false;
  13686. if (member.jid
  13687. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  13688. member.isFocus = true;
  13689. }
  13690. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  13691. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  13692. if (from == this.myroomjid) {
  13693. if (member.affiliation == 'owner') this.isOwner = true;
  13694. if (this.role !== member.role) {
  13695. this.role = member.role;
  13696. eventEmitter.emit(XMPPEvents.LOCALROLE_CHANGED,
  13697. from, member, pres, Moderator.isModerator());
  13698. }
  13699. if (!this.joined) {
  13700. this.joined = true;
  13701. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  13702. this.list_members.push(from);
  13703. }
  13704. } else if (this.members[from] === undefined) {
  13705. // new participant
  13706. this.members[from] = member;
  13707. this.list_members.push(from);
  13708. console.log('entered', from, member);
  13709. if (member.isFocus) {
  13710. this.focusMucJid = from;
  13711. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  13712. }
  13713. else {
  13714. var id = $(pres).find('>userID').text();
  13715. var email = $(pres).find('>email');
  13716. if (email.length > 0) {
  13717. id = email.text();
  13718. }
  13719. eventEmitter.emit(XMPPEvents.MUC_ENTER, from, id, member.displayName);
  13720. }
  13721. } else {
  13722. // Presence update for existing participant
  13723. // Watch role change:
  13724. if (this.members[from].role != member.role) {
  13725. this.members[from].role = member.role;
  13726. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  13727. member.role, member.displayName);
  13728. }
  13729. }
  13730. // Always trigger presence to update bindings
  13731. this.parsePresence(from, member, pres);
  13732. // Trigger status message update
  13733. if (member.status) {
  13734. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  13735. }
  13736. return true;
  13737. },
  13738. onPresenceUnavailable: function (pres) {
  13739. var from = pres.getAttribute('from');
  13740. // room destroyed ?
  13741. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  13742. '>destroy').length) {
  13743. var reason;
  13744. var reasonSelect = $(pres).find(
  13745. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  13746. '>destroy>reason');
  13747. if (reasonSelect.length) {
  13748. reason = reasonSelect.text();
  13749. }
  13750. XMPP.disposeConference(false);
  13751. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  13752. return true;
  13753. }
  13754. // Status code 110 indicates that this notification is "self-presence".
  13755. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  13756. delete this.members[from];
  13757. this.list_members.splice(this.list_members.indexOf(from), 1);
  13758. this.onParticipantLeft(from);
  13759. }
  13760. // If the status code is 110 this means we're leaving and we would like
  13761. // to remove everyone else from our view, so we trigger the event.
  13762. else if (this.list_members.length > 1) {
  13763. for (var i = 0; i < this.list_members.length; i++) {
  13764. var member = this.list_members[i];
  13765. delete this.members[i];
  13766. this.list_members.splice(i, 1);
  13767. this.onParticipantLeft(member);
  13768. }
  13769. }
  13770. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  13771. $(document).trigger('kicked.muc', [from]);
  13772. if (this.myroomjid === from) {
  13773. XMPP.disposeConference(false);
  13774. eventEmitter.emit(XMPPEvents.KICKED);
  13775. }
  13776. }
  13777. return true;
  13778. },
  13779. onPresenceError: function (pres) {
  13780. var from = pres.getAttribute('from');
  13781. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13782. console.log('on password required', from);
  13783. var self = this;
  13784. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  13785. self.doJoin(from, value);
  13786. });
  13787. } else if ($(pres).find(
  13788. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13789. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  13790. if (toDomain === config.hosts.anonymousdomain) {
  13791. // enter the room by replying with 'not-authorized'. This would
  13792. // result in reconnection from authorized domain.
  13793. // We're either missing Jicofo/Prosody config for anonymous
  13794. // domains or something is wrong.
  13795. // XMPP.promptLogin();
  13796. APP.UI.messageHandler.openReportDialog(null,
  13797. "dialog.joinError", pres);
  13798. } else {
  13799. console.warn('onPresError ', pres);
  13800. APP.UI.messageHandler.openReportDialog(null,
  13801. "dialog.connectError",
  13802. pres);
  13803. }
  13804. } else {
  13805. console.warn('onPresError ', pres);
  13806. APP.UI.messageHandler.openReportDialog(null,
  13807. "dialog.connectError",
  13808. pres);
  13809. }
  13810. return true;
  13811. },
  13812. sendMessage: function (body, nickname) {
  13813. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  13814. msg.c('body', body).up();
  13815. if (nickname) {
  13816. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  13817. }
  13818. this.connection.send(msg);
  13819. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  13820. },
  13821. setSubject: function (subject) {
  13822. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  13823. msg.c('subject', subject);
  13824. this.connection.send(msg);
  13825. console.log("topic changed to " + subject);
  13826. },
  13827. onMessage: function (msg) {
  13828. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  13829. var from = msg.getAttribute('from');
  13830. var nick =
  13831. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  13832. .text() ||
  13833. Strophe.getResourceFromJid(from);
  13834. var txt = $(msg).find('>body').text();
  13835. var type = msg.getAttribute("type");
  13836. if (type == "error") {
  13837. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  13838. $(msg).find('>text').text(), txt);
  13839. return true;
  13840. }
  13841. var subject = $(msg).find('>subject');
  13842. if (subject.length) {
  13843. var subjectText = subject.text();
  13844. if (subjectText || subjectText == "") {
  13845. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  13846. console.log("Subject is changed to " + subjectText);
  13847. }
  13848. }
  13849. if (txt) {
  13850. console.log('chat', nick, txt);
  13851. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  13852. from, nick, txt, this.myroomjid);
  13853. }
  13854. return true;
  13855. },
  13856. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  13857. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  13858. var ob = this;
  13859. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  13860. function (res) {
  13861. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  13862. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  13863. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13864. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  13865. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  13866. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  13867. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  13868. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  13869. ob.connection.sendIQ(formsubmit,
  13870. onSuccess,
  13871. onError);
  13872. } else {
  13873. onNotSupported();
  13874. }
  13875. }, onError);
  13876. },
  13877. kick: function (jid) {
  13878. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  13879. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  13880. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  13881. .c('reason').t('You have been kicked.').up().up().up();
  13882. this.connection.sendIQ(
  13883. kickIQ,
  13884. function (result) {
  13885. console.log('Kick participant with jid: ', jid, result);
  13886. },
  13887. function (error) {
  13888. console.log('Kick participant error: ', error);
  13889. });
  13890. },
  13891. sendPresence: function () {
  13892. var pres = $pres({to: this.presMap['to'] });
  13893. pres.c('x', {xmlns: this.presMap['xns']});
  13894. if (this.presMap['password']) {
  13895. pres.c('password').t(this.presMap['password']).up();
  13896. }
  13897. pres.up();
  13898. // Send XEP-0115 'c' stanza that contains our capabilities info
  13899. if (this.connection.caps) {
  13900. this.connection.caps.node = config.clientNode;
  13901. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  13902. }
  13903. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  13904. .t(navigator.userAgent).up();
  13905. if (this.presMap['bridgeIsDown']) {
  13906. pres.c('bridgeIsDown').up();
  13907. }
  13908. if (this.presMap['email']) {
  13909. pres.c('email').t(this.presMap['email']).up();
  13910. }
  13911. if (this.presMap['userId']) {
  13912. pres.c('userId').t(this.presMap['userId']).up();
  13913. }
  13914. if (this.presMap['displayName']) {
  13915. // XEP-0172
  13916. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  13917. .t(this.presMap['displayName']).up();
  13918. }
  13919. if (this.presMap['audions']) {
  13920. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  13921. .t(this.presMap['audiomuted']).up();
  13922. }
  13923. if (this.presMap['videons']) {
  13924. pres.c('videomuted', {xmlns: this.presMap['videons']})
  13925. .t(this.presMap['videomuted']).up();
  13926. }
  13927. if (this.presMap['statsns']) {
  13928. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  13929. for (var stat in this.presMap["stats"])
  13930. if (this.presMap["stats"][stat] != null)
  13931. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  13932. pres.up();
  13933. }
  13934. if (this.presMap['prezins']) {
  13935. pres.c('prezi',
  13936. {xmlns: this.presMap['prezins'],
  13937. 'url': this.presMap['preziurl']})
  13938. .c('current').t(this.presMap['prezicurrent']).up().up();
  13939. }
  13940. if (this.presMap['etherpadns']) {
  13941. pres.c('etherpad', {xmlns: this.presMap['etherpadns']})
  13942. .t(this.presMap['etherpadname']).up();
  13943. }
  13944. if (this.presMap['medians']) {
  13945. pres.c('media', {xmlns: this.presMap['medians']});
  13946. var sourceNumber = 0;
  13947. Object.keys(this.presMap).forEach(function (key) {
  13948. if (key.indexOf('source') >= 0) {
  13949. sourceNumber++;
  13950. }
  13951. });
  13952. if (sourceNumber > 0)
  13953. for (var i = 1; i <= sourceNumber / 3; i++) {
  13954. pres.c('source',
  13955. {type: this.presMap['source' + i + '_type'],
  13956. ssrc: this.presMap['source' + i + '_ssrc'],
  13957. direction: this.presMap['source' + i + '_direction']
  13958. || 'sendrecv' }
  13959. ).up();
  13960. }
  13961. }
  13962. pres.up();
  13963. this.connection.send(pres);
  13964. },
  13965. addDisplayNameToPresence: function (displayName) {
  13966. this.presMap['displayName'] = displayName;
  13967. },
  13968. addMediaToPresence: function (sourceNumber, mtype, ssrcs, direction) {
  13969. if (!this.presMap['medians'])
  13970. this.presMap['medians'] = 'http://estos.de/ns/mjs';
  13971. this.presMap['source' + sourceNumber + '_type'] = mtype;
  13972. this.presMap['source' + sourceNumber + '_ssrc'] = ssrcs;
  13973. this.presMap['source' + sourceNumber + '_direction'] = direction;
  13974. },
  13975. clearPresenceMedia: function () {
  13976. var self = this;
  13977. Object.keys(this.presMap).forEach(function (key) {
  13978. if (key.indexOf('source') != -1) {
  13979. delete self.presMap[key];
  13980. }
  13981. });
  13982. },
  13983. addPreziToPresence: function (url, currentSlide) {
  13984. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  13985. this.presMap['preziurl'] = url;
  13986. this.presMap['prezicurrent'] = currentSlide;
  13987. },
  13988. removePreziFromPresence: function () {
  13989. delete this.presMap['prezins'];
  13990. delete this.presMap['preziurl'];
  13991. delete this.presMap['prezicurrent'];
  13992. },
  13993. addCurrentSlideToPresence: function (currentSlide) {
  13994. this.presMap['prezicurrent'] = currentSlide;
  13995. },
  13996. getPrezi: function (roomjid) {
  13997. return this.preziMap[roomjid];
  13998. },
  13999. addEtherpadToPresence: function (etherpadName) {
  14000. this.presMap['etherpadns'] = 'http://jitsi.org/jitmeet/etherpad';
  14001. this.presMap['etherpadname'] = etherpadName;
  14002. },
  14003. addAudioInfoToPresence: function (isMuted) {
  14004. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  14005. this.presMap['audiomuted'] = isMuted.toString();
  14006. },
  14007. addVideoInfoToPresence: function (isMuted) {
  14008. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  14009. this.presMap['videomuted'] = isMuted.toString();
  14010. },
  14011. addConnectionInfoToPresence: function (stats) {
  14012. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  14013. this.presMap['stats'] = stats;
  14014. },
  14015. findJidFromResource: function (resourceJid) {
  14016. if (resourceJid &&
  14017. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  14018. return this.myroomjid;
  14019. }
  14020. var peerJid = null;
  14021. Object.keys(this.members).some(function (jid) {
  14022. peerJid = jid;
  14023. return Strophe.getResourceFromJid(jid) === resourceJid;
  14024. });
  14025. return peerJid;
  14026. },
  14027. addBridgeIsDownToPresence: function () {
  14028. this.presMap['bridgeIsDown'] = true;
  14029. },
  14030. addEmailToPresence: function (email) {
  14031. this.presMap['email'] = email;
  14032. },
  14033. addUserIdToPresence: function (userId) {
  14034. this.presMap['userId'] = userId;
  14035. },
  14036. isModerator: function () {
  14037. return this.role === 'moderator';
  14038. },
  14039. getMemberRole: function (peerJid) {
  14040. if (this.members[peerJid]) {
  14041. return this.members[peerJid].role;
  14042. }
  14043. return null;
  14044. },
  14045. onParticipantLeft: function (jid) {
  14046. eventEmitter.emit(XMPPEvents.MUC_LEFT, jid);
  14047. this.connection.jingle.terminateByJid(jid);
  14048. if (this.getPrezi(jid)) {
  14049. $(document).trigger('presentationremoved.muc',
  14050. [jid, this.getPrezi(jid)]);
  14051. }
  14052. Moderator.onMucLeft(jid);
  14053. },
  14054. parsePresence: function (from, memeber, pres) {
  14055. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  14056. bridgeIsDown = true;
  14057. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  14058. }
  14059. if(memeber.isFocus)
  14060. return;
  14061. var self = this;
  14062. // Remove old ssrcs coming from the jid
  14063. Object.keys(this.ssrc2jid).forEach(function (ssrc) {
  14064. if (self.ssrc2jid[ssrc] == from) {
  14065. delete self.ssrc2jid[ssrc];
  14066. }
  14067. });
  14068. var changedStreams = [];
  14069. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  14070. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  14071. var ssrcV = ssrc.getAttribute('ssrc');
  14072. self.ssrc2jid[ssrcV] = from;
  14073. JingleSession.notReceivedSSRCs.push(ssrcV);
  14074. var type = ssrc.getAttribute('type');
  14075. var direction = ssrc.getAttribute('direction');
  14076. changedStreams.push({type: type, direction: direction});
  14077. });
  14078. eventEmitter.emit(XMPPEvents.CHANGED_STREAMS, from, changedStreams);
  14079. var displayName = !config.displayJids
  14080. ? memeber.displayName : Strophe.getResourceFromJid(from);
  14081. if (displayName && displayName.length > 0)
  14082. {
  14083. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  14084. }
  14085. var id = $(pres).find('>userID').text();
  14086. var email = $(pres).find('>email');
  14087. if(email.length > 0) {
  14088. id = email.text();
  14089. }
  14090. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  14091. }
  14092. });
  14093. };
  14094. },{"../../service/xmpp/XMPPEvents":97,"./JingleSession":48,"./moderator":53}],56:[function(require,module,exports){
  14095. /* jshint -W117 */
  14096. var JingleSession = require("./JingleSession");
  14097. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14098. module.exports = function(XMPP, eventEmitter)
  14099. {
  14100. function CallIncomingJingle(sid, connection) {
  14101. var sess = connection.jingle.sessions[sid];
  14102. // TODO: do we check activecall == null?
  14103. connection.jingle.activecall = sess;
  14104. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  14105. // TODO: check affiliation and/or role
  14106. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  14107. sess.usedrip = true; // not-so-naive trickle ice
  14108. sess.sendAnswer();
  14109. sess.accept();
  14110. };
  14111. Strophe.addConnectionPlugin('jingle', {
  14112. connection: null,
  14113. sessions: {},
  14114. jid2session: {},
  14115. ice_config: {iceServers: []},
  14116. pc_constraints: {},
  14117. activecall: null,
  14118. media_constraints: {
  14119. mandatory: {
  14120. 'OfferToReceiveAudio': true,
  14121. 'OfferToReceiveVideo': true
  14122. }
  14123. // MozDontOfferDataChannel: true when this is firefox
  14124. },
  14125. init: function (conn) {
  14126. this.connection = conn;
  14127. if (this.connection.disco) {
  14128. // http://xmpp.org/extensions/xep-0167.html#support
  14129. // http://xmpp.org/extensions/xep-0176.html#support
  14130. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  14131. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  14132. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  14133. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  14134. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  14135. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  14136. // this is dealt with by SDP O/A so we don't need to annouce this
  14137. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  14138. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  14139. if (config.useRtcpMux) {
  14140. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  14141. }
  14142. if (config.useBundle) {
  14143. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  14144. }
  14145. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  14146. }
  14147. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  14148. },
  14149. onJingle: function (iq) {
  14150. var sid = $(iq).find('jingle').attr('sid');
  14151. var action = $(iq).find('jingle').attr('action');
  14152. var fromJid = iq.getAttribute('from');
  14153. // send ack first
  14154. var ack = $iq({type: 'result',
  14155. to: fromJid,
  14156. id: iq.getAttribute('id')
  14157. });
  14158. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  14159. var sess = this.sessions[sid];
  14160. if ('session-initiate' != action) {
  14161. if (sess === null) {
  14162. ack.type = 'error';
  14163. ack.c('error', {type: 'cancel'})
  14164. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  14165. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  14166. this.connection.send(ack);
  14167. return true;
  14168. }
  14169. // compare from to sess.peerjid (bare jid comparison for later compat with message-mode)
  14170. // local jid is not checked
  14171. if (Strophe.getBareJidFromJid(fromJid) != Strophe.getBareJidFromJid(sess.peerjid)) {
  14172. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  14173. ack.type = 'error';
  14174. ack.c('error', {type: 'cancel'})
  14175. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  14176. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  14177. this.connection.send(ack);
  14178. return true;
  14179. }
  14180. } else if (sess !== undefined) {
  14181. // existing session with same session id
  14182. // this might be out-of-order if the sess.peerjid is the same as from
  14183. ack.type = 'error';
  14184. ack.c('error', {type: 'cancel'})
  14185. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  14186. console.warn('duplicate session id', sid);
  14187. this.connection.send(ack);
  14188. return true;
  14189. }
  14190. // FIXME: check for a defined action
  14191. this.connection.send(ack);
  14192. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  14193. switch (action) {
  14194. case 'session-initiate':
  14195. sess = new JingleSession(
  14196. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  14197. this.connection, XMPP);
  14198. // configure session
  14199. sess.media_constraints = this.media_constraints;
  14200. sess.pc_constraints = this.pc_constraints;
  14201. sess.ice_config = this.ice_config;
  14202. sess.initiate(fromJid, false);
  14203. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  14204. sess.setRemoteDescription($(iq).find('>jingle'), 'offer');
  14205. this.sessions[sess.sid] = sess;
  14206. this.jid2session[sess.peerjid] = sess;
  14207. // the callback should either
  14208. // .sendAnswer and .accept
  14209. // or .sendTerminate -- not necessarily synchronus
  14210. CallIncomingJingle(sess.sid, this.connection);
  14211. break;
  14212. case 'session-accept':
  14213. sess.setRemoteDescription($(iq).find('>jingle'), 'answer');
  14214. sess.accept();
  14215. $(document).trigger('callaccepted.jingle', [sess.sid]);
  14216. break;
  14217. case 'session-terminate':
  14218. // If this is not the focus sending the terminate, we have
  14219. // nothing more to do here.
  14220. if (Object.keys(this.sessions).length < 1
  14221. || !(this.sessions[Object.keys(this.sessions)[0]]
  14222. instanceof JingleSession))
  14223. {
  14224. break;
  14225. }
  14226. console.log('terminating...', sess.sid);
  14227. sess.terminate();
  14228. this.terminate(sess.sid);
  14229. if ($(iq).find('>jingle>reason').length) {
  14230. $(document).trigger('callterminated.jingle', [
  14231. sess.sid,
  14232. sess.peerjid,
  14233. $(iq).find('>jingle>reason>:first')[0].tagName,
  14234. $(iq).find('>jingle>reason>text').text()
  14235. ]);
  14236. } else {
  14237. $(document).trigger('callterminated.jingle',
  14238. [sess.sid, sess.peerjid]);
  14239. }
  14240. break;
  14241. case 'transport-info':
  14242. sess.addIceCandidate($(iq).find('>jingle>content'));
  14243. break;
  14244. case 'session-info':
  14245. var affected;
  14246. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14247. $(document).trigger('ringing.jingle', [sess.sid]);
  14248. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14249. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14250. $(document).trigger('mute.jingle', [sess.sid, affected]);
  14251. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14252. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14253. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  14254. }
  14255. break;
  14256. case 'addsource': // FIXME: proprietary, un-jingleish
  14257. case 'source-add': // FIXME: proprietary
  14258. sess.addSource($(iq).find('>jingle>content'), fromJid);
  14259. break;
  14260. case 'removesource': // FIXME: proprietary, un-jingleish
  14261. case 'source-remove': // FIXME: proprietary
  14262. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  14263. break;
  14264. default:
  14265. console.warn('jingle action not implemented', action);
  14266. break;
  14267. }
  14268. return true;
  14269. },
  14270. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  14271. var sess = new JingleSession(myjid || this.connection.jid,
  14272. Math.random().toString(36).substr(2, 12), // random string
  14273. this.connection, XMPP);
  14274. // configure session
  14275. sess.media_constraints = this.media_constraints;
  14276. sess.pc_constraints = this.pc_constraints;
  14277. sess.ice_config = this.ice_config;
  14278. sess.initiate(peerjid, true);
  14279. this.sessions[sess.sid] = sess;
  14280. this.jid2session[sess.peerjid] = sess;
  14281. sess.sendOffer();
  14282. return sess;
  14283. },
  14284. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  14285. if (sid === null || sid === undefined) {
  14286. for (sid in this.sessions) {
  14287. if (this.sessions[sid].state != 'ended') {
  14288. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14289. this.sessions[sid].terminate();
  14290. }
  14291. delete this.jid2session[this.sessions[sid].peerjid];
  14292. delete this.sessions[sid];
  14293. }
  14294. } else if (this.sessions.hasOwnProperty(sid)) {
  14295. if (this.sessions[sid].state != 'ended') {
  14296. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14297. this.sessions[sid].terminate();
  14298. }
  14299. delete this.jid2session[this.sessions[sid].peerjid];
  14300. delete this.sessions[sid];
  14301. }
  14302. },
  14303. // Used to terminate a session when an unavailable presence is received.
  14304. terminateByJid: function (jid) {
  14305. if (this.jid2session.hasOwnProperty(jid)) {
  14306. var sess = this.jid2session[jid];
  14307. if (sess) {
  14308. sess.terminate();
  14309. console.log('peer went away silently', jid);
  14310. delete this.sessions[sess.sid];
  14311. delete this.jid2session[jid];
  14312. $(document).trigger('callterminated.jingle',
  14313. [sess.sid, jid], 'gone');
  14314. }
  14315. }
  14316. },
  14317. terminateRemoteByJid: function (jid, reason) {
  14318. if (this.jid2session.hasOwnProperty(jid)) {
  14319. var sess = this.jid2session[jid];
  14320. if (sess) {
  14321. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  14322. sess.terminate();
  14323. console.log('terminate peer with jid', sess.sid, jid);
  14324. delete this.sessions[sess.sid];
  14325. delete this.jid2session[jid];
  14326. $(document).trigger('callterminated.jingle',
  14327. [sess.sid, jid, 'kicked']);
  14328. }
  14329. }
  14330. },
  14331. getStunAndTurnCredentials: function () {
  14332. // get stun and turn configuration from server via xep-0215
  14333. // uses time-limited credentials as described in
  14334. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  14335. //
  14336. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  14337. // for a prosody module which implements this
  14338. //
  14339. // currently, this doesn't work with updateIce and therefore credentials with a long
  14340. // validity have to be fetched before creating the peerconnection
  14341. // TODO: implement refresh via updateIce as described in
  14342. // https://code.google.com/p/webrtc/issues/detail?id=1650
  14343. var self = this;
  14344. this.connection.sendIQ(
  14345. $iq({type: 'get', to: this.connection.domain})
  14346. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  14347. function (res) {
  14348. var iceservers = [];
  14349. $(res).find('>services>service').each(function (idx, el) {
  14350. el = $(el);
  14351. var dict = {};
  14352. var type = el.attr('type');
  14353. switch (type) {
  14354. case 'stun':
  14355. dict.url = 'stun:' + el.attr('host');
  14356. if (el.attr('port')) {
  14357. dict.url += ':' + el.attr('port');
  14358. }
  14359. iceservers.push(dict);
  14360. break;
  14361. case 'turn':
  14362. case 'turns':
  14363. dict.url = type + ':';
  14364. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  14365. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  14366. dict.url += el.attr('username') + '@';
  14367. } else {
  14368. dict.username = el.attr('username'); // only works in M28
  14369. }
  14370. }
  14371. dict.url += el.attr('host');
  14372. if (el.attr('port') && el.attr('port') != '3478') {
  14373. dict.url += ':' + el.attr('port');
  14374. }
  14375. if (el.attr('transport') && el.attr('transport') != 'udp') {
  14376. dict.url += '?transport=' + el.attr('transport');
  14377. }
  14378. if (el.attr('password')) {
  14379. dict.credential = el.attr('password');
  14380. }
  14381. iceservers.push(dict);
  14382. break;
  14383. }
  14384. });
  14385. self.ice_config.iceServers = iceservers;
  14386. },
  14387. function (err) {
  14388. console.warn('getting turn credentials failed', err);
  14389. console.warn('is mod_turncredentials or similar installed?');
  14390. }
  14391. );
  14392. // implement push?
  14393. },
  14394. /**
  14395. * Populates the log data
  14396. */
  14397. populateData: function () {
  14398. var data = {};
  14399. Object.keys(this.sessions).forEach(function (sid) {
  14400. var session = this.sessions[sid];
  14401. if (session.peerconnection && session.peerconnection.updateLog) {
  14402. // FIXME: should probably be a .dump call
  14403. data["jingle_" + session.sid] = {
  14404. updateLog: session.peerconnection.updateLog,
  14405. stats: session.peerconnection.stats,
  14406. url: window.location.href
  14407. };
  14408. }
  14409. });
  14410. return data;
  14411. }
  14412. });
  14413. };
  14414. },{"../../service/xmpp/XMPPEvents":97,"./JingleSession":48}],57:[function(require,module,exports){
  14415. /* global Strophe */
  14416. module.exports = function () {
  14417. Strophe.addConnectionPlugin('logger', {
  14418. // logs raw stanzas and makes them available for download as JSON
  14419. connection: null,
  14420. log: [],
  14421. init: function (conn) {
  14422. this.connection = conn;
  14423. this.connection.rawInput = this.log_incoming.bind(this);
  14424. this.connection.rawOutput = this.log_outgoing.bind(this);
  14425. },
  14426. log_incoming: function (stanza) {
  14427. this.log.push([new Date().getTime(), 'incoming', stanza]);
  14428. },
  14429. log_outgoing: function (stanza) {
  14430. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  14431. }
  14432. });
  14433. };
  14434. },{}],58:[function(require,module,exports){
  14435. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  14436. setAudioMuted, Strophe */
  14437. /**
  14438. * Moderate connection plugin.
  14439. */
  14440. module.exports = function (XMPP) {
  14441. Strophe.addConnectionPlugin('moderate', {
  14442. connection: null,
  14443. init: function (conn) {
  14444. this.connection = conn;
  14445. this.connection.addHandler(this.onMute.bind(this),
  14446. 'http://jitsi.org/jitmeet/audio',
  14447. 'iq',
  14448. 'set',
  14449. null,
  14450. null);
  14451. },
  14452. setMute: function (jid, mute) {
  14453. console.info("set mute", mute);
  14454. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  14455. .c('mute', {
  14456. xmlns: 'http://jitsi.org/jitmeet/audio',
  14457. jid: jid
  14458. })
  14459. .t(mute.toString())
  14460. .up();
  14461. this.connection.sendIQ(
  14462. iqToFocus,
  14463. function (result) {
  14464. console.log('set mute', result);
  14465. },
  14466. function (error) {
  14467. console.log('set mute error', error);
  14468. });
  14469. },
  14470. onMute: function (iq) {
  14471. var from = iq.getAttribute('from');
  14472. if (from !== this.connection.emuc.focusMucJid) {
  14473. console.warn("Ignored mute from non focus peer");
  14474. return false;
  14475. }
  14476. var mute = $(iq).find('mute');
  14477. if (mute.length) {
  14478. var doMuteAudio = mute.text() === "true";
  14479. APP.UI.setAudioMuted(doMuteAudio);
  14480. XMPP.forceMuted = doMuteAudio;
  14481. }
  14482. return true;
  14483. },
  14484. eject: function (jid) {
  14485. // We're not the focus, so can't terminate
  14486. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  14487. this.connection.emuc.kick(jid);
  14488. }
  14489. });
  14490. }
  14491. },{}],59:[function(require,module,exports){
  14492. /* jshint -W117 */
  14493. module.exports = function() {
  14494. Strophe.addConnectionPlugin('rayo',
  14495. {
  14496. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  14497. connection: null,
  14498. init: function (conn) {
  14499. this.connection = conn;
  14500. if (this.connection.disco) {
  14501. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  14502. }
  14503. this.connection.addHandler(
  14504. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  14505. },
  14506. onRayo: function (iq) {
  14507. console.info("Rayo IQ", iq);
  14508. },
  14509. dial: function (to, from, roomName, roomPass) {
  14510. var self = this;
  14511. var req = $iq(
  14512. {
  14513. type: 'set',
  14514. to: this.connection.emuc.focusMucJid
  14515. }
  14516. );
  14517. req.c('dial',
  14518. {
  14519. xmlns: this.RAYO_XMLNS,
  14520. to: to,
  14521. from: from
  14522. });
  14523. req.c('header',
  14524. {
  14525. name: 'JvbRoomName',
  14526. value: roomName
  14527. }).up();
  14528. if (roomPass !== null && roomPass.length) {
  14529. req.c('header',
  14530. {
  14531. name: 'JvbRoomPassword',
  14532. value: roomPass
  14533. }).up();
  14534. }
  14535. this.connection.sendIQ(
  14536. req,
  14537. function (result) {
  14538. console.info('Dial result ', result);
  14539. var resource = $(result).find('ref').attr('uri');
  14540. this.call_resource = resource.substr('xmpp:'.length);
  14541. console.info(
  14542. "Received call resource: " + this.call_resource);
  14543. },
  14544. function (error) {
  14545. console.info('Dial error ', error);
  14546. }
  14547. );
  14548. },
  14549. hang_up: function () {
  14550. if (!this.call_resource) {
  14551. console.warn("No call in progress");
  14552. return;
  14553. }
  14554. var self = this;
  14555. var req = $iq(
  14556. {
  14557. type: 'set',
  14558. to: this.call_resource
  14559. }
  14560. );
  14561. req.c('hangup',
  14562. {
  14563. xmlns: this.RAYO_XMLNS
  14564. });
  14565. this.connection.sendIQ(
  14566. req,
  14567. function (result) {
  14568. console.info('Hangup result ', result);
  14569. self.call_resource = null;
  14570. },
  14571. function (error) {
  14572. console.info('Hangup error ', error);
  14573. self.call_resource = null;
  14574. }
  14575. );
  14576. }
  14577. }
  14578. );
  14579. };
  14580. },{}],60:[function(require,module,exports){
  14581. /**
  14582. * Strophe logger implementation. Logs from level WARN and above.
  14583. */
  14584. module.exports = function () {
  14585. Strophe.log = function (level, msg) {
  14586. switch (level) {
  14587. case Strophe.LogLevel.WARN:
  14588. console.warn("Strophe: " + msg);
  14589. break;
  14590. case Strophe.LogLevel.ERROR:
  14591. case Strophe.LogLevel.FATAL:
  14592. console.error("Strophe: " + msg);
  14593. break;
  14594. }
  14595. };
  14596. Strophe.getStatusString = function (status) {
  14597. switch (status) {
  14598. case Strophe.Status.ERROR:
  14599. return "ERROR";
  14600. case Strophe.Status.CONNECTING:
  14601. return "CONNECTING";
  14602. case Strophe.Status.CONNFAIL:
  14603. return "CONNFAIL";
  14604. case Strophe.Status.AUTHENTICATING:
  14605. return "AUTHENTICATING";
  14606. case Strophe.Status.AUTHFAIL:
  14607. return "AUTHFAIL";
  14608. case Strophe.Status.CONNECTED:
  14609. return "CONNECTED";
  14610. case Strophe.Status.DISCONNECTED:
  14611. return "DISCONNECTED";
  14612. case Strophe.Status.DISCONNECTING:
  14613. return "DISCONNECTING";
  14614. case Strophe.Status.ATTACHED:
  14615. return "ATTACHED";
  14616. default:
  14617. return "unknown";
  14618. }
  14619. };
  14620. };
  14621. },{}],61:[function(require,module,exports){
  14622. /* global $, APP, config, Strophe*/
  14623. var Moderator = require("./moderator");
  14624. var EventEmitter = require("events");
  14625. var Recording = require("./recording");
  14626. var SDP = require("./SDP");
  14627. var Pako = require("pako");
  14628. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  14629. var UIEvents = require("../../service/UI/UIEvents");
  14630. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14631. var eventEmitter = new EventEmitter();
  14632. var connection = null;
  14633. var authenticatedUser = false;
  14634. function connect(jid, password) {
  14635. connection = XMPP.createConnection();
  14636. Moderator.setConnection(connection);
  14637. if (connection.disco) {
  14638. // for chrome, add multistream cap
  14639. }
  14640. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  14641. if (config.useIPv6) {
  14642. // https://code.google.com/p/webrtc/issues/detail?id=2828
  14643. if (!connection.jingle.pc_constraints.optional)
  14644. connection.jingle.pc_constraints.optional = [];
  14645. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  14646. }
  14647. var anonymousConnectionFailed = false;
  14648. connection.connect(jid, password, function (status, msg) {
  14649. console.log('Strophe status changed to',
  14650. Strophe.getStatusString(status));
  14651. if (status === Strophe.Status.CONNECTED) {
  14652. if (config.useStunTurn) {
  14653. connection.jingle.getStunAndTurnCredentials();
  14654. }
  14655. console.info("My Jabber ID: " + connection.jid);
  14656. if(password)
  14657. authenticatedUser = true;
  14658. maybeDoJoin();
  14659. } else if (status === Strophe.Status.CONNFAIL) {
  14660. if(msg === 'x-strophe-bad-non-anon-jid') {
  14661. anonymousConnectionFailed = true;
  14662. }
  14663. } else if (status === Strophe.Status.DISCONNECTED) {
  14664. if(anonymousConnectionFailed) {
  14665. // prompt user for username and password
  14666. XMPP.promptLogin();
  14667. }
  14668. } else if (status === Strophe.Status.AUTHFAIL) {
  14669. // wrong password or username, prompt user
  14670. XMPP.promptLogin();
  14671. }
  14672. });
  14673. }
  14674. function maybeDoJoin() {
  14675. if (connection && connection.connected &&
  14676. Strophe.getResourceFromJid(connection.jid)
  14677. && (APP.RTC.localAudio || APP.RTC.localVideo)) {
  14678. // .connected is true while connecting?
  14679. doJoin();
  14680. }
  14681. }
  14682. function doJoin() {
  14683. var roomName = APP.UI.generateRoomName();
  14684. Moderator.allocateConferenceFocus(
  14685. roomName, APP.UI.checkForNicknameAndJoin);
  14686. }
  14687. function initStrophePlugins()
  14688. {
  14689. require("./strophe.emuc")(XMPP, eventEmitter);
  14690. require("./strophe.jingle")(XMPP, eventEmitter);
  14691. require("./strophe.moderate")(XMPP);
  14692. require("./strophe.util")();
  14693. require("./strophe.rayo")();
  14694. require("./strophe.logger")();
  14695. }
  14696. function registerListeners() {
  14697. APP.RTC.addStreamListener(maybeDoJoin,
  14698. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  14699. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  14700. XMPP.addToPresence("displayName", nickname);
  14701. });
  14702. }
  14703. function setupEvents() {
  14704. $(window).bind('beforeunload', function () {
  14705. if (connection && connection.connected) {
  14706. // ensure signout
  14707. $.ajax({
  14708. type: 'POST',
  14709. url: config.bosh,
  14710. async: false,
  14711. cache: false,
  14712. contentType: 'application/xml',
  14713. data: "<body rid='" + (connection.rid || connection._proto.rid)
  14714. + "' xmlns='http://jabber.org/protocol/httpbind' sid='"
  14715. + (connection.sid || connection._proto.sid)
  14716. + "' type='terminate'>" +
  14717. "<presence xmlns='jabber:client' type='unavailable'/>" +
  14718. "</body>",
  14719. success: function (data) {
  14720. console.log('signed out');
  14721. console.log(data);
  14722. },
  14723. error: function (XMLHttpRequest, textStatus, errorThrown) {
  14724. console.log('signout error',
  14725. textStatus + ' (' + errorThrown + ')');
  14726. }
  14727. });
  14728. }
  14729. XMPP.disposeConference(true);
  14730. });
  14731. }
  14732. var XMPP = {
  14733. sessionTerminated: false,
  14734. /**
  14735. * XMPP connection status
  14736. */
  14737. Status: Strophe.Status,
  14738. /**
  14739. * Remembers if we were muted by the focus.
  14740. * @type {boolean}
  14741. */
  14742. forceMuted: false,
  14743. start: function () {
  14744. setupEvents();
  14745. initStrophePlugins();
  14746. registerListeners();
  14747. Moderator.init(this, eventEmitter);
  14748. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  14749. // Force authenticated domain if room is appended with '?login=true'
  14750. if (config.hosts.anonymousdomain &&
  14751. window.location.search.indexOf("login=true") !== -1) {
  14752. configDomain = config.hosts.domain;
  14753. }
  14754. var jid = configDomain || window.location.hostname;
  14755. connect(jid, null);
  14756. },
  14757. createConnection: function () {
  14758. var bosh = config.bosh || '/http-bind';
  14759. return new Strophe.Connection(bosh);
  14760. },
  14761. getStatusString: function (status) {
  14762. return Strophe.getStatusString(status);
  14763. },
  14764. promptLogin: function () {
  14765. // FIXME: re-use LoginDialog which supports retries
  14766. APP.UI.showLoginPopup(connect);
  14767. },
  14768. joinRoom: function(roomName, useNicks, nick)
  14769. {
  14770. var roomjid;
  14771. roomjid = roomName;
  14772. if (useNicks) {
  14773. if (nick) {
  14774. roomjid += '/' + nick;
  14775. } else {
  14776. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  14777. }
  14778. } else {
  14779. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  14780. if(!authenticatedUser)
  14781. tmpJid = tmpJid.substr(0, 8);
  14782. roomjid += '/' + tmpJid;
  14783. }
  14784. connection.emuc.doJoin(roomjid);
  14785. },
  14786. myJid: function () {
  14787. if(!connection)
  14788. return null;
  14789. return connection.emuc.myroomjid;
  14790. },
  14791. myResource: function () {
  14792. if(!connection || ! connection.emuc.myroomjid)
  14793. return null;
  14794. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  14795. },
  14796. disposeConference: function (onUnload) {
  14797. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  14798. var handler = connection.jingle.activecall;
  14799. if (handler && handler.peerconnection) {
  14800. // FIXME: probably removing streams is not required and close() should
  14801. // be enough
  14802. if (APP.RTC.localAudio) {
  14803. handler.peerconnection.removeStream(APP.RTC.localAudio.getOriginalStream(), onUnload);
  14804. }
  14805. if (APP.RTC.localVideo) {
  14806. handler.peerconnection.removeStream(APP.RTC.localVideo.getOriginalStream(), onUnload);
  14807. }
  14808. handler.peerconnection.close();
  14809. }
  14810. connection.jingle.activecall = null;
  14811. if(!onUnload)
  14812. {
  14813. this.sessionTerminated = true;
  14814. connection.emuc.doLeave();
  14815. }
  14816. },
  14817. addListener: function(type, listener)
  14818. {
  14819. eventEmitter.on(type, listener);
  14820. },
  14821. removeListener: function (type, listener) {
  14822. eventEmitter.removeListener(type, listener);
  14823. },
  14824. allocateConferenceFocus: function(roomName, callback) {
  14825. Moderator.allocateConferenceFocus(roomName, callback);
  14826. },
  14827. getLoginUrl: function (roomName, callback) {
  14828. Moderator.getLoginUrl(roomName, callback);
  14829. },
  14830. getPopupLoginUrl: function (roomName, callback) {
  14831. Moderator.getPopupLoginUrl(roomName, callback);
  14832. },
  14833. isModerator: function () {
  14834. return Moderator.isModerator();
  14835. },
  14836. isSipGatewayEnabled: function () {
  14837. return Moderator.isSipGatewayEnabled();
  14838. },
  14839. isExternalAuthEnabled: function () {
  14840. return Moderator.isExternalAuthEnabled();
  14841. },
  14842. switchStreams: function (stream, oldStream, callback) {
  14843. if (connection && connection.jingle.activecall) {
  14844. // FIXME: will block switchInProgress on true value in case of exception
  14845. connection.jingle.activecall.switchStreams(stream, oldStream, callback);
  14846. } else {
  14847. // We are done immediately
  14848. console.warn("No conference handler or conference not started yet");
  14849. callback();
  14850. }
  14851. },
  14852. setVideoMute: function (mute, callback, options) {
  14853. if(!connection || !APP.RTC.localVideo)
  14854. return;
  14855. var localCallback = function (mute) {
  14856. connection.emuc.addVideoInfoToPresence(mute);
  14857. connection.emuc.sendPresence();
  14858. return callback(mute);
  14859. };
  14860. if (mute == APP.RTC.localVideo.isMuted())
  14861. {
  14862. // Even if no change occurs, the specified callback is to be executed.
  14863. // The specified callback may, optionally, return a successCallback
  14864. // which is to be executed as well.
  14865. var successCallback = localCallback(mute);
  14866. if (successCallback) {
  14867. successCallback();
  14868. }
  14869. } else {
  14870. APP.RTC.localVideo.setMute(!mute);
  14871. if(connection.jingle.activecall)
  14872. {
  14873. connection.jingle.activecall.setVideoMute(
  14874. mute, localCallback, options);
  14875. }
  14876. else {
  14877. localCallback(mute);
  14878. }
  14879. }
  14880. },
  14881. setAudioMute: function (mute, callback) {
  14882. if (!(connection && APP.RTC.localAudio)) {
  14883. return false;
  14884. }
  14885. if (this.forceMuted && !mute) {
  14886. console.info("Asking focus for unmute");
  14887. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  14888. // FIXME: wait for result before resetting muted status
  14889. this.forceMuted = false;
  14890. }
  14891. if (mute == APP.RTC.localAudio.isMuted()) {
  14892. // Nothing to do
  14893. return true;
  14894. }
  14895. // It is not clear what is the right way to handle multiple tracks.
  14896. // So at least make sure that they are all muted or all unmuted and
  14897. // that we send presence just once.
  14898. APP.RTC.localAudio.mute();
  14899. // isMuted is the opposite of audioEnabled
  14900. connection.emuc.addAudioInfoToPresence(mute);
  14901. connection.emuc.sendPresence();
  14902. callback();
  14903. return true;
  14904. },
  14905. // Really mute video, i.e. dont even send black frames
  14906. muteVideo: function (pc, unmute) {
  14907. // FIXME: this probably needs another of those lovely state safeguards...
  14908. // which checks for iceconn == connected and sigstate == stable
  14909. pc.setRemoteDescription(pc.remoteDescription,
  14910. function () {
  14911. pc.createAnswer(
  14912. function (answer) {
  14913. var sdp = new SDP(answer.sdp);
  14914. if (sdp.media.length > 1) {
  14915. if (unmute)
  14916. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  14917. else
  14918. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  14919. sdp.raw = sdp.session + sdp.media.join('');
  14920. answer.sdp = sdp.raw;
  14921. }
  14922. pc.setLocalDescription(answer,
  14923. function () {
  14924. console.log('mute SLD ok');
  14925. },
  14926. function (error) {
  14927. console.log('mute SLD error');
  14928. APP.UI.messageHandler.showError("dialog.error",
  14929. "dialog.SLDFailure");
  14930. }
  14931. );
  14932. },
  14933. function (error) {
  14934. console.log(error);
  14935. APP.UI.messageHandler.showError();
  14936. }
  14937. );
  14938. },
  14939. function (error) {
  14940. console.log('muteVideo SRD error');
  14941. APP.UI.messageHandler.showError("dialog.error",
  14942. "dialog.SRDFailure");
  14943. }
  14944. );
  14945. },
  14946. toggleRecording: function (tokenEmptyCallback,
  14947. startingCallback, startedCallback) {
  14948. Recording.toggleRecording(tokenEmptyCallback,
  14949. startingCallback, startedCallback, connection);
  14950. },
  14951. addToPresence: function (name, value, dontSend) {
  14952. switch (name)
  14953. {
  14954. case "displayName":
  14955. connection.emuc.addDisplayNameToPresence(value);
  14956. break;
  14957. case "etherpad":
  14958. connection.emuc.addEtherpadToPresence(value);
  14959. break;
  14960. case "prezi":
  14961. connection.emuc.addPreziToPresence(value, 0);
  14962. break;
  14963. case "preziSlide":
  14964. connection.emuc.addCurrentSlideToPresence(value);
  14965. break;
  14966. case "connectionQuality":
  14967. connection.emuc.addConnectionInfoToPresence(value);
  14968. break;
  14969. case "email":
  14970. connection.emuc.addEmailToPresence(value);
  14971. default :
  14972. console.log("Unknown tag for presence.");
  14973. return;
  14974. }
  14975. if(!dontSend)
  14976. connection.emuc.sendPresence();
  14977. },
  14978. /**
  14979. * Sends 'data' as a log message to the focus. Returns true iff a message
  14980. * was sent.
  14981. * @param data
  14982. * @returns {boolean} true iff a message was sent.
  14983. */
  14984. sendLogs: function (data) {
  14985. if(!connection.emuc.focusMucJid)
  14986. return false;
  14987. var deflate = true;
  14988. var content = JSON.stringify(data);
  14989. if (deflate) {
  14990. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  14991. }
  14992. content = Base64.encode(content);
  14993. // XEP-0337-ish
  14994. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  14995. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  14996. id: 'PeerConnectionStats'});
  14997. message.c('message').t(content).up();
  14998. if (deflate) {
  14999. message.c('tag', {name: "deflated", value: "true"}).up();
  15000. }
  15001. message.up();
  15002. connection.send(message);
  15003. return true;
  15004. },
  15005. populateData: function () {
  15006. var data = {};
  15007. if (connection.jingle) {
  15008. data = connection.jingle.populateData();
  15009. }
  15010. return data;
  15011. },
  15012. getLogger: function () {
  15013. if(connection.logger)
  15014. return connection.logger.log;
  15015. return null;
  15016. },
  15017. getPrezi: function () {
  15018. return connection.emuc.getPrezi(this.myJid());
  15019. },
  15020. removePreziFromPresence: function () {
  15021. connection.emuc.removePreziFromPresence();
  15022. connection.emuc.sendPresence();
  15023. },
  15024. sendChatMessage: function (message, nickname) {
  15025. connection.emuc.sendMessage(message, nickname);
  15026. },
  15027. setSubject: function (topic) {
  15028. connection.emuc.setSubject(topic);
  15029. },
  15030. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  15031. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  15032. },
  15033. dial: function (to, from, roomName,roomPass) {
  15034. connection.rayo.dial(to, from, roomName,roomPass);
  15035. },
  15036. setMute: function (jid, mute) {
  15037. connection.moderate.setMute(jid, mute);
  15038. },
  15039. eject: function (jid) {
  15040. connection.moderate.eject(jid);
  15041. },
  15042. logout: function (callback) {
  15043. Moderator.logout(callback);
  15044. },
  15045. findJidFromResource: function (resource) {
  15046. return connection.emuc.findJidFromResource(resource);
  15047. },
  15048. getMembers: function () {
  15049. return connection.emuc.members;
  15050. },
  15051. getJidFromSSRC: function (ssrc) {
  15052. if(!connection)
  15053. return null;
  15054. return connection.emuc.ssrc2jid[ssrc];
  15055. },
  15056. getMUCJoined: function () {
  15057. return connection.emuc.joined;
  15058. },
  15059. getSessions: function () {
  15060. return connection.jingle.sessions;
  15061. }
  15062. };
  15063. module.exports = XMPP;
  15064. },{"../../service/RTC/StreamEventTypes":91,"../../service/UI/UIEvents":92,"../../service/xmpp/XMPPEvents":97,"./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":98,"pako":63}],62:[function(require,module,exports){
  15065. // i18next, v1.7.7
  15066. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  15067. // Distributed under MIT license
  15068. // http://i18next.com
  15069. (function() {
  15070. // add indexOf to non ECMA-262 standard compliant browsers
  15071. if (!Array.prototype.indexOf) {
  15072. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  15073. "use strict";
  15074. if (this == null) {
  15075. throw new TypeError();
  15076. }
  15077. var t = Object(this);
  15078. var len = t.length >>> 0;
  15079. if (len === 0) {
  15080. return -1;
  15081. }
  15082. var n = 0;
  15083. if (arguments.length > 0) {
  15084. n = Number(arguments[1]);
  15085. if (n != n) { // shortcut for verifying if it's NaN
  15086. n = 0;
  15087. } else if (n != 0 && n != Infinity && n != -Infinity) {
  15088. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  15089. }
  15090. }
  15091. if (n >= len) {
  15092. return -1;
  15093. }
  15094. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  15095. for (; k < len; k++) {
  15096. if (k in t && t[k] === searchElement) {
  15097. return k;
  15098. }
  15099. }
  15100. return -1;
  15101. }
  15102. }
  15103. // add lastIndexOf to non ECMA-262 standard compliant browsers
  15104. if (!Array.prototype.lastIndexOf) {
  15105. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  15106. "use strict";
  15107. if (this == null) {
  15108. throw new TypeError();
  15109. }
  15110. var t = Object(this);
  15111. var len = t.length >>> 0;
  15112. if (len === 0) {
  15113. return -1;
  15114. }
  15115. var n = len;
  15116. if (arguments.length > 1) {
  15117. n = Number(arguments[1]);
  15118. if (n != n) {
  15119. n = 0;
  15120. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  15121. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  15122. }
  15123. }
  15124. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  15125. for (; k >= 0; k--) {
  15126. if (k in t && t[k] === searchElement) {
  15127. return k;
  15128. }
  15129. }
  15130. return -1;
  15131. };
  15132. }
  15133. // Add string trim for IE8.
  15134. if (typeof String.prototype.trim !== 'function') {
  15135. String.prototype.trim = function() {
  15136. return this.replace(/^\s+|\s+$/g, '');
  15137. }
  15138. }
  15139. var root = this
  15140. , $ = root.jQuery || root.Zepto
  15141. , i18n = {}
  15142. , resStore = {}
  15143. , currentLng
  15144. , replacementCounter = 0
  15145. , languages = []
  15146. , initialized = false
  15147. , sync = {};
  15148. // Export the i18next object for **CommonJS**.
  15149. // If we're not in CommonJS, add `i18n` to the
  15150. // global object or to jquery.
  15151. if (typeof module !== 'undefined' && module.exports) {
  15152. if (!$) {
  15153. try {
  15154. $ = require('jquery');
  15155. } catch(e) {
  15156. // just ignore
  15157. }
  15158. }
  15159. if ($) {
  15160. $.i18n = $.i18n || i18n;
  15161. }
  15162. module.exports = i18n;
  15163. } else {
  15164. if ($) {
  15165. $.i18n = $.i18n || i18n;
  15166. }
  15167. root.i18n = root.i18n || i18n;
  15168. }
  15169. sync = {
  15170. load: function(lngs, options, cb) {
  15171. if (options.useLocalStorage) {
  15172. sync._loadLocal(lngs, options, function(err, store) {
  15173. var missingLngs = [];
  15174. for (var i = 0, len = lngs.length; i < len; i++) {
  15175. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  15176. }
  15177. if (missingLngs.length > 0) {
  15178. sync._fetch(missingLngs, options, function(err, fetched) {
  15179. f.extend(store, fetched);
  15180. sync._storeLocal(fetched);
  15181. cb(null, store);
  15182. });
  15183. } else {
  15184. cb(null, store);
  15185. }
  15186. });
  15187. } else {
  15188. sync._fetch(lngs, options, function(err, store){
  15189. cb(null, store);
  15190. });
  15191. }
  15192. },
  15193. _loadLocal: function(lngs, options, cb) {
  15194. var store = {}
  15195. , nowMS = new Date().getTime();
  15196. if(window.localStorage) {
  15197. var todo = lngs.length;
  15198. f.each(lngs, function(key, lng) {
  15199. var local = window.localStorage.getItem('res_' + lng);
  15200. if (local) {
  15201. local = JSON.parse(local);
  15202. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  15203. store[lng] = local;
  15204. }
  15205. }
  15206. todo--; // wait for all done befor callback
  15207. if (todo === 0) cb(null, store);
  15208. });
  15209. }
  15210. },
  15211. _storeLocal: function(store) {
  15212. if(window.localStorage) {
  15213. for (var m in store) {
  15214. store[m].i18nStamp = new Date().getTime();
  15215. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  15216. }
  15217. }
  15218. return;
  15219. },
  15220. _fetch: function(lngs, options, cb) {
  15221. var ns = options.ns
  15222. , store = {};
  15223. if (!options.dynamicLoad) {
  15224. var todo = ns.namespaces.length * lngs.length
  15225. , errors;
  15226. // load each file individual
  15227. f.each(ns.namespaces, function(nsIndex, nsValue) {
  15228. f.each(lngs, function(lngIndex, lngValue) {
  15229. // Call this once our translation has returned.
  15230. var loadComplete = function(err, data) {
  15231. if (err) {
  15232. errors = errors || [];
  15233. errors.push(err);
  15234. }
  15235. store[lngValue] = store[lngValue] || {};
  15236. store[lngValue][nsValue] = data;
  15237. todo--; // wait for all done befor callback
  15238. if (todo === 0) cb(errors, store);
  15239. };
  15240. if(typeof options.customLoad == 'function'){
  15241. // Use the specified custom callback.
  15242. options.customLoad(lngValue, nsValue, options, loadComplete);
  15243. } else {
  15244. //~ // Use our inbuilt sync.
  15245. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  15246. }
  15247. });
  15248. });
  15249. } else {
  15250. // Call this once our translation has returned.
  15251. var loadComplete = function(err, data) {
  15252. cb(null, data);
  15253. };
  15254. if(typeof options.customLoad == 'function'){
  15255. // Use the specified custom callback.
  15256. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  15257. } else {
  15258. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  15259. // load all needed stuff once
  15260. f.ajax({
  15261. url: url,
  15262. success: function(data, status, xhr) {
  15263. f.log('loaded: ' + url);
  15264. loadComplete(null, data);
  15265. },
  15266. error : function(xhr, status, error) {
  15267. f.log('failed loading: ' + url);
  15268. loadComplete('failed loading resource.json error: ' + error);
  15269. },
  15270. dataType: "json",
  15271. async : options.getAsync
  15272. });
  15273. }
  15274. }
  15275. },
  15276. _fetchOne: function(lng, ns, options, done) {
  15277. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  15278. f.ajax({
  15279. url: url,
  15280. success: function(data, status, xhr) {
  15281. f.log('loaded: ' + url);
  15282. done(null, data);
  15283. },
  15284. error : function(xhr, status, error) {
  15285. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  15286. // file loaded but invalid json, stop waste time !
  15287. f.error('There is a typo in: ' + url);
  15288. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  15289. f.log('Does not exist: ' + url);
  15290. } else {
  15291. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  15292. f.log(theStatus + ' when loading ' + url);
  15293. }
  15294. done(error, {});
  15295. },
  15296. dataType: "json",
  15297. async : options.getAsync
  15298. });
  15299. },
  15300. postMissing: function(lng, ns, key, defaultValue, lngs) {
  15301. var payload = {};
  15302. payload[key] = defaultValue;
  15303. var urls = [];
  15304. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  15305. for (var i = 0; i < o.fallbackLng.length; i++) {
  15306. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  15307. }
  15308. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  15309. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  15310. } else if (o.sendMissingTo === 'all') {
  15311. for (var i = 0, l = lngs.length; i < l; i++) {
  15312. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  15313. }
  15314. }
  15315. for (var y = 0, len = urls.length; y < len; y++) {
  15316. var item = urls[y];
  15317. f.ajax({
  15318. url: item.url,
  15319. type: o.sendType,
  15320. data: payload,
  15321. success: function(data, status, xhr) {
  15322. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  15323. // add key to resStore
  15324. var keys = key.split('.');
  15325. var x = 0;
  15326. var value = resStore[item.lng][ns];
  15327. while (keys[x]) {
  15328. if (x === keys.length - 1) {
  15329. value = value[keys[x]] = defaultValue;
  15330. } else {
  15331. value = value[keys[x]] = value[keys[x]] || {};
  15332. }
  15333. x++;
  15334. }
  15335. },
  15336. error : function(xhr, status, error) {
  15337. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  15338. },
  15339. dataType: "json",
  15340. async : o.postAsync
  15341. });
  15342. }
  15343. },
  15344. reload: reload
  15345. };
  15346. // defaults
  15347. var o = {
  15348. lng: undefined,
  15349. load: 'all',
  15350. preload: [],
  15351. lowerCaseLng: false,
  15352. returnObjectTrees: false,
  15353. fallbackLng: ['dev'],
  15354. fallbackNS: [],
  15355. detectLngQS: 'setLng',
  15356. detectLngFromLocalStorage: false,
  15357. ns: 'translation',
  15358. fallbackOnNull: true,
  15359. fallbackOnEmpty: false,
  15360. fallbackToDefaultNS: false,
  15361. nsseparator: ':',
  15362. keyseparator: '.',
  15363. selectorAttr: 'data-i18n',
  15364. debug: false,
  15365. resGetPath: 'locales/__lng__/__ns__.json',
  15366. resPostPath: 'locales/add/__lng__/__ns__',
  15367. getAsync: true,
  15368. postAsync: true,
  15369. resStore: undefined,
  15370. useLocalStorage: false,
  15371. localStorageExpirationTime: 7*24*60*60*1000,
  15372. dynamicLoad: false,
  15373. sendMissing: false,
  15374. sendMissingTo: 'fallback', // current | all
  15375. sendType: 'POST',
  15376. interpolationPrefix: '__',
  15377. interpolationSuffix: '__',
  15378. defaultVariables: false,
  15379. reusePrefix: '$t(',
  15380. reuseSuffix: ')',
  15381. pluralSuffix: '_plural',
  15382. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  15383. contextNotFound: ['context_not_found', Math.random()].join(''),
  15384. escapeInterpolation: false,
  15385. indefiniteSuffix: '_indefinite',
  15386. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  15387. setJqueryExt: true,
  15388. defaultValueFromContent: true,
  15389. useDataAttrOptions: false,
  15390. cookieExpirationTime: undefined,
  15391. useCookie: true,
  15392. cookieName: 'i18next',
  15393. cookieDomain: undefined,
  15394. objectTreeKeyHandler: undefined,
  15395. postProcess: undefined,
  15396. parseMissingKey: undefined,
  15397. missingKeyHandler: sync.postMissing,
  15398. shortcutFunction: 'sprintf' // or: defaultValue
  15399. };
  15400. function _extend(target, source) {
  15401. if (!source || typeof source === 'function') {
  15402. return target;
  15403. }
  15404. for (var attr in source) { target[attr] = source[attr]; }
  15405. return target;
  15406. }
  15407. function _deepExtend(target, source) {
  15408. for (var prop in source)
  15409. if (prop in target)
  15410. _deepExtend(target[prop], source[prop]);
  15411. else
  15412. target[prop] = source[prop];
  15413. return target;
  15414. }
  15415. function _each(object, callback, args) {
  15416. var name, i = 0,
  15417. length = object.length,
  15418. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  15419. if (args) {
  15420. if (isObj) {
  15421. for (name in object) {
  15422. if (callback.apply(object[name], args) === false) {
  15423. break;
  15424. }
  15425. }
  15426. } else {
  15427. for ( ; i < length; ) {
  15428. if (callback.apply(object[i++], args) === false) {
  15429. break;
  15430. }
  15431. }
  15432. }
  15433. // A special, fast, case for the most common use of each
  15434. } else {
  15435. if (isObj) {
  15436. for (name in object) {
  15437. if (callback.call(object[name], name, object[name]) === false) {
  15438. break;
  15439. }
  15440. }
  15441. } else {
  15442. for ( ; i < length; ) {
  15443. if (callback.call(object[i], i, object[i++]) === false) {
  15444. break;
  15445. }
  15446. }
  15447. }
  15448. }
  15449. return object;
  15450. }
  15451. var _entityMap = {
  15452. "&": "&amp;",
  15453. "<": "&lt;",
  15454. ">": "&gt;",
  15455. '"': '&quot;',
  15456. "'": '&#39;',
  15457. "/": '&#x2F;'
  15458. };
  15459. function _escape(data) {
  15460. if (typeof data === 'string') {
  15461. return data.replace(/[&<>"'\/]/g, function (s) {
  15462. return _entityMap[s];
  15463. });
  15464. }else{
  15465. return data;
  15466. }
  15467. }
  15468. function _ajax(options) {
  15469. // v0.5.0 of https://github.com/goloroden/http.js
  15470. var getXhr = function (callback) {
  15471. // Use the native XHR object if the browser supports it.
  15472. if (window.XMLHttpRequest) {
  15473. return callback(null, new XMLHttpRequest());
  15474. } else if (window.ActiveXObject) {
  15475. // In Internet Explorer check for ActiveX versions of the XHR object.
  15476. try {
  15477. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  15478. } catch (e) {
  15479. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  15480. }
  15481. }
  15482. // If no XHR support was found, throw an error.
  15483. return callback(new Error());
  15484. };
  15485. var encodeUsingUrlEncoding = function (data) {
  15486. if(typeof data === 'string') {
  15487. return data;
  15488. }
  15489. var result = [];
  15490. for(var dataItem in data) {
  15491. if(data.hasOwnProperty(dataItem)) {
  15492. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  15493. }
  15494. }
  15495. return result.join('&');
  15496. };
  15497. var utf8 = function (text) {
  15498. text = text.replace(/\r\n/g, '\n');
  15499. var result = '';
  15500. for(var i = 0; i < text.length; i++) {
  15501. var c = text.charCodeAt(i);
  15502. if(c < 128) {
  15503. result += String.fromCharCode(c);
  15504. } else if((c > 127) && (c < 2048)) {
  15505. result += String.fromCharCode((c >> 6) | 192);
  15506. result += String.fromCharCode((c & 63) | 128);
  15507. } else {
  15508. result += String.fromCharCode((c >> 12) | 224);
  15509. result += String.fromCharCode(((c >> 6) & 63) | 128);
  15510. result += String.fromCharCode((c & 63) | 128);
  15511. }
  15512. }
  15513. return result;
  15514. };
  15515. var base64 = function (text) {
  15516. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  15517. text = utf8(text);
  15518. var result = '',
  15519. chr1, chr2, chr3,
  15520. enc1, enc2, enc3, enc4,
  15521. i = 0;
  15522. do {
  15523. chr1 = text.charCodeAt(i++);
  15524. chr2 = text.charCodeAt(i++);
  15525. chr3 = text.charCodeAt(i++);
  15526. enc1 = chr1 >> 2;
  15527. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  15528. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  15529. enc4 = chr3 & 63;
  15530. if(isNaN(chr2)) {
  15531. enc3 = enc4 = 64;
  15532. } else if(isNaN(chr3)) {
  15533. enc4 = 64;
  15534. }
  15535. result +=
  15536. keyStr.charAt(enc1) +
  15537. keyStr.charAt(enc2) +
  15538. keyStr.charAt(enc3) +
  15539. keyStr.charAt(enc4);
  15540. chr1 = chr2 = chr3 = '';
  15541. enc1 = enc2 = enc3 = enc4 = '';
  15542. } while(i < text.length);
  15543. return result;
  15544. };
  15545. var mergeHeaders = function () {
  15546. // Use the first header object as base.
  15547. var result = arguments[0];
  15548. // Iterate through the remaining header objects and add them.
  15549. for(var i = 1; i < arguments.length; i++) {
  15550. var currentHeaders = arguments[i];
  15551. for(var header in currentHeaders) {
  15552. if(currentHeaders.hasOwnProperty(header)) {
  15553. result[header] = currentHeaders[header];
  15554. }
  15555. }
  15556. }
  15557. // Return the merged headers.
  15558. return result;
  15559. };
  15560. var ajax = function (method, url, options, callback) {
  15561. // Adjust parameters.
  15562. if(typeof options === 'function') {
  15563. callback = options;
  15564. options = {};
  15565. }
  15566. // Set default parameter values.
  15567. options.cache = options.cache || false;
  15568. options.data = options.data || {};
  15569. options.headers = options.headers || {};
  15570. options.jsonp = options.jsonp || false;
  15571. options.async = options.async === undefined ? true : options.async;
  15572. // Merge the various header objects.
  15573. var headers = mergeHeaders({
  15574. 'accept': '*/*',
  15575. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  15576. }, ajax.headers, options.headers);
  15577. // Encode the data according to the content-type.
  15578. var payload;
  15579. if (headers['content-type'] === 'application/json') {
  15580. payload = JSON.stringify(options.data);
  15581. } else {
  15582. payload = encodeUsingUrlEncoding(options.data);
  15583. }
  15584. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  15585. // if neccessary.
  15586. if(method === 'GET') {
  15587. // Setup the query string.
  15588. var queryString = [];
  15589. if(payload) {
  15590. queryString.push(payload);
  15591. payload = null;
  15592. }
  15593. // Handle caching.
  15594. if(!options.cache) {
  15595. queryString.push('_=' + (new Date()).getTime());
  15596. }
  15597. // If neccessary prepare the query string for a JSONP call.
  15598. if(options.jsonp) {
  15599. queryString.push('callback=' + options.jsonp);
  15600. queryString.push('jsonp=' + options.jsonp);
  15601. }
  15602. // Merge the query string and attach it to the url.
  15603. queryString = queryString.join('&');
  15604. if (queryString.length > 1) {
  15605. if (url.indexOf('?') > -1) {
  15606. url += '&' + queryString;
  15607. } else {
  15608. url += '?' + queryString;
  15609. }
  15610. }
  15611. // Make a JSONP call if neccessary.
  15612. if(options.jsonp) {
  15613. var head = document.getElementsByTagName('head')[0];
  15614. var script = document.createElement('script');
  15615. script.type = 'text/javascript';
  15616. script.src = url;
  15617. head.appendChild(script);
  15618. return;
  15619. }
  15620. }
  15621. // Since we got here, it is no JSONP request, so make a normal XHR request.
  15622. getXhr(function (err, xhr) {
  15623. if(err) return callback(err);
  15624. // Open the request.
  15625. xhr.open(method, url, options.async);
  15626. // Set the request headers.
  15627. for(var header in headers) {
  15628. if(headers.hasOwnProperty(header)) {
  15629. xhr.setRequestHeader(header, headers[header]);
  15630. }
  15631. }
  15632. // Handle the request events.
  15633. xhr.onreadystatechange = function () {
  15634. if(xhr.readyState === 4) {
  15635. var data = xhr.responseText || '';
  15636. // If no callback is given, return.
  15637. if(!callback) {
  15638. return;
  15639. }
  15640. // Return an object that provides access to the data as text and JSON.
  15641. callback(xhr.status, {
  15642. text: function () {
  15643. return data;
  15644. },
  15645. json: function () {
  15646. try {
  15647. return JSON.parse(data)
  15648. } catch (e) {
  15649. f.error('Can not parse JSON. URL: ' + url);
  15650. return {};
  15651. }
  15652. }
  15653. });
  15654. }
  15655. };
  15656. // Actually send the XHR request.
  15657. xhr.send(payload);
  15658. });
  15659. };
  15660. // Define the external interface.
  15661. var http = {
  15662. authBasic: function (username, password) {
  15663. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  15664. },
  15665. connect: function (url, options, callback) {
  15666. return ajax('CONNECT', url, options, callback);
  15667. },
  15668. del: function (url, options, callback) {
  15669. return ajax('DELETE', url, options, callback);
  15670. },
  15671. get: function (url, options, callback) {
  15672. return ajax('GET', url, options, callback);
  15673. },
  15674. head: function (url, options, callback) {
  15675. return ajax('HEAD', url, options, callback);
  15676. },
  15677. headers: function (headers) {
  15678. ajax.headers = headers || {};
  15679. },
  15680. isAllowed: function (url, verb, callback) {
  15681. this.options(url, function (status, data) {
  15682. callback(data.text().indexOf(verb) !== -1);
  15683. });
  15684. },
  15685. options: function (url, options, callback) {
  15686. return ajax('OPTIONS', url, options, callback);
  15687. },
  15688. patch: function (url, options, callback) {
  15689. return ajax('PATCH', url, options, callback);
  15690. },
  15691. post: function (url, options, callback) {
  15692. return ajax('POST', url, options, callback);
  15693. },
  15694. put: function (url, options, callback) {
  15695. return ajax('PUT', url, options, callback);
  15696. },
  15697. trace: function (url, options, callback) {
  15698. return ajax('TRACE', url, options, callback);
  15699. }
  15700. };
  15701. var methode = options.type ? options.type.toLowerCase() : 'get';
  15702. http[methode](options.url, options, function (status, data) {
  15703. // file: protocol always gives status code 0, so check for data
  15704. if (status === 200 || (status === 0 && data.text())) {
  15705. options.success(data.json(), status, null);
  15706. } else {
  15707. options.error(data.text(), status, null);
  15708. }
  15709. });
  15710. }
  15711. var _cookie = {
  15712. create: function(name,value,minutes,domain) {
  15713. var expires;
  15714. if (minutes) {
  15715. var date = new Date();
  15716. date.setTime(date.getTime()+(minutes*60*1000));
  15717. expires = "; expires="+date.toGMTString();
  15718. }
  15719. else expires = "";
  15720. domain = (domain)? "domain="+domain+";" : "";
  15721. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  15722. },
  15723. read: function(name) {
  15724. var nameEQ = name + "=";
  15725. var ca = document.cookie.split(';');
  15726. for(var i=0;i < ca.length;i++) {
  15727. var c = ca[i];
  15728. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  15729. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  15730. }
  15731. return null;
  15732. },
  15733. remove: function(name) {
  15734. this.create(name,"",-1);
  15735. }
  15736. };
  15737. var cookie_noop = {
  15738. create: function(name,value,minutes,domain) {},
  15739. read: function(name) { return null; },
  15740. remove: function(name) {}
  15741. };
  15742. // move dependent functions to a container so that
  15743. // they can be overriden easier in no jquery environment (node.js)
  15744. var f = {
  15745. extend: $ ? $.extend : _extend,
  15746. deepExtend: _deepExtend,
  15747. each: $ ? $.each : _each,
  15748. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  15749. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  15750. detectLanguage: detectLanguage,
  15751. escape: _escape,
  15752. log: function(str) {
  15753. if (o.debug && typeof console !== "undefined") console.log(str);
  15754. },
  15755. error: function(str) {
  15756. if (typeof console !== "undefined") console.error(str);
  15757. },
  15758. getCountyIndexOfLng: function(lng) {
  15759. var lng_index = 0;
  15760. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  15761. return lng_index;
  15762. },
  15763. toLanguages: function(lng) {
  15764. var log = this.log;
  15765. function applyCase(l) {
  15766. var ret = l;
  15767. if (typeof l === 'string' && l.indexOf('-') > -1) {
  15768. var parts = l.split('-');
  15769. ret = o.lowerCaseLng ?
  15770. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  15771. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  15772. } else {
  15773. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  15774. }
  15775. return ret;
  15776. }
  15777. var languages = [];
  15778. var whitelist = o.lngWhitelist || false;
  15779. var addLanguage = function(language){
  15780. //reject langs not whitelisted
  15781. if(!whitelist || whitelist.indexOf(language) > -1){
  15782. languages.push(language);
  15783. }else{
  15784. log('rejecting non-whitelisted language: ' + language);
  15785. }
  15786. };
  15787. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  15788. var parts = lng.split('-');
  15789. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  15790. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  15791. } else {
  15792. addLanguage(applyCase(lng));
  15793. }
  15794. for (var i = 0; i < o.fallbackLng.length; i++) {
  15795. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  15796. }
  15797. return languages;
  15798. },
  15799. regexEscape: function(str) {
  15800. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  15801. },
  15802. regexReplacementEscape: function(strOrFn) {
  15803. if (typeof strOrFn === 'string') {
  15804. return strOrFn.replace(/\$/g, "$$$$");
  15805. } else {
  15806. return strOrFn;
  15807. }
  15808. },
  15809. localStorage: {
  15810. setItem: function(key, value) {
  15811. if (window.localStorage) {
  15812. try {
  15813. window.localStorage.setItem(key, value);
  15814. } catch (e) {
  15815. f.log('failed to set value for key "' + key + '" to localStorage.');
  15816. }
  15817. }
  15818. }
  15819. }
  15820. };
  15821. function init(options, cb) {
  15822. if (typeof options === 'function') {
  15823. cb = options;
  15824. options = {};
  15825. }
  15826. options = options || {};
  15827. // override defaults with passed in options
  15828. f.extend(o, options);
  15829. delete o.fixLng; /* passed in each time */
  15830. // override functions: .log(), .detectLanguage(), etc
  15831. if (o.functions) {
  15832. delete o.functions;
  15833. f.extend(f, options.functions);
  15834. }
  15835. // create namespace object if namespace is passed in as string
  15836. if (typeof o.ns == 'string') {
  15837. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  15838. }
  15839. // fallback namespaces
  15840. if (typeof o.fallbackNS == 'string') {
  15841. o.fallbackNS = [o.fallbackNS];
  15842. }
  15843. // fallback languages
  15844. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  15845. o.fallbackLng = [o.fallbackLng];
  15846. }
  15847. // escape prefix/suffix
  15848. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  15849. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  15850. if (!o.lng) o.lng = f.detectLanguage();
  15851. languages = f.toLanguages(o.lng);
  15852. currentLng = languages[0];
  15853. f.log('currentLng set to: ' + currentLng);
  15854. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  15855. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  15856. }
  15857. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  15858. f.localStorage.setItem('i18next_lng', currentLng);
  15859. }
  15860. var lngTranslate = translate;
  15861. if (options.fixLng) {
  15862. lngTranslate = function(key, options) {
  15863. options = options || {};
  15864. options.lng = options.lng || lngTranslate.lng;
  15865. return translate(key, options);
  15866. };
  15867. lngTranslate.lng = currentLng;
  15868. }
  15869. pluralExtensions.setCurrentLng(currentLng);
  15870. // add JQuery extensions
  15871. if ($ && o.setJqueryExt) addJqueryFunct();
  15872. // jQuery deferred
  15873. var deferred;
  15874. if ($ && $.Deferred) {
  15875. deferred = $.Deferred();
  15876. }
  15877. // return immidiatly if res are passed in
  15878. if (o.resStore) {
  15879. resStore = o.resStore;
  15880. initialized = true;
  15881. if (cb) cb(lngTranslate);
  15882. if (deferred) deferred.resolve(lngTranslate);
  15883. if (deferred) return deferred.promise();
  15884. return;
  15885. }
  15886. // languages to load
  15887. var lngsToLoad = f.toLanguages(o.lng);
  15888. if (typeof o.preload === 'string') o.preload = [o.preload];
  15889. for (var i = 0, l = o.preload.length; i < l; i++) {
  15890. var pres = f.toLanguages(o.preload[i]);
  15891. for (var y = 0, len = pres.length; y < len; y++) {
  15892. if (lngsToLoad.indexOf(pres[y]) < 0) {
  15893. lngsToLoad.push(pres[y]);
  15894. }
  15895. }
  15896. }
  15897. // else load them
  15898. i18n.sync.load(lngsToLoad, o, function(err, store) {
  15899. resStore = store;
  15900. initialized = true;
  15901. if (cb) cb(lngTranslate);
  15902. if (deferred) deferred.resolve(lngTranslate);
  15903. });
  15904. if (deferred) return deferred.promise();
  15905. }
  15906. function preload(lngs, cb) {
  15907. if (typeof lngs === 'string') lngs = [lngs];
  15908. for (var i = 0, l = lngs.length; i < l; i++) {
  15909. if (o.preload.indexOf(lngs[i]) < 0) {
  15910. o.preload.push(lngs[i]);
  15911. }
  15912. }
  15913. return init(cb);
  15914. }
  15915. function addResourceBundle(lng, ns, resources, deep) {
  15916. if (typeof ns !== 'string') {
  15917. resources = ns;
  15918. ns = o.ns.defaultNs;
  15919. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  15920. o.ns.namespaces.push(ns);
  15921. }
  15922. resStore[lng] = resStore[lng] || {};
  15923. resStore[lng][ns] = resStore[lng][ns] || {};
  15924. if (deep) {
  15925. f.deepExtend(resStore[lng][ns], resources);
  15926. } else {
  15927. f.extend(resStore[lng][ns], resources);
  15928. }
  15929. }
  15930. function hasResourceBundle(lng, ns) {
  15931. if (typeof ns !== 'string') {
  15932. ns = o.ns.defaultNs;
  15933. }
  15934. resStore[lng] = resStore[lng] || {};
  15935. var res = resStore[lng][ns] || {};
  15936. var hasValues = false;
  15937. for(var prop in res) {
  15938. if (res.hasOwnProperty(prop)) {
  15939. hasValues = true;
  15940. }
  15941. }
  15942. return hasValues;
  15943. }
  15944. function removeResourceBundle(lng, ns) {
  15945. if (typeof ns !== 'string') {
  15946. ns = o.ns.defaultNs;
  15947. }
  15948. resStore[lng] = resStore[lng] || {};
  15949. resStore[lng][ns] = {};
  15950. }
  15951. function addResource(lng, ns, key, value) {
  15952. if (typeof ns !== 'string') {
  15953. resource = ns;
  15954. ns = o.ns.defaultNs;
  15955. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  15956. o.ns.namespaces.push(ns);
  15957. }
  15958. resStore[lng] = resStore[lng] || {};
  15959. resStore[lng][ns] = resStore[lng][ns] || {};
  15960. var keys = key.split(o.keyseparator);
  15961. var x = 0;
  15962. var node = resStore[lng][ns];
  15963. var origRef = node;
  15964. while (keys[x]) {
  15965. if (x == keys.length - 1)
  15966. node[keys[x]] = value;
  15967. else {
  15968. if (node[keys[x]] == null)
  15969. node[keys[x]] = {};
  15970. node = node[keys[x]];
  15971. }
  15972. x++;
  15973. }
  15974. }
  15975. function addResources(lng, ns, resources) {
  15976. if (typeof ns !== 'string') {
  15977. resource = ns;
  15978. ns = o.ns.defaultNs;
  15979. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  15980. o.ns.namespaces.push(ns);
  15981. }
  15982. for (var m in resources) {
  15983. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  15984. }
  15985. }
  15986. function setDefaultNamespace(ns) {
  15987. o.ns.defaultNs = ns;
  15988. }
  15989. function loadNamespace(namespace, cb) {
  15990. loadNamespaces([namespace], cb);
  15991. }
  15992. function loadNamespaces(namespaces, cb) {
  15993. var opts = {
  15994. dynamicLoad: o.dynamicLoad,
  15995. resGetPath: o.resGetPath,
  15996. getAsync: o.getAsync,
  15997. customLoad: o.customLoad,
  15998. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  15999. };
  16000. // languages to load
  16001. var lngsToLoad = f.toLanguages(o.lng);
  16002. if (typeof o.preload === 'string') o.preload = [o.preload];
  16003. for (var i = 0, l = o.preload.length; i < l; i++) {
  16004. var pres = f.toLanguages(o.preload[i]);
  16005. for (var y = 0, len = pres.length; y < len; y++) {
  16006. if (lngsToLoad.indexOf(pres[y]) < 0) {
  16007. lngsToLoad.push(pres[y]);
  16008. }
  16009. }
  16010. }
  16011. // check if we have to load
  16012. var lngNeedLoad = [];
  16013. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  16014. var needLoad = false;
  16015. var resSet = resStore[lngsToLoad[a]];
  16016. if (resSet) {
  16017. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  16018. if (!resSet[namespaces[b]]) needLoad = true;
  16019. }
  16020. } else {
  16021. needLoad = true;
  16022. }
  16023. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  16024. }
  16025. if (lngNeedLoad.length) {
  16026. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  16027. var todo = namespaces.length * lngNeedLoad.length;
  16028. // load each file individual
  16029. f.each(namespaces, function(nsIndex, nsValue) {
  16030. // append namespace to namespace array
  16031. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  16032. o.ns.namespaces.push(nsValue);
  16033. }
  16034. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  16035. resStore[lngValue] = resStore[lngValue] || {};
  16036. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  16037. todo--; // wait for all done befor callback
  16038. if (todo === 0 && cb) {
  16039. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  16040. cb();
  16041. }
  16042. });
  16043. });
  16044. });
  16045. } else {
  16046. if (cb) cb();
  16047. }
  16048. }
  16049. function setLng(lng, options, cb) {
  16050. if (typeof options === 'function') {
  16051. cb = options;
  16052. options = {};
  16053. } else if (!options) {
  16054. options = {};
  16055. }
  16056. options.lng = lng;
  16057. return init(options, cb);
  16058. }
  16059. function lng() {
  16060. return currentLng;
  16061. }
  16062. function reload(cb) {
  16063. resStore = {};
  16064. setLng(currentLng, cb);
  16065. }
  16066. function addJqueryFunct() {
  16067. // $.t shortcut
  16068. $.t = $.t || translate;
  16069. function parse(ele, key, options) {
  16070. if (key.length === 0) return;
  16071. var attr = 'text';
  16072. if (key.indexOf('[') === 0) {
  16073. var parts = key.split(']');
  16074. key = parts[1];
  16075. attr = parts[0].substr(1, parts[0].length-1);
  16076. }
  16077. if (key.indexOf(';') === key.length-1) {
  16078. key = key.substr(0, key.length-2);
  16079. }
  16080. var optionsToUse;
  16081. if (attr === 'html') {
  16082. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  16083. ele.html($.t(key, optionsToUse));
  16084. } else if (attr === 'text') {
  16085. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  16086. ele.text($.t(key, optionsToUse));
  16087. } else if (attr === 'prepend') {
  16088. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  16089. ele.prepend($.t(key, optionsToUse));
  16090. } else if (attr === 'append') {
  16091. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  16092. ele.append($.t(key, optionsToUse));
  16093. } else if (attr.indexOf("data-") === 0) {
  16094. var dataAttr = attr.substr(("data-").length);
  16095. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  16096. var translated = $.t(key, optionsToUse);
  16097. //we change into the data cache
  16098. ele.data(dataAttr, translated);
  16099. //we change into the dom
  16100. ele.attr(attr, translated);
  16101. } else {
  16102. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  16103. ele.attr(attr, $.t(key, optionsToUse));
  16104. }
  16105. }
  16106. function localize(ele, options) {
  16107. var key = ele.attr(o.selectorAttr);
  16108. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  16109. if (!key) return;
  16110. var target = ele
  16111. , targetSelector = ele.data("i18n-target");
  16112. if (targetSelector) {
  16113. target = ele.find(targetSelector) || ele;
  16114. }
  16115. if (!options && o.useDataAttrOptions === true) {
  16116. options = ele.data("i18n-options");
  16117. }
  16118. options = options || {};
  16119. if (key.indexOf(';') >= 0) {
  16120. var keys = key.split(';');
  16121. $.each(keys, function(m, k) {
  16122. if (k !== '') parse(target, k, options);
  16123. });
  16124. } else {
  16125. parse(target, key, options);
  16126. }
  16127. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  16128. }
  16129. // fn
  16130. $.fn.i18n = function (options) {
  16131. return this.each(function() {
  16132. // localize element itself
  16133. localize($(this), options);
  16134. // localize childs
  16135. var elements = $(this).find('[' + o.selectorAttr + ']');
  16136. elements.each(function() {
  16137. localize($(this), options);
  16138. });
  16139. });
  16140. };
  16141. }
  16142. function applyReplacement(str, replacementHash, nestedKey, options) {
  16143. if (!str) return str;
  16144. options = options || replacementHash; // first call uses replacement hash combined with options
  16145. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  16146. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  16147. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  16148. , unEscapingSuffix = 'HTML'+suffix;
  16149. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  16150. f.each(hash, function(key, value) {
  16151. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  16152. if (typeof value === 'object' && value !== null) {
  16153. str = applyReplacement(str, value, nextKey, options);
  16154. } else {
  16155. if (options.escapeInterpolation || o.escapeInterpolation) {
  16156. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  16157. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  16158. } else {
  16159. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  16160. }
  16161. // str = options.escapeInterpolation;
  16162. }
  16163. });
  16164. return str;
  16165. }
  16166. // append it to functions
  16167. f.applyReplacement = applyReplacement;
  16168. function applyReuse(translated, options) {
  16169. var comma = ',';
  16170. var options_open = '{';
  16171. var options_close = '}';
  16172. var opts = f.extend({}, options);
  16173. delete opts.postProcess;
  16174. while (translated.indexOf(o.reusePrefix) != -1) {
  16175. replacementCounter++;
  16176. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  16177. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  16178. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  16179. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  16180. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  16181. if (index_of_end_of_closing <= index_of_opening) {
  16182. f.error('there is an missing closing in following translation value', translated);
  16183. return '';
  16184. }
  16185. if (token_without_symbols.indexOf(comma) != -1) {
  16186. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  16187. 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) {
  16188. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  16189. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  16190. try {
  16191. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  16192. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  16193. } catch (e) {
  16194. }
  16195. }
  16196. }
  16197. var translated_token = _translate(token_without_symbols, opts);
  16198. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  16199. }
  16200. return translated;
  16201. }
  16202. function hasContext(options) {
  16203. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  16204. }
  16205. function needsPlural(options, lng) {
  16206. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  16207. }
  16208. function needsIndefiniteArticle(options) {
  16209. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  16210. }
  16211. function exists(key, options) {
  16212. options = options || {};
  16213. var notFound = _getDefaultValue(key, options)
  16214. , found = _find(key, options);
  16215. return found !== undefined || found === notFound;
  16216. }
  16217. function translate(key, options) {
  16218. options = options || {};
  16219. if (!initialized) {
  16220. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  16221. return options.defaultValue || '';
  16222. };
  16223. replacementCounter = 0;
  16224. return _translate.apply(null, arguments);
  16225. }
  16226. function _getDefaultValue(key, options) {
  16227. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  16228. }
  16229. function _injectSprintfProcessor() {
  16230. var values = [];
  16231. // mh: build array from second argument onwards
  16232. for (var i = 1; i < arguments.length; i++) {
  16233. values.push(arguments[i]);
  16234. }
  16235. return {
  16236. postProcess: 'sprintf',
  16237. sprintf: values
  16238. };
  16239. }
  16240. function _translate(potentialKeys, options) {
  16241. if (options && typeof options !== 'object') {
  16242. if (o.shortcutFunction === 'sprintf') {
  16243. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  16244. options = _injectSprintfProcessor.apply(null, arguments);
  16245. } else if (o.shortcutFunction === 'defaultValue') {
  16246. options = {
  16247. defaultValue: options
  16248. }
  16249. }
  16250. } else {
  16251. options = options || {};
  16252. }
  16253. if (typeof o.defaultVariables === 'object') {
  16254. options = f.extend({}, o.defaultVariables, options);
  16255. }
  16256. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  16257. if (typeof potentialKeys === 'string') {
  16258. potentialKeys = [potentialKeys];
  16259. }
  16260. var key = potentialKeys[0];
  16261. if (potentialKeys.length > 1) {
  16262. for (var i = 0; i < potentialKeys.length; i++) {
  16263. key = potentialKeys[i];
  16264. if (exists(key, options)) {
  16265. break;
  16266. }
  16267. }
  16268. }
  16269. var notFound = _getDefaultValue(key, options)
  16270. , found = _find(key, options)
  16271. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  16272. , ns = options.ns || o.ns.defaultNs
  16273. , parts;
  16274. // split ns and key
  16275. if (key.indexOf(o.nsseparator) > -1) {
  16276. parts = key.split(o.nsseparator);
  16277. ns = parts[0];
  16278. key = parts[1];
  16279. }
  16280. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  16281. if (options.lng) {
  16282. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  16283. } else {
  16284. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  16285. }
  16286. }
  16287. var postProcessor = options.postProcess || o.postProcess;
  16288. if (found !== undefined && postProcessor) {
  16289. if (postProcessors[postProcessor]) {
  16290. found = postProcessors[postProcessor](found, key, options);
  16291. }
  16292. }
  16293. // process notFound if function exists
  16294. var splitNotFound = notFound;
  16295. if (notFound.indexOf(o.nsseparator) > -1) {
  16296. parts = notFound.split(o.nsseparator);
  16297. splitNotFound = parts[1];
  16298. }
  16299. if (splitNotFound === key && o.parseMissingKey) {
  16300. notFound = o.parseMissingKey(notFound);
  16301. }
  16302. if (found === undefined) {
  16303. notFound = applyReplacement(notFound, options);
  16304. notFound = applyReuse(notFound, options);
  16305. if (postProcessor && postProcessors[postProcessor]) {
  16306. var val = _getDefaultValue(key, options);
  16307. found = postProcessors[postProcessor](val, key, options);
  16308. }
  16309. }
  16310. return (found !== undefined) ? found : notFound;
  16311. }
  16312. function _find(key, options) {
  16313. options = options || {};
  16314. var optionWithoutCount, translated
  16315. , notFound = _getDefaultValue(key, options)
  16316. , lngs = languages;
  16317. if (!resStore) { return notFound; } // no resStore to translate from
  16318. // CI mode
  16319. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  16320. // passed in lng
  16321. if (options.lngs) lngs = options.lngs;
  16322. if (options.lng) {
  16323. lngs = f.toLanguages(options.lng, options.fallbackLng);
  16324. if (!resStore[lngs[0]]) {
  16325. var oldAsync = o.getAsync;
  16326. o.getAsync = false;
  16327. i18n.sync.load(lngs, o, function(err, store) {
  16328. f.extend(resStore, store);
  16329. o.getAsync = oldAsync;
  16330. });
  16331. }
  16332. }
  16333. var ns = options.ns || o.ns.defaultNs;
  16334. if (key.indexOf(o.nsseparator) > -1) {
  16335. var parts = key.split(o.nsseparator);
  16336. ns = parts[0];
  16337. key = parts[1];
  16338. }
  16339. if (hasContext(options)) {
  16340. optionWithoutCount = f.extend({}, options);
  16341. delete optionWithoutCount.context;
  16342. optionWithoutCount.defaultValue = o.contextNotFound;
  16343. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  16344. translated = translate(contextKey, optionWithoutCount);
  16345. if (translated != o.contextNotFound) {
  16346. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  16347. } // else continue translation with original/nonContext key
  16348. }
  16349. if (needsPlural(options, lngs[0])) {
  16350. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  16351. delete optionWithoutCount.count;
  16352. delete optionWithoutCount.lng;
  16353. optionWithoutCount.defaultValue = o.pluralNotFound;
  16354. var pluralKey;
  16355. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  16356. pluralKey = ns + o.nsseparator + key;
  16357. } else {
  16358. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  16359. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  16360. if (pluralExtension >= 0) {
  16361. pluralKey = pluralKey + '_' + pluralExtension;
  16362. } else if (pluralExtension === 1) {
  16363. pluralKey = ns + o.nsseparator + key; // singular
  16364. }
  16365. }
  16366. translated = translate(pluralKey, optionWithoutCount);
  16367. if (translated != o.pluralNotFound) {
  16368. return applyReplacement(translated, {
  16369. count: options.count,
  16370. interpolationPrefix: options.interpolationPrefix,
  16371. interpolationSuffix: options.interpolationSuffix
  16372. }); // apply replacement for count only
  16373. } else if (lngs.length > 1) {
  16374. // remove failed lng
  16375. var clone = lngs.slice();
  16376. clone.shift();
  16377. options = f.extend(options, { lngs: clone });
  16378. delete options.lng;
  16379. // retry with fallbacks
  16380. translated = translate(ns + o.nsseparator + key, options);
  16381. if (translated != o.pluralNotFound) return translated;
  16382. } else {
  16383. return translated;
  16384. }
  16385. }
  16386. if (needsIndefiniteArticle(options)) {
  16387. var optionsWithoutIndef = f.extend({}, options);
  16388. delete optionsWithoutIndef.indefinite_article;
  16389. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  16390. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  16391. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  16392. translated = translate(indefiniteKey, optionsWithoutIndef);
  16393. if (translated != o.indefiniteNotFound) {
  16394. return translated;
  16395. }
  16396. }
  16397. var found;
  16398. var keys = key.split(o.keyseparator);
  16399. for (var i = 0, len = lngs.length; i < len; i++ ) {
  16400. if (found !== undefined) break;
  16401. var l = lngs[i];
  16402. var x = 0;
  16403. var value = resStore[l] && resStore[l][ns];
  16404. while (keys[x]) {
  16405. value = value && value[keys[x]];
  16406. x++;
  16407. }
  16408. if (value !== undefined) {
  16409. var valueType = Object.prototype.toString.apply(value);
  16410. if (typeof value === 'string') {
  16411. value = applyReplacement(value, options);
  16412. value = applyReuse(value, options);
  16413. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  16414. value = value.join('\n');
  16415. value = applyReplacement(value, options);
  16416. value = applyReuse(value, options);
  16417. } else if (value === null && o.fallbackOnNull === true) {
  16418. value = undefined;
  16419. } else if (value !== null) {
  16420. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  16421. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  16422. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  16423. } else {
  16424. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  16425. 'returned an object instead of string.';
  16426. f.log(value);
  16427. }
  16428. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  16429. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  16430. f.each(value, function(m) {
  16431. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  16432. });
  16433. value = copy;
  16434. }
  16435. }
  16436. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  16437. value = undefined;
  16438. found = value;
  16439. }
  16440. }
  16441. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  16442. // set flag for fallback lookup - avoid recursion
  16443. options.isFallbackLookup = true;
  16444. if (o.fallbackNS.length) {
  16445. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  16446. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  16447. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  16448. /* compare value without namespace */
  16449. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  16450. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  16451. if (foundValue !== notFoundValue) break;
  16452. }
  16453. }
  16454. } else {
  16455. found = _find(key, options); // fallback to default NS
  16456. }
  16457. options.isFallbackLookup = false;
  16458. }
  16459. return found;
  16460. }
  16461. function detectLanguage() {
  16462. var detectedLng;
  16463. var whitelist = o.lngWhitelist || [];
  16464. var userLngChoices = [];
  16465. // get from qs
  16466. var qsParm = [];
  16467. if (typeof window !== 'undefined') {
  16468. (function() {
  16469. var query = window.location.search.substring(1);
  16470. var params = query.split('&');
  16471. for (var i=0; i<params.length; i++) {
  16472. var pos = params[i].indexOf('=');
  16473. if (pos > 0) {
  16474. var key = params[i].substring(0,pos);
  16475. if (key == o.detectLngQS) {
  16476. userLngChoices.push(params[i].substring(pos+1));
  16477. }
  16478. }
  16479. }
  16480. })();
  16481. }
  16482. // get from cookie
  16483. if (o.useCookie && typeof document !== 'undefined') {
  16484. var c = f.cookie.read(o.cookieName);
  16485. if (c) userLngChoices.push(c);
  16486. }
  16487. // get from localStorage
  16488. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  16489. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  16490. }
  16491. // get from navigator
  16492. if (typeof navigator !== 'undefined') {
  16493. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  16494. for (var i=0;i<navigator.languages.length;i++) {
  16495. userLngChoices.push(navigator.languages[i]);
  16496. }
  16497. }
  16498. if (navigator.userLanguage) {
  16499. userLngChoices.push(navigator.userLanguage);
  16500. }
  16501. if (navigator.language) {
  16502. userLngChoices.push(navigator.language);
  16503. }
  16504. }
  16505. (function() {
  16506. for (var i=0;i<userLngChoices.length;i++) {
  16507. var lng = userLngChoices[i];
  16508. if (lng.indexOf('-') > -1) {
  16509. var parts = lng.split('-');
  16510. lng = o.lowerCaseLng ?
  16511. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  16512. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  16513. }
  16514. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  16515. detectedLng = lng;
  16516. break;
  16517. }
  16518. }
  16519. })();
  16520. //fallback
  16521. if (!detectedLng){
  16522. detectedLng = o.fallbackLng[0];
  16523. }
  16524. return detectedLng;
  16525. }
  16526. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  16527. /* [code, name, numbers, pluralsType] */
  16528. var _rules = [
  16529. ["ach", "Acholi", [1,2], 1],
  16530. ["af", "Afrikaans",[1,2], 2],
  16531. ["ak", "Akan", [1,2], 1],
  16532. ["am", "Amharic", [1,2], 1],
  16533. ["an", "Aragonese",[1,2], 2],
  16534. ["ar", "Arabic", [0,1,2,3,11,100],5],
  16535. ["arn", "Mapudungun",[1,2], 1],
  16536. ["ast", "Asturian", [1,2], 2],
  16537. ["ay", "Aymará", [1], 3],
  16538. ["az", "Azerbaijani",[1,2],2],
  16539. ["be", "Belarusian",[1,2,5],4],
  16540. ["bg", "Bulgarian",[1,2], 2],
  16541. ["bn", "Bengali", [1,2], 2],
  16542. ["bo", "Tibetan", [1], 3],
  16543. ["br", "Breton", [1,2], 1],
  16544. ["bs", "Bosnian", [1,2,5],4],
  16545. ["ca", "Catalan", [1,2], 2],
  16546. ["cgg", "Chiga", [1], 3],
  16547. ["cs", "Czech", [1,2,5],6],
  16548. ["csb", "Kashubian",[1,2,5],7],
  16549. ["cy", "Welsh", [1,2,3,8],8],
  16550. ["da", "Danish", [1,2], 2],
  16551. ["de", "German", [1,2], 2],
  16552. ["dev", "Development Fallback", [1,2], 2],
  16553. ["dz", "Dzongkha", [1], 3],
  16554. ["el", "Greek", [1,2], 2],
  16555. ["en", "English", [1,2], 2],
  16556. ["eo", "Esperanto",[1,2], 2],
  16557. ["es", "Spanish", [1,2], 2],
  16558. ["es_ar","Argentinean Spanish", [1,2], 2],
  16559. ["et", "Estonian", [1,2], 2],
  16560. ["eu", "Basque", [1,2], 2],
  16561. ["fa", "Persian", [1], 3],
  16562. ["fi", "Finnish", [1,2], 2],
  16563. ["fil", "Filipino", [1,2], 1],
  16564. ["fo", "Faroese", [1,2], 2],
  16565. ["fr", "French", [1,2], 9],
  16566. ["fur", "Friulian", [1,2], 2],
  16567. ["fy", "Frisian", [1,2], 2],
  16568. ["ga", "Irish", [1,2,3,7,11],10],
  16569. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  16570. ["gl", "Galician", [1,2], 2],
  16571. ["gu", "Gujarati", [1,2], 2],
  16572. ["gun", "Gun", [1,2], 1],
  16573. ["ha", "Hausa", [1,2], 2],
  16574. ["he", "Hebrew", [1,2], 2],
  16575. ["hi", "Hindi", [1,2], 2],
  16576. ["hr", "Croatian", [1,2,5],4],
  16577. ["hu", "Hungarian",[1,2], 2],
  16578. ["hy", "Armenian", [1,2], 2],
  16579. ["ia", "Interlingua",[1,2],2],
  16580. ["id", "Indonesian",[1], 3],
  16581. ["is", "Icelandic",[1,2], 12],
  16582. ["it", "Italian", [1,2], 2],
  16583. ["ja", "Japanese", [1], 3],
  16584. ["jbo", "Lojban", [1], 3],
  16585. ["jv", "Javanese", [0,1], 13],
  16586. ["ka", "Georgian", [1], 3],
  16587. ["kk", "Kazakh", [1], 3],
  16588. ["km", "Khmer", [1], 3],
  16589. ["kn", "Kannada", [1,2], 2],
  16590. ["ko", "Korean", [1], 3],
  16591. ["ku", "Kurdish", [1,2], 2],
  16592. ["kw", "Cornish", [1,2,3,4],14],
  16593. ["ky", "Kyrgyz", [1], 3],
  16594. ["lb", "Letzeburgesch",[1,2],2],
  16595. ["ln", "Lingala", [1,2], 1],
  16596. ["lo", "Lao", [1], 3],
  16597. ["lt", "Lithuanian",[1,2,10],15],
  16598. ["lv", "Latvian", [1,2,0],16],
  16599. ["mai", "Maithili", [1,2], 2],
  16600. ["mfe", "Mauritian Creole",[1,2],1],
  16601. ["mg", "Malagasy", [1,2], 1],
  16602. ["mi", "Maori", [1,2], 1],
  16603. ["mk", "Macedonian",[1,2],17],
  16604. ["ml", "Malayalam",[1,2], 2],
  16605. ["mn", "Mongolian",[1,2], 2],
  16606. ["mnk", "Mandinka", [0,1,2],18],
  16607. ["mr", "Marathi", [1,2], 2],
  16608. ["ms", "Malay", [1], 3],
  16609. ["mt", "Maltese", [1,2,11,20],19],
  16610. ["nah", "Nahuatl", [1,2], 2],
  16611. ["nap", "Neapolitan",[1,2], 2],
  16612. ["nb", "Norwegian Bokmal",[1,2],2],
  16613. ["ne", "Nepali", [1,2], 2],
  16614. ["nl", "Dutch", [1,2], 2],
  16615. ["nn", "Norwegian Nynorsk",[1,2],2],
  16616. ["no", "Norwegian",[1,2], 2],
  16617. ["nso", "Northern Sotho",[1,2],2],
  16618. ["oc", "Occitan", [1,2], 1],
  16619. ["or", "Oriya", [2,1], 2],
  16620. ["pa", "Punjabi", [1,2], 2],
  16621. ["pap", "Papiamento",[1,2], 2],
  16622. ["pl", "Polish", [1,2,5],7],
  16623. ["pms", "Piemontese",[1,2], 2],
  16624. ["ps", "Pashto", [1,2], 2],
  16625. ["pt", "Portuguese",[1,2], 2],
  16626. ["pt_br","Brazilian Portuguese",[1,2], 2],
  16627. ["rm", "Romansh", [1,2], 2],
  16628. ["ro", "Romanian", [1,2,20],20],
  16629. ["ru", "Russian", [1,2,5],4],
  16630. ["sah", "Yakut", [1], 3],
  16631. ["sco", "Scots", [1,2], 2],
  16632. ["se", "Northern Sami",[1,2], 2],
  16633. ["si", "Sinhala", [1,2], 2],
  16634. ["sk", "Slovak", [1,2,5],6],
  16635. ["sl", "Slovenian",[5,1,2,3],21],
  16636. ["so", "Somali", [1,2], 2],
  16637. ["son", "Songhay", [1,2], 2],
  16638. ["sq", "Albanian", [1,2], 2],
  16639. ["sr", "Serbian", [1,2,5],4],
  16640. ["su", "Sundanese",[1], 3],
  16641. ["sv", "Swedish", [1,2], 2],
  16642. ["sw", "Swahili", [1,2], 2],
  16643. ["ta", "Tamil", [1,2], 2],
  16644. ["te", "Telugu", [1,2], 2],
  16645. ["tg", "Tajik", [1,2], 1],
  16646. ["th", "Thai", [1], 3],
  16647. ["ti", "Tigrinya", [1,2], 1],
  16648. ["tk", "Turkmen", [1,2], 2],
  16649. ["tr", "Turkish", [1,2], 1],
  16650. ["tt", "Tatar", [1], 3],
  16651. ["ug", "Uyghur", [1], 3],
  16652. ["uk", "Ukrainian",[1,2,5],4],
  16653. ["ur", "Urdu", [1,2], 2],
  16654. ["uz", "Uzbek", [1,2], 1],
  16655. ["vi", "Vietnamese",[1], 3],
  16656. ["wa", "Walloon", [1,2], 1],
  16657. ["wo", "Wolof", [1], 3],
  16658. ["yo", "Yoruba", [1,2], 2],
  16659. ["zh", "Chinese", [1], 3]
  16660. ];
  16661. var _rulesPluralsTypes = {
  16662. 1: function(n) {return Number(n > 1);},
  16663. 2: function(n) {return Number(n != 1);},
  16664. 3: function(n) {return 0;},
  16665. 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);},
  16666. 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);},
  16667. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  16668. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  16669. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  16670. 9: function(n) {return Number(n >= 2);},
  16671. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  16672. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  16673. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  16674. 13: function(n) {return Number(n !== 0);},
  16675. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  16676. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  16677. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  16678. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  16679. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  16680. 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);},
  16681. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  16682. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  16683. };
  16684. var pluralExtensions = {
  16685. rules: (function () {
  16686. var l, rules = {};
  16687. for (l=_rules.length; l-- ;) {
  16688. rules[_rules[l][0]] = {
  16689. name: _rules[l][1],
  16690. numbers: _rules[l][2],
  16691. plurals: _rulesPluralsTypes[_rules[l][3]]
  16692. }
  16693. }
  16694. return rules;
  16695. }()),
  16696. // you can add your own pluralExtensions
  16697. addRule: function(lng, obj) {
  16698. pluralExtensions.rules[lng] = obj;
  16699. },
  16700. setCurrentLng: function(lng) {
  16701. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  16702. var parts = lng.split('-');
  16703. pluralExtensions.currentRule = {
  16704. lng: lng,
  16705. rule: pluralExtensions.rules[parts[0]]
  16706. };
  16707. }
  16708. },
  16709. needsPlural: function(lng, count) {
  16710. var parts = lng.split('-');
  16711. var ext;
  16712. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  16713. ext = pluralExtensions.currentRule.rule;
  16714. } else {
  16715. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  16716. }
  16717. if (ext && ext.numbers.length <= 1) {
  16718. return false;
  16719. } else {
  16720. return this.get(lng, count) !== 1;
  16721. }
  16722. },
  16723. get: function(lng, count) {
  16724. var parts = lng.split('-');
  16725. function getResult(l, c) {
  16726. var ext;
  16727. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  16728. ext = pluralExtensions.currentRule.rule;
  16729. } else {
  16730. ext = pluralExtensions.rules[l];
  16731. }
  16732. if (ext) {
  16733. var i;
  16734. if (ext.noAbs) {
  16735. i = ext.plurals(c);
  16736. } else {
  16737. i = ext.plurals(Math.abs(c));
  16738. }
  16739. var number = ext.numbers[i];
  16740. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  16741. if (number === 2) {
  16742. number = -1; // regular plural
  16743. } else if (number === 1) {
  16744. number = 1; // singular
  16745. }
  16746. }//console.log(count + '-' + number);
  16747. return number;
  16748. } else {
  16749. return c === 1 ? '1' : '-1';
  16750. }
  16751. }
  16752. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  16753. }
  16754. };
  16755. var postProcessors = {};
  16756. var addPostProcessor = function(name, fc) {
  16757. postProcessors[name] = fc;
  16758. };
  16759. // sprintf support
  16760. var sprintf = (function() {
  16761. function get_type(variable) {
  16762. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  16763. }
  16764. function str_repeat(input, multiplier) {
  16765. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  16766. return output.join('');
  16767. }
  16768. var str_format = function() {
  16769. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  16770. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  16771. }
  16772. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  16773. };
  16774. str_format.format = function(parse_tree, argv) {
  16775. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  16776. for (i = 0; i < tree_length; i++) {
  16777. node_type = get_type(parse_tree[i]);
  16778. if (node_type === 'string') {
  16779. output.push(parse_tree[i]);
  16780. }
  16781. else if (node_type === 'array') {
  16782. match = parse_tree[i]; // convenience purposes only
  16783. if (match[2]) { // keyword argument
  16784. arg = argv[cursor];
  16785. for (k = 0; k < match[2].length; k++) {
  16786. if (!arg.hasOwnProperty(match[2][k])) {
  16787. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  16788. }
  16789. arg = arg[match[2][k]];
  16790. }
  16791. }
  16792. else if (match[1]) { // positional argument (explicit)
  16793. arg = argv[match[1]];
  16794. }
  16795. else { // positional argument (implicit)
  16796. arg = argv[cursor++];
  16797. }
  16798. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  16799. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  16800. }
  16801. switch (match[8]) {
  16802. case 'b': arg = arg.toString(2); break;
  16803. case 'c': arg = String.fromCharCode(arg); break;
  16804. case 'd': arg = parseInt(arg, 10); break;
  16805. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  16806. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  16807. case 'o': arg = arg.toString(8); break;
  16808. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  16809. case 'u': arg = Math.abs(arg); break;
  16810. case 'x': arg = arg.toString(16); break;
  16811. case 'X': arg = arg.toString(16).toUpperCase(); break;
  16812. }
  16813. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  16814. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  16815. pad_length = match[6] - String(arg).length;
  16816. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  16817. output.push(match[5] ? arg + pad : pad + arg);
  16818. }
  16819. }
  16820. return output.join('');
  16821. };
  16822. str_format.cache = {};
  16823. str_format.parse = function(fmt) {
  16824. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  16825. while (_fmt) {
  16826. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  16827. parse_tree.push(match[0]);
  16828. }
  16829. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  16830. parse_tree.push('%');
  16831. }
  16832. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  16833. if (match[2]) {
  16834. arg_names |= 1;
  16835. var field_list = [], replacement_field = match[2], field_match = [];
  16836. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  16837. field_list.push(field_match[1]);
  16838. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  16839. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  16840. field_list.push(field_match[1]);
  16841. }
  16842. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  16843. field_list.push(field_match[1]);
  16844. }
  16845. else {
  16846. throw('[sprintf] huh?');
  16847. }
  16848. }
  16849. }
  16850. else {
  16851. throw('[sprintf] huh?');
  16852. }
  16853. match[2] = field_list;
  16854. }
  16855. else {
  16856. arg_names |= 2;
  16857. }
  16858. if (arg_names === 3) {
  16859. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  16860. }
  16861. parse_tree.push(match);
  16862. }
  16863. else {
  16864. throw('[sprintf] huh?');
  16865. }
  16866. _fmt = _fmt.substring(match[0].length);
  16867. }
  16868. return parse_tree;
  16869. };
  16870. return str_format;
  16871. })();
  16872. var vsprintf = function(fmt, argv) {
  16873. argv.unshift(fmt);
  16874. return sprintf.apply(null, argv);
  16875. };
  16876. addPostProcessor("sprintf", function(val, key, opts) {
  16877. if (!opts.sprintf) return val;
  16878. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  16879. return vsprintf(val, opts.sprintf);
  16880. } else if (typeof opts.sprintf === 'object') {
  16881. return sprintf(val, opts.sprintf);
  16882. }
  16883. return val;
  16884. });
  16885. // public api interface
  16886. i18n.init = init;
  16887. i18n.setLng = setLng;
  16888. i18n.preload = preload;
  16889. i18n.addResourceBundle = addResourceBundle;
  16890. i18n.hasResourceBundle = hasResourceBundle;
  16891. i18n.addResource = addResource;
  16892. i18n.addResources = addResources;
  16893. i18n.removeResourceBundle = removeResourceBundle;
  16894. i18n.loadNamespace = loadNamespace;
  16895. i18n.loadNamespaces = loadNamespaces;
  16896. i18n.setDefaultNamespace = setDefaultNamespace;
  16897. i18n.t = translate;
  16898. i18n.translate = translate;
  16899. i18n.exists = exists;
  16900. i18n.detectLanguage = f.detectLanguage;
  16901. i18n.pluralExtensions = pluralExtensions;
  16902. i18n.sync = sync;
  16903. i18n.functions = f;
  16904. i18n.lng = lng;
  16905. i18n.addPostProcessor = addPostProcessor;
  16906. i18n.options = o;
  16907. })();
  16908. },{"jquery":"jquery"}],63:[function(require,module,exports){
  16909. // Top level file is just a mixin of submodules & constants
  16910. 'use strict';
  16911. var assign = require('./lib/utils/common').assign;
  16912. var deflate = require('./lib/deflate');
  16913. var inflate = require('./lib/inflate');
  16914. var constants = require('./lib/zlib/constants');
  16915. var pako = {};
  16916. assign(pako, deflate, inflate, constants);
  16917. module.exports = pako;
  16918. },{"./lib/deflate":64,"./lib/inflate":65,"./lib/utils/common":66,"./lib/zlib/constants":69}],64:[function(require,module,exports){
  16919. 'use strict';
  16920. var zlib_deflate = require('./zlib/deflate.js');
  16921. var utils = require('./utils/common');
  16922. var strings = require('./utils/strings');
  16923. var msg = require('./zlib/messages');
  16924. var zstream = require('./zlib/zstream');
  16925. /* Public constants ==========================================================*/
  16926. /* ===========================================================================*/
  16927. var Z_NO_FLUSH = 0;
  16928. var Z_FINISH = 4;
  16929. var Z_OK = 0;
  16930. var Z_STREAM_END = 1;
  16931. var Z_DEFAULT_COMPRESSION = -1;
  16932. var Z_DEFAULT_STRATEGY = 0;
  16933. var Z_DEFLATED = 8;
  16934. /* ===========================================================================*/
  16935. /**
  16936. * class Deflate
  16937. *
  16938. * Generic JS-style wrapper for zlib calls. If you don't need
  16939. * streaming behaviour - use more simple functions: [[deflate]],
  16940. * [[deflateRaw]] and [[gzip]].
  16941. **/
  16942. /* internal
  16943. * Deflate.chunks -> Array
  16944. *
  16945. * Chunks of output data, if [[Deflate#onData]] not overriden.
  16946. **/
  16947. /**
  16948. * Deflate.result -> Uint8Array|Array
  16949. *
  16950. * Compressed result, generated by default [[Deflate#onData]]
  16951. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  16952. * (call [[Deflate#push]] with `Z_FINISH` / `true` param).
  16953. **/
  16954. /**
  16955. * Deflate.err -> Number
  16956. *
  16957. * Error code after deflate finished. 0 (Z_OK) on success.
  16958. * You will not need it in real life, because deflate errors
  16959. * are possible only on wrong options or bad `onData` / `onEnd`
  16960. * custom handlers.
  16961. **/
  16962. /**
  16963. * Deflate.msg -> String
  16964. *
  16965. * Error message, if [[Deflate.err]] != 0
  16966. **/
  16967. /**
  16968. * new Deflate(options)
  16969. * - options (Object): zlib deflate options.
  16970. *
  16971. * Creates new deflator instance with specified params. Throws exception
  16972. * on bad params. Supported options:
  16973. *
  16974. * - `level`
  16975. * - `windowBits`
  16976. * - `memLevel`
  16977. * - `strategy`
  16978. *
  16979. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  16980. * for more information on these.
  16981. *
  16982. * Additional options, for internal needs:
  16983. *
  16984. * - `chunkSize` - size of generated data chunks (16K by default)
  16985. * - `raw` (Boolean) - do raw deflate
  16986. * - `gzip` (Boolean) - create gzip wrapper
  16987. * - `to` (String) - if equal to 'string', then result will be "binary string"
  16988. * (each char code [0..255])
  16989. * - `header` (Object) - custom header for gzip
  16990. * - `text` (Boolean) - true if compressed data believed to be text
  16991. * - `time` (Number) - modification time, unix timestamp
  16992. * - `os` (Number) - operation system code
  16993. * - `extra` (Array) - array of bytes with extra data (max 65536)
  16994. * - `name` (String) - file name (binary string)
  16995. * - `comment` (String) - comment (binary string)
  16996. * - `hcrc` (Boolean) - true if header crc should be added
  16997. *
  16998. * ##### Example:
  16999. *
  17000. * ```javascript
  17001. * var pako = require('pako')
  17002. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  17003. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  17004. *
  17005. * var deflate = new pako.Deflate({ level: 3});
  17006. *
  17007. * deflate.push(chunk1, false);
  17008. * deflate.push(chunk2, true); // true -> last chunk
  17009. *
  17010. * if (deflate.err) { throw new Error(deflate.err); }
  17011. *
  17012. * console.log(deflate.result);
  17013. * ```
  17014. **/
  17015. var Deflate = function(options) {
  17016. this.options = utils.assign({
  17017. level: Z_DEFAULT_COMPRESSION,
  17018. method: Z_DEFLATED,
  17019. chunkSize: 16384,
  17020. windowBits: 15,
  17021. memLevel: 8,
  17022. strategy: Z_DEFAULT_STRATEGY,
  17023. to: ''
  17024. }, options || {});
  17025. var opt = this.options;
  17026. if (opt.raw && (opt.windowBits > 0)) {
  17027. opt.windowBits = -opt.windowBits;
  17028. }
  17029. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  17030. opt.windowBits += 16;
  17031. }
  17032. this.err = 0; // error code, if happens (0 = Z_OK)
  17033. this.msg = ''; // error message
  17034. this.ended = false; // used to avoid multiple onEnd() calls
  17035. this.chunks = []; // chunks of compressed data
  17036. this.strm = new zstream();
  17037. this.strm.avail_out = 0;
  17038. var status = zlib_deflate.deflateInit2(
  17039. this.strm,
  17040. opt.level,
  17041. opt.method,
  17042. opt.windowBits,
  17043. opt.memLevel,
  17044. opt.strategy
  17045. );
  17046. if (status !== Z_OK) {
  17047. throw new Error(msg[status]);
  17048. }
  17049. if (opt.header) {
  17050. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  17051. }
  17052. };
  17053. /**
  17054. * Deflate#push(data[, mode]) -> Boolean
  17055. * - data (Uint8Array|Array|String): input data. Strings will be converted to
  17056. * utf8 byte sequence.
  17057. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  17058. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  17059. *
  17060. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  17061. * new compressed chunks. Returns `true` on success. The last data block must have
  17062. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  17063. * [[Deflate#onEnd]].
  17064. *
  17065. * On fail call [[Deflate#onEnd]] with error code and return false.
  17066. *
  17067. * We strongly recommend to use `Uint8Array` on input for best speed (output
  17068. * array format is detected automatically). Also, don't skip last param and always
  17069. * use the same type in your code (boolean or number). That will improve JS speed.
  17070. *
  17071. * For regular `Array`-s make sure all elements are [0..255].
  17072. *
  17073. * ##### Example
  17074. *
  17075. * ```javascript
  17076. * push(chunk, false); // push one of data chunks
  17077. * ...
  17078. * push(chunk, true); // push last chunk
  17079. * ```
  17080. **/
  17081. Deflate.prototype.push = function(data, mode) {
  17082. var strm = this.strm;
  17083. var chunkSize = this.options.chunkSize;
  17084. var status, _mode;
  17085. if (this.ended) { return false; }
  17086. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  17087. // Convert data if needed
  17088. if (typeof data === 'string') {
  17089. // If we need to compress text, change encoding to utf8.
  17090. strm.input = strings.string2buf(data);
  17091. } else {
  17092. strm.input = data;
  17093. }
  17094. strm.next_in = 0;
  17095. strm.avail_in = strm.input.length;
  17096. do {
  17097. if (strm.avail_out === 0) {
  17098. strm.output = new utils.Buf8(chunkSize);
  17099. strm.next_out = 0;
  17100. strm.avail_out = chunkSize;
  17101. }
  17102. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  17103. if (status !== Z_STREAM_END && status !== Z_OK) {
  17104. this.onEnd(status);
  17105. this.ended = true;
  17106. return false;
  17107. }
  17108. if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) {
  17109. if (this.options.to === 'string') {
  17110. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  17111. } else {
  17112. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  17113. }
  17114. }
  17115. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  17116. // Finalize on the last chunk.
  17117. if (_mode === Z_FINISH) {
  17118. status = zlib_deflate.deflateEnd(this.strm);
  17119. this.onEnd(status);
  17120. this.ended = true;
  17121. return status === Z_OK;
  17122. }
  17123. return true;
  17124. };
  17125. /**
  17126. * Deflate#onData(chunk) -> Void
  17127. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  17128. * on js engine support. When string output requested, each chunk
  17129. * will be string.
  17130. *
  17131. * By default, stores data blocks in `chunks[]` property and glue
  17132. * those in `onEnd`. Override this handler, if you need another behaviour.
  17133. **/
  17134. Deflate.prototype.onData = function(chunk) {
  17135. this.chunks.push(chunk);
  17136. };
  17137. /**
  17138. * Deflate#onEnd(status) -> Void
  17139. * - status (Number): deflate status. 0 (Z_OK) on success,
  17140. * other if not.
  17141. *
  17142. * Called once after you tell deflate that input stream complete
  17143. * or error happenned. By default - join collected chunks,
  17144. * free memory and fill `results` / `err` properties.
  17145. **/
  17146. Deflate.prototype.onEnd = function(status) {
  17147. // On success - join
  17148. if (status === Z_OK) {
  17149. if (this.options.to === 'string') {
  17150. this.result = this.chunks.join('');
  17151. } else {
  17152. this.result = utils.flattenChunks(this.chunks);
  17153. }
  17154. }
  17155. this.chunks = [];
  17156. this.err = status;
  17157. this.msg = this.strm.msg;
  17158. };
  17159. /**
  17160. * deflate(data[, options]) -> Uint8Array|Array|String
  17161. * - data (Uint8Array|Array|String): input data to compress.
  17162. * - options (Object): zlib deflate options.
  17163. *
  17164. * Compress `data` with deflate alrorythm and `options`.
  17165. *
  17166. * Supported options are:
  17167. *
  17168. * - level
  17169. * - windowBits
  17170. * - memLevel
  17171. * - strategy
  17172. *
  17173. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17174. * for more information on these.
  17175. *
  17176. * Sugar (options):
  17177. *
  17178. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  17179. * negative windowBits implicitly.
  17180. * - `to` (String) - if equal to 'string', then result will be "binary string"
  17181. * (each char code [0..255])
  17182. *
  17183. * ##### Example:
  17184. *
  17185. * ```javascript
  17186. * var pako = require('pako')
  17187. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  17188. *
  17189. * console.log(pako.deflate(data));
  17190. * ```
  17191. **/
  17192. function deflate(input, options) {
  17193. var deflator = new Deflate(options);
  17194. deflator.push(input, true);
  17195. // That will never happens, if you don't cheat with options :)
  17196. if (deflator.err) { throw deflator.msg; }
  17197. return deflator.result;
  17198. }
  17199. /**
  17200. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  17201. * - data (Uint8Array|Array|String): input data to compress.
  17202. * - options (Object): zlib deflate options.
  17203. *
  17204. * The same as [[deflate]], but creates raw data, without wrapper
  17205. * (header and adler32 crc).
  17206. **/
  17207. function deflateRaw(input, options) {
  17208. options = options || {};
  17209. options.raw = true;
  17210. return deflate(input, options);
  17211. }
  17212. /**
  17213. * gzip(data[, options]) -> Uint8Array|Array|String
  17214. * - data (Uint8Array|Array|String): input data to compress.
  17215. * - options (Object): zlib deflate options.
  17216. *
  17217. * The same as [[deflate]], but create gzip wrapper instead of
  17218. * deflate one.
  17219. **/
  17220. function gzip(input, options) {
  17221. options = options || {};
  17222. options.gzip = true;
  17223. return deflate(input, options);
  17224. }
  17225. exports.Deflate = Deflate;
  17226. exports.deflate = deflate;
  17227. exports.deflateRaw = deflateRaw;
  17228. exports.gzip = gzip;
  17229. },{"./utils/common":66,"./utils/strings":67,"./zlib/deflate.js":71,"./zlib/messages":76,"./zlib/zstream":78}],65:[function(require,module,exports){
  17230. 'use strict';
  17231. var zlib_inflate = require('./zlib/inflate.js');
  17232. var utils = require('./utils/common');
  17233. var strings = require('./utils/strings');
  17234. var c = require('./zlib/constants');
  17235. var msg = require('./zlib/messages');
  17236. var zstream = require('./zlib/zstream');
  17237. var gzheader = require('./zlib/gzheader');
  17238. /**
  17239. * class Inflate
  17240. *
  17241. * Generic JS-style wrapper for zlib calls. If you don't need
  17242. * streaming behaviour - use more simple functions: [[inflate]]
  17243. * and [[inflateRaw]].
  17244. **/
  17245. /* internal
  17246. * inflate.chunks -> Array
  17247. *
  17248. * Chunks of output data, if [[Inflate#onData]] not overriden.
  17249. **/
  17250. /**
  17251. * Inflate.result -> Uint8Array|Array|String
  17252. *
  17253. * Uncompressed result, generated by default [[Inflate#onData]]
  17254. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  17255. * (call [[Inflate#push]] with `Z_FINISH` / `true` param).
  17256. **/
  17257. /**
  17258. * Inflate.err -> Number
  17259. *
  17260. * Error code after inflate finished. 0 (Z_OK) on success.
  17261. * Should be checked if broken data possible.
  17262. **/
  17263. /**
  17264. * Inflate.msg -> String
  17265. *
  17266. * Error message, if [[Inflate.err]] != 0
  17267. **/
  17268. /**
  17269. * new Inflate(options)
  17270. * - options (Object): zlib inflate options.
  17271. *
  17272. * Creates new inflator instance with specified params. Throws exception
  17273. * on bad params. Supported options:
  17274. *
  17275. * - `windowBits`
  17276. *
  17277. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17278. * for more information on these.
  17279. *
  17280. * Additional options, for internal needs:
  17281. *
  17282. * - `chunkSize` - size of generated data chunks (16K by default)
  17283. * - `raw` (Boolean) - do raw inflate
  17284. * - `to` (String) - if equal to 'string', then result will be converted
  17285. * from utf8 to utf16 (javascript) string. When string output requested,
  17286. * chunk length can differ from `chunkSize`, depending on content.
  17287. *
  17288. * By default, when no options set, autodetect deflate/gzip data format via
  17289. * wrapper header.
  17290. *
  17291. * ##### Example:
  17292. *
  17293. * ```javascript
  17294. * var pako = require('pako')
  17295. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  17296. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  17297. *
  17298. * var inflate = new pako.Inflate({ level: 3});
  17299. *
  17300. * inflate.push(chunk1, false);
  17301. * inflate.push(chunk2, true); // true -> last chunk
  17302. *
  17303. * if (inflate.err) { throw new Error(inflate.err); }
  17304. *
  17305. * console.log(inflate.result);
  17306. * ```
  17307. **/
  17308. var Inflate = function(options) {
  17309. this.options = utils.assign({
  17310. chunkSize: 16384,
  17311. windowBits: 0,
  17312. to: ''
  17313. }, options || {});
  17314. var opt = this.options;
  17315. // Force window size for `raw` data, if not set directly,
  17316. // because we have no header for autodetect.
  17317. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  17318. opt.windowBits = -opt.windowBits;
  17319. if (opt.windowBits === 0) { opt.windowBits = -15; }
  17320. }
  17321. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  17322. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  17323. !(options && options.windowBits)) {
  17324. opt.windowBits += 32;
  17325. }
  17326. // Gzip header has no info about windows size, we can do autodetect only
  17327. // for deflate. So, if window size not set, force it to max when gzip possible
  17328. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  17329. // bit 3 (16) -> gzipped data
  17330. // bit 4 (32) -> autodetect gzip/deflate
  17331. if ((opt.windowBits & 15) === 0) {
  17332. opt.windowBits |= 15;
  17333. }
  17334. }
  17335. this.err = 0; // error code, if happens (0 = Z_OK)
  17336. this.msg = ''; // error message
  17337. this.ended = false; // used to avoid multiple onEnd() calls
  17338. this.chunks = []; // chunks of compressed data
  17339. this.strm = new zstream();
  17340. this.strm.avail_out = 0;
  17341. var status = zlib_inflate.inflateInit2(
  17342. this.strm,
  17343. opt.windowBits
  17344. );
  17345. if (status !== c.Z_OK) {
  17346. throw new Error(msg[status]);
  17347. }
  17348. this.header = new gzheader();
  17349. zlib_inflate.inflateGetHeader(this.strm, this.header);
  17350. };
  17351. /**
  17352. * Inflate#push(data[, mode]) -> Boolean
  17353. * - data (Uint8Array|Array|String): input data
  17354. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  17355. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  17356. *
  17357. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  17358. * new output chunks. Returns `true` on success. The last data block must have
  17359. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  17360. * [[Inflate#onEnd]].
  17361. *
  17362. * On fail call [[Inflate#onEnd]] with error code and return false.
  17363. *
  17364. * We strongly recommend to use `Uint8Array` on input for best speed (output
  17365. * format is detected automatically). Also, don't skip last param and always
  17366. * use the same type in your code (boolean or number). That will improve JS speed.
  17367. *
  17368. * For regular `Array`-s make sure all elements are [0..255].
  17369. *
  17370. * ##### Example
  17371. *
  17372. * ```javascript
  17373. * push(chunk, false); // push one of data chunks
  17374. * ...
  17375. * push(chunk, true); // push last chunk
  17376. * ```
  17377. **/
  17378. Inflate.prototype.push = function(data, mode) {
  17379. var strm = this.strm;
  17380. var chunkSize = this.options.chunkSize;
  17381. var status, _mode;
  17382. var next_out_utf8, tail, utf8str;
  17383. if (this.ended) { return false; }
  17384. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  17385. // Convert data if needed
  17386. if (typeof data === 'string') {
  17387. // Only binary strings can be decompressed on practice
  17388. strm.input = strings.binstring2buf(data);
  17389. } else {
  17390. strm.input = data;
  17391. }
  17392. strm.next_in = 0;
  17393. strm.avail_in = strm.input.length;
  17394. do {
  17395. if (strm.avail_out === 0) {
  17396. strm.output = new utils.Buf8(chunkSize);
  17397. strm.next_out = 0;
  17398. strm.avail_out = chunkSize;
  17399. }
  17400. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  17401. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  17402. this.onEnd(status);
  17403. this.ended = true;
  17404. return false;
  17405. }
  17406. if (strm.next_out) {
  17407. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) {
  17408. if (this.options.to === 'string') {
  17409. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  17410. tail = strm.next_out - next_out_utf8;
  17411. utf8str = strings.buf2string(strm.output, next_out_utf8);
  17412. // move tail
  17413. strm.next_out = tail;
  17414. strm.avail_out = chunkSize - tail;
  17415. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  17416. this.onData(utf8str);
  17417. } else {
  17418. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  17419. }
  17420. }
  17421. }
  17422. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  17423. if (status === c.Z_STREAM_END) {
  17424. _mode = c.Z_FINISH;
  17425. }
  17426. // Finalize on the last chunk.
  17427. if (_mode === c.Z_FINISH) {
  17428. status = zlib_inflate.inflateEnd(this.strm);
  17429. this.onEnd(status);
  17430. this.ended = true;
  17431. return status === c.Z_OK;
  17432. }
  17433. return true;
  17434. };
  17435. /**
  17436. * Inflate#onData(chunk) -> Void
  17437. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  17438. * on js engine support. When string output requested, each chunk
  17439. * will be string.
  17440. *
  17441. * By default, stores data blocks in `chunks[]` property and glue
  17442. * those in `onEnd`. Override this handler, if you need another behaviour.
  17443. **/
  17444. Inflate.prototype.onData = function(chunk) {
  17445. this.chunks.push(chunk);
  17446. };
  17447. /**
  17448. * Inflate#onEnd(status) -> Void
  17449. * - status (Number): inflate status. 0 (Z_OK) on success,
  17450. * other if not.
  17451. *
  17452. * Called once after you tell inflate that input stream complete
  17453. * or error happenned. By default - join collected chunks,
  17454. * free memory and fill `results` / `err` properties.
  17455. **/
  17456. Inflate.prototype.onEnd = function(status) {
  17457. // On success - join
  17458. if (status === c.Z_OK) {
  17459. if (this.options.to === 'string') {
  17460. // Glue & convert here, until we teach pako to send
  17461. // utf8 alligned strings to onData
  17462. this.result = this.chunks.join('');
  17463. } else {
  17464. this.result = utils.flattenChunks(this.chunks);
  17465. }
  17466. }
  17467. this.chunks = [];
  17468. this.err = status;
  17469. this.msg = this.strm.msg;
  17470. };
  17471. /**
  17472. * inflate(data[, options]) -> Uint8Array|Array|String
  17473. * - data (Uint8Array|Array|String): input data to decompress.
  17474. * - options (Object): zlib inflate options.
  17475. *
  17476. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  17477. * format via wrapper header by default. That's why we don't provide
  17478. * separate `ungzip` method.
  17479. *
  17480. * Supported options are:
  17481. *
  17482. * - windowBits
  17483. *
  17484. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17485. * for more information.
  17486. *
  17487. * Sugar (options):
  17488. *
  17489. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  17490. * negative windowBits implicitly.
  17491. * - `to` (String) - if equal to 'string', then result will be converted
  17492. * from utf8 to utf16 (javascript) string. When string output requested,
  17493. * chunk length can differ from `chunkSize`, depending on content.
  17494. *
  17495. *
  17496. * ##### Example:
  17497. *
  17498. * ```javascript
  17499. * var pako = require('pako')
  17500. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  17501. * , output;
  17502. *
  17503. * try {
  17504. * output = pako.inflate(input);
  17505. * } catch (err)
  17506. * console.log(err);
  17507. * }
  17508. * ```
  17509. **/
  17510. function inflate(input, options) {
  17511. var inflator = new Inflate(options);
  17512. inflator.push(input, true);
  17513. // That will never happens, if you don't cheat with options :)
  17514. if (inflator.err) { throw inflator.msg; }
  17515. return inflator.result;
  17516. }
  17517. /**
  17518. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  17519. * - data (Uint8Array|Array|String): input data to decompress.
  17520. * - options (Object): zlib inflate options.
  17521. *
  17522. * The same as [[inflate]], but creates raw data, without wrapper
  17523. * (header and adler32 crc).
  17524. **/
  17525. function inflateRaw(input, options) {
  17526. options = options || {};
  17527. options.raw = true;
  17528. return inflate(input, options);
  17529. }
  17530. /**
  17531. * ungzip(data[, options]) -> Uint8Array|Array|String
  17532. * - data (Uint8Array|Array|String): input data to decompress.
  17533. * - options (Object): zlib inflate options.
  17534. *
  17535. * Just shortcut to [[inflate]], because it autodetects format
  17536. * by header.content. Done for convenience.
  17537. **/
  17538. exports.Inflate = Inflate;
  17539. exports.inflate = inflate;
  17540. exports.inflateRaw = inflateRaw;
  17541. exports.ungzip = inflate;
  17542. },{"./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){
  17543. 'use strict';
  17544. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  17545. (typeof Uint16Array !== 'undefined') &&
  17546. (typeof Int32Array !== 'undefined');
  17547. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  17548. var sources = Array.prototype.slice.call(arguments, 1);
  17549. while (sources.length) {
  17550. var source = sources.shift();
  17551. if (!source) { continue; }
  17552. if (typeof(source) !== 'object') {
  17553. throw new TypeError(source + 'must be non-object');
  17554. }
  17555. for (var p in source) {
  17556. if (source.hasOwnProperty(p)) {
  17557. obj[p] = source[p];
  17558. }
  17559. }
  17560. }
  17561. return obj;
  17562. };
  17563. // reduce buffer size, avoiding mem copy
  17564. exports.shrinkBuf = function (buf, size) {
  17565. if (buf.length === size) { return buf; }
  17566. if (buf.subarray) { return buf.subarray(0, size); }
  17567. buf.length = size;
  17568. return buf;
  17569. };
  17570. var fnTyped = {
  17571. arraySet: function (dest, src, src_offs, len, dest_offs) {
  17572. if (src.subarray && dest.subarray) {
  17573. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  17574. return;
  17575. }
  17576. // Fallback to ordinary array
  17577. for(var i=0; i<len; i++) {
  17578. dest[dest_offs + i] = src[src_offs + i];
  17579. }
  17580. },
  17581. // Join array of chunks to single array.
  17582. flattenChunks: function(chunks) {
  17583. var i, l, len, pos, chunk, result;
  17584. // calculate data length
  17585. len = 0;
  17586. for (i=0, l=chunks.length; i<l; i++) {
  17587. len += chunks[i].length;
  17588. }
  17589. // join chunks
  17590. result = new Uint8Array(len);
  17591. pos = 0;
  17592. for (i=0, l=chunks.length; i<l; i++) {
  17593. chunk = chunks[i];
  17594. result.set(chunk, pos);
  17595. pos += chunk.length;
  17596. }
  17597. return result;
  17598. }
  17599. };
  17600. var fnUntyped = {
  17601. arraySet: function (dest, src, src_offs, len, dest_offs) {
  17602. for(var i=0; i<len; i++) {
  17603. dest[dest_offs + i] = src[src_offs + i];
  17604. }
  17605. },
  17606. // Join array of chunks to single array.
  17607. flattenChunks: function(chunks) {
  17608. return [].concat.apply([], chunks);
  17609. }
  17610. };
  17611. // Enable/Disable typed arrays use, for testing
  17612. //
  17613. exports.setTyped = function (on) {
  17614. if (on) {
  17615. exports.Buf8 = Uint8Array;
  17616. exports.Buf16 = Uint16Array;
  17617. exports.Buf32 = Int32Array;
  17618. exports.assign(exports, fnTyped);
  17619. } else {
  17620. exports.Buf8 = Array;
  17621. exports.Buf16 = Array;
  17622. exports.Buf32 = Array;
  17623. exports.assign(exports, fnUntyped);
  17624. }
  17625. };
  17626. exports.setTyped(TYPED_OK);
  17627. },{}],67:[function(require,module,exports){
  17628. // String encode/decode helpers
  17629. 'use strict';
  17630. var utils = require('./common');
  17631. // Quick check if we can use fast array to bin string conversion
  17632. //
  17633. // - apply(Array) can fail on Android 2.2
  17634. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  17635. //
  17636. var STR_APPLY_OK = true;
  17637. var STR_APPLY_UIA_OK = true;
  17638. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  17639. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  17640. // Table with utf8 lengths (calculated by first byte of sequence)
  17641. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  17642. // because max possible codepoint is 0x10ffff
  17643. var _utf8len = new utils.Buf8(256);
  17644. for (var i=0; i<256; i++) {
  17645. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  17646. }
  17647. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  17648. // convert string to array (typed, when possible)
  17649. exports.string2buf = function (str) {
  17650. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  17651. // count binary size
  17652. for (m_pos = 0; m_pos < str_len; m_pos++) {
  17653. c = str.charCodeAt(m_pos);
  17654. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  17655. c2 = str.charCodeAt(m_pos+1);
  17656. if ((c2 & 0xfc00) === 0xdc00) {
  17657. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  17658. m_pos++;
  17659. }
  17660. }
  17661. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  17662. }
  17663. // allocate buffer
  17664. buf = new utils.Buf8(buf_len);
  17665. // convert
  17666. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  17667. c = str.charCodeAt(m_pos);
  17668. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  17669. c2 = str.charCodeAt(m_pos+1);
  17670. if ((c2 & 0xfc00) === 0xdc00) {
  17671. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  17672. m_pos++;
  17673. }
  17674. }
  17675. if (c < 0x80) {
  17676. /* one byte */
  17677. buf[i++] = c;
  17678. } else if (c < 0x800) {
  17679. /* two bytes */
  17680. buf[i++] = 0xC0 | (c >>> 6);
  17681. buf[i++] = 0x80 | (c & 0x3f);
  17682. } else if (c < 0x10000) {
  17683. /* three bytes */
  17684. buf[i++] = 0xE0 | (c >>> 12);
  17685. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  17686. buf[i++] = 0x80 | (c & 0x3f);
  17687. } else {
  17688. /* four bytes */
  17689. buf[i++] = 0xf0 | (c >>> 18);
  17690. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  17691. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  17692. buf[i++] = 0x80 | (c & 0x3f);
  17693. }
  17694. }
  17695. return buf;
  17696. };
  17697. // Helper (used in 2 places)
  17698. function buf2binstring(buf, len) {
  17699. // use fallback for big arrays to avoid stack overflow
  17700. if (len < 65537) {
  17701. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  17702. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  17703. }
  17704. }
  17705. var result = '';
  17706. for(var i=0; i < len; i++) {
  17707. result += String.fromCharCode(buf[i]);
  17708. }
  17709. return result;
  17710. }
  17711. // Convert byte array to binary string
  17712. exports.buf2binstring = function(buf) {
  17713. return buf2binstring(buf, buf.length);
  17714. };
  17715. // Convert binary string (typed, when possible)
  17716. exports.binstring2buf = function(str) {
  17717. var buf = new utils.Buf8(str.length);
  17718. for(var i=0, len=buf.length; i < len; i++) {
  17719. buf[i] = str.charCodeAt(i);
  17720. }
  17721. return buf;
  17722. };
  17723. // convert array to string
  17724. exports.buf2string = function (buf, max) {
  17725. var i, out, c, c_len;
  17726. var len = max || buf.length;
  17727. // Reserve max possible length (2 words per char)
  17728. // NB: by unknown reasons, Array is significantly faster for
  17729. // String.fromCharCode.apply than Uint16Array.
  17730. var utf16buf = new Array(len*2);
  17731. for (out=0, i=0; i<len;) {
  17732. c = buf[i++];
  17733. // quick process ascii
  17734. if (c < 0x80) { utf16buf[out++] = c; continue; }
  17735. c_len = _utf8len[c];
  17736. // skip 5 & 6 byte codes
  17737. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  17738. // apply mask on first byte
  17739. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  17740. // join the rest
  17741. while (c_len > 1 && i < len) {
  17742. c = (c << 6) | (buf[i++] & 0x3f);
  17743. c_len--;
  17744. }
  17745. // terminated by end of string?
  17746. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  17747. if (c < 0x10000) {
  17748. utf16buf[out++] = c;
  17749. } else {
  17750. c -= 0x10000;
  17751. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  17752. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  17753. }
  17754. }
  17755. return buf2binstring(utf16buf, out);
  17756. };
  17757. // Calculate max possible position in utf8 buffer,
  17758. // that will not break sequence. If that's not possible
  17759. // - (very small limits) return max size as is.
  17760. //
  17761. // buf[] - utf8 bytes array
  17762. // max - length limit (mandatory);
  17763. exports.utf8border = function(buf, max) {
  17764. var pos;
  17765. max = max || buf.length;
  17766. if (max > buf.length) { max = buf.length; }
  17767. // go back from last position, until start of sequence found
  17768. pos = max-1;
  17769. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  17770. // Fuckup - very small and broken sequence,
  17771. // return max, because we should return something anyway.
  17772. if (pos < 0) { return max; }
  17773. // If we came to start of buffer - that means vuffer is too small,
  17774. // return max too.
  17775. if (pos === 0) { return max; }
  17776. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  17777. };
  17778. },{"./common":66}],68:[function(require,module,exports){
  17779. 'use strict';
  17780. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  17781. // It doesn't worth to make additional optimizationa as in original.
  17782. // Small size is preferable.
  17783. function adler32(adler, buf, len, pos) {
  17784. var s1 = (adler & 0xffff) |0
  17785. , s2 = ((adler >>> 16) & 0xffff) |0
  17786. , n = 0;
  17787. while (len !== 0) {
  17788. // Set limit ~ twice less than 5552, to keep
  17789. // s2 in 31-bits, because we force signed ints.
  17790. // in other case %= will fail.
  17791. n = len > 2000 ? 2000 : len;
  17792. len -= n;
  17793. do {
  17794. s1 = (s1 + buf[pos++]) |0;
  17795. s2 = (s2 + s1) |0;
  17796. } while (--n);
  17797. s1 %= 65521;
  17798. s2 %= 65521;
  17799. }
  17800. return (s1 | (s2 << 16)) |0;
  17801. }
  17802. module.exports = adler32;
  17803. },{}],69:[function(require,module,exports){
  17804. module.exports = {
  17805. /* Allowed flush values; see deflate() and inflate() below for details */
  17806. Z_NO_FLUSH: 0,
  17807. Z_PARTIAL_FLUSH: 1,
  17808. Z_SYNC_FLUSH: 2,
  17809. Z_FULL_FLUSH: 3,
  17810. Z_FINISH: 4,
  17811. Z_BLOCK: 5,
  17812. Z_TREES: 6,
  17813. /* Return codes for the compression/decompression functions. Negative values
  17814. * are errors, positive values are used for special but normal events.
  17815. */
  17816. Z_OK: 0,
  17817. Z_STREAM_END: 1,
  17818. Z_NEED_DICT: 2,
  17819. Z_ERRNO: -1,
  17820. Z_STREAM_ERROR: -2,
  17821. Z_DATA_ERROR: -3,
  17822. //Z_MEM_ERROR: -4,
  17823. Z_BUF_ERROR: -5,
  17824. //Z_VERSION_ERROR: -6,
  17825. /* compression levels */
  17826. Z_NO_COMPRESSION: 0,
  17827. Z_BEST_SPEED: 1,
  17828. Z_BEST_COMPRESSION: 9,
  17829. Z_DEFAULT_COMPRESSION: -1,
  17830. Z_FILTERED: 1,
  17831. Z_HUFFMAN_ONLY: 2,
  17832. Z_RLE: 3,
  17833. Z_FIXED: 4,
  17834. Z_DEFAULT_STRATEGY: 0,
  17835. /* Possible values of the data_type field (though see inflate()) */
  17836. Z_BINARY: 0,
  17837. Z_TEXT: 1,
  17838. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  17839. Z_UNKNOWN: 2,
  17840. /* The deflate compression method */
  17841. Z_DEFLATED: 8
  17842. //Z_NULL: null // Use -1 or null inline, depending on var type
  17843. };
  17844. },{}],70:[function(require,module,exports){
  17845. 'use strict';
  17846. // Note: we can't get significant speed boost here.
  17847. // So write code to minimize size - no pregenerated tables
  17848. // and array tools dependencies.
  17849. // Use ordinary array, since untyped makes no boost here
  17850. function makeTable() {
  17851. var c, table = [];
  17852. for(var n =0; n < 256; n++){
  17853. c = n;
  17854. for(var k =0; k < 8; k++){
  17855. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  17856. }
  17857. table[n] = c;
  17858. }
  17859. return table;
  17860. }
  17861. // Create table on load. Just 255 signed longs. Not a problem.
  17862. var crcTable = makeTable();
  17863. function crc32(crc, buf, len, pos) {
  17864. var t = crcTable
  17865. , end = pos + len;
  17866. crc = crc ^ (-1);
  17867. for (var i = pos; i < end; i++ ) {
  17868. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  17869. }
  17870. return (crc ^ (-1)); // >>> 0;
  17871. }
  17872. module.exports = crc32;
  17873. },{}],71:[function(require,module,exports){
  17874. 'use strict';
  17875. var utils = require('../utils/common');
  17876. var trees = require('./trees');
  17877. var adler32 = require('./adler32');
  17878. var crc32 = require('./crc32');
  17879. var msg = require('./messages');
  17880. /* Public constants ==========================================================*/
  17881. /* ===========================================================================*/
  17882. /* Allowed flush values; see deflate() and inflate() below for details */
  17883. var Z_NO_FLUSH = 0;
  17884. var Z_PARTIAL_FLUSH = 1;
  17885. //var Z_SYNC_FLUSH = 2;
  17886. var Z_FULL_FLUSH = 3;
  17887. var Z_FINISH = 4;
  17888. var Z_BLOCK = 5;
  17889. //var Z_TREES = 6;
  17890. /* Return codes for the compression/decompression functions. Negative values
  17891. * are errors, positive values are used for special but normal events.
  17892. */
  17893. var Z_OK = 0;
  17894. var Z_STREAM_END = 1;
  17895. //var Z_NEED_DICT = 2;
  17896. //var Z_ERRNO = -1;
  17897. var Z_STREAM_ERROR = -2;
  17898. var Z_DATA_ERROR = -3;
  17899. //var Z_MEM_ERROR = -4;
  17900. var Z_BUF_ERROR = -5;
  17901. //var Z_VERSION_ERROR = -6;
  17902. /* compression levels */
  17903. //var Z_NO_COMPRESSION = 0;
  17904. //var Z_BEST_SPEED = 1;
  17905. //var Z_BEST_COMPRESSION = 9;
  17906. var Z_DEFAULT_COMPRESSION = -1;
  17907. var Z_FILTERED = 1;
  17908. var Z_HUFFMAN_ONLY = 2;
  17909. var Z_RLE = 3;
  17910. var Z_FIXED = 4;
  17911. var Z_DEFAULT_STRATEGY = 0;
  17912. /* Possible values of the data_type field (though see inflate()) */
  17913. //var Z_BINARY = 0;
  17914. //var Z_TEXT = 1;
  17915. //var Z_ASCII = 1; // = Z_TEXT
  17916. var Z_UNKNOWN = 2;
  17917. /* The deflate compression method */
  17918. var Z_DEFLATED = 8;
  17919. /*============================================================================*/
  17920. var MAX_MEM_LEVEL = 9;
  17921. /* Maximum value for memLevel in deflateInit2 */
  17922. var MAX_WBITS = 15;
  17923. /* 32K LZ77 window */
  17924. var DEF_MEM_LEVEL = 8;
  17925. var LENGTH_CODES = 29;
  17926. /* number of length codes, not counting the special END_BLOCK code */
  17927. var LITERALS = 256;
  17928. /* number of literal bytes 0..255 */
  17929. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  17930. /* number of Literal or Length codes, including the END_BLOCK code */
  17931. var D_CODES = 30;
  17932. /* number of distance codes */
  17933. var BL_CODES = 19;
  17934. /* number of codes used to transfer the bit lengths */
  17935. var HEAP_SIZE = 2*L_CODES + 1;
  17936. /* maximum heap size */
  17937. var MAX_BITS = 15;
  17938. /* All codes must not exceed MAX_BITS bits */
  17939. var MIN_MATCH = 3;
  17940. var MAX_MATCH = 258;
  17941. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  17942. var PRESET_DICT = 0x20;
  17943. var INIT_STATE = 42;
  17944. var EXTRA_STATE = 69;
  17945. var NAME_STATE = 73;
  17946. var COMMENT_STATE = 91;
  17947. var HCRC_STATE = 103;
  17948. var BUSY_STATE = 113;
  17949. var FINISH_STATE = 666;
  17950. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  17951. var BS_BLOCK_DONE = 2; /* block flush performed */
  17952. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  17953. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  17954. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  17955. function err(strm, errorCode) {
  17956. strm.msg = msg[errorCode];
  17957. return errorCode;
  17958. }
  17959. function rank(f) {
  17960. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  17961. }
  17962. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  17963. /* =========================================================================
  17964. * Flush as much pending output as possible. All deflate() output goes
  17965. * through this function so some applications may wish to modify it
  17966. * to avoid allocating a large strm->output buffer and copying into it.
  17967. * (See also read_buf()).
  17968. */
  17969. function flush_pending(strm) {
  17970. var s = strm.state;
  17971. //_tr_flush_bits(s);
  17972. var len = s.pending;
  17973. if (len > strm.avail_out) {
  17974. len = strm.avail_out;
  17975. }
  17976. if (len === 0) { return; }
  17977. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  17978. strm.next_out += len;
  17979. s.pending_out += len;
  17980. strm.total_out += len;
  17981. strm.avail_out -= len;
  17982. s.pending -= len;
  17983. if (s.pending === 0) {
  17984. s.pending_out = 0;
  17985. }
  17986. }
  17987. function flush_block_only (s, last) {
  17988. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  17989. s.block_start = s.strstart;
  17990. flush_pending(s.strm);
  17991. }
  17992. function put_byte(s, b) {
  17993. s.pending_buf[s.pending++] = b;
  17994. }
  17995. /* =========================================================================
  17996. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  17997. * IN assertion: the stream state is correct and there is enough room in
  17998. * pending_buf.
  17999. */
  18000. function putShortMSB(s, b) {
  18001. // put_byte(s, (Byte)(b >> 8));
  18002. // put_byte(s, (Byte)(b & 0xff));
  18003. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  18004. s.pending_buf[s.pending++] = b & 0xff;
  18005. }
  18006. /* ===========================================================================
  18007. * Read a new buffer from the current input stream, update the adler32
  18008. * and total number of bytes read. All deflate() input goes through
  18009. * this function so some applications may wish to modify it to avoid
  18010. * allocating a large strm->input buffer and copying from it.
  18011. * (See also flush_pending()).
  18012. */
  18013. function read_buf(strm, buf, start, size) {
  18014. var len = strm.avail_in;
  18015. if (len > size) { len = size; }
  18016. if (len === 0) { return 0; }
  18017. strm.avail_in -= len;
  18018. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  18019. if (strm.state.wrap === 1) {
  18020. strm.adler = adler32(strm.adler, buf, len, start);
  18021. }
  18022. else if (strm.state.wrap === 2) {
  18023. strm.adler = crc32(strm.adler, buf, len, start);
  18024. }
  18025. strm.next_in += len;
  18026. strm.total_in += len;
  18027. return len;
  18028. }
  18029. /* ===========================================================================
  18030. * Set match_start to the longest match starting at the given string and
  18031. * return its length. Matches shorter or equal to prev_length are discarded,
  18032. * in which case the result is equal to prev_length and match_start is
  18033. * garbage.
  18034. * IN assertions: cur_match is the head of the hash chain for the current
  18035. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  18036. * OUT assertion: the match length is not greater than s->lookahead.
  18037. */
  18038. function longest_match(s, cur_match) {
  18039. var chain_length = s.max_chain_length; /* max hash chain length */
  18040. var scan = s.strstart; /* current string */
  18041. var match; /* matched string */
  18042. var len; /* length of current match */
  18043. var best_len = s.prev_length; /* best match length so far */
  18044. var nice_match = s.nice_match; /* stop if match long enough */
  18045. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  18046. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  18047. var _win = s.window; // shortcut
  18048. var wmask = s.w_mask;
  18049. var prev = s.prev;
  18050. /* Stop when cur_match becomes <= limit. To simplify the code,
  18051. * we prevent matches with the string of window index 0.
  18052. */
  18053. var strend = s.strstart + MAX_MATCH;
  18054. var scan_end1 = _win[scan + best_len - 1];
  18055. var scan_end = _win[scan + best_len];
  18056. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  18057. * It is easy to get rid of this optimization if necessary.
  18058. */
  18059. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  18060. /* Do not waste too much time if we already have a good match: */
  18061. if (s.prev_length >= s.good_match) {
  18062. chain_length >>= 2;
  18063. }
  18064. /* Do not look for matches beyond the end of the input. This is necessary
  18065. * to make deflate deterministic.
  18066. */
  18067. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  18068. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  18069. do {
  18070. // Assert(cur_match < s->strstart, "no future");
  18071. match = cur_match;
  18072. /* Skip to next match if the match length cannot increase
  18073. * or if the match length is less than 2. Note that the checks below
  18074. * for insufficient lookahead only occur occasionally for performance
  18075. * reasons. Therefore uninitialized memory will be accessed, and
  18076. * conditional jumps will be made that depend on those values.
  18077. * However the length of the match is limited to the lookahead, so
  18078. * the output of deflate is not affected by the uninitialized values.
  18079. */
  18080. if (_win[match + best_len] !== scan_end ||
  18081. _win[match + best_len - 1] !== scan_end1 ||
  18082. _win[match] !== _win[scan] ||
  18083. _win[++match] !== _win[scan + 1]) {
  18084. continue;
  18085. }
  18086. /* The check at best_len-1 can be removed because it will be made
  18087. * again later. (This heuristic is not always a win.)
  18088. * It is not necessary to compare scan[2] and match[2] since they
  18089. * are always equal when the other bytes match, given that
  18090. * the hash keys are equal and that HASH_BITS >= 8.
  18091. */
  18092. scan += 2;
  18093. match++;
  18094. // Assert(*scan == *match, "match[2]?");
  18095. /* We check for insufficient lookahead only every 8th comparison;
  18096. * the 256th check will be made at strstart+258.
  18097. */
  18098. do {
  18099. /*jshint noempty:false*/
  18100. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18101. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18102. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18103. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18104. scan < strend);
  18105. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  18106. len = MAX_MATCH - (strend - scan);
  18107. scan = strend - MAX_MATCH;
  18108. if (len > best_len) {
  18109. s.match_start = cur_match;
  18110. best_len = len;
  18111. if (len >= nice_match) {
  18112. break;
  18113. }
  18114. scan_end1 = _win[scan + best_len - 1];
  18115. scan_end = _win[scan + best_len];
  18116. }
  18117. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  18118. if (best_len <= s.lookahead) {
  18119. return best_len;
  18120. }
  18121. return s.lookahead;
  18122. }
  18123. /* ===========================================================================
  18124. * Fill the window when the lookahead becomes insufficient.
  18125. * Updates strstart and lookahead.
  18126. *
  18127. * IN assertion: lookahead < MIN_LOOKAHEAD
  18128. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  18129. * At least one byte has been read, or avail_in == 0; reads are
  18130. * performed for at least two bytes (required for the zip translate_eol
  18131. * option -- not supported here).
  18132. */
  18133. function fill_window(s) {
  18134. var _w_size = s.w_size;
  18135. var p, n, m, more, str;
  18136. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  18137. do {
  18138. more = s.window_size - s.lookahead - s.strstart;
  18139. // JS ints have 32 bit, block below not needed
  18140. /* Deal with !@#$% 64K limit: */
  18141. //if (sizeof(int) <= 2) {
  18142. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  18143. // more = wsize;
  18144. //
  18145. // } else if (more == (unsigned)(-1)) {
  18146. // /* Very unlikely, but possible on 16 bit machine if
  18147. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  18148. // */
  18149. // more--;
  18150. // }
  18151. //}
  18152. /* If the window is almost full and there is insufficient lookahead,
  18153. * move the upper half to the lower one to make room in the upper half.
  18154. */
  18155. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  18156. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  18157. s.match_start -= _w_size;
  18158. s.strstart -= _w_size;
  18159. /* we now have strstart >= MAX_DIST */
  18160. s.block_start -= _w_size;
  18161. /* Slide the hash table (could be avoided with 32 bit values
  18162. at the expense of memory usage). We slide even when level == 0
  18163. to keep the hash table consistent if we switch back to level > 0
  18164. later. (Using level 0 permanently is not an optimal usage of
  18165. zlib, so we don't care about this pathological case.)
  18166. */
  18167. n = s.hash_size;
  18168. p = n;
  18169. do {
  18170. m = s.head[--p];
  18171. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  18172. } while (--n);
  18173. n = _w_size;
  18174. p = n;
  18175. do {
  18176. m = s.prev[--p];
  18177. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  18178. /* If n is not on any hash chain, prev[n] is garbage but
  18179. * its value will never be used.
  18180. */
  18181. } while (--n);
  18182. more += _w_size;
  18183. }
  18184. if (s.strm.avail_in === 0) {
  18185. break;
  18186. }
  18187. /* If there was no sliding:
  18188. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  18189. * more == window_size - lookahead - strstart
  18190. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  18191. * => more >= window_size - 2*WSIZE + 2
  18192. * In the BIG_MEM or MMAP case (not yet supported),
  18193. * window_size == input_size + MIN_LOOKAHEAD &&
  18194. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  18195. * Otherwise, window_size == 2*WSIZE so more >= 2.
  18196. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  18197. */
  18198. //Assert(more >= 2, "more < 2");
  18199. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  18200. s.lookahead += n;
  18201. /* Initialize the hash value now that we have some input: */
  18202. if (s.lookahead + s.insert >= MIN_MATCH) {
  18203. str = s.strstart - s.insert;
  18204. s.ins_h = s.window[str];
  18205. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  18206. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  18207. //#if MIN_MATCH != 3
  18208. // Call update_hash() MIN_MATCH-3 more times
  18209. //#endif
  18210. while (s.insert) {
  18211. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  18212. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  18213. s.prev[str & s.w_mask] = s.head[s.ins_h];
  18214. s.head[s.ins_h] = str;
  18215. str++;
  18216. s.insert--;
  18217. if (s.lookahead + s.insert < MIN_MATCH) {
  18218. break;
  18219. }
  18220. }
  18221. }
  18222. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  18223. * but this is not important since only literal bytes will be emitted.
  18224. */
  18225. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  18226. /* If the WIN_INIT bytes after the end of the current data have never been
  18227. * written, then zero those bytes in order to avoid memory check reports of
  18228. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  18229. * the longest match routines. Update the high water mark for the next
  18230. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  18231. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  18232. */
  18233. // if (s.high_water < s.window_size) {
  18234. // var curr = s.strstart + s.lookahead;
  18235. // var init = 0;
  18236. //
  18237. // if (s.high_water < curr) {
  18238. // /* Previous high water mark below current data -- zero WIN_INIT
  18239. // * bytes or up to end of window, whichever is less.
  18240. // */
  18241. // init = s.window_size - curr;
  18242. // if (init > WIN_INIT)
  18243. // init = WIN_INIT;
  18244. // zmemzero(s->window + curr, (unsigned)init);
  18245. // s->high_water = curr + init;
  18246. // }
  18247. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  18248. // /* High water mark at or above current data, but below current data
  18249. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  18250. // * to end of window, whichever is less.
  18251. // */
  18252. // init = (ulg)curr + WIN_INIT - s->high_water;
  18253. // if (init > s->window_size - s->high_water)
  18254. // init = s->window_size - s->high_water;
  18255. // zmemzero(s->window + s->high_water, (unsigned)init);
  18256. // s->high_water += init;
  18257. // }
  18258. // }
  18259. //
  18260. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  18261. // "not enough room for search");
  18262. }
  18263. /* ===========================================================================
  18264. * Copy without compression as much as possible from the input stream, return
  18265. * the current block state.
  18266. * This function does not insert new strings in the dictionary since
  18267. * uncompressible data is probably not useful. This function is used
  18268. * only for the level=0 compression option.
  18269. * NOTE: this function should be optimized to avoid extra copying from
  18270. * window to pending_buf.
  18271. */
  18272. function deflate_stored(s, flush) {
  18273. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  18274. * to pending_buf_size, and each stored block has a 5 byte header:
  18275. */
  18276. var max_block_size = 0xffff;
  18277. if (max_block_size > s.pending_buf_size - 5) {
  18278. max_block_size = s.pending_buf_size - 5;
  18279. }
  18280. /* Copy as much as possible from input to output: */
  18281. for (;;) {
  18282. /* Fill the window as much as possible: */
  18283. if (s.lookahead <= 1) {
  18284. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  18285. // s->block_start >= (long)s->w_size, "slide too late");
  18286. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  18287. // s.block_start >= s.w_size)) {
  18288. // throw new Error("slide too late");
  18289. // }
  18290. fill_window(s);
  18291. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  18292. return BS_NEED_MORE;
  18293. }
  18294. if (s.lookahead === 0) {
  18295. break;
  18296. }
  18297. /* flush the current block */
  18298. }
  18299. //Assert(s->block_start >= 0L, "block gone");
  18300. // if (s.block_start < 0) throw new Error("block gone");
  18301. s.strstart += s.lookahead;
  18302. s.lookahead = 0;
  18303. /* Emit a stored block if pending_buf will be full: */
  18304. var max_start = s.block_start + max_block_size;
  18305. if (s.strstart === 0 || s.strstart >= max_start) {
  18306. /* strstart == 0 is possible when wraparound on 16-bit machine */
  18307. s.lookahead = s.strstart - max_start;
  18308. s.strstart = max_start;
  18309. /*** FLUSH_BLOCK(s, 0); ***/
  18310. flush_block_only(s, false);
  18311. if (s.strm.avail_out === 0) {
  18312. return BS_NEED_MORE;
  18313. }
  18314. /***/
  18315. }
  18316. /* Flush if we may have to slide, otherwise block_start may become
  18317. * negative and the data will be gone:
  18318. */
  18319. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  18320. /*** FLUSH_BLOCK(s, 0); ***/
  18321. flush_block_only(s, false);
  18322. if (s.strm.avail_out === 0) {
  18323. return BS_NEED_MORE;
  18324. }
  18325. /***/
  18326. }
  18327. }
  18328. s.insert = 0;
  18329. if (flush === Z_FINISH) {
  18330. /*** FLUSH_BLOCK(s, 1); ***/
  18331. flush_block_only(s, true);
  18332. if (s.strm.avail_out === 0) {
  18333. return BS_FINISH_STARTED;
  18334. }
  18335. /***/
  18336. return BS_FINISH_DONE;
  18337. }
  18338. if (s.strstart > s.block_start) {
  18339. /*** FLUSH_BLOCK(s, 0); ***/
  18340. flush_block_only(s, false);
  18341. if (s.strm.avail_out === 0) {
  18342. return BS_NEED_MORE;
  18343. }
  18344. /***/
  18345. }
  18346. return BS_NEED_MORE;
  18347. }
  18348. /* ===========================================================================
  18349. * Compress as much as possible from the input stream, return the current
  18350. * block state.
  18351. * This function does not perform lazy evaluation of matches and inserts
  18352. * new strings in the dictionary only for unmatched strings or for short
  18353. * matches. It is used only for the fast compression options.
  18354. */
  18355. function deflate_fast(s, flush) {
  18356. var hash_head; /* head of the hash chain */
  18357. var bflush; /* set if current block must be flushed */
  18358. for (;;) {
  18359. /* Make sure that we always have enough lookahead, except
  18360. * at the end of the input file. We need MAX_MATCH bytes
  18361. * for the next match, plus MIN_MATCH bytes to insert the
  18362. * string following the next match.
  18363. */
  18364. if (s.lookahead < MIN_LOOKAHEAD) {
  18365. fill_window(s);
  18366. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  18367. return BS_NEED_MORE;
  18368. }
  18369. if (s.lookahead === 0) {
  18370. break; /* flush the current block */
  18371. }
  18372. }
  18373. /* Insert the string window[strstart .. strstart+2] in the
  18374. * dictionary, and set hash_head to the head of the hash chain:
  18375. */
  18376. hash_head = 0/*NIL*/;
  18377. if (s.lookahead >= MIN_MATCH) {
  18378. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18379. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18380. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18381. s.head[s.ins_h] = s.strstart;
  18382. /***/
  18383. }
  18384. /* Find the longest match, discarding those <= prev_length.
  18385. * At this point we have always match_length < MIN_MATCH
  18386. */
  18387. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  18388. /* To simplify the code, we prevent matches with the string
  18389. * of window index 0 (in particular we have to avoid a match
  18390. * of the string with itself at the start of the input file).
  18391. */
  18392. s.match_length = longest_match(s, hash_head);
  18393. /* longest_match() sets match_start */
  18394. }
  18395. if (s.match_length >= MIN_MATCH) {
  18396. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  18397. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  18398. s.match_length - MIN_MATCH, bflush); ***/
  18399. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  18400. s.lookahead -= s.match_length;
  18401. /* Insert new strings in the hash table only if the match length
  18402. * is not too large. This saves time but degrades compression.
  18403. */
  18404. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  18405. s.match_length--; /* string at strstart already in table */
  18406. do {
  18407. s.strstart++;
  18408. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18409. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18410. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18411. s.head[s.ins_h] = s.strstart;
  18412. /***/
  18413. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  18414. * always MIN_MATCH bytes ahead.
  18415. */
  18416. } while (--s.match_length !== 0);
  18417. s.strstart++;
  18418. } else
  18419. {
  18420. s.strstart += s.match_length;
  18421. s.match_length = 0;
  18422. s.ins_h = s.window[s.strstart];
  18423. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  18424. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  18425. //#if MIN_MATCH != 3
  18426. // Call UPDATE_HASH() MIN_MATCH-3 more times
  18427. //#endif
  18428. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  18429. * matter since it will be recomputed at next deflate call.
  18430. */
  18431. }
  18432. } else {
  18433. /* No match, output a literal byte */
  18434. //Tracevv((stderr,"%c", s.window[s.strstart]));
  18435. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18436. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18437. s.lookahead--;
  18438. s.strstart++;
  18439. }
  18440. if (bflush) {
  18441. /*** FLUSH_BLOCK(s, 0); ***/
  18442. flush_block_only(s, false);
  18443. if (s.strm.avail_out === 0) {
  18444. return BS_NEED_MORE;
  18445. }
  18446. /***/
  18447. }
  18448. }
  18449. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  18450. if (flush === Z_FINISH) {
  18451. /*** FLUSH_BLOCK(s, 1); ***/
  18452. flush_block_only(s, true);
  18453. if (s.strm.avail_out === 0) {
  18454. return BS_FINISH_STARTED;
  18455. }
  18456. /***/
  18457. return BS_FINISH_DONE;
  18458. }
  18459. if (s.last_lit) {
  18460. /*** FLUSH_BLOCK(s, 0); ***/
  18461. flush_block_only(s, false);
  18462. if (s.strm.avail_out === 0) {
  18463. return BS_NEED_MORE;
  18464. }
  18465. /***/
  18466. }
  18467. return BS_BLOCK_DONE;
  18468. }
  18469. /* ===========================================================================
  18470. * Same as above, but achieves better compression. We use a lazy
  18471. * evaluation for matches: a match is finally adopted only if there is
  18472. * no better match at the next window position.
  18473. */
  18474. function deflate_slow(s, flush) {
  18475. var hash_head; /* head of hash chain */
  18476. var bflush; /* set if current block must be flushed */
  18477. var max_insert;
  18478. /* Process the input block. */
  18479. for (;;) {
  18480. /* Make sure that we always have enough lookahead, except
  18481. * at the end of the input file. We need MAX_MATCH bytes
  18482. * for the next match, plus MIN_MATCH bytes to insert the
  18483. * string following the next match.
  18484. */
  18485. if (s.lookahead < MIN_LOOKAHEAD) {
  18486. fill_window(s);
  18487. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  18488. return BS_NEED_MORE;
  18489. }
  18490. if (s.lookahead === 0) { break; } /* flush the current block */
  18491. }
  18492. /* Insert the string window[strstart .. strstart+2] in the
  18493. * dictionary, and set hash_head to the head of the hash chain:
  18494. */
  18495. hash_head = 0/*NIL*/;
  18496. if (s.lookahead >= MIN_MATCH) {
  18497. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18498. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18499. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18500. s.head[s.ins_h] = s.strstart;
  18501. /***/
  18502. }
  18503. /* Find the longest match, discarding those <= prev_length.
  18504. */
  18505. s.prev_length = s.match_length;
  18506. s.prev_match = s.match_start;
  18507. s.match_length = MIN_MATCH-1;
  18508. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  18509. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  18510. /* To simplify the code, we prevent matches with the string
  18511. * of window index 0 (in particular we have to avoid a match
  18512. * of the string with itself at the start of the input file).
  18513. */
  18514. s.match_length = longest_match(s, hash_head);
  18515. /* longest_match() sets match_start */
  18516. if (s.match_length <= 5 &&
  18517. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  18518. /* If prev_match is also MIN_MATCH, match_start is garbage
  18519. * but we will ignore the current match anyway.
  18520. */
  18521. s.match_length = MIN_MATCH-1;
  18522. }
  18523. }
  18524. /* If there was a match at the previous step and the current
  18525. * match is not better, output the previous match:
  18526. */
  18527. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  18528. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  18529. /* Do not insert strings in hash table beyond this. */
  18530. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  18531. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  18532. s.prev_length - MIN_MATCH, bflush);***/
  18533. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  18534. /* Insert in hash table all strings up to the end of the match.
  18535. * strstart-1 and strstart are already inserted. If there is not
  18536. * enough lookahead, the last two strings are not inserted in
  18537. * the hash table.
  18538. */
  18539. s.lookahead -= s.prev_length-1;
  18540. s.prev_length -= 2;
  18541. do {
  18542. if (++s.strstart <= max_insert) {
  18543. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18544. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18545. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18546. s.head[s.ins_h] = s.strstart;
  18547. /***/
  18548. }
  18549. } while (--s.prev_length !== 0);
  18550. s.match_available = 0;
  18551. s.match_length = MIN_MATCH-1;
  18552. s.strstart++;
  18553. if (bflush) {
  18554. /*** FLUSH_BLOCK(s, 0); ***/
  18555. flush_block_only(s, false);
  18556. if (s.strm.avail_out === 0) {
  18557. return BS_NEED_MORE;
  18558. }
  18559. /***/
  18560. }
  18561. } else if (s.match_available) {
  18562. /* If there was no match at the previous position, output a
  18563. * single literal. If there was a match but the current match
  18564. * is longer, truncate the previous match to a single literal.
  18565. */
  18566. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  18567. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  18568. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  18569. if (bflush) {
  18570. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  18571. flush_block_only(s, false);
  18572. /***/
  18573. }
  18574. s.strstart++;
  18575. s.lookahead--;
  18576. if (s.strm.avail_out === 0) {
  18577. return BS_NEED_MORE;
  18578. }
  18579. } else {
  18580. /* There is no previous match to compare with, wait for
  18581. * the next step to decide.
  18582. */
  18583. s.match_available = 1;
  18584. s.strstart++;
  18585. s.lookahead--;
  18586. }
  18587. }
  18588. //Assert (flush != Z_NO_FLUSH, "no flush?");
  18589. if (s.match_available) {
  18590. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  18591. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  18592. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  18593. s.match_available = 0;
  18594. }
  18595. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  18596. if (flush === Z_FINISH) {
  18597. /*** FLUSH_BLOCK(s, 1); ***/
  18598. flush_block_only(s, true);
  18599. if (s.strm.avail_out === 0) {
  18600. return BS_FINISH_STARTED;
  18601. }
  18602. /***/
  18603. return BS_FINISH_DONE;
  18604. }
  18605. if (s.last_lit) {
  18606. /*** FLUSH_BLOCK(s, 0); ***/
  18607. flush_block_only(s, false);
  18608. if (s.strm.avail_out === 0) {
  18609. return BS_NEED_MORE;
  18610. }
  18611. /***/
  18612. }
  18613. return BS_BLOCK_DONE;
  18614. }
  18615. /* ===========================================================================
  18616. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  18617. * one. Do not maintain a hash table. (It will be regenerated if this run of
  18618. * deflate switches away from Z_RLE.)
  18619. */
  18620. function deflate_rle(s, flush) {
  18621. var bflush; /* set if current block must be flushed */
  18622. var prev; /* byte at distance one to match */
  18623. var scan, strend; /* scan goes up to strend for length of run */
  18624. var _win = s.window;
  18625. for (;;) {
  18626. /* Make sure that we always have enough lookahead, except
  18627. * at the end of the input file. We need MAX_MATCH bytes
  18628. * for the longest run, plus one for the unrolled loop.
  18629. */
  18630. if (s.lookahead <= MAX_MATCH) {
  18631. fill_window(s);
  18632. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  18633. return BS_NEED_MORE;
  18634. }
  18635. if (s.lookahead === 0) { break; } /* flush the current block */
  18636. }
  18637. /* See how many times the previous byte repeats */
  18638. s.match_length = 0;
  18639. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  18640. scan = s.strstart - 1;
  18641. prev = _win[scan];
  18642. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  18643. strend = s.strstart + MAX_MATCH;
  18644. do {
  18645. /*jshint noempty:false*/
  18646. } while (prev === _win[++scan] && prev === _win[++scan] &&
  18647. prev === _win[++scan] && prev === _win[++scan] &&
  18648. prev === _win[++scan] && prev === _win[++scan] &&
  18649. prev === _win[++scan] && prev === _win[++scan] &&
  18650. scan < strend);
  18651. s.match_length = MAX_MATCH - (strend - scan);
  18652. if (s.match_length > s.lookahead) {
  18653. s.match_length = s.lookahead;
  18654. }
  18655. }
  18656. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  18657. }
  18658. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  18659. if (s.match_length >= MIN_MATCH) {
  18660. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  18661. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  18662. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  18663. s.lookahead -= s.match_length;
  18664. s.strstart += s.match_length;
  18665. s.match_length = 0;
  18666. } else {
  18667. /* No match, output a literal byte */
  18668. //Tracevv((stderr,"%c", s->window[s->strstart]));
  18669. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18670. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18671. s.lookahead--;
  18672. s.strstart++;
  18673. }
  18674. if (bflush) {
  18675. /*** FLUSH_BLOCK(s, 0); ***/
  18676. flush_block_only(s, false);
  18677. if (s.strm.avail_out === 0) {
  18678. return BS_NEED_MORE;
  18679. }
  18680. /***/
  18681. }
  18682. }
  18683. s.insert = 0;
  18684. if (flush === Z_FINISH) {
  18685. /*** FLUSH_BLOCK(s, 1); ***/
  18686. flush_block_only(s, true);
  18687. if (s.strm.avail_out === 0) {
  18688. return BS_FINISH_STARTED;
  18689. }
  18690. /***/
  18691. return BS_FINISH_DONE;
  18692. }
  18693. if (s.last_lit) {
  18694. /*** FLUSH_BLOCK(s, 0); ***/
  18695. flush_block_only(s, false);
  18696. if (s.strm.avail_out === 0) {
  18697. return BS_NEED_MORE;
  18698. }
  18699. /***/
  18700. }
  18701. return BS_BLOCK_DONE;
  18702. }
  18703. /* ===========================================================================
  18704. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  18705. * (It will be regenerated if this run of deflate switches away from Huffman.)
  18706. */
  18707. function deflate_huff(s, flush) {
  18708. var bflush; /* set if current block must be flushed */
  18709. for (;;) {
  18710. /* Make sure that we have a literal to write. */
  18711. if (s.lookahead === 0) {
  18712. fill_window(s);
  18713. if (s.lookahead === 0) {
  18714. if (flush === Z_NO_FLUSH) {
  18715. return BS_NEED_MORE;
  18716. }
  18717. break; /* flush the current block */
  18718. }
  18719. }
  18720. /* Output a literal byte */
  18721. s.match_length = 0;
  18722. //Tracevv((stderr,"%c", s->window[s->strstart]));
  18723. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18724. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18725. s.lookahead--;
  18726. s.strstart++;
  18727. if (bflush) {
  18728. /*** FLUSH_BLOCK(s, 0); ***/
  18729. flush_block_only(s, false);
  18730. if (s.strm.avail_out === 0) {
  18731. return BS_NEED_MORE;
  18732. }
  18733. /***/
  18734. }
  18735. }
  18736. s.insert = 0;
  18737. if (flush === Z_FINISH) {
  18738. /*** FLUSH_BLOCK(s, 1); ***/
  18739. flush_block_only(s, true);
  18740. if (s.strm.avail_out === 0) {
  18741. return BS_FINISH_STARTED;
  18742. }
  18743. /***/
  18744. return BS_FINISH_DONE;
  18745. }
  18746. if (s.last_lit) {
  18747. /*** FLUSH_BLOCK(s, 0); ***/
  18748. flush_block_only(s, false);
  18749. if (s.strm.avail_out === 0) {
  18750. return BS_NEED_MORE;
  18751. }
  18752. /***/
  18753. }
  18754. return BS_BLOCK_DONE;
  18755. }
  18756. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  18757. * the desired pack level (0..9). The values given below have been tuned to
  18758. * exclude worst case performance for pathological files. Better values may be
  18759. * found for specific files.
  18760. */
  18761. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  18762. this.good_length = good_length;
  18763. this.max_lazy = max_lazy;
  18764. this.nice_length = nice_length;
  18765. this.max_chain = max_chain;
  18766. this.func = func;
  18767. };
  18768. var configuration_table;
  18769. configuration_table = [
  18770. /* good lazy nice chain */
  18771. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  18772. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  18773. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  18774. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  18775. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  18776. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  18777. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  18778. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  18779. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  18780. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  18781. ];
  18782. /* ===========================================================================
  18783. * Initialize the "longest match" routines for a new zlib stream
  18784. */
  18785. function lm_init(s) {
  18786. s.window_size = 2 * s.w_size;
  18787. /*** CLEAR_HASH(s); ***/
  18788. zero(s.head); // Fill with NIL (= 0);
  18789. /* Set the default configuration parameters:
  18790. */
  18791. s.max_lazy_match = configuration_table[s.level].max_lazy;
  18792. s.good_match = configuration_table[s.level].good_length;
  18793. s.nice_match = configuration_table[s.level].nice_length;
  18794. s.max_chain_length = configuration_table[s.level].max_chain;
  18795. s.strstart = 0;
  18796. s.block_start = 0;
  18797. s.lookahead = 0;
  18798. s.insert = 0;
  18799. s.match_length = s.prev_length = MIN_MATCH - 1;
  18800. s.match_available = 0;
  18801. s.ins_h = 0;
  18802. }
  18803. function DeflateState() {
  18804. this.strm = null; /* pointer back to this zlib stream */
  18805. this.status = 0; /* as the name implies */
  18806. this.pending_buf = null; /* output still pending */
  18807. this.pending_buf_size = 0; /* size of pending_buf */
  18808. this.pending_out = 0; /* next pending byte to output to the stream */
  18809. this.pending = 0; /* nb of bytes in the pending buffer */
  18810. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  18811. this.gzhead = null; /* gzip header information to write */
  18812. this.gzindex = 0; /* where in extra, name, or comment */
  18813. this.method = Z_DEFLATED; /* can only be DEFLATED */
  18814. this.last_flush = -1; /* value of flush param for previous deflate call */
  18815. this.w_size = 0; /* LZ77 window size (32K by default) */
  18816. this.w_bits = 0; /* log2(w_size) (8..16) */
  18817. this.w_mask = 0; /* w_size - 1 */
  18818. this.window = null;
  18819. /* Sliding window. Input bytes are read into the second half of the window,
  18820. * and move to the first half later to keep a dictionary of at least wSize
  18821. * bytes. With this organization, matches are limited to a distance of
  18822. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  18823. * performed with a length multiple of the block size.
  18824. */
  18825. this.window_size = 0;
  18826. /* Actual size of window: 2*wSize, except when the user input buffer
  18827. * is directly used as sliding window.
  18828. */
  18829. this.prev = null;
  18830. /* Link to older string with same hash index. To limit the size of this
  18831. * array to 64K, this link is maintained only for the last 32K strings.
  18832. * An index in this array is thus a window index modulo 32K.
  18833. */
  18834. this.head = null; /* Heads of the hash chains or NIL. */
  18835. this.ins_h = 0; /* hash index of string to be inserted */
  18836. this.hash_size = 0; /* number of elements in hash table */
  18837. this.hash_bits = 0; /* log2(hash_size) */
  18838. this.hash_mask = 0; /* hash_size-1 */
  18839. this.hash_shift = 0;
  18840. /* Number of bits by which ins_h must be shifted at each input
  18841. * step. It must be such that after MIN_MATCH steps, the oldest
  18842. * byte no longer takes part in the hash key, that is:
  18843. * hash_shift * MIN_MATCH >= hash_bits
  18844. */
  18845. this.block_start = 0;
  18846. /* Window position at the beginning of the current output block. Gets
  18847. * negative when the window is moved backwards.
  18848. */
  18849. this.match_length = 0; /* length of best match */
  18850. this.prev_match = 0; /* previous match */
  18851. this.match_available = 0; /* set if previous match exists */
  18852. this.strstart = 0; /* start of string to insert */
  18853. this.match_start = 0; /* start of matching string */
  18854. this.lookahead = 0; /* number of valid bytes ahead in window */
  18855. this.prev_length = 0;
  18856. /* Length of the best match at previous step. Matches not greater than this
  18857. * are discarded. This is used in the lazy match evaluation.
  18858. */
  18859. this.max_chain_length = 0;
  18860. /* To speed up deflation, hash chains are never searched beyond this
  18861. * length. A higher limit improves compression ratio but degrades the
  18862. * speed.
  18863. */
  18864. this.max_lazy_match = 0;
  18865. /* Attempt to find a better match only when the current match is strictly
  18866. * smaller than this value. This mechanism is used only for compression
  18867. * levels >= 4.
  18868. */
  18869. // That's alias to max_lazy_match, don't use directly
  18870. //this.max_insert_length = 0;
  18871. /* Insert new strings in the hash table only if the match length is not
  18872. * greater than this length. This saves time but degrades compression.
  18873. * max_insert_length is used only for compression levels <= 3.
  18874. */
  18875. this.level = 0; /* compression level (1..9) */
  18876. this.strategy = 0; /* favor or force Huffman coding*/
  18877. this.good_match = 0;
  18878. /* Use a faster search when the previous match is longer than this */
  18879. this.nice_match = 0; /* Stop searching when current match exceeds this */
  18880. /* used by trees.c: */
  18881. /* Didn't use ct_data typedef below to suppress compiler warning */
  18882. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  18883. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  18884. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  18885. // Use flat array of DOUBLE size, with interleaved fata,
  18886. // because JS does not support effective
  18887. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  18888. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  18889. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  18890. zero(this.dyn_ltree);
  18891. zero(this.dyn_dtree);
  18892. zero(this.bl_tree);
  18893. this.l_desc = null; /* desc. for literal tree */
  18894. this.d_desc = null; /* desc. for distance tree */
  18895. this.bl_desc = null; /* desc. for bit length tree */
  18896. //ush bl_count[MAX_BITS+1];
  18897. this.bl_count = new utils.Buf16(MAX_BITS+1);
  18898. /* number of codes at each bit length for an optimal tree */
  18899. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  18900. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  18901. zero(this.heap);
  18902. this.heap_len = 0; /* number of elements in the heap */
  18903. this.heap_max = 0; /* element of largest frequency */
  18904. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  18905. * The same heap array is used to build all trees.
  18906. */
  18907. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  18908. zero(this.depth);
  18909. /* Depth of each subtree used as tie breaker for trees of equal frequency
  18910. */
  18911. this.l_buf = 0; /* buffer index for literals or lengths */
  18912. this.lit_bufsize = 0;
  18913. /* Size of match buffer for literals/lengths. There are 4 reasons for
  18914. * limiting lit_bufsize to 64K:
  18915. * - frequencies can be kept in 16 bit counters
  18916. * - if compression is not successful for the first block, all input
  18917. * data is still in the window so we can still emit a stored block even
  18918. * when input comes from standard input. (This can also be done for
  18919. * all blocks if lit_bufsize is not greater than 32K.)
  18920. * - if compression is not successful for a file smaller than 64K, we can
  18921. * even emit a stored file instead of a stored block (saving 5 bytes).
  18922. * This is applicable only for zip (not gzip or zlib).
  18923. * - creating new Huffman trees less frequently may not provide fast
  18924. * adaptation to changes in the input data statistics. (Take for
  18925. * example a binary file with poorly compressible code followed by
  18926. * a highly compressible string table.) Smaller buffer sizes give
  18927. * fast adaptation but have of course the overhead of transmitting
  18928. * trees more frequently.
  18929. * - I can't count above 4
  18930. */
  18931. this.last_lit = 0; /* running index in l_buf */
  18932. this.d_buf = 0;
  18933. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  18934. * the same number of elements. To use different lengths, an extra flag
  18935. * array would be necessary.
  18936. */
  18937. this.opt_len = 0; /* bit length of current block with optimal trees */
  18938. this.static_len = 0; /* bit length of current block with static trees */
  18939. this.matches = 0; /* number of string matches in current block */
  18940. this.insert = 0; /* bytes at end of window left to insert */
  18941. this.bi_buf = 0;
  18942. /* Output buffer. bits are inserted starting at the bottom (least
  18943. * significant bits).
  18944. */
  18945. this.bi_valid = 0;
  18946. /* Number of valid bits in bi_buf. All bits above the last valid bit
  18947. * are always zero.
  18948. */
  18949. // Used for window memory init. We safely ignore it for JS. That makes
  18950. // sense only for pointers and memory check tools.
  18951. //this.high_water = 0;
  18952. /* High water mark offset in window for initialized bytes -- bytes above
  18953. * this are set to zero in order to avoid memory check warnings when
  18954. * longest match routines access bytes past the input. This is then
  18955. * updated to the new high water mark.
  18956. */
  18957. }
  18958. function deflateResetKeep(strm) {
  18959. var s;
  18960. if (!strm || !strm.state) {
  18961. return err(strm, Z_STREAM_ERROR);
  18962. }
  18963. strm.total_in = strm.total_out = 0;
  18964. strm.data_type = Z_UNKNOWN;
  18965. s = strm.state;
  18966. s.pending = 0;
  18967. s.pending_out = 0;
  18968. if (s.wrap < 0) {
  18969. s.wrap = -s.wrap;
  18970. /* was made negative by deflate(..., Z_FINISH); */
  18971. }
  18972. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  18973. strm.adler = (s.wrap === 2) ?
  18974. 0 // crc32(0, Z_NULL, 0)
  18975. :
  18976. 1; // adler32(0, Z_NULL, 0)
  18977. s.last_flush = Z_NO_FLUSH;
  18978. trees._tr_init(s);
  18979. return Z_OK;
  18980. }
  18981. function deflateReset(strm) {
  18982. var ret = deflateResetKeep(strm);
  18983. if (ret === Z_OK) {
  18984. lm_init(strm.state);
  18985. }
  18986. return ret;
  18987. }
  18988. function deflateSetHeader(strm, head) {
  18989. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  18990. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  18991. strm.state.gzhead = head;
  18992. return Z_OK;
  18993. }
  18994. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  18995. if (!strm) { // === Z_NULL
  18996. return Z_STREAM_ERROR;
  18997. }
  18998. var wrap = 1;
  18999. if (level === Z_DEFAULT_COMPRESSION) {
  19000. level = 6;
  19001. }
  19002. if (windowBits < 0) { /* suppress zlib wrapper */
  19003. wrap = 0;
  19004. windowBits = -windowBits;
  19005. }
  19006. else if (windowBits > 15) {
  19007. wrap = 2; /* write gzip wrapper instead */
  19008. windowBits -= 16;
  19009. }
  19010. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  19011. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  19012. strategy < 0 || strategy > Z_FIXED) {
  19013. return err(strm, Z_STREAM_ERROR);
  19014. }
  19015. if (windowBits === 8) {
  19016. windowBits = 9;
  19017. }
  19018. /* until 256-byte window bug fixed */
  19019. var s = new DeflateState();
  19020. strm.state = s;
  19021. s.strm = strm;
  19022. s.wrap = wrap;
  19023. s.gzhead = null;
  19024. s.w_bits = windowBits;
  19025. s.w_size = 1 << s.w_bits;
  19026. s.w_mask = s.w_size - 1;
  19027. s.hash_bits = memLevel + 7;
  19028. s.hash_size = 1 << s.hash_bits;
  19029. s.hash_mask = s.hash_size - 1;
  19030. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  19031. s.window = new utils.Buf8(s.w_size * 2);
  19032. s.head = new utils.Buf16(s.hash_size);
  19033. s.prev = new utils.Buf16(s.w_size);
  19034. // Don't need mem init magic for JS.
  19035. //s.high_water = 0; /* nothing written to s->window yet */
  19036. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  19037. s.pending_buf_size = s.lit_bufsize * 4;
  19038. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  19039. s.d_buf = s.lit_bufsize >> 1;
  19040. s.l_buf = (1 + 2) * s.lit_bufsize;
  19041. s.level = level;
  19042. s.strategy = strategy;
  19043. s.method = method;
  19044. return deflateReset(strm);
  19045. }
  19046. function deflateInit(strm, level) {
  19047. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  19048. }
  19049. function deflate(strm, flush) {
  19050. var old_flush, s;
  19051. var beg, val; // for gzip header write only
  19052. if (!strm || !strm.state ||
  19053. flush > Z_BLOCK || flush < 0) {
  19054. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  19055. }
  19056. s = strm.state;
  19057. if (!strm.output ||
  19058. (!strm.input && strm.avail_in !== 0) ||
  19059. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  19060. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  19061. }
  19062. s.strm = strm; /* just in case */
  19063. old_flush = s.last_flush;
  19064. s.last_flush = flush;
  19065. /* Write the header */
  19066. if (s.status === INIT_STATE) {
  19067. if (s.wrap === 2) { // GZIP header
  19068. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  19069. put_byte(s, 31);
  19070. put_byte(s, 139);
  19071. put_byte(s, 8);
  19072. if (!s.gzhead) { // s->gzhead == Z_NULL
  19073. put_byte(s, 0);
  19074. put_byte(s, 0);
  19075. put_byte(s, 0);
  19076. put_byte(s, 0);
  19077. put_byte(s, 0);
  19078. put_byte(s, s.level === 9 ? 2 :
  19079. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  19080. 4 : 0));
  19081. put_byte(s, OS_CODE);
  19082. s.status = BUSY_STATE;
  19083. }
  19084. else {
  19085. put_byte(s, (s.gzhead.text ? 1 : 0) +
  19086. (s.gzhead.hcrc ? 2 : 0) +
  19087. (!s.gzhead.extra ? 0 : 4) +
  19088. (!s.gzhead.name ? 0 : 8) +
  19089. (!s.gzhead.comment ? 0 : 16)
  19090. );
  19091. put_byte(s, s.gzhead.time & 0xff);
  19092. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  19093. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  19094. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  19095. put_byte(s, s.level === 9 ? 2 :
  19096. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  19097. 4 : 0));
  19098. put_byte(s, s.gzhead.os & 0xff);
  19099. if (s.gzhead.extra && s.gzhead.extra.length) {
  19100. put_byte(s, s.gzhead.extra.length & 0xff);
  19101. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  19102. }
  19103. if (s.gzhead.hcrc) {
  19104. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  19105. }
  19106. s.gzindex = 0;
  19107. s.status = EXTRA_STATE;
  19108. }
  19109. }
  19110. else // DEFLATE header
  19111. {
  19112. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  19113. var level_flags = -1;
  19114. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  19115. level_flags = 0;
  19116. } else if (s.level < 6) {
  19117. level_flags = 1;
  19118. } else if (s.level === 6) {
  19119. level_flags = 2;
  19120. } else {
  19121. level_flags = 3;
  19122. }
  19123. header |= (level_flags << 6);
  19124. if (s.strstart !== 0) { header |= PRESET_DICT; }
  19125. header += 31 - (header % 31);
  19126. s.status = BUSY_STATE;
  19127. putShortMSB(s, header);
  19128. /* Save the adler32 of the preset dictionary: */
  19129. if (s.strstart !== 0) {
  19130. putShortMSB(s, strm.adler >>> 16);
  19131. putShortMSB(s, strm.adler & 0xffff);
  19132. }
  19133. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  19134. }
  19135. }
  19136. //#ifdef GZIP
  19137. if (s.status === EXTRA_STATE) {
  19138. if (s.gzhead.extra/* != Z_NULL*/) {
  19139. beg = s.pending; /* start of bytes to update crc */
  19140. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  19141. if (s.pending === s.pending_buf_size) {
  19142. if (s.gzhead.hcrc && s.pending > beg) {
  19143. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19144. }
  19145. flush_pending(strm);
  19146. beg = s.pending;
  19147. if (s.pending === s.pending_buf_size) {
  19148. break;
  19149. }
  19150. }
  19151. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  19152. s.gzindex++;
  19153. }
  19154. if (s.gzhead.hcrc && s.pending > beg) {
  19155. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19156. }
  19157. if (s.gzindex === s.gzhead.extra.length) {
  19158. s.gzindex = 0;
  19159. s.status = NAME_STATE;
  19160. }
  19161. }
  19162. else {
  19163. s.status = NAME_STATE;
  19164. }
  19165. }
  19166. if (s.status === NAME_STATE) {
  19167. if (s.gzhead.name/* != Z_NULL*/) {
  19168. beg = s.pending; /* start of bytes to update crc */
  19169. //int val;
  19170. do {
  19171. if (s.pending === s.pending_buf_size) {
  19172. if (s.gzhead.hcrc && s.pending > beg) {
  19173. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19174. }
  19175. flush_pending(strm);
  19176. beg = s.pending;
  19177. if (s.pending === s.pending_buf_size) {
  19178. val = 1;
  19179. break;
  19180. }
  19181. }
  19182. // JS specific: little magic to add zero terminator to end of string
  19183. if (s.gzindex < s.gzhead.name.length) {
  19184. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  19185. } else {
  19186. val = 0;
  19187. }
  19188. put_byte(s, val);
  19189. } while (val !== 0);
  19190. if (s.gzhead.hcrc && s.pending > beg){
  19191. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19192. }
  19193. if (val === 0) {
  19194. s.gzindex = 0;
  19195. s.status = COMMENT_STATE;
  19196. }
  19197. }
  19198. else {
  19199. s.status = COMMENT_STATE;
  19200. }
  19201. }
  19202. if (s.status === COMMENT_STATE) {
  19203. if (s.gzhead.comment/* != Z_NULL*/) {
  19204. beg = s.pending; /* start of bytes to update crc */
  19205. //int val;
  19206. do {
  19207. if (s.pending === s.pending_buf_size) {
  19208. if (s.gzhead.hcrc && s.pending > beg) {
  19209. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19210. }
  19211. flush_pending(strm);
  19212. beg = s.pending;
  19213. if (s.pending === s.pending_buf_size) {
  19214. val = 1;
  19215. break;
  19216. }
  19217. }
  19218. // JS specific: little magic to add zero terminator to end of string
  19219. if (s.gzindex < s.gzhead.comment.length) {
  19220. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  19221. } else {
  19222. val = 0;
  19223. }
  19224. put_byte(s, val);
  19225. } while (val !== 0);
  19226. if (s.gzhead.hcrc && s.pending > beg) {
  19227. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19228. }
  19229. if (val === 0) {
  19230. s.status = HCRC_STATE;
  19231. }
  19232. }
  19233. else {
  19234. s.status = HCRC_STATE;
  19235. }
  19236. }
  19237. if (s.status === HCRC_STATE) {
  19238. if (s.gzhead.hcrc) {
  19239. if (s.pending + 2 > s.pending_buf_size) {
  19240. flush_pending(strm);
  19241. }
  19242. if (s.pending + 2 <= s.pending_buf_size) {
  19243. put_byte(s, strm.adler & 0xff);
  19244. put_byte(s, (strm.adler >> 8) & 0xff);
  19245. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  19246. s.status = BUSY_STATE;
  19247. }
  19248. }
  19249. else {
  19250. s.status = BUSY_STATE;
  19251. }
  19252. }
  19253. //#endif
  19254. /* Flush as much pending output as possible */
  19255. if (s.pending !== 0) {
  19256. flush_pending(strm);
  19257. if (strm.avail_out === 0) {
  19258. /* Since avail_out is 0, deflate will be called again with
  19259. * more output space, but possibly with both pending and
  19260. * avail_in equal to zero. There won't be anything to do,
  19261. * but this is not an error situation so make sure we
  19262. * return OK instead of BUF_ERROR at next call of deflate:
  19263. */
  19264. s.last_flush = -1;
  19265. return Z_OK;
  19266. }
  19267. /* Make sure there is something to do and avoid duplicate consecutive
  19268. * flushes. For repeated and useless calls with Z_FINISH, we keep
  19269. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  19270. */
  19271. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  19272. flush !== Z_FINISH) {
  19273. return err(strm, Z_BUF_ERROR);
  19274. }
  19275. /* User must not provide more input after the first FINISH: */
  19276. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  19277. return err(strm, Z_BUF_ERROR);
  19278. }
  19279. /* Start a new block or continue the current one.
  19280. */
  19281. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  19282. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  19283. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  19284. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  19285. configuration_table[s.level].func(s, flush));
  19286. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  19287. s.status = FINISH_STATE;
  19288. }
  19289. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  19290. if (strm.avail_out === 0) {
  19291. s.last_flush = -1;
  19292. /* avoid BUF_ERROR next call, see above */
  19293. }
  19294. return Z_OK;
  19295. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  19296. * of deflate should use the same flush parameter to make sure
  19297. * that the flush is complete. So we don't have to output an
  19298. * empty block here, this will be done at next call. This also
  19299. * ensures that for a very small output buffer, we emit at most
  19300. * one empty block.
  19301. */
  19302. }
  19303. if (bstate === BS_BLOCK_DONE) {
  19304. if (flush === Z_PARTIAL_FLUSH) {
  19305. trees._tr_align(s);
  19306. }
  19307. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  19308. trees._tr_stored_block(s, 0, 0, false);
  19309. /* For a full flush, this empty block will be recognized
  19310. * as a special marker by inflate_sync().
  19311. */
  19312. if (flush === Z_FULL_FLUSH) {
  19313. /*** CLEAR_HASH(s); ***/ /* forget history */
  19314. zero(s.head); // Fill with NIL (= 0);
  19315. if (s.lookahead === 0) {
  19316. s.strstart = 0;
  19317. s.block_start = 0;
  19318. s.insert = 0;
  19319. }
  19320. }
  19321. }
  19322. flush_pending(strm);
  19323. if (strm.avail_out === 0) {
  19324. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  19325. return Z_OK;
  19326. }
  19327. }
  19328. }
  19329. //Assert(strm->avail_out > 0, "bug2");
  19330. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  19331. if (flush !== Z_FINISH) { return Z_OK; }
  19332. if (s.wrap <= 0) { return Z_STREAM_END; }
  19333. /* Write the trailer */
  19334. if (s.wrap === 2) {
  19335. put_byte(s, strm.adler & 0xff);
  19336. put_byte(s, (strm.adler >> 8) & 0xff);
  19337. put_byte(s, (strm.adler >> 16) & 0xff);
  19338. put_byte(s, (strm.adler >> 24) & 0xff);
  19339. put_byte(s, strm.total_in & 0xff);
  19340. put_byte(s, (strm.total_in >> 8) & 0xff);
  19341. put_byte(s, (strm.total_in >> 16) & 0xff);
  19342. put_byte(s, (strm.total_in >> 24) & 0xff);
  19343. }
  19344. else
  19345. {
  19346. putShortMSB(s, strm.adler >>> 16);
  19347. putShortMSB(s, strm.adler & 0xffff);
  19348. }
  19349. flush_pending(strm);
  19350. /* If avail_out is zero, the application will call deflate again
  19351. * to flush the rest.
  19352. */
  19353. if (s.wrap > 0) { s.wrap = -s.wrap; }
  19354. /* write the trailer only once! */
  19355. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  19356. }
  19357. function deflateEnd(strm) {
  19358. var status;
  19359. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  19360. return Z_STREAM_ERROR;
  19361. }
  19362. status = strm.state.status;
  19363. if (status !== INIT_STATE &&
  19364. status !== EXTRA_STATE &&
  19365. status !== NAME_STATE &&
  19366. status !== COMMENT_STATE &&
  19367. status !== HCRC_STATE &&
  19368. status !== BUSY_STATE &&
  19369. status !== FINISH_STATE
  19370. ) {
  19371. return err(strm, Z_STREAM_ERROR);
  19372. }
  19373. strm.state = null;
  19374. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  19375. }
  19376. /* =========================================================================
  19377. * Copy the source state to the destination state
  19378. */
  19379. //function deflateCopy(dest, source) {
  19380. //
  19381. //}
  19382. exports.deflateInit = deflateInit;
  19383. exports.deflateInit2 = deflateInit2;
  19384. exports.deflateReset = deflateReset;
  19385. exports.deflateResetKeep = deflateResetKeep;
  19386. exports.deflateSetHeader = deflateSetHeader;
  19387. exports.deflate = deflate;
  19388. exports.deflateEnd = deflateEnd;
  19389. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  19390. /* Not implemented
  19391. exports.deflateBound = deflateBound;
  19392. exports.deflateCopy = deflateCopy;
  19393. exports.deflateSetDictionary = deflateSetDictionary;
  19394. exports.deflateParams = deflateParams;
  19395. exports.deflatePending = deflatePending;
  19396. exports.deflatePrime = deflatePrime;
  19397. exports.deflateTune = deflateTune;
  19398. */
  19399. },{"../utils/common":66,"./adler32":68,"./crc32":70,"./messages":76,"./trees":77}],72:[function(require,module,exports){
  19400. 'use strict';
  19401. function GZheader() {
  19402. /* true if compressed data believed to be text */
  19403. this.text = 0;
  19404. /* modification time */
  19405. this.time = 0;
  19406. /* extra flags (not used when writing a gzip file) */
  19407. this.xflags = 0;
  19408. /* operating system */
  19409. this.os = 0;
  19410. /* pointer to extra field or Z_NULL if none */
  19411. this.extra = null;
  19412. /* extra field length (valid if extra != Z_NULL) */
  19413. this.extra_len = 0; // Actually, we don't need it in JS,
  19414. // but leave for few code modifications
  19415. //
  19416. // Setup limits is not necessary because in js we should not preallocate memory
  19417. // for inflate use constant limit in 65536 bytes
  19418. //
  19419. /* space at extra (only when reading header) */
  19420. // this.extra_max = 0;
  19421. /* pointer to zero-terminated file name or Z_NULL */
  19422. this.name = '';
  19423. /* space at name (only when reading header) */
  19424. // this.name_max = 0;
  19425. /* pointer to zero-terminated comment or Z_NULL */
  19426. this.comment = '';
  19427. /* space at comment (only when reading header) */
  19428. // this.comm_max = 0;
  19429. /* true if there was or will be a header crc */
  19430. this.hcrc = 0;
  19431. /* true when done reading gzip header (not used when writing a gzip file) */
  19432. this.done = false;
  19433. }
  19434. module.exports = GZheader;
  19435. },{}],73:[function(require,module,exports){
  19436. 'use strict';
  19437. // See state defs from inflate.js
  19438. var BAD = 30; /* got a data error -- remain here until reset */
  19439. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  19440. /*
  19441. Decode literal, length, and distance codes and write out the resulting
  19442. literal and match bytes until either not enough input or output is
  19443. available, an end-of-block is encountered, or a data error is encountered.
  19444. When large enough input and output buffers are supplied to inflate(), for
  19445. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  19446. inflate execution time is spent in this routine.
  19447. Entry assumptions:
  19448. state.mode === LEN
  19449. strm.avail_in >= 6
  19450. strm.avail_out >= 258
  19451. start >= strm.avail_out
  19452. state.bits < 8
  19453. On return, state.mode is one of:
  19454. LEN -- ran out of enough output space or enough available input
  19455. TYPE -- reached end of block code, inflate() to interpret next block
  19456. BAD -- error in block data
  19457. Notes:
  19458. - The maximum input bits used by a length/distance pair is 15 bits for the
  19459. length code, 5 bits for the length extra, 15 bits for the distance code,
  19460. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  19461. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  19462. checking for available input while decoding.
  19463. - The maximum bytes that a single length/distance pair can output is 258
  19464. bytes, which is the maximum length that can be coded. inflate_fast()
  19465. requires strm.avail_out >= 258 for each loop to avoid checking for
  19466. output space.
  19467. */
  19468. module.exports = function inflate_fast(strm, start) {
  19469. var state;
  19470. var _in; /* local strm.input */
  19471. var last; /* have enough input while in < last */
  19472. var _out; /* local strm.output */
  19473. var beg; /* inflate()'s initial strm.output */
  19474. var end; /* while out < end, enough space available */
  19475. //#ifdef INFLATE_STRICT
  19476. var dmax; /* maximum distance from zlib header */
  19477. //#endif
  19478. var wsize; /* window size or zero if not using window */
  19479. var whave; /* valid bytes in the window */
  19480. var wnext; /* window write index */
  19481. var window; /* allocated sliding window, if wsize != 0 */
  19482. var hold; /* local strm.hold */
  19483. var bits; /* local strm.bits */
  19484. var lcode; /* local strm.lencode */
  19485. var dcode; /* local strm.distcode */
  19486. var lmask; /* mask for first level of length codes */
  19487. var dmask; /* mask for first level of distance codes */
  19488. var here; /* retrieved table entry */
  19489. var op; /* code bits, operation, extra bits, or */
  19490. /* window position, window bytes to copy */
  19491. var len; /* match length, unused bytes */
  19492. var dist; /* match distance */
  19493. var from; /* where to copy match from */
  19494. var from_source;
  19495. var input, output; // JS specific, because we have no pointers
  19496. /* copy state to local variables */
  19497. state = strm.state;
  19498. //here = state.here;
  19499. _in = strm.next_in;
  19500. input = strm.input;
  19501. last = _in + (strm.avail_in - 5);
  19502. _out = strm.next_out;
  19503. output = strm.output;
  19504. beg = _out - (start - strm.avail_out);
  19505. end = _out + (strm.avail_out - 257);
  19506. //#ifdef INFLATE_STRICT
  19507. dmax = state.dmax;
  19508. //#endif
  19509. wsize = state.wsize;
  19510. whave = state.whave;
  19511. wnext = state.wnext;
  19512. window = state.window;
  19513. hold = state.hold;
  19514. bits = state.bits;
  19515. lcode = state.lencode;
  19516. dcode = state.distcode;
  19517. lmask = (1 << state.lenbits) - 1;
  19518. dmask = (1 << state.distbits) - 1;
  19519. /* decode literals and length/distances until end-of-block or not enough
  19520. input data or output space */
  19521. top:
  19522. do {
  19523. if (bits < 15) {
  19524. hold += input[_in++] << bits;
  19525. bits += 8;
  19526. hold += input[_in++] << bits;
  19527. bits += 8;
  19528. }
  19529. here = lcode[hold & lmask];
  19530. dolen:
  19531. for (;;) { // Goto emulation
  19532. op = here >>> 24/*here.bits*/;
  19533. hold >>>= op;
  19534. bits -= op;
  19535. op = (here >>> 16) & 0xff/*here.op*/;
  19536. if (op === 0) { /* literal */
  19537. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  19538. // "inflate: literal '%c'\n" :
  19539. // "inflate: literal 0x%02x\n", here.val));
  19540. output[_out++] = here & 0xffff/*here.val*/;
  19541. }
  19542. else if (op & 16) { /* length base */
  19543. len = here & 0xffff/*here.val*/;
  19544. op &= 15; /* number of extra bits */
  19545. if (op) {
  19546. if (bits < op) {
  19547. hold += input[_in++] << bits;
  19548. bits += 8;
  19549. }
  19550. len += hold & ((1 << op) - 1);
  19551. hold >>>= op;
  19552. bits -= op;
  19553. }
  19554. //Tracevv((stderr, "inflate: length %u\n", len));
  19555. if (bits < 15) {
  19556. hold += input[_in++] << bits;
  19557. bits += 8;
  19558. hold += input[_in++] << bits;
  19559. bits += 8;
  19560. }
  19561. here = dcode[hold & dmask];
  19562. dodist:
  19563. for (;;) { // goto emulation
  19564. op = here >>> 24/*here.bits*/;
  19565. hold >>>= op;
  19566. bits -= op;
  19567. op = (here >>> 16) & 0xff/*here.op*/;
  19568. if (op & 16) { /* distance base */
  19569. dist = here & 0xffff/*here.val*/;
  19570. op &= 15; /* number of extra bits */
  19571. if (bits < op) {
  19572. hold += input[_in++] << bits;
  19573. bits += 8;
  19574. if (bits < op) {
  19575. hold += input[_in++] << bits;
  19576. bits += 8;
  19577. }
  19578. }
  19579. dist += hold & ((1 << op) - 1);
  19580. //#ifdef INFLATE_STRICT
  19581. if (dist > dmax) {
  19582. strm.msg = 'invalid distance too far back';
  19583. state.mode = BAD;
  19584. break top;
  19585. }
  19586. //#endif
  19587. hold >>>= op;
  19588. bits -= op;
  19589. //Tracevv((stderr, "inflate: distance %u\n", dist));
  19590. op = _out - beg; /* max distance in output */
  19591. if (dist > op) { /* see if copy from window */
  19592. op = dist - op; /* distance back in window */
  19593. if (op > whave) {
  19594. if (state.sane) {
  19595. strm.msg = 'invalid distance too far back';
  19596. state.mode = BAD;
  19597. break top;
  19598. }
  19599. // (!) This block is disabled in zlib defailts,
  19600. // don't enable it for binary compatibility
  19601. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  19602. // if (len <= op - whave) {
  19603. // do {
  19604. // output[_out++] = 0;
  19605. // } while (--len);
  19606. // continue top;
  19607. // }
  19608. // len -= op - whave;
  19609. // do {
  19610. // output[_out++] = 0;
  19611. // } while (--op > whave);
  19612. // if (op === 0) {
  19613. // from = _out - dist;
  19614. // do {
  19615. // output[_out++] = output[from++];
  19616. // } while (--len);
  19617. // continue top;
  19618. // }
  19619. //#endif
  19620. }
  19621. from = 0; // window index
  19622. from_source = window;
  19623. if (wnext === 0) { /* very common case */
  19624. from += wsize - op;
  19625. if (op < len) { /* some from window */
  19626. len -= op;
  19627. do {
  19628. output[_out++] = window[from++];
  19629. } while (--op);
  19630. from = _out - dist; /* rest from output */
  19631. from_source = output;
  19632. }
  19633. }
  19634. else if (wnext < op) { /* wrap around window */
  19635. from += wsize + wnext - op;
  19636. op -= wnext;
  19637. if (op < len) { /* some from end of window */
  19638. len -= op;
  19639. do {
  19640. output[_out++] = window[from++];
  19641. } while (--op);
  19642. from = 0;
  19643. if (wnext < len) { /* some from start of window */
  19644. op = wnext;
  19645. len -= op;
  19646. do {
  19647. output[_out++] = window[from++];
  19648. } while (--op);
  19649. from = _out - dist; /* rest from output */
  19650. from_source = output;
  19651. }
  19652. }
  19653. }
  19654. else { /* contiguous in window */
  19655. from += wnext - op;
  19656. if (op < len) { /* some from window */
  19657. len -= op;
  19658. do {
  19659. output[_out++] = window[from++];
  19660. } while (--op);
  19661. from = _out - dist; /* rest from output */
  19662. from_source = output;
  19663. }
  19664. }
  19665. while (len > 2) {
  19666. output[_out++] = from_source[from++];
  19667. output[_out++] = from_source[from++];
  19668. output[_out++] = from_source[from++];
  19669. len -= 3;
  19670. }
  19671. if (len) {
  19672. output[_out++] = from_source[from++];
  19673. if (len > 1) {
  19674. output[_out++] = from_source[from++];
  19675. }
  19676. }
  19677. }
  19678. else {
  19679. from = _out - dist; /* copy direct from output */
  19680. do { /* minimum length is three */
  19681. output[_out++] = output[from++];
  19682. output[_out++] = output[from++];
  19683. output[_out++] = output[from++];
  19684. len -= 3;
  19685. } while (len > 2);
  19686. if (len) {
  19687. output[_out++] = output[from++];
  19688. if (len > 1) {
  19689. output[_out++] = output[from++];
  19690. }
  19691. }
  19692. }
  19693. }
  19694. else if ((op & 64) === 0) { /* 2nd level distance code */
  19695. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  19696. continue dodist;
  19697. }
  19698. else {
  19699. strm.msg = 'invalid distance code';
  19700. state.mode = BAD;
  19701. break top;
  19702. }
  19703. break; // need to emulate goto via "continue"
  19704. }
  19705. }
  19706. else if ((op & 64) === 0) { /* 2nd level length code */
  19707. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  19708. continue dolen;
  19709. }
  19710. else if (op & 32) { /* end-of-block */
  19711. //Tracevv((stderr, "inflate: end of block\n"));
  19712. state.mode = TYPE;
  19713. break top;
  19714. }
  19715. else {
  19716. strm.msg = 'invalid literal/length code';
  19717. state.mode = BAD;
  19718. break top;
  19719. }
  19720. break; // need to emulate goto via "continue"
  19721. }
  19722. } while (_in < last && _out < end);
  19723. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  19724. len = bits >> 3;
  19725. _in -= len;
  19726. bits -= len << 3;
  19727. hold &= (1 << bits) - 1;
  19728. /* update state and return */
  19729. strm.next_in = _in;
  19730. strm.next_out = _out;
  19731. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  19732. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  19733. state.hold = hold;
  19734. state.bits = bits;
  19735. return;
  19736. };
  19737. },{}],74:[function(require,module,exports){
  19738. 'use strict';
  19739. var utils = require('../utils/common');
  19740. var adler32 = require('./adler32');
  19741. var crc32 = require('./crc32');
  19742. var inflate_fast = require('./inffast');
  19743. var inflate_table = require('./inftrees');
  19744. var CODES = 0;
  19745. var LENS = 1;
  19746. var DISTS = 2;
  19747. /* Public constants ==========================================================*/
  19748. /* ===========================================================================*/
  19749. /* Allowed flush values; see deflate() and inflate() below for details */
  19750. //var Z_NO_FLUSH = 0;
  19751. //var Z_PARTIAL_FLUSH = 1;
  19752. //var Z_SYNC_FLUSH = 2;
  19753. //var Z_FULL_FLUSH = 3;
  19754. var Z_FINISH = 4;
  19755. var Z_BLOCK = 5;
  19756. var Z_TREES = 6;
  19757. /* Return codes for the compression/decompression functions. Negative values
  19758. * are errors, positive values are used for special but normal events.
  19759. */
  19760. var Z_OK = 0;
  19761. var Z_STREAM_END = 1;
  19762. var Z_NEED_DICT = 2;
  19763. //var Z_ERRNO = -1;
  19764. var Z_STREAM_ERROR = -2;
  19765. var Z_DATA_ERROR = -3;
  19766. var Z_MEM_ERROR = -4;
  19767. var Z_BUF_ERROR = -5;
  19768. //var Z_VERSION_ERROR = -6;
  19769. /* The deflate compression method */
  19770. var Z_DEFLATED = 8;
  19771. /* STATES ====================================================================*/
  19772. /* ===========================================================================*/
  19773. var HEAD = 1; /* i: waiting for magic header */
  19774. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  19775. var TIME = 3; /* i: waiting for modification time (gzip) */
  19776. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  19777. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  19778. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  19779. var NAME = 7; /* i: waiting for end of file name (gzip) */
  19780. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  19781. var HCRC = 9; /* i: waiting for header crc (gzip) */
  19782. var DICTID = 10; /* i: waiting for dictionary check value */
  19783. var DICT = 11; /* waiting for inflateSetDictionary() call */
  19784. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  19785. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  19786. var STORED = 14; /* i: waiting for stored size (length and complement) */
  19787. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  19788. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  19789. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  19790. var LENLENS = 18; /* i: waiting for code length code lengths */
  19791. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  19792. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  19793. var LEN = 21; /* i: waiting for length/lit/eob code */
  19794. var LENEXT = 22; /* i: waiting for length extra bits */
  19795. var DIST = 23; /* i: waiting for distance code */
  19796. var DISTEXT = 24; /* i: waiting for distance extra bits */
  19797. var MATCH = 25; /* o: waiting for output space to copy string */
  19798. var LIT = 26; /* o: waiting for output space to write literal */
  19799. var CHECK = 27; /* i: waiting for 32-bit check value */
  19800. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  19801. var DONE = 29; /* finished check, done -- remain here until reset */
  19802. var BAD = 30; /* got a data error -- remain here until reset */
  19803. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  19804. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  19805. /* ===========================================================================*/
  19806. var ENOUGH_LENS = 852;
  19807. var ENOUGH_DISTS = 592;
  19808. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  19809. var MAX_WBITS = 15;
  19810. /* 32K LZ77 window */
  19811. var DEF_WBITS = MAX_WBITS;
  19812. function ZSWAP32(q) {
  19813. return (((q >>> 24) & 0xff) +
  19814. ((q >>> 8) & 0xff00) +
  19815. ((q & 0xff00) << 8) +
  19816. ((q & 0xff) << 24));
  19817. }
  19818. function InflateState() {
  19819. this.mode = 0; /* current inflate mode */
  19820. this.last = false; /* true if processing last block */
  19821. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  19822. this.havedict = false; /* true if dictionary provided */
  19823. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  19824. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  19825. this.check = 0; /* protected copy of check value */
  19826. this.total = 0; /* protected copy of output count */
  19827. // TODO: may be {}
  19828. this.head = null; /* where to save gzip header information */
  19829. /* sliding window */
  19830. this.wbits = 0; /* log base 2 of requested window size */
  19831. this.wsize = 0; /* window size or zero if not using window */
  19832. this.whave = 0; /* valid bytes in the window */
  19833. this.wnext = 0; /* window write index */
  19834. this.window = null; /* allocated sliding window, if needed */
  19835. /* bit accumulator */
  19836. this.hold = 0; /* input bit accumulator */
  19837. this.bits = 0; /* number of bits in "in" */
  19838. /* for string and stored block copying */
  19839. this.length = 0; /* literal or length of data to copy */
  19840. this.offset = 0; /* distance back to copy string from */
  19841. /* for table and code decoding */
  19842. this.extra = 0; /* extra bits needed */
  19843. /* fixed and dynamic code tables */
  19844. this.lencode = null; /* starting table for length/literal codes */
  19845. this.distcode = null; /* starting table for distance codes */
  19846. this.lenbits = 0; /* index bits for lencode */
  19847. this.distbits = 0; /* index bits for distcode */
  19848. /* dynamic table building */
  19849. this.ncode = 0; /* number of code length code lengths */
  19850. this.nlen = 0; /* number of length code lengths */
  19851. this.ndist = 0; /* number of distance code lengths */
  19852. this.have = 0; /* number of code lengths in lens[] */
  19853. this.next = null; /* next available space in codes[] */
  19854. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  19855. this.work = new utils.Buf16(288); /* work area for code table building */
  19856. /*
  19857. because we don't have pointers in js, we use lencode and distcode directly
  19858. as buffers so we don't need codes
  19859. */
  19860. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  19861. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  19862. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  19863. this.sane = 0; /* if false, allow invalid distance too far */
  19864. this.back = 0; /* bits back of last unprocessed length/lit */
  19865. this.was = 0; /* initial length of match */
  19866. }
  19867. function inflateResetKeep(strm) {
  19868. var state;
  19869. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19870. state = strm.state;
  19871. strm.total_in = strm.total_out = state.total = 0;
  19872. strm.msg = ''; /*Z_NULL*/
  19873. if (state.wrap) { /* to support ill-conceived Java test suite */
  19874. strm.adler = state.wrap & 1;
  19875. }
  19876. state.mode = HEAD;
  19877. state.last = 0;
  19878. state.havedict = 0;
  19879. state.dmax = 32768;
  19880. state.head = null/*Z_NULL*/;
  19881. state.hold = 0;
  19882. state.bits = 0;
  19883. //state.lencode = state.distcode = state.next = state.codes;
  19884. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  19885. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  19886. state.sane = 1;
  19887. state.back = -1;
  19888. //Tracev((stderr, "inflate: reset\n"));
  19889. return Z_OK;
  19890. }
  19891. function inflateReset(strm) {
  19892. var state;
  19893. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19894. state = strm.state;
  19895. state.wsize = 0;
  19896. state.whave = 0;
  19897. state.wnext = 0;
  19898. return inflateResetKeep(strm);
  19899. }
  19900. function inflateReset2(strm, windowBits) {
  19901. var wrap;
  19902. var state;
  19903. /* get the state */
  19904. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19905. state = strm.state;
  19906. /* extract wrap request from windowBits parameter */
  19907. if (windowBits < 0) {
  19908. wrap = 0;
  19909. windowBits = -windowBits;
  19910. }
  19911. else {
  19912. wrap = (windowBits >> 4) + 1;
  19913. if (windowBits < 48) {
  19914. windowBits &= 15;
  19915. }
  19916. }
  19917. /* set number of window bits, free window if different */
  19918. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  19919. return Z_STREAM_ERROR;
  19920. }
  19921. if (state.window !== null && state.wbits !== windowBits) {
  19922. state.window = null;
  19923. }
  19924. /* update state and reset the rest of it */
  19925. state.wrap = wrap;
  19926. state.wbits = windowBits;
  19927. return inflateReset(strm);
  19928. }
  19929. function inflateInit2(strm, windowBits) {
  19930. var ret;
  19931. var state;
  19932. if (!strm) { return Z_STREAM_ERROR; }
  19933. //strm.msg = Z_NULL; /* in case we return an error */
  19934. state = new InflateState();
  19935. //if (state === Z_NULL) return Z_MEM_ERROR;
  19936. //Tracev((stderr, "inflate: allocated\n"));
  19937. strm.state = state;
  19938. state.window = null/*Z_NULL*/;
  19939. ret = inflateReset2(strm, windowBits);
  19940. if (ret !== Z_OK) {
  19941. strm.state = null/*Z_NULL*/;
  19942. }
  19943. return ret;
  19944. }
  19945. function inflateInit(strm) {
  19946. return inflateInit2(strm, DEF_WBITS);
  19947. }
  19948. /*
  19949. Return state with length and distance decoding tables and index sizes set to
  19950. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  19951. If BUILDFIXED is defined, then instead this routine builds the tables the
  19952. first time it's called, and returns those tables the first time and
  19953. thereafter. This reduces the size of the code by about 2K bytes, in
  19954. exchange for a little execution time. However, BUILDFIXED should not be
  19955. used for threaded applications, since the rewriting of the tables and virgin
  19956. may not be thread-safe.
  19957. */
  19958. var virgin = true;
  19959. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  19960. function fixedtables(state) {
  19961. /* build fixed huffman tables if first call (may not be thread safe) */
  19962. if (virgin) {
  19963. var sym;
  19964. lenfix = new utils.Buf32(512);
  19965. distfix = new utils.Buf32(32);
  19966. /* literal/length table */
  19967. sym = 0;
  19968. while (sym < 144) { state.lens[sym++] = 8; }
  19969. while (sym < 256) { state.lens[sym++] = 9; }
  19970. while (sym < 280) { state.lens[sym++] = 7; }
  19971. while (sym < 288) { state.lens[sym++] = 8; }
  19972. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  19973. /* distance table */
  19974. sym = 0;
  19975. while (sym < 32) { state.lens[sym++] = 5; }
  19976. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  19977. /* do this just once */
  19978. virgin = false;
  19979. }
  19980. state.lencode = lenfix;
  19981. state.lenbits = 9;
  19982. state.distcode = distfix;
  19983. state.distbits = 5;
  19984. }
  19985. /*
  19986. Update the window with the last wsize (normally 32K) bytes written before
  19987. returning. If window does not exist yet, create it. This is only called
  19988. when a window is already in use, or when output has been written during this
  19989. inflate call, but the end of the deflate stream has not been reached yet.
  19990. It is also called to create a window for dictionary data when a dictionary
  19991. is loaded.
  19992. Providing output buffers larger than 32K to inflate() should provide a speed
  19993. advantage, since only the last 32K of output is copied to the sliding window
  19994. upon return from inflate(), and since all distances after the first 32K of
  19995. output will fall in the output data, making match copies simpler and faster.
  19996. The advantage may be dependent on the size of the processor's data caches.
  19997. */
  19998. function updatewindow(strm, src, end, copy) {
  19999. var dist;
  20000. var state = strm.state;
  20001. /* if it hasn't been done already, allocate space for the window */
  20002. if (state.window === null) {
  20003. state.wsize = 1 << state.wbits;
  20004. state.wnext = 0;
  20005. state.whave = 0;
  20006. state.window = new utils.Buf8(state.wsize);
  20007. }
  20008. /* copy state->wsize or less output bytes into the circular window */
  20009. if (copy >= state.wsize) {
  20010. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  20011. state.wnext = 0;
  20012. state.whave = state.wsize;
  20013. }
  20014. else {
  20015. dist = state.wsize - state.wnext;
  20016. if (dist > copy) {
  20017. dist = copy;
  20018. }
  20019. //zmemcpy(state->window + state->wnext, end - copy, dist);
  20020. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  20021. copy -= dist;
  20022. if (copy) {
  20023. //zmemcpy(state->window, end - copy, copy);
  20024. utils.arraySet(state.window,src, end - copy, copy, 0);
  20025. state.wnext = copy;
  20026. state.whave = state.wsize;
  20027. }
  20028. else {
  20029. state.wnext += dist;
  20030. if (state.wnext === state.wsize) { state.wnext = 0; }
  20031. if (state.whave < state.wsize) { state.whave += dist; }
  20032. }
  20033. }
  20034. return 0;
  20035. }
  20036. function inflate(strm, flush) {
  20037. var state;
  20038. var input, output; // input/output buffers
  20039. var next; /* next input INDEX */
  20040. var put; /* next output INDEX */
  20041. var have, left; /* available input and output */
  20042. var hold; /* bit buffer */
  20043. var bits; /* bits in bit buffer */
  20044. var _in, _out; /* save starting available input and output */
  20045. var copy; /* number of stored or match bytes to copy */
  20046. var from; /* where to copy match bytes from */
  20047. var from_source;
  20048. var here = 0; /* current decoding table entry */
  20049. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  20050. //var last; /* parent table entry */
  20051. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  20052. var len; /* length to copy for repeats, bits to drop */
  20053. var ret; /* return code */
  20054. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  20055. var opts;
  20056. var n; // temporary var for NEED_BITS
  20057. var order = /* permutation of code lengths */
  20058. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  20059. if (!strm || !strm.state || !strm.output ||
  20060. (!strm.input && strm.avail_in !== 0)) {
  20061. return Z_STREAM_ERROR;
  20062. }
  20063. state = strm.state;
  20064. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  20065. //--- LOAD() ---
  20066. put = strm.next_out;
  20067. output = strm.output;
  20068. left = strm.avail_out;
  20069. next = strm.next_in;
  20070. input = strm.input;
  20071. have = strm.avail_in;
  20072. hold = state.hold;
  20073. bits = state.bits;
  20074. //---
  20075. _in = have;
  20076. _out = left;
  20077. ret = Z_OK;
  20078. inf_leave: // goto emulation
  20079. for (;;) {
  20080. switch (state.mode) {
  20081. case HEAD:
  20082. if (state.wrap === 0) {
  20083. state.mode = TYPEDO;
  20084. break;
  20085. }
  20086. //=== NEEDBITS(16);
  20087. while (bits < 16) {
  20088. if (have === 0) { break inf_leave; }
  20089. have--;
  20090. hold += input[next++] << bits;
  20091. bits += 8;
  20092. }
  20093. //===//
  20094. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  20095. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  20096. //=== CRC2(state.check, hold);
  20097. hbuf[0] = hold & 0xff;
  20098. hbuf[1] = (hold >>> 8) & 0xff;
  20099. state.check = crc32(state.check, hbuf, 2, 0);
  20100. //===//
  20101. //=== INITBITS();
  20102. hold = 0;
  20103. bits = 0;
  20104. //===//
  20105. state.mode = FLAGS;
  20106. break;
  20107. }
  20108. state.flags = 0; /* expect zlib header */
  20109. if (state.head) {
  20110. state.head.done = false;
  20111. }
  20112. if (!(state.wrap & 1) || /* check if zlib header allowed */
  20113. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  20114. strm.msg = 'incorrect header check';
  20115. state.mode = BAD;
  20116. break;
  20117. }
  20118. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  20119. strm.msg = 'unknown compression method';
  20120. state.mode = BAD;
  20121. break;
  20122. }
  20123. //--- DROPBITS(4) ---//
  20124. hold >>>= 4;
  20125. bits -= 4;
  20126. //---//
  20127. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  20128. if (state.wbits === 0) {
  20129. state.wbits = len;
  20130. }
  20131. else if (len > state.wbits) {
  20132. strm.msg = 'invalid window size';
  20133. state.mode = BAD;
  20134. break;
  20135. }
  20136. state.dmax = 1 << len;
  20137. //Tracev((stderr, "inflate: zlib header ok\n"));
  20138. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  20139. state.mode = hold & 0x200 ? DICTID : TYPE;
  20140. //=== INITBITS();
  20141. hold = 0;
  20142. bits = 0;
  20143. //===//
  20144. break;
  20145. case FLAGS:
  20146. //=== NEEDBITS(16); */
  20147. while (bits < 16) {
  20148. if (have === 0) { break inf_leave; }
  20149. have--;
  20150. hold += input[next++] << bits;
  20151. bits += 8;
  20152. }
  20153. //===//
  20154. state.flags = hold;
  20155. if ((state.flags & 0xff) !== Z_DEFLATED) {
  20156. strm.msg = 'unknown compression method';
  20157. state.mode = BAD;
  20158. break;
  20159. }
  20160. if (state.flags & 0xe000) {
  20161. strm.msg = 'unknown header flags set';
  20162. state.mode = BAD;
  20163. break;
  20164. }
  20165. if (state.head) {
  20166. state.head.text = ((hold >> 8) & 1);
  20167. }
  20168. if (state.flags & 0x0200) {
  20169. //=== CRC2(state.check, hold);
  20170. hbuf[0] = hold & 0xff;
  20171. hbuf[1] = (hold >>> 8) & 0xff;
  20172. state.check = crc32(state.check, hbuf, 2, 0);
  20173. //===//
  20174. }
  20175. //=== INITBITS();
  20176. hold = 0;
  20177. bits = 0;
  20178. //===//
  20179. state.mode = TIME;
  20180. /* falls through */
  20181. case TIME:
  20182. //=== NEEDBITS(32); */
  20183. while (bits < 32) {
  20184. if (have === 0) { break inf_leave; }
  20185. have--;
  20186. hold += input[next++] << bits;
  20187. bits += 8;
  20188. }
  20189. //===//
  20190. if (state.head) {
  20191. state.head.time = hold;
  20192. }
  20193. if (state.flags & 0x0200) {
  20194. //=== CRC4(state.check, hold)
  20195. hbuf[0] = hold & 0xff;
  20196. hbuf[1] = (hold >>> 8) & 0xff;
  20197. hbuf[2] = (hold >>> 16) & 0xff;
  20198. hbuf[3] = (hold >>> 24) & 0xff;
  20199. state.check = crc32(state.check, hbuf, 4, 0);
  20200. //===
  20201. }
  20202. //=== INITBITS();
  20203. hold = 0;
  20204. bits = 0;
  20205. //===//
  20206. state.mode = OS;
  20207. /* falls through */
  20208. case OS:
  20209. //=== NEEDBITS(16); */
  20210. while (bits < 16) {
  20211. if (have === 0) { break inf_leave; }
  20212. have--;
  20213. hold += input[next++] << bits;
  20214. bits += 8;
  20215. }
  20216. //===//
  20217. if (state.head) {
  20218. state.head.xflags = (hold & 0xff);
  20219. state.head.os = (hold >> 8);
  20220. }
  20221. if (state.flags & 0x0200) {
  20222. //=== CRC2(state.check, hold);
  20223. hbuf[0] = hold & 0xff;
  20224. hbuf[1] = (hold >>> 8) & 0xff;
  20225. state.check = crc32(state.check, hbuf, 2, 0);
  20226. //===//
  20227. }
  20228. //=== INITBITS();
  20229. hold = 0;
  20230. bits = 0;
  20231. //===//
  20232. state.mode = EXLEN;
  20233. /* falls through */
  20234. case EXLEN:
  20235. if (state.flags & 0x0400) {
  20236. //=== NEEDBITS(16); */
  20237. while (bits < 16) {
  20238. if (have === 0) { break inf_leave; }
  20239. have--;
  20240. hold += input[next++] << bits;
  20241. bits += 8;
  20242. }
  20243. //===//
  20244. state.length = hold;
  20245. if (state.head) {
  20246. state.head.extra_len = hold;
  20247. }
  20248. if (state.flags & 0x0200) {
  20249. //=== CRC2(state.check, hold);
  20250. hbuf[0] = hold & 0xff;
  20251. hbuf[1] = (hold >>> 8) & 0xff;
  20252. state.check = crc32(state.check, hbuf, 2, 0);
  20253. //===//
  20254. }
  20255. //=== INITBITS();
  20256. hold = 0;
  20257. bits = 0;
  20258. //===//
  20259. }
  20260. else if (state.head) {
  20261. state.head.extra = null/*Z_NULL*/;
  20262. }
  20263. state.mode = EXTRA;
  20264. /* falls through */
  20265. case EXTRA:
  20266. if (state.flags & 0x0400) {
  20267. copy = state.length;
  20268. if (copy > have) { copy = have; }
  20269. if (copy) {
  20270. if (state.head) {
  20271. len = state.head.extra_len - state.length;
  20272. if (!state.head.extra) {
  20273. // Use untyped array for more conveniend processing later
  20274. state.head.extra = new Array(state.head.extra_len);
  20275. }
  20276. utils.arraySet(
  20277. state.head.extra,
  20278. input,
  20279. next,
  20280. // extra field is limited to 65536 bytes
  20281. // - no need for additional size check
  20282. copy,
  20283. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  20284. len
  20285. );
  20286. //zmemcpy(state.head.extra + len, next,
  20287. // len + copy > state.head.extra_max ?
  20288. // state.head.extra_max - len : copy);
  20289. }
  20290. if (state.flags & 0x0200) {
  20291. state.check = crc32(state.check, input, copy, next);
  20292. }
  20293. have -= copy;
  20294. next += copy;
  20295. state.length -= copy;
  20296. }
  20297. if (state.length) { break inf_leave; }
  20298. }
  20299. state.length = 0;
  20300. state.mode = NAME;
  20301. /* falls through */
  20302. case NAME:
  20303. if (state.flags & 0x0800) {
  20304. if (have === 0) { break inf_leave; }
  20305. copy = 0;
  20306. do {
  20307. // TODO: 2 or 1 bytes?
  20308. len = input[next + copy++];
  20309. /* use constant limit because in js we should not preallocate memory */
  20310. if (state.head && len &&
  20311. (state.length < 65536 /*state.head.name_max*/)) {
  20312. state.head.name += String.fromCharCode(len);
  20313. }
  20314. } while (len && copy < have);
  20315. if (state.flags & 0x0200) {
  20316. state.check = crc32(state.check, input, copy, next);
  20317. }
  20318. have -= copy;
  20319. next += copy;
  20320. if (len) { break inf_leave; }
  20321. }
  20322. else if (state.head) {
  20323. state.head.name = null;
  20324. }
  20325. state.length = 0;
  20326. state.mode = COMMENT;
  20327. /* falls through */
  20328. case COMMENT:
  20329. if (state.flags & 0x1000) {
  20330. if (have === 0) { break inf_leave; }
  20331. copy = 0;
  20332. do {
  20333. len = input[next + copy++];
  20334. /* use constant limit because in js we should not preallocate memory */
  20335. if (state.head && len &&
  20336. (state.length < 65536 /*state.head.comm_max*/)) {
  20337. state.head.comment += String.fromCharCode(len);
  20338. }
  20339. } while (len && copy < have);
  20340. if (state.flags & 0x0200) {
  20341. state.check = crc32(state.check, input, copy, next);
  20342. }
  20343. have -= copy;
  20344. next += copy;
  20345. if (len) { break inf_leave; }
  20346. }
  20347. else if (state.head) {
  20348. state.head.comment = null;
  20349. }
  20350. state.mode = HCRC;
  20351. /* falls through */
  20352. case HCRC:
  20353. if (state.flags & 0x0200) {
  20354. //=== NEEDBITS(16); */
  20355. while (bits < 16) {
  20356. if (have === 0) { break inf_leave; }
  20357. have--;
  20358. hold += input[next++] << bits;
  20359. bits += 8;
  20360. }
  20361. //===//
  20362. if (hold !== (state.check & 0xffff)) {
  20363. strm.msg = 'header crc mismatch';
  20364. state.mode = BAD;
  20365. break;
  20366. }
  20367. //=== INITBITS();
  20368. hold = 0;
  20369. bits = 0;
  20370. //===//
  20371. }
  20372. if (state.head) {
  20373. state.head.hcrc = ((state.flags >> 9) & 1);
  20374. state.head.done = true;
  20375. }
  20376. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  20377. state.mode = TYPE;
  20378. break;
  20379. case DICTID:
  20380. //=== NEEDBITS(32); */
  20381. while (bits < 32) {
  20382. if (have === 0) { break inf_leave; }
  20383. have--;
  20384. hold += input[next++] << bits;
  20385. bits += 8;
  20386. }
  20387. //===//
  20388. strm.adler = state.check = ZSWAP32(hold);
  20389. //=== INITBITS();
  20390. hold = 0;
  20391. bits = 0;
  20392. //===//
  20393. state.mode = DICT;
  20394. /* falls through */
  20395. case DICT:
  20396. if (state.havedict === 0) {
  20397. //--- RESTORE() ---
  20398. strm.next_out = put;
  20399. strm.avail_out = left;
  20400. strm.next_in = next;
  20401. strm.avail_in = have;
  20402. state.hold = hold;
  20403. state.bits = bits;
  20404. //---
  20405. return Z_NEED_DICT;
  20406. }
  20407. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  20408. state.mode = TYPE;
  20409. /* falls through */
  20410. case TYPE:
  20411. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  20412. /* falls through */
  20413. case TYPEDO:
  20414. if (state.last) {
  20415. //--- BYTEBITS() ---//
  20416. hold >>>= bits & 7;
  20417. bits -= bits & 7;
  20418. //---//
  20419. state.mode = CHECK;
  20420. break;
  20421. }
  20422. //=== NEEDBITS(3); */
  20423. while (bits < 3) {
  20424. if (have === 0) { break inf_leave; }
  20425. have--;
  20426. hold += input[next++] << bits;
  20427. bits += 8;
  20428. }
  20429. //===//
  20430. state.last = (hold & 0x01)/*BITS(1)*/;
  20431. //--- DROPBITS(1) ---//
  20432. hold >>>= 1;
  20433. bits -= 1;
  20434. //---//
  20435. switch ((hold & 0x03)/*BITS(2)*/) {
  20436. case 0: /* stored block */
  20437. //Tracev((stderr, "inflate: stored block%s\n",
  20438. // state.last ? " (last)" : ""));
  20439. state.mode = STORED;
  20440. break;
  20441. case 1: /* fixed block */
  20442. fixedtables(state);
  20443. //Tracev((stderr, "inflate: fixed codes block%s\n",
  20444. // state.last ? " (last)" : ""));
  20445. state.mode = LEN_; /* decode codes */
  20446. if (flush === Z_TREES) {
  20447. //--- DROPBITS(2) ---//
  20448. hold >>>= 2;
  20449. bits -= 2;
  20450. //---//
  20451. break inf_leave;
  20452. }
  20453. break;
  20454. case 2: /* dynamic block */
  20455. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  20456. // state.last ? " (last)" : ""));
  20457. state.mode = TABLE;
  20458. break;
  20459. case 3:
  20460. strm.msg = 'invalid block type';
  20461. state.mode = BAD;
  20462. }
  20463. //--- DROPBITS(2) ---//
  20464. hold >>>= 2;
  20465. bits -= 2;
  20466. //---//
  20467. break;
  20468. case STORED:
  20469. //--- BYTEBITS() ---// /* go to byte boundary */
  20470. hold >>>= bits & 7;
  20471. bits -= bits & 7;
  20472. //---//
  20473. //=== NEEDBITS(32); */
  20474. while (bits < 32) {
  20475. if (have === 0) { break inf_leave; }
  20476. have--;
  20477. hold += input[next++] << bits;
  20478. bits += 8;
  20479. }
  20480. //===//
  20481. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  20482. strm.msg = 'invalid stored block lengths';
  20483. state.mode = BAD;
  20484. break;
  20485. }
  20486. state.length = hold & 0xffff;
  20487. //Tracev((stderr, "inflate: stored length %u\n",
  20488. // state.length));
  20489. //=== INITBITS();
  20490. hold = 0;
  20491. bits = 0;
  20492. //===//
  20493. state.mode = COPY_;
  20494. if (flush === Z_TREES) { break inf_leave; }
  20495. /* falls through */
  20496. case COPY_:
  20497. state.mode = COPY;
  20498. /* falls through */
  20499. case COPY:
  20500. copy = state.length;
  20501. if (copy) {
  20502. if (copy > have) { copy = have; }
  20503. if (copy > left) { copy = left; }
  20504. if (copy === 0) { break inf_leave; }
  20505. //--- zmemcpy(put, next, copy); ---
  20506. utils.arraySet(output, input, next, copy, put);
  20507. //---//
  20508. have -= copy;
  20509. next += copy;
  20510. left -= copy;
  20511. put += copy;
  20512. state.length -= copy;
  20513. break;
  20514. }
  20515. //Tracev((stderr, "inflate: stored end\n"));
  20516. state.mode = TYPE;
  20517. break;
  20518. case TABLE:
  20519. //=== NEEDBITS(14); */
  20520. while (bits < 14) {
  20521. if (have === 0) { break inf_leave; }
  20522. have--;
  20523. hold += input[next++] << bits;
  20524. bits += 8;
  20525. }
  20526. //===//
  20527. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  20528. //--- DROPBITS(5) ---//
  20529. hold >>>= 5;
  20530. bits -= 5;
  20531. //---//
  20532. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  20533. //--- DROPBITS(5) ---//
  20534. hold >>>= 5;
  20535. bits -= 5;
  20536. //---//
  20537. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  20538. //--- DROPBITS(4) ---//
  20539. hold >>>= 4;
  20540. bits -= 4;
  20541. //---//
  20542. //#ifndef PKZIP_BUG_WORKAROUND
  20543. if (state.nlen > 286 || state.ndist > 30) {
  20544. strm.msg = 'too many length or distance symbols';
  20545. state.mode = BAD;
  20546. break;
  20547. }
  20548. //#endif
  20549. //Tracev((stderr, "inflate: table sizes ok\n"));
  20550. state.have = 0;
  20551. state.mode = LENLENS;
  20552. /* falls through */
  20553. case LENLENS:
  20554. while (state.have < state.ncode) {
  20555. //=== NEEDBITS(3);
  20556. while (bits < 3) {
  20557. if (have === 0) { break inf_leave; }
  20558. have--;
  20559. hold += input[next++] << bits;
  20560. bits += 8;
  20561. }
  20562. //===//
  20563. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  20564. //--- DROPBITS(3) ---//
  20565. hold >>>= 3;
  20566. bits -= 3;
  20567. //---//
  20568. }
  20569. while (state.have < 19) {
  20570. state.lens[order[state.have++]] = 0;
  20571. }
  20572. // We have separate tables & no pointers. 2 commented lines below not needed.
  20573. //state.next = state.codes;
  20574. //state.lencode = state.next;
  20575. // Switch to use dynamic table
  20576. state.lencode = state.lendyn;
  20577. state.lenbits = 7;
  20578. opts = {bits: state.lenbits};
  20579. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  20580. state.lenbits = opts.bits;
  20581. if (ret) {
  20582. strm.msg = 'invalid code lengths set';
  20583. state.mode = BAD;
  20584. break;
  20585. }
  20586. //Tracev((stderr, "inflate: code lengths ok\n"));
  20587. state.have = 0;
  20588. state.mode = CODELENS;
  20589. /* falls through */
  20590. case CODELENS:
  20591. while (state.have < state.nlen + state.ndist) {
  20592. for (;;) {
  20593. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  20594. here_bits = here >>> 24;
  20595. here_op = (here >>> 16) & 0xff;
  20596. here_val = here & 0xffff;
  20597. if ((here_bits) <= bits) { break; }
  20598. //--- PULLBYTE() ---//
  20599. if (have === 0) { break inf_leave; }
  20600. have--;
  20601. hold += input[next++] << bits;
  20602. bits += 8;
  20603. //---//
  20604. }
  20605. if (here_val < 16) {
  20606. //--- DROPBITS(here.bits) ---//
  20607. hold >>>= here_bits;
  20608. bits -= here_bits;
  20609. //---//
  20610. state.lens[state.have++] = here_val;
  20611. }
  20612. else {
  20613. if (here_val === 16) {
  20614. //=== NEEDBITS(here.bits + 2);
  20615. n = here_bits + 2;
  20616. while (bits < n) {
  20617. if (have === 0) { break inf_leave; }
  20618. have--;
  20619. hold += input[next++] << bits;
  20620. bits += 8;
  20621. }
  20622. //===//
  20623. //--- DROPBITS(here.bits) ---//
  20624. hold >>>= here_bits;
  20625. bits -= here_bits;
  20626. //---//
  20627. if (state.have === 0) {
  20628. strm.msg = 'invalid bit length repeat';
  20629. state.mode = BAD;
  20630. break;
  20631. }
  20632. len = state.lens[state.have - 1];
  20633. copy = 3 + (hold & 0x03);//BITS(2);
  20634. //--- DROPBITS(2) ---//
  20635. hold >>>= 2;
  20636. bits -= 2;
  20637. //---//
  20638. }
  20639. else if (here_val === 17) {
  20640. //=== NEEDBITS(here.bits + 3);
  20641. n = here_bits + 3;
  20642. while (bits < n) {
  20643. if (have === 0) { break inf_leave; }
  20644. have--;
  20645. hold += input[next++] << bits;
  20646. bits += 8;
  20647. }
  20648. //===//
  20649. //--- DROPBITS(here.bits) ---//
  20650. hold >>>= here_bits;
  20651. bits -= here_bits;
  20652. //---//
  20653. len = 0;
  20654. copy = 3 + (hold & 0x07);//BITS(3);
  20655. //--- DROPBITS(3) ---//
  20656. hold >>>= 3;
  20657. bits -= 3;
  20658. //---//
  20659. }
  20660. else {
  20661. //=== NEEDBITS(here.bits + 7);
  20662. n = here_bits + 7;
  20663. while (bits < n) {
  20664. if (have === 0) { break inf_leave; }
  20665. have--;
  20666. hold += input[next++] << bits;
  20667. bits += 8;
  20668. }
  20669. //===//
  20670. //--- DROPBITS(here.bits) ---//
  20671. hold >>>= here_bits;
  20672. bits -= here_bits;
  20673. //---//
  20674. len = 0;
  20675. copy = 11 + (hold & 0x7f);//BITS(7);
  20676. //--- DROPBITS(7) ---//
  20677. hold >>>= 7;
  20678. bits -= 7;
  20679. //---//
  20680. }
  20681. if (state.have + copy > state.nlen + state.ndist) {
  20682. strm.msg = 'invalid bit length repeat';
  20683. state.mode = BAD;
  20684. break;
  20685. }
  20686. while (copy--) {
  20687. state.lens[state.have++] = len;
  20688. }
  20689. }
  20690. }
  20691. /* handle error breaks in while */
  20692. if (state.mode === BAD) { break; }
  20693. /* check for end-of-block code (better have one) */
  20694. if (state.lens[256] === 0) {
  20695. strm.msg = 'invalid code -- missing end-of-block';
  20696. state.mode = BAD;
  20697. break;
  20698. }
  20699. /* build code tables -- note: do not change the lenbits or distbits
  20700. values here (9 and 6) without reading the comments in inftrees.h
  20701. concerning the ENOUGH constants, which depend on those values */
  20702. state.lenbits = 9;
  20703. opts = {bits: state.lenbits};
  20704. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  20705. // We have separate tables & no pointers. 2 commented lines below not needed.
  20706. // state.next_index = opts.table_index;
  20707. state.lenbits = opts.bits;
  20708. // state.lencode = state.next;
  20709. if (ret) {
  20710. strm.msg = 'invalid literal/lengths set';
  20711. state.mode = BAD;
  20712. break;
  20713. }
  20714. state.distbits = 6;
  20715. //state.distcode.copy(state.codes);
  20716. // Switch to use dynamic table
  20717. state.distcode = state.distdyn;
  20718. opts = {bits: state.distbits};
  20719. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  20720. // We have separate tables & no pointers. 2 commented lines below not needed.
  20721. // state.next_index = opts.table_index;
  20722. state.distbits = opts.bits;
  20723. // state.distcode = state.next;
  20724. if (ret) {
  20725. strm.msg = 'invalid distances set';
  20726. state.mode = BAD;
  20727. break;
  20728. }
  20729. //Tracev((stderr, 'inflate: codes ok\n'));
  20730. state.mode = LEN_;
  20731. if (flush === Z_TREES) { break inf_leave; }
  20732. /* falls through */
  20733. case LEN_:
  20734. state.mode = LEN;
  20735. /* falls through */
  20736. case LEN:
  20737. if (have >= 6 && left >= 258) {
  20738. //--- RESTORE() ---
  20739. strm.next_out = put;
  20740. strm.avail_out = left;
  20741. strm.next_in = next;
  20742. strm.avail_in = have;
  20743. state.hold = hold;
  20744. state.bits = bits;
  20745. //---
  20746. inflate_fast(strm, _out);
  20747. //--- LOAD() ---
  20748. put = strm.next_out;
  20749. output = strm.output;
  20750. left = strm.avail_out;
  20751. next = strm.next_in;
  20752. input = strm.input;
  20753. have = strm.avail_in;
  20754. hold = state.hold;
  20755. bits = state.bits;
  20756. //---
  20757. if (state.mode === TYPE) {
  20758. state.back = -1;
  20759. }
  20760. break;
  20761. }
  20762. state.back = 0;
  20763. for (;;) {
  20764. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  20765. here_bits = here >>> 24;
  20766. here_op = (here >>> 16) & 0xff;
  20767. here_val = here & 0xffff;
  20768. if (here_bits <= bits) { break; }
  20769. //--- PULLBYTE() ---//
  20770. if (have === 0) { break inf_leave; }
  20771. have--;
  20772. hold += input[next++] << bits;
  20773. bits += 8;
  20774. //---//
  20775. }
  20776. if (here_op && (here_op & 0xf0) === 0) {
  20777. last_bits = here_bits;
  20778. last_op = here_op;
  20779. last_val = here_val;
  20780. for (;;) {
  20781. here = state.lencode[last_val +
  20782. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  20783. here_bits = here >>> 24;
  20784. here_op = (here >>> 16) & 0xff;
  20785. here_val = here & 0xffff;
  20786. if ((last_bits + here_bits) <= bits) { break; }
  20787. //--- PULLBYTE() ---//
  20788. if (have === 0) { break inf_leave; }
  20789. have--;
  20790. hold += input[next++] << bits;
  20791. bits += 8;
  20792. //---//
  20793. }
  20794. //--- DROPBITS(last.bits) ---//
  20795. hold >>>= last_bits;
  20796. bits -= last_bits;
  20797. //---//
  20798. state.back += last_bits;
  20799. }
  20800. //--- DROPBITS(here.bits) ---//
  20801. hold >>>= here_bits;
  20802. bits -= here_bits;
  20803. //---//
  20804. state.back += here_bits;
  20805. state.length = here_val;
  20806. if (here_op === 0) {
  20807. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  20808. // "inflate: literal '%c'\n" :
  20809. // "inflate: literal 0x%02x\n", here.val));
  20810. state.mode = LIT;
  20811. break;
  20812. }
  20813. if (here_op & 32) {
  20814. //Tracevv((stderr, "inflate: end of block\n"));
  20815. state.back = -1;
  20816. state.mode = TYPE;
  20817. break;
  20818. }
  20819. if (here_op & 64) {
  20820. strm.msg = 'invalid literal/length code';
  20821. state.mode = BAD;
  20822. break;
  20823. }
  20824. state.extra = here_op & 15;
  20825. state.mode = LENEXT;
  20826. /* falls through */
  20827. case LENEXT:
  20828. if (state.extra) {
  20829. //=== NEEDBITS(state.extra);
  20830. n = state.extra;
  20831. while (bits < n) {
  20832. if (have === 0) { break inf_leave; }
  20833. have--;
  20834. hold += input[next++] << bits;
  20835. bits += 8;
  20836. }
  20837. //===//
  20838. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  20839. //--- DROPBITS(state.extra) ---//
  20840. hold >>>= state.extra;
  20841. bits -= state.extra;
  20842. //---//
  20843. state.back += state.extra;
  20844. }
  20845. //Tracevv((stderr, "inflate: length %u\n", state.length));
  20846. state.was = state.length;
  20847. state.mode = DIST;
  20848. /* falls through */
  20849. case DIST:
  20850. for (;;) {
  20851. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  20852. here_bits = here >>> 24;
  20853. here_op = (here >>> 16) & 0xff;
  20854. here_val = here & 0xffff;
  20855. if ((here_bits) <= bits) { break; }
  20856. //--- PULLBYTE() ---//
  20857. if (have === 0) { break inf_leave; }
  20858. have--;
  20859. hold += input[next++] << bits;
  20860. bits += 8;
  20861. //---//
  20862. }
  20863. if ((here_op & 0xf0) === 0) {
  20864. last_bits = here_bits;
  20865. last_op = here_op;
  20866. last_val = here_val;
  20867. for (;;) {
  20868. here = state.distcode[last_val +
  20869. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  20870. here_bits = here >>> 24;
  20871. here_op = (here >>> 16) & 0xff;
  20872. here_val = here & 0xffff;
  20873. if ((last_bits + here_bits) <= bits) { break; }
  20874. //--- PULLBYTE() ---//
  20875. if (have === 0) { break inf_leave; }
  20876. have--;
  20877. hold += input[next++] << bits;
  20878. bits += 8;
  20879. //---//
  20880. }
  20881. //--- DROPBITS(last.bits) ---//
  20882. hold >>>= last_bits;
  20883. bits -= last_bits;
  20884. //---//
  20885. state.back += last_bits;
  20886. }
  20887. //--- DROPBITS(here.bits) ---//
  20888. hold >>>= here_bits;
  20889. bits -= here_bits;
  20890. //---//
  20891. state.back += here_bits;
  20892. if (here_op & 64) {
  20893. strm.msg = 'invalid distance code';
  20894. state.mode = BAD;
  20895. break;
  20896. }
  20897. state.offset = here_val;
  20898. state.extra = (here_op) & 15;
  20899. state.mode = DISTEXT;
  20900. /* falls through */
  20901. case DISTEXT:
  20902. if (state.extra) {
  20903. //=== NEEDBITS(state.extra);
  20904. n = state.extra;
  20905. while (bits < n) {
  20906. if (have === 0) { break inf_leave; }
  20907. have--;
  20908. hold += input[next++] << bits;
  20909. bits += 8;
  20910. }
  20911. //===//
  20912. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  20913. //--- DROPBITS(state.extra) ---//
  20914. hold >>>= state.extra;
  20915. bits -= state.extra;
  20916. //---//
  20917. state.back += state.extra;
  20918. }
  20919. //#ifdef INFLATE_STRICT
  20920. if (state.offset > state.dmax) {
  20921. strm.msg = 'invalid distance too far back';
  20922. state.mode = BAD;
  20923. break;
  20924. }
  20925. //#endif
  20926. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  20927. state.mode = MATCH;
  20928. /* falls through */
  20929. case MATCH:
  20930. if (left === 0) { break inf_leave; }
  20931. copy = _out - left;
  20932. if (state.offset > copy) { /* copy from window */
  20933. copy = state.offset - copy;
  20934. if (copy > state.whave) {
  20935. if (state.sane) {
  20936. strm.msg = 'invalid distance too far back';
  20937. state.mode = BAD;
  20938. break;
  20939. }
  20940. // (!) This block is disabled in zlib defailts,
  20941. // don't enable it for binary compatibility
  20942. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  20943. // Trace((stderr, "inflate.c too far\n"));
  20944. // copy -= state.whave;
  20945. // if (copy > state.length) { copy = state.length; }
  20946. // if (copy > left) { copy = left; }
  20947. // left -= copy;
  20948. // state.length -= copy;
  20949. // do {
  20950. // output[put++] = 0;
  20951. // } while (--copy);
  20952. // if (state.length === 0) { state.mode = LEN; }
  20953. // break;
  20954. //#endif
  20955. }
  20956. if (copy > state.wnext) {
  20957. copy -= state.wnext;
  20958. from = state.wsize - copy;
  20959. }
  20960. else {
  20961. from = state.wnext - copy;
  20962. }
  20963. if (copy > state.length) { copy = state.length; }
  20964. from_source = state.window;
  20965. }
  20966. else { /* copy from output */
  20967. from_source = output;
  20968. from = put - state.offset;
  20969. copy = state.length;
  20970. }
  20971. if (copy > left) { copy = left; }
  20972. left -= copy;
  20973. state.length -= copy;
  20974. do {
  20975. output[put++] = from_source[from++];
  20976. } while (--copy);
  20977. if (state.length === 0) { state.mode = LEN; }
  20978. break;
  20979. case LIT:
  20980. if (left === 0) { break inf_leave; }
  20981. output[put++] = state.length;
  20982. left--;
  20983. state.mode = LEN;
  20984. break;
  20985. case CHECK:
  20986. if (state.wrap) {
  20987. //=== NEEDBITS(32);
  20988. while (bits < 32) {
  20989. if (have === 0) { break inf_leave; }
  20990. have--;
  20991. // Use '|' insdead of '+' to make sure that result is signed
  20992. hold |= input[next++] << bits;
  20993. bits += 8;
  20994. }
  20995. //===//
  20996. _out -= left;
  20997. strm.total_out += _out;
  20998. state.total += _out;
  20999. if (_out) {
  21000. strm.adler = state.check =
  21001. /*UPDATE(state.check, put - _out, _out);*/
  21002. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  21003. }
  21004. _out = left;
  21005. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  21006. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  21007. strm.msg = 'incorrect data check';
  21008. state.mode = BAD;
  21009. break;
  21010. }
  21011. //=== INITBITS();
  21012. hold = 0;
  21013. bits = 0;
  21014. //===//
  21015. //Tracev((stderr, "inflate: check matches trailer\n"));
  21016. }
  21017. state.mode = LENGTH;
  21018. /* falls through */
  21019. case LENGTH:
  21020. if (state.wrap && state.flags) {
  21021. //=== NEEDBITS(32);
  21022. while (bits < 32) {
  21023. if (have === 0) { break inf_leave; }
  21024. have--;
  21025. hold += input[next++] << bits;
  21026. bits += 8;
  21027. }
  21028. //===//
  21029. if (hold !== (state.total & 0xffffffff)) {
  21030. strm.msg = 'incorrect length check';
  21031. state.mode = BAD;
  21032. break;
  21033. }
  21034. //=== INITBITS();
  21035. hold = 0;
  21036. bits = 0;
  21037. //===//
  21038. //Tracev((stderr, "inflate: length matches trailer\n"));
  21039. }
  21040. state.mode = DONE;
  21041. /* falls through */
  21042. case DONE:
  21043. ret = Z_STREAM_END;
  21044. break inf_leave;
  21045. case BAD:
  21046. ret = Z_DATA_ERROR;
  21047. break inf_leave;
  21048. case MEM:
  21049. return Z_MEM_ERROR;
  21050. case SYNC:
  21051. /* falls through */
  21052. default:
  21053. return Z_STREAM_ERROR;
  21054. }
  21055. }
  21056. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  21057. /*
  21058. Return from inflate(), updating the total counts and the check value.
  21059. If there was no progress during the inflate() call, return a buffer
  21060. error. Call updatewindow() to create and/or update the window state.
  21061. Note: a memory error from inflate() is non-recoverable.
  21062. */
  21063. //--- RESTORE() ---
  21064. strm.next_out = put;
  21065. strm.avail_out = left;
  21066. strm.next_in = next;
  21067. strm.avail_in = have;
  21068. state.hold = hold;
  21069. state.bits = bits;
  21070. //---
  21071. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  21072. (state.mode < CHECK || flush !== Z_FINISH))) {
  21073. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  21074. state.mode = MEM;
  21075. return Z_MEM_ERROR;
  21076. }
  21077. }
  21078. _in -= strm.avail_in;
  21079. _out -= strm.avail_out;
  21080. strm.total_in += _in;
  21081. strm.total_out += _out;
  21082. state.total += _out;
  21083. if (state.wrap && _out) {
  21084. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  21085. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  21086. }
  21087. strm.data_type = state.bits + (state.last ? 64 : 0) +
  21088. (state.mode === TYPE ? 128 : 0) +
  21089. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  21090. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  21091. ret = Z_BUF_ERROR;
  21092. }
  21093. return ret;
  21094. }
  21095. function inflateEnd(strm) {
  21096. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  21097. return Z_STREAM_ERROR;
  21098. }
  21099. var state = strm.state;
  21100. if (state.window) {
  21101. state.window = null;
  21102. }
  21103. strm.state = null;
  21104. return Z_OK;
  21105. }
  21106. function inflateGetHeader(strm, head) {
  21107. var state;
  21108. /* check state */
  21109. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21110. state = strm.state;
  21111. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  21112. /* save header structure */
  21113. state.head = head;
  21114. head.done = false;
  21115. return Z_OK;
  21116. }
  21117. exports.inflateReset = inflateReset;
  21118. exports.inflateReset2 = inflateReset2;
  21119. exports.inflateResetKeep = inflateResetKeep;
  21120. exports.inflateInit = inflateInit;
  21121. exports.inflateInit2 = inflateInit2;
  21122. exports.inflate = inflate;
  21123. exports.inflateEnd = inflateEnd;
  21124. exports.inflateGetHeader = inflateGetHeader;
  21125. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  21126. /* Not implemented
  21127. exports.inflateCopy = inflateCopy;
  21128. exports.inflateGetDictionary = inflateGetDictionary;
  21129. exports.inflateMark = inflateMark;
  21130. exports.inflatePrime = inflatePrime;
  21131. exports.inflateSetDictionary = inflateSetDictionary;
  21132. exports.inflateSync = inflateSync;
  21133. exports.inflateSyncPoint = inflateSyncPoint;
  21134. exports.inflateUndermine = inflateUndermine;
  21135. */
  21136. },{"../utils/common":66,"./adler32":68,"./crc32":70,"./inffast":73,"./inftrees":75}],75:[function(require,module,exports){
  21137. 'use strict';
  21138. var utils = require('../utils/common');
  21139. var MAXBITS = 15;
  21140. var ENOUGH_LENS = 852;
  21141. var ENOUGH_DISTS = 592;
  21142. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  21143. var CODES = 0;
  21144. var LENS = 1;
  21145. var DISTS = 2;
  21146. var lbase = [ /* Length codes 257..285 base */
  21147. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  21148. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  21149. ];
  21150. var lext = [ /* Length codes 257..285 extra */
  21151. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  21152. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  21153. ];
  21154. var dbase = [ /* Distance codes 0..29 base */
  21155. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  21156. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  21157. 8193, 12289, 16385, 24577, 0, 0
  21158. ];
  21159. var dext = [ /* Distance codes 0..29 extra */
  21160. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  21161. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  21162. 28, 28, 29, 29, 64, 64
  21163. ];
  21164. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  21165. {
  21166. var bits = opts.bits;
  21167. //here = opts.here; /* table entry for duplication */
  21168. var len = 0; /* a code's length in bits */
  21169. var sym = 0; /* index of code symbols */
  21170. var min = 0, max = 0; /* minimum and maximum code lengths */
  21171. var root = 0; /* number of index bits for root table */
  21172. var curr = 0; /* number of index bits for current table */
  21173. var drop = 0; /* code bits to drop for sub-table */
  21174. var left = 0; /* number of prefix codes available */
  21175. var used = 0; /* code entries in table used */
  21176. var huff = 0; /* Huffman code */
  21177. var incr; /* for incrementing code, index */
  21178. var fill; /* index for replicating entries */
  21179. var low; /* low bits for current root entry */
  21180. var mask; /* mask for low root bits */
  21181. var next; /* next available space in table */
  21182. var base = null; /* base value table to use */
  21183. var base_index = 0;
  21184. // var shoextra; /* extra bits table to use */
  21185. var end; /* use base and extra for symbol > end */
  21186. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  21187. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  21188. var extra = null;
  21189. var extra_index = 0;
  21190. var here_bits, here_op, here_val;
  21191. /*
  21192. Process a set of code lengths to create a canonical Huffman code. The
  21193. code lengths are lens[0..codes-1]. Each length corresponds to the
  21194. symbols 0..codes-1. The Huffman code is generated by first sorting the
  21195. symbols by length from short to long, and retaining the symbol order
  21196. for codes with equal lengths. Then the code starts with all zero bits
  21197. for the first code of the shortest length, and the codes are integer
  21198. increments for the same length, and zeros are appended as the length
  21199. increases. For the deflate format, these bits are stored backwards
  21200. from their more natural integer increment ordering, and so when the
  21201. decoding tables are built in the large loop below, the integer codes
  21202. are incremented backwards.
  21203. This routine assumes, but does not check, that all of the entries in
  21204. lens[] are in the range 0..MAXBITS. The caller must assure this.
  21205. 1..MAXBITS is interpreted as that code length. zero means that that
  21206. symbol does not occur in this code.
  21207. The codes are sorted by computing a count of codes for each length,
  21208. creating from that a table of starting indices for each length in the
  21209. sorted table, and then entering the symbols in order in the sorted
  21210. table. The sorted table is work[], with that space being provided by
  21211. the caller.
  21212. The length counts are used for other purposes as well, i.e. finding
  21213. the minimum and maximum length codes, determining if there are any
  21214. codes at all, checking for a valid set of lengths, and looking ahead
  21215. at length counts to determine sub-table sizes when building the
  21216. decoding tables.
  21217. */
  21218. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  21219. for (len = 0; len <= MAXBITS; len++) {
  21220. count[len] = 0;
  21221. }
  21222. for (sym = 0; sym < codes; sym++) {
  21223. count[lens[lens_index + sym]]++;
  21224. }
  21225. /* bound code lengths, force root to be within code lengths */
  21226. root = bits;
  21227. for (max = MAXBITS; max >= 1; max--) {
  21228. if (count[max] !== 0) { break; }
  21229. }
  21230. if (root > max) {
  21231. root = max;
  21232. }
  21233. if (max === 0) { /* no symbols to code at all */
  21234. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  21235. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  21236. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  21237. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  21238. //table.op[opts.table_index] = 64;
  21239. //table.bits[opts.table_index] = 1;
  21240. //table.val[opts.table_index++] = 0;
  21241. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  21242. opts.bits = 1;
  21243. return 0; /* no symbols, but wait for decoding to report error */
  21244. }
  21245. for (min = 1; min < max; min++) {
  21246. if (count[min] !== 0) { break; }
  21247. }
  21248. if (root < min) {
  21249. root = min;
  21250. }
  21251. /* check for an over-subscribed or incomplete set of lengths */
  21252. left = 1;
  21253. for (len = 1; len <= MAXBITS; len++) {
  21254. left <<= 1;
  21255. left -= count[len];
  21256. if (left < 0) {
  21257. return -1;
  21258. } /* over-subscribed */
  21259. }
  21260. if (left > 0 && (type === CODES || max !== 1)) {
  21261. return -1; /* incomplete set */
  21262. }
  21263. /* generate offsets into symbol table for each length for sorting */
  21264. offs[1] = 0;
  21265. for (len = 1; len < MAXBITS; len++) {
  21266. offs[len + 1] = offs[len] + count[len];
  21267. }
  21268. /* sort symbols by length, by symbol order within each length */
  21269. for (sym = 0; sym < codes; sym++) {
  21270. if (lens[lens_index + sym] !== 0) {
  21271. work[offs[lens[lens_index + sym]]++] = sym;
  21272. }
  21273. }
  21274. /*
  21275. Create and fill in decoding tables. In this loop, the table being
  21276. filled is at next and has curr index bits. The code being used is huff
  21277. with length len. That code is converted to an index by dropping drop
  21278. bits off of the bottom. For codes where len is less than drop + curr,
  21279. those top drop + curr - len bits are incremented through all values to
  21280. fill the table with replicated entries.
  21281. root is the number of index bits for the root table. When len exceeds
  21282. root, sub-tables are created pointed to by the root entry with an index
  21283. of the low root bits of huff. This is saved in low to check for when a
  21284. new sub-table should be started. drop is zero when the root table is
  21285. being filled, and drop is root when sub-tables are being filled.
  21286. When a new sub-table is needed, it is necessary to look ahead in the
  21287. code lengths to determine what size sub-table is needed. The length
  21288. counts are used for this, and so count[] is decremented as codes are
  21289. entered in the tables.
  21290. used keeps track of how many table entries have been allocated from the
  21291. provided *table space. It is checked for LENS and DIST tables against
  21292. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  21293. the initial root table size constants. See the comments in inftrees.h
  21294. for more information.
  21295. sym increments through all symbols, and the loop terminates when
  21296. all codes of length max, i.e. all codes, have been processed. This
  21297. routine permits incomplete codes, so another loop after this one fills
  21298. in the rest of the decoding tables with invalid code markers.
  21299. */
  21300. /* set up for code type */
  21301. // poor man optimization - use if-else instead of switch,
  21302. // to avoid deopts in old v8
  21303. if (type === CODES) {
  21304. base = extra = work; /* dummy value--not used */
  21305. end = 19;
  21306. } else if (type === LENS) {
  21307. base = lbase;
  21308. base_index -= 257;
  21309. extra = lext;
  21310. extra_index -= 257;
  21311. end = 256;
  21312. } else { /* DISTS */
  21313. base = dbase;
  21314. extra = dext;
  21315. end = -1;
  21316. }
  21317. /* initialize opts for loop */
  21318. huff = 0; /* starting code */
  21319. sym = 0; /* starting code symbol */
  21320. len = min; /* starting code length */
  21321. next = table_index; /* current table to fill in */
  21322. curr = root; /* current table index bits */
  21323. drop = 0; /* current bits to drop from code for index */
  21324. low = -1; /* trigger new sub-table when len > root */
  21325. used = 1 << root; /* use root table entries */
  21326. mask = used - 1; /* mask for comparing low */
  21327. /* check available table space */
  21328. if ((type === LENS && used > ENOUGH_LENS) ||
  21329. (type === DISTS && used > ENOUGH_DISTS)) {
  21330. return 1;
  21331. }
  21332. var i=0;
  21333. /* process all codes and make table entries */
  21334. for (;;) {
  21335. i++;
  21336. /* create table entry */
  21337. here_bits = len - drop;
  21338. if (work[sym] < end) {
  21339. here_op = 0;
  21340. here_val = work[sym];
  21341. }
  21342. else if (work[sym] > end) {
  21343. here_op = extra[extra_index + work[sym]];
  21344. here_val = base[base_index + work[sym]];
  21345. }
  21346. else {
  21347. here_op = 32 + 64; /* end of block */
  21348. here_val = 0;
  21349. }
  21350. /* replicate for those indices with low len bits equal to huff */
  21351. incr = 1 << (len - drop);
  21352. fill = 1 << curr;
  21353. min = fill; /* save offset to next table */
  21354. do {
  21355. fill -= incr;
  21356. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  21357. } while (fill !== 0);
  21358. /* backwards increment the len-bit code huff */
  21359. incr = 1 << (len - 1);
  21360. while (huff & incr) {
  21361. incr >>= 1;
  21362. }
  21363. if (incr !== 0) {
  21364. huff &= incr - 1;
  21365. huff += incr;
  21366. } else {
  21367. huff = 0;
  21368. }
  21369. /* go to next symbol, update count, len */
  21370. sym++;
  21371. if (--count[len] === 0) {
  21372. if (len === max) { break; }
  21373. len = lens[lens_index + work[sym]];
  21374. }
  21375. /* create new sub-table if needed */
  21376. if (len > root && (huff & mask) !== low) {
  21377. /* if first time, transition to sub-tables */
  21378. if (drop === 0) {
  21379. drop = root;
  21380. }
  21381. /* increment past last table */
  21382. next += min; /* here min is 1 << curr */
  21383. /* determine length of next table */
  21384. curr = len - drop;
  21385. left = 1 << curr;
  21386. while (curr + drop < max) {
  21387. left -= count[curr + drop];
  21388. if (left <= 0) { break; }
  21389. curr++;
  21390. left <<= 1;
  21391. }
  21392. /* check for enough space */
  21393. used += 1 << curr;
  21394. if ((type === LENS && used > ENOUGH_LENS) ||
  21395. (type === DISTS && used > ENOUGH_DISTS)) {
  21396. return 1;
  21397. }
  21398. /* point entry in root table to sub-table */
  21399. low = huff & mask;
  21400. /*table.op[low] = curr;
  21401. table.bits[low] = root;
  21402. table.val[low] = next - opts.table_index;*/
  21403. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  21404. }
  21405. }
  21406. /* fill in remaining table entry if code is incomplete (guaranteed to have
  21407. at most one remaining entry, since if the code is incomplete, the
  21408. maximum code length that was allowed to get this far is one bit) */
  21409. if (huff !== 0) {
  21410. //table.op[next + huff] = 64; /* invalid code marker */
  21411. //table.bits[next + huff] = len - drop;
  21412. //table.val[next + huff] = 0;
  21413. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  21414. }
  21415. /* set return parameters */
  21416. //opts.table_index += used;
  21417. opts.bits = root;
  21418. return 0;
  21419. };
  21420. },{"../utils/common":66}],76:[function(require,module,exports){
  21421. 'use strict';
  21422. module.exports = {
  21423. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  21424. '1': 'stream end', /* Z_STREAM_END 1 */
  21425. '0': '', /* Z_OK 0 */
  21426. '-1': 'file error', /* Z_ERRNO (-1) */
  21427. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  21428. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  21429. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  21430. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  21431. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  21432. };
  21433. },{}],77:[function(require,module,exports){
  21434. 'use strict';
  21435. var utils = require('../utils/common');
  21436. /* Public constants ==========================================================*/
  21437. /* ===========================================================================*/
  21438. //var Z_FILTERED = 1;
  21439. //var Z_HUFFMAN_ONLY = 2;
  21440. //var Z_RLE = 3;
  21441. var Z_FIXED = 4;
  21442. //var Z_DEFAULT_STRATEGY = 0;
  21443. /* Possible values of the data_type field (though see inflate()) */
  21444. var Z_BINARY = 0;
  21445. var Z_TEXT = 1;
  21446. //var Z_ASCII = 1; // = Z_TEXT
  21447. var Z_UNKNOWN = 2;
  21448. /*============================================================================*/
  21449. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  21450. // From zutil.h
  21451. var STORED_BLOCK = 0;
  21452. var STATIC_TREES = 1;
  21453. var DYN_TREES = 2;
  21454. /* The three kinds of block type */
  21455. var MIN_MATCH = 3;
  21456. var MAX_MATCH = 258;
  21457. /* The minimum and maximum match lengths */
  21458. // From deflate.h
  21459. /* ===========================================================================
  21460. * Internal compression state.
  21461. */
  21462. var LENGTH_CODES = 29;
  21463. /* number of length codes, not counting the special END_BLOCK code */
  21464. var LITERALS = 256;
  21465. /* number of literal bytes 0..255 */
  21466. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  21467. /* number of Literal or Length codes, including the END_BLOCK code */
  21468. var D_CODES = 30;
  21469. /* number of distance codes */
  21470. var BL_CODES = 19;
  21471. /* number of codes used to transfer the bit lengths */
  21472. var HEAP_SIZE = 2*L_CODES + 1;
  21473. /* maximum heap size */
  21474. var MAX_BITS = 15;
  21475. /* All codes must not exceed MAX_BITS bits */
  21476. var Buf_size = 16;
  21477. /* size of bit buffer in bi_buf */
  21478. /* ===========================================================================
  21479. * Constants
  21480. */
  21481. var MAX_BL_BITS = 7;
  21482. /* Bit length codes must not exceed MAX_BL_BITS bits */
  21483. var END_BLOCK = 256;
  21484. /* end of block literal code */
  21485. var REP_3_6 = 16;
  21486. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  21487. var REPZ_3_10 = 17;
  21488. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  21489. var REPZ_11_138 = 18;
  21490. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  21491. var extra_lbits = /* extra bits for each length code */
  21492. [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];
  21493. var extra_dbits = /* extra bits for each distance code */
  21494. [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];
  21495. var extra_blbits = /* extra bits for each bit length code */
  21496. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  21497. var bl_order =
  21498. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  21499. /* The lengths of the bit length codes are sent in order of decreasing
  21500. * probability, to avoid transmitting the lengths for unused bit length codes.
  21501. */
  21502. /* ===========================================================================
  21503. * Local data. These are initialized only once.
  21504. */
  21505. // We pre-fill arrays with 0 to avoid uninitialized gaps
  21506. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  21507. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  21508. var static_ltree = new Array((L_CODES+2) * 2);
  21509. zero(static_ltree);
  21510. /* The static literal tree. Since the bit lengths are imposed, there is no
  21511. * need for the L_CODES extra codes used during heap construction. However
  21512. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  21513. * below).
  21514. */
  21515. var static_dtree = new Array(D_CODES * 2);
  21516. zero(static_dtree);
  21517. /* The static distance tree. (Actually a trivial tree since all codes use
  21518. * 5 bits.)
  21519. */
  21520. var _dist_code = new Array(DIST_CODE_LEN);
  21521. zero(_dist_code);
  21522. /* Distance codes. The first 256 values correspond to the distances
  21523. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  21524. * the 15 bit distances.
  21525. */
  21526. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  21527. zero(_length_code);
  21528. /* length code for each normalized match length (0 == MIN_MATCH) */
  21529. var base_length = new Array(LENGTH_CODES);
  21530. zero(base_length);
  21531. /* First normalized length for each code (0 = MIN_MATCH) */
  21532. var base_dist = new Array(D_CODES);
  21533. zero(base_dist);
  21534. /* First normalized distance for each code (0 = distance of 1) */
  21535. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  21536. this.static_tree = static_tree; /* static tree or NULL */
  21537. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  21538. this.extra_base = extra_base; /* base index for extra_bits */
  21539. this.elems = elems; /* max number of elements in the tree */
  21540. this.max_length = max_length; /* max bit length for the codes */
  21541. // show if `static_tree` has data or dummy - needed for monomorphic objects
  21542. this.has_stree = static_tree && static_tree.length;
  21543. };
  21544. var static_l_desc;
  21545. var static_d_desc;
  21546. var static_bl_desc;
  21547. var TreeDesc = function(dyn_tree, stat_desc) {
  21548. this.dyn_tree = dyn_tree; /* the dynamic tree */
  21549. this.max_code = 0; /* largest code with non zero frequency */
  21550. this.stat_desc = stat_desc; /* the corresponding static tree */
  21551. };
  21552. function d_code(dist) {
  21553. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  21554. }
  21555. /* ===========================================================================
  21556. * Output a short LSB first on the stream.
  21557. * IN assertion: there is enough room in pendingBuf.
  21558. */
  21559. function put_short (s, w) {
  21560. // put_byte(s, (uch)((w) & 0xff));
  21561. // put_byte(s, (uch)((ush)(w) >> 8));
  21562. s.pending_buf[s.pending++] = (w) & 0xff;
  21563. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  21564. }
  21565. /* ===========================================================================
  21566. * Send a value on a given number of bits.
  21567. * IN assertion: length <= 16 and value fits in length bits.
  21568. */
  21569. function send_bits(s, value, length) {
  21570. if (s.bi_valid > (Buf_size - length)) {
  21571. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  21572. put_short(s, s.bi_buf);
  21573. s.bi_buf = value >> (Buf_size - s.bi_valid);
  21574. s.bi_valid += length - Buf_size;
  21575. } else {
  21576. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  21577. s.bi_valid += length;
  21578. }
  21579. }
  21580. function send_code(s, c, tree) {
  21581. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  21582. }
  21583. /* ===========================================================================
  21584. * Reverse the first len bits of a code, using straightforward code (a faster
  21585. * method would use a table)
  21586. * IN assertion: 1 <= len <= 15
  21587. */
  21588. function bi_reverse(code, len) {
  21589. var res = 0;
  21590. do {
  21591. res |= code & 1;
  21592. code >>>= 1;
  21593. res <<= 1;
  21594. } while (--len > 0);
  21595. return res >>> 1;
  21596. }
  21597. /* ===========================================================================
  21598. * Flush the bit buffer, keeping at most 7 bits in it.
  21599. */
  21600. function bi_flush(s) {
  21601. if (s.bi_valid === 16) {
  21602. put_short(s, s.bi_buf);
  21603. s.bi_buf = 0;
  21604. s.bi_valid = 0;
  21605. } else if (s.bi_valid >= 8) {
  21606. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  21607. s.bi_buf >>= 8;
  21608. s.bi_valid -= 8;
  21609. }
  21610. }
  21611. /* ===========================================================================
  21612. * Compute the optimal bit lengths for a tree and update the total bit length
  21613. * for the current block.
  21614. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  21615. * above are the tree nodes sorted by increasing frequency.
  21616. * OUT assertions: the field len is set to the optimal bit length, the
  21617. * array bl_count contains the frequencies for each bit length.
  21618. * The length opt_len is updated; static_len is also updated if stree is
  21619. * not null.
  21620. */
  21621. function gen_bitlen(s, desc)
  21622. // deflate_state *s;
  21623. // tree_desc *desc; /* the tree descriptor */
  21624. {
  21625. var tree = desc.dyn_tree;
  21626. var max_code = desc.max_code;
  21627. var stree = desc.stat_desc.static_tree;
  21628. var has_stree = desc.stat_desc.has_stree;
  21629. var extra = desc.stat_desc.extra_bits;
  21630. var base = desc.stat_desc.extra_base;
  21631. var max_length = desc.stat_desc.max_length;
  21632. var h; /* heap index */
  21633. var n, m; /* iterate over the tree elements */
  21634. var bits; /* bit length */
  21635. var xbits; /* extra bits */
  21636. var f; /* frequency */
  21637. var overflow = 0; /* number of elements with bit length too large */
  21638. for (bits = 0; bits <= MAX_BITS; bits++) {
  21639. s.bl_count[bits] = 0;
  21640. }
  21641. /* In a first pass, compute the optimal bit lengths (which may
  21642. * overflow in the case of the bit length tree).
  21643. */
  21644. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  21645. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  21646. n = s.heap[h];
  21647. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  21648. if (bits > max_length) {
  21649. bits = max_length;
  21650. overflow++;
  21651. }
  21652. tree[n*2 + 1]/*.Len*/ = bits;
  21653. /* We overwrite tree[n].Dad which is no longer needed */
  21654. if (n > max_code) { continue; } /* not a leaf node */
  21655. s.bl_count[bits]++;
  21656. xbits = 0;
  21657. if (n >= base) {
  21658. xbits = extra[n-base];
  21659. }
  21660. f = tree[n * 2]/*.Freq*/;
  21661. s.opt_len += f * (bits + xbits);
  21662. if (has_stree) {
  21663. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  21664. }
  21665. }
  21666. if (overflow === 0) { return; }
  21667. // Trace((stderr,"\nbit length overflow\n"));
  21668. /* This happens for example on obj2 and pic of the Calgary corpus */
  21669. /* Find the first bit length which could increase: */
  21670. do {
  21671. bits = max_length-1;
  21672. while (s.bl_count[bits] === 0) { bits--; }
  21673. s.bl_count[bits]--; /* move one leaf down the tree */
  21674. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  21675. s.bl_count[max_length]--;
  21676. /* The brother of the overflow item also moves one step up,
  21677. * but this does not affect bl_count[max_length]
  21678. */
  21679. overflow -= 2;
  21680. } while (overflow > 0);
  21681. /* Now recompute all bit lengths, scanning in increasing frequency.
  21682. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  21683. * lengths instead of fixing only the wrong ones. This idea is taken
  21684. * from 'ar' written by Haruhiko Okumura.)
  21685. */
  21686. for (bits = max_length; bits !== 0; bits--) {
  21687. n = s.bl_count[bits];
  21688. while (n !== 0) {
  21689. m = s.heap[--h];
  21690. if (m > max_code) { continue; }
  21691. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  21692. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  21693. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  21694. tree[m*2 + 1]/*.Len*/ = bits;
  21695. }
  21696. n--;
  21697. }
  21698. }
  21699. }
  21700. /* ===========================================================================
  21701. * Generate the codes for a given tree and bit counts (which need not be
  21702. * optimal).
  21703. * IN assertion: the array bl_count contains the bit length statistics for
  21704. * the given tree and the field len is set for all tree elements.
  21705. * OUT assertion: the field code is set for all tree elements of non
  21706. * zero code length.
  21707. */
  21708. function gen_codes(tree, max_code, bl_count)
  21709. // ct_data *tree; /* the tree to decorate */
  21710. // int max_code; /* largest code with non zero frequency */
  21711. // ushf *bl_count; /* number of codes at each bit length */
  21712. {
  21713. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  21714. var code = 0; /* running code value */
  21715. var bits; /* bit index */
  21716. var n; /* code index */
  21717. /* The distribution counts are first used to generate the code values
  21718. * without bit reversal.
  21719. */
  21720. for (bits = 1; bits <= MAX_BITS; bits++) {
  21721. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  21722. }
  21723. /* Check that the bit counts in bl_count are consistent. The last code
  21724. * must be all ones.
  21725. */
  21726. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  21727. // "inconsistent bit counts");
  21728. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  21729. for (n = 0; n <= max_code; n++) {
  21730. var len = tree[n*2 + 1]/*.Len*/;
  21731. if (len === 0) { continue; }
  21732. /* Now reverse the bits */
  21733. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  21734. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  21735. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  21736. }
  21737. }
  21738. /* ===========================================================================
  21739. * Initialize the various 'constant' tables.
  21740. */
  21741. function tr_static_init() {
  21742. var n; /* iterates over tree elements */
  21743. var bits; /* bit counter */
  21744. var length; /* length value */
  21745. var code; /* code value */
  21746. var dist; /* distance index */
  21747. var bl_count = new Array(MAX_BITS+1);
  21748. /* number of codes at each bit length for an optimal tree */
  21749. // do check in _tr_init()
  21750. //if (static_init_done) return;
  21751. /* For some embedded targets, global variables are not initialized: */
  21752. /*#ifdef NO_INIT_GLOBAL_POINTERS
  21753. static_l_desc.static_tree = static_ltree;
  21754. static_l_desc.extra_bits = extra_lbits;
  21755. static_d_desc.static_tree = static_dtree;
  21756. static_d_desc.extra_bits = extra_dbits;
  21757. static_bl_desc.extra_bits = extra_blbits;
  21758. #endif*/
  21759. /* Initialize the mapping length (0..255) -> length code (0..28) */
  21760. length = 0;
  21761. for (code = 0; code < LENGTH_CODES-1; code++) {
  21762. base_length[code] = length;
  21763. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  21764. _length_code[length++] = code;
  21765. }
  21766. }
  21767. //Assert (length == 256, "tr_static_init: length != 256");
  21768. /* Note that the length 255 (match length 258) can be represented
  21769. * in two different ways: code 284 + 5 bits or code 285, so we
  21770. * overwrite length_code[255] to use the best encoding:
  21771. */
  21772. _length_code[length-1] = code;
  21773. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  21774. dist = 0;
  21775. for (code = 0 ; code < 16; code++) {
  21776. base_dist[code] = dist;
  21777. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  21778. _dist_code[dist++] = code;
  21779. }
  21780. }
  21781. //Assert (dist == 256, "tr_static_init: dist != 256");
  21782. dist >>= 7; /* from now on, all distances are divided by 128 */
  21783. for ( ; code < D_CODES; code++) {
  21784. base_dist[code] = dist << 7;
  21785. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  21786. _dist_code[256 + dist++] = code;
  21787. }
  21788. }
  21789. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  21790. /* Construct the codes of the static literal tree */
  21791. for (bits = 0; bits <= MAX_BITS; bits++) {
  21792. bl_count[bits] = 0;
  21793. }
  21794. n = 0;
  21795. while (n <= 143) {
  21796. static_ltree[n*2 + 1]/*.Len*/ = 8;
  21797. n++;
  21798. bl_count[8]++;
  21799. }
  21800. while (n <= 255) {
  21801. static_ltree[n*2 + 1]/*.Len*/ = 9;
  21802. n++;
  21803. bl_count[9]++;
  21804. }
  21805. while (n <= 279) {
  21806. static_ltree[n*2 + 1]/*.Len*/ = 7;
  21807. n++;
  21808. bl_count[7]++;
  21809. }
  21810. while (n <= 287) {
  21811. static_ltree[n*2 + 1]/*.Len*/ = 8;
  21812. n++;
  21813. bl_count[8]++;
  21814. }
  21815. /* Codes 286 and 287 do not exist, but we must include them in the
  21816. * tree construction to get a canonical Huffman tree (longest code
  21817. * all ones)
  21818. */
  21819. gen_codes(static_ltree, L_CODES+1, bl_count);
  21820. /* The static distance tree is trivial: */
  21821. for (n = 0; n < D_CODES; n++) {
  21822. static_dtree[n*2 + 1]/*.Len*/ = 5;
  21823. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  21824. }
  21825. // Now data ready and we can init static trees
  21826. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  21827. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  21828. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  21829. //static_init_done = true;
  21830. }
  21831. /* ===========================================================================
  21832. * Initialize a new block.
  21833. */
  21834. function init_block(s) {
  21835. var n; /* iterates over tree elements */
  21836. /* Initialize the trees. */
  21837. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  21838. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  21839. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  21840. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  21841. s.opt_len = s.static_len = 0;
  21842. s.last_lit = s.matches = 0;
  21843. }
  21844. /* ===========================================================================
  21845. * Flush the bit buffer and align the output on a byte boundary
  21846. */
  21847. function bi_windup(s)
  21848. {
  21849. if (s.bi_valid > 8) {
  21850. put_short(s, s.bi_buf);
  21851. } else if (s.bi_valid > 0) {
  21852. //put_byte(s, (Byte)s->bi_buf);
  21853. s.pending_buf[s.pending++] = s.bi_buf;
  21854. }
  21855. s.bi_buf = 0;
  21856. s.bi_valid = 0;
  21857. }
  21858. /* ===========================================================================
  21859. * Copy a stored block, storing first the length and its
  21860. * one's complement if requested.
  21861. */
  21862. function copy_block(s, buf, len, header)
  21863. //DeflateState *s;
  21864. //charf *buf; /* the input data */
  21865. //unsigned len; /* its length */
  21866. //int header; /* true if block header must be written */
  21867. {
  21868. bi_windup(s); /* align on byte boundary */
  21869. if (header) {
  21870. put_short(s, len);
  21871. put_short(s, ~len);
  21872. }
  21873. // while (len--) {
  21874. // put_byte(s, *buf++);
  21875. // }
  21876. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  21877. s.pending += len;
  21878. }
  21879. /* ===========================================================================
  21880. * Compares to subtrees, using the tree depth as tie breaker when
  21881. * the subtrees have equal frequency. This minimizes the worst case length.
  21882. */
  21883. function smaller(tree, n, m, depth) {
  21884. var _n2 = n*2;
  21885. var _m2 = m*2;
  21886. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  21887. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  21888. }
  21889. /* ===========================================================================
  21890. * Restore the heap property by moving down the tree starting at node k,
  21891. * exchanging a node with the smallest of its two sons if necessary, stopping
  21892. * when the heap property is re-established (each father smaller than its
  21893. * two sons).
  21894. */
  21895. function pqdownheap(s, tree, k)
  21896. // deflate_state *s;
  21897. // ct_data *tree; /* the tree to restore */
  21898. // int k; /* node to move down */
  21899. {
  21900. var v = s.heap[k];
  21901. var j = k << 1; /* left son of k */
  21902. while (j <= s.heap_len) {
  21903. /* Set j to the smallest of the two sons: */
  21904. if (j < s.heap_len &&
  21905. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  21906. j++;
  21907. }
  21908. /* Exit if v is smaller than both sons */
  21909. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  21910. /* Exchange v with the smallest son */
  21911. s.heap[k] = s.heap[j];
  21912. k = j;
  21913. /* And continue down the tree, setting j to the left son of k */
  21914. j <<= 1;
  21915. }
  21916. s.heap[k] = v;
  21917. }
  21918. // inlined manually
  21919. // var SMALLEST = 1;
  21920. /* ===========================================================================
  21921. * Send the block data compressed using the given Huffman trees
  21922. */
  21923. function compress_block(s, ltree, dtree)
  21924. // deflate_state *s;
  21925. // const ct_data *ltree; /* literal tree */
  21926. // const ct_data *dtree; /* distance tree */
  21927. {
  21928. var dist; /* distance of matched string */
  21929. var lc; /* match length or unmatched char (if dist == 0) */
  21930. var lx = 0; /* running index in l_buf */
  21931. var code; /* the code to send */
  21932. var extra; /* number of extra bits to send */
  21933. if (s.last_lit !== 0) {
  21934. do {
  21935. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  21936. lc = s.pending_buf[s.l_buf + lx];
  21937. lx++;
  21938. if (dist === 0) {
  21939. send_code(s, lc, ltree); /* send a literal byte */
  21940. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  21941. } else {
  21942. /* Here, lc is the match length - MIN_MATCH */
  21943. code = _length_code[lc];
  21944. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  21945. extra = extra_lbits[code];
  21946. if (extra !== 0) {
  21947. lc -= base_length[code];
  21948. send_bits(s, lc, extra); /* send the extra length bits */
  21949. }
  21950. dist--; /* dist is now the match distance - 1 */
  21951. code = d_code(dist);
  21952. //Assert (code < D_CODES, "bad d_code");
  21953. send_code(s, code, dtree); /* send the distance code */
  21954. extra = extra_dbits[code];
  21955. if (extra !== 0) {
  21956. dist -= base_dist[code];
  21957. send_bits(s, dist, extra); /* send the extra distance bits */
  21958. }
  21959. } /* literal or match pair ? */
  21960. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  21961. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  21962. // "pendingBuf overflow");
  21963. } while (lx < s.last_lit);
  21964. }
  21965. send_code(s, END_BLOCK, ltree);
  21966. }
  21967. /* ===========================================================================
  21968. * Construct one Huffman tree and assigns the code bit strings and lengths.
  21969. * Update the total bit length for the current block.
  21970. * IN assertion: the field freq is set for all tree elements.
  21971. * OUT assertions: the fields len and code are set to the optimal bit length
  21972. * and corresponding code. The length opt_len is updated; static_len is
  21973. * also updated if stree is not null. The field max_code is set.
  21974. */
  21975. function build_tree(s, desc)
  21976. // deflate_state *s;
  21977. // tree_desc *desc; /* the tree descriptor */
  21978. {
  21979. var tree = desc.dyn_tree;
  21980. var stree = desc.stat_desc.static_tree;
  21981. var has_stree = desc.stat_desc.has_stree;
  21982. var elems = desc.stat_desc.elems;
  21983. var n, m; /* iterate over heap elements */
  21984. var max_code = -1; /* largest code with non zero frequency */
  21985. var node; /* new node being created */
  21986. /* Construct the initial heap, with least frequent element in
  21987. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  21988. * heap[0] is not used.
  21989. */
  21990. s.heap_len = 0;
  21991. s.heap_max = HEAP_SIZE;
  21992. for (n = 0; n < elems; n++) {
  21993. if (tree[n * 2]/*.Freq*/ !== 0) {
  21994. s.heap[++s.heap_len] = max_code = n;
  21995. s.depth[n] = 0;
  21996. } else {
  21997. tree[n*2 + 1]/*.Len*/ = 0;
  21998. }
  21999. }
  22000. /* The pkzip format requires that at least one distance code exists,
  22001. * and that at least one bit should be sent even if there is only one
  22002. * possible code. So to avoid special checks later on we force at least
  22003. * two codes of non zero frequency.
  22004. */
  22005. while (s.heap_len < 2) {
  22006. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  22007. tree[node * 2]/*.Freq*/ = 1;
  22008. s.depth[node] = 0;
  22009. s.opt_len--;
  22010. if (has_stree) {
  22011. s.static_len -= stree[node*2 + 1]/*.Len*/;
  22012. }
  22013. /* node is 0 or 1 so it does not have extra bits */
  22014. }
  22015. desc.max_code = max_code;
  22016. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  22017. * establish sub-heaps of increasing lengths:
  22018. */
  22019. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  22020. /* Construct the Huffman tree by repeatedly combining the least two
  22021. * frequent nodes.
  22022. */
  22023. node = elems; /* next internal node of the tree */
  22024. do {
  22025. //pqremove(s, tree, n); /* n = node of least frequency */
  22026. /*** pqremove ***/
  22027. n = s.heap[1/*SMALLEST*/];
  22028. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  22029. pqdownheap(s, tree, 1/*SMALLEST*/);
  22030. /***/
  22031. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  22032. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  22033. s.heap[--s.heap_max] = m;
  22034. /* Create a new node father of n and m */
  22035. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  22036. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  22037. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  22038. /* and insert the new node in the heap */
  22039. s.heap[1/*SMALLEST*/] = node++;
  22040. pqdownheap(s, tree, 1/*SMALLEST*/);
  22041. } while (s.heap_len >= 2);
  22042. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  22043. /* At this point, the fields freq and dad are set. We can now
  22044. * generate the bit lengths.
  22045. */
  22046. gen_bitlen(s, desc);
  22047. /* The field len is now set, we can generate the bit codes */
  22048. gen_codes(tree, max_code, s.bl_count);
  22049. }
  22050. /* ===========================================================================
  22051. * Scan a literal or distance tree to determine the frequencies of the codes
  22052. * in the bit length tree.
  22053. */
  22054. function scan_tree(s, tree, max_code)
  22055. // deflate_state *s;
  22056. // ct_data *tree; /* the tree to be scanned */
  22057. // int max_code; /* and its largest code of non zero frequency */
  22058. {
  22059. var n; /* iterates over all tree elements */
  22060. var prevlen = -1; /* last emitted length */
  22061. var curlen; /* length of current code */
  22062. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  22063. var count = 0; /* repeat count of the current code */
  22064. var max_count = 7; /* max repeat count */
  22065. var min_count = 4; /* min repeat count */
  22066. if (nextlen === 0) {
  22067. max_count = 138;
  22068. min_count = 3;
  22069. }
  22070. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  22071. for (n = 0; n <= max_code; n++) {
  22072. curlen = nextlen;
  22073. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  22074. if (++count < max_count && curlen === nextlen) {
  22075. continue;
  22076. } else if (count < min_count) {
  22077. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  22078. } else if (curlen !== 0) {
  22079. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  22080. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  22081. } else if (count <= 10) {
  22082. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  22083. } else {
  22084. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  22085. }
  22086. count = 0;
  22087. prevlen = curlen;
  22088. if (nextlen === 0) {
  22089. max_count = 138;
  22090. min_count = 3;
  22091. } else if (curlen === nextlen) {
  22092. max_count = 6;
  22093. min_count = 3;
  22094. } else {
  22095. max_count = 7;
  22096. min_count = 4;
  22097. }
  22098. }
  22099. }
  22100. /* ===========================================================================
  22101. * Send a literal or distance tree in compressed form, using the codes in
  22102. * bl_tree.
  22103. */
  22104. function send_tree(s, tree, max_code)
  22105. // deflate_state *s;
  22106. // ct_data *tree; /* the tree to be scanned */
  22107. // int max_code; /* and its largest code of non zero frequency */
  22108. {
  22109. var n; /* iterates over all tree elements */
  22110. var prevlen = -1; /* last emitted length */
  22111. var curlen; /* length of current code */
  22112. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  22113. var count = 0; /* repeat count of the current code */
  22114. var max_count = 7; /* max repeat count */
  22115. var min_count = 4; /* min repeat count */
  22116. /* tree[max_code+1].Len = -1; */ /* guard already set */
  22117. if (nextlen === 0) {
  22118. max_count = 138;
  22119. min_count = 3;
  22120. }
  22121. for (n = 0; n <= max_code; n++) {
  22122. curlen = nextlen;
  22123. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  22124. if (++count < max_count && curlen === nextlen) {
  22125. continue;
  22126. } else if (count < min_count) {
  22127. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  22128. } else if (curlen !== 0) {
  22129. if (curlen !== prevlen) {
  22130. send_code(s, curlen, s.bl_tree);
  22131. count--;
  22132. }
  22133. //Assert(count >= 3 && count <= 6, " 3_6?");
  22134. send_code(s, REP_3_6, s.bl_tree);
  22135. send_bits(s, count-3, 2);
  22136. } else if (count <= 10) {
  22137. send_code(s, REPZ_3_10, s.bl_tree);
  22138. send_bits(s, count-3, 3);
  22139. } else {
  22140. send_code(s, REPZ_11_138, s.bl_tree);
  22141. send_bits(s, count-11, 7);
  22142. }
  22143. count = 0;
  22144. prevlen = curlen;
  22145. if (nextlen === 0) {
  22146. max_count = 138;
  22147. min_count = 3;
  22148. } else if (curlen === nextlen) {
  22149. max_count = 6;
  22150. min_count = 3;
  22151. } else {
  22152. max_count = 7;
  22153. min_count = 4;
  22154. }
  22155. }
  22156. }
  22157. /* ===========================================================================
  22158. * Construct the Huffman tree for the bit lengths and return the index in
  22159. * bl_order of the last bit length code to send.
  22160. */
  22161. function build_bl_tree(s) {
  22162. var max_blindex; /* index of last bit length code of non zero freq */
  22163. /* Determine the bit length frequencies for literal and distance trees */
  22164. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  22165. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  22166. /* Build the bit length tree: */
  22167. build_tree(s, s.bl_desc);
  22168. /* opt_len now includes the length of the tree representations, except
  22169. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  22170. */
  22171. /* Determine the number of bit length codes to send. The pkzip format
  22172. * requires that at least 4 bit length codes be sent. (appnote.txt says
  22173. * 3 but the actual value used is 4.)
  22174. */
  22175. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  22176. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  22177. break;
  22178. }
  22179. }
  22180. /* Update opt_len to include the bit length tree and counts */
  22181. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  22182. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  22183. // s->opt_len, s->static_len));
  22184. return max_blindex;
  22185. }
  22186. /* ===========================================================================
  22187. * Send the header for a block using dynamic Huffman trees: the counts, the
  22188. * lengths of the bit length codes, the literal tree and the distance tree.
  22189. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  22190. */
  22191. function send_all_trees(s, lcodes, dcodes, blcodes)
  22192. // deflate_state *s;
  22193. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  22194. {
  22195. var rank; /* index in bl_order */
  22196. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  22197. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  22198. // "too many codes");
  22199. //Tracev((stderr, "\nbl counts: "));
  22200. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  22201. send_bits(s, dcodes-1, 5);
  22202. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  22203. for (rank = 0; rank < blcodes; rank++) {
  22204. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  22205. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  22206. }
  22207. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  22208. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  22209. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  22210. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  22211. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  22212. }
  22213. /* ===========================================================================
  22214. * Check if the data type is TEXT or BINARY, using the following algorithm:
  22215. * - TEXT if the two conditions below are satisfied:
  22216. * a) There are no non-portable control characters belonging to the
  22217. * "black list" (0..6, 14..25, 28..31).
  22218. * b) There is at least one printable character belonging to the
  22219. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  22220. * - BINARY otherwise.
  22221. * - The following partially-portable control characters form a
  22222. * "gray list" that is ignored in this detection algorithm:
  22223. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  22224. * IN assertion: the fields Freq of dyn_ltree are set.
  22225. */
  22226. function detect_data_type(s) {
  22227. /* black_mask is the bit mask of black-listed bytes
  22228. * set bits 0..6, 14..25, and 28..31
  22229. * 0xf3ffc07f = binary 11110011111111111100000001111111
  22230. */
  22231. var black_mask = 0xf3ffc07f;
  22232. var n;
  22233. /* Check for non-textual ("black-listed") bytes. */
  22234. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  22235. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  22236. return Z_BINARY;
  22237. }
  22238. }
  22239. /* Check for textual ("white-listed") bytes. */
  22240. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  22241. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  22242. return Z_TEXT;
  22243. }
  22244. for (n = 32; n < LITERALS; n++) {
  22245. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  22246. return Z_TEXT;
  22247. }
  22248. }
  22249. /* There are no "black-listed" or "white-listed" bytes:
  22250. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  22251. */
  22252. return Z_BINARY;
  22253. }
  22254. var static_init_done = false;
  22255. /* ===========================================================================
  22256. * Initialize the tree data structures for a new zlib stream.
  22257. */
  22258. function _tr_init(s)
  22259. {
  22260. if (!static_init_done) {
  22261. tr_static_init();
  22262. static_init_done = true;
  22263. }
  22264. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  22265. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  22266. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  22267. s.bi_buf = 0;
  22268. s.bi_valid = 0;
  22269. /* Initialize the first block of the first file: */
  22270. init_block(s);
  22271. }
  22272. /* ===========================================================================
  22273. * Send a stored block
  22274. */
  22275. function _tr_stored_block(s, buf, stored_len, last)
  22276. //DeflateState *s;
  22277. //charf *buf; /* input block */
  22278. //ulg stored_len; /* length of input block */
  22279. //int last; /* one if this is the last block for a file */
  22280. {
  22281. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  22282. copy_block(s, buf, stored_len, true); /* with header */
  22283. }
  22284. /* ===========================================================================
  22285. * Send one empty static block to give enough lookahead for inflate.
  22286. * This takes 10 bits, of which 7 may remain in the bit buffer.
  22287. */
  22288. function _tr_align(s) {
  22289. send_bits(s, STATIC_TREES<<1, 3);
  22290. send_code(s, END_BLOCK, static_ltree);
  22291. bi_flush(s);
  22292. }
  22293. /* ===========================================================================
  22294. * Determine the best encoding for the current block: dynamic trees, static
  22295. * trees or store, and output the encoded block to the zip file.
  22296. */
  22297. function _tr_flush_block(s, buf, stored_len, last)
  22298. //DeflateState *s;
  22299. //charf *buf; /* input block, or NULL if too old */
  22300. //ulg stored_len; /* length of input block */
  22301. //int last; /* one if this is the last block for a file */
  22302. {
  22303. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  22304. var max_blindex = 0; /* index of last bit length code of non zero freq */
  22305. /* Build the Huffman trees unless a stored block is forced */
  22306. if (s.level > 0) {
  22307. /* Check if the file is binary or text */
  22308. if (s.strm.data_type === Z_UNKNOWN) {
  22309. s.strm.data_type = detect_data_type(s);
  22310. }
  22311. /* Construct the literal and distance trees */
  22312. build_tree(s, s.l_desc);
  22313. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  22314. // s->static_len));
  22315. build_tree(s, s.d_desc);
  22316. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  22317. // s->static_len));
  22318. /* At this point, opt_len and static_len are the total bit lengths of
  22319. * the compressed block data, excluding the tree representations.
  22320. */
  22321. /* Build the bit length tree for the above two trees, and get the index
  22322. * in bl_order of the last bit length code to send.
  22323. */
  22324. max_blindex = build_bl_tree(s);
  22325. /* Determine the best encoding. Compute the block lengths in bytes. */
  22326. opt_lenb = (s.opt_len+3+7) >>> 3;
  22327. static_lenb = (s.static_len+3+7) >>> 3;
  22328. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  22329. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  22330. // s->last_lit));
  22331. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  22332. } else {
  22333. // Assert(buf != (char*)0, "lost buf");
  22334. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  22335. }
  22336. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  22337. /* 4: two words for the lengths */
  22338. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  22339. * Otherwise we can't have processed more than WSIZE input bytes since
  22340. * the last block flush, because compression would have been
  22341. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  22342. * transform a block into a stored block.
  22343. */
  22344. _tr_stored_block(s, buf, stored_len, last);
  22345. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  22346. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  22347. compress_block(s, static_ltree, static_dtree);
  22348. } else {
  22349. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  22350. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  22351. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  22352. }
  22353. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  22354. /* The above check is made mod 2^32, for files larger than 512 MB
  22355. * and uLong implemented on 32 bits.
  22356. */
  22357. init_block(s);
  22358. if (last) {
  22359. bi_windup(s);
  22360. }
  22361. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  22362. // s->compressed_len-7*last));
  22363. }
  22364. /* ===========================================================================
  22365. * Save the match info and tally the frequency counts. Return true if
  22366. * the current block must be flushed.
  22367. */
  22368. function _tr_tally(s, dist, lc)
  22369. // deflate_state *s;
  22370. // unsigned dist; /* distance of matched string */
  22371. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  22372. {
  22373. //var out_length, in_length, dcode;
  22374. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  22375. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  22376. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  22377. s.last_lit++;
  22378. if (dist === 0) {
  22379. /* lc is the unmatched char */
  22380. s.dyn_ltree[lc*2]/*.Freq*/++;
  22381. } else {
  22382. s.matches++;
  22383. /* Here, lc is the match length - MIN_MATCH */
  22384. dist--; /* dist = match distance - 1 */
  22385. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  22386. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  22387. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  22388. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  22389. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  22390. }
  22391. // (!) This block is disabled in zlib defailts,
  22392. // don't enable it for binary compatibility
  22393. //#ifdef TRUNCATE_BLOCK
  22394. // /* Try to guess if it is profitable to stop the current block here */
  22395. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  22396. // /* Compute an upper bound for the compressed length */
  22397. // out_length = s.last_lit*8;
  22398. // in_length = s.strstart - s.block_start;
  22399. //
  22400. // for (dcode = 0; dcode < D_CODES; dcode++) {
  22401. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  22402. // }
  22403. // out_length >>>= 3;
  22404. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  22405. // // s->last_lit, in_length, out_length,
  22406. // // 100L - out_length*100L/in_length));
  22407. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  22408. // return true;
  22409. // }
  22410. // }
  22411. //#endif
  22412. return (s.last_lit === s.lit_bufsize-1);
  22413. /* We avoid equality with lit_bufsize because of wraparound at 64K
  22414. * on 16 bit machines and because stored blocks are restricted to
  22415. * 64K-1 bytes.
  22416. */
  22417. }
  22418. exports._tr_init = _tr_init;
  22419. exports._tr_stored_block = _tr_stored_block;
  22420. exports._tr_flush_block = _tr_flush_block;
  22421. exports._tr_tally = _tr_tally;
  22422. exports._tr_align = _tr_align;
  22423. },{"../utils/common":66}],78:[function(require,module,exports){
  22424. 'use strict';
  22425. function ZStream() {
  22426. /* next input byte */
  22427. this.input = null; // JS specific, because we have no pointers
  22428. this.next_in = 0;
  22429. /* number of bytes available at input */
  22430. this.avail_in = 0;
  22431. /* total number of input bytes read so far */
  22432. this.total_in = 0;
  22433. /* next output byte should be put there */
  22434. this.output = null; // JS specific, because we have no pointers
  22435. this.next_out = 0;
  22436. /* remaining free space at output */
  22437. this.avail_out = 0;
  22438. /* total number of bytes output so far */
  22439. this.total_out = 0;
  22440. /* last error message, NULL if no error */
  22441. this.msg = ''/*Z_NULL*/;
  22442. /* not visible by applications */
  22443. this.state = null;
  22444. /* best guess about the data type: binary or text */
  22445. this.data_type = 2/*Z_UNKNOWN*/;
  22446. /* adler32 value of the uncompressed data */
  22447. this.adler = 0;
  22448. }
  22449. module.exports = ZStream;
  22450. },{}],79:[function(require,module,exports){
  22451. module.exports = function arrayEquals(array) {
  22452. // if the other array is a falsy value, return
  22453. if (!array)
  22454. return false;
  22455. // compare lengths - can save a lot of time
  22456. if (this.length != array.length)
  22457. return false;
  22458. for (var i = 0, l = this.length; i < l; i++) {
  22459. // Check if we have nested arrays
  22460. if (this[i] instanceof Array && array[i] instanceof Array) {
  22461. // recurse into the nested arrays
  22462. if (!arrayEquals.apply(this[i], [array[i]]))
  22463. return false;
  22464. } else if (this[i] != array[i]) {
  22465. // Warning - two different object instances will never be equal:
  22466. // {x:20} != {x:20}
  22467. return false;
  22468. }
  22469. }
  22470. return true;
  22471. }
  22472. },{}],80:[function(require,module,exports){
  22473. exports.Interop = require('./interop');
  22474. },{"./interop":81}],81:[function(require,module,exports){
  22475. var transform = require('./transform');
  22476. var arrayEquals = require('./array-equals');
  22477. function Interop() { }
  22478. module.exports = Interop;
  22479. /**
  22480. * This map holds the most recent Plan A offer/answer SDP that was converted
  22481. * to Plan B, with the SDP type ('offer' or 'answer') as keys and the SDP
  22482. * string as values.
  22483. *
  22484. * @type {{}}
  22485. */
  22486. var cache = {};
  22487. /**
  22488. * This method transforms a Plan A SDP to an equivalent Plan B SDP. A
  22489. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  22490. * application.
  22491. *
  22492. * @param desc
  22493. * @returns {*}
  22494. */
  22495. Interop.prototype.toPlanB = function(desc) {
  22496. //#region Preliminary input validation.
  22497. if (typeof desc !== 'object' || desc === null ||
  22498. typeof desc.sdp !== 'string') {
  22499. console.warn('An empty description was passed as an argument.');
  22500. return desc;
  22501. }
  22502. // Objectify the SDP for easier manipulation.
  22503. var session = transform.parse(desc.sdp);
  22504. // If the SDP contains no media, there's nothing to transform.
  22505. if (typeof session.media === 'undefined' ||
  22506. !Array.isArray(session.media) || session.media.length === 0) {
  22507. console.warn('The description has no media.');
  22508. return desc;
  22509. }
  22510. // Try some heuristics to "make sure" this is a Plan A SDP. Plan B SDP has
  22511. // a video, an audio and a data "channel" at most.
  22512. if (session.media.length <= 3 && session.media.every(function(m) {
  22513. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  22514. })) {
  22515. console.warn('This description does not look like Plan A.');
  22516. return desc;
  22517. }
  22518. //#endregion
  22519. // Plan A SDP is our "precious". Cache it for later use in the Plan B ->
  22520. // Plan A transformation.
  22521. cache[desc.type] = desc.sdp;
  22522. //#region Convert from Plan A to Plan B.
  22523. // We rebuild the session.media array.
  22524. var media = session.media;
  22525. session.media = [];
  22526. // Associative array that maps channel types to channel objects for fast
  22527. // access to channel objects by their type, e.g. channels['audio']->channel
  22528. // obj.
  22529. var channels = {};
  22530. // Used to build the group:BUNDLE value after the channels construction
  22531. // loop.
  22532. var types = [];
  22533. // Implode the Plan A m-lines/tracks into Plan B "channels".
  22534. media.forEach(function(mLine) {
  22535. // rtcp-mux is required in the Plan B SDP.
  22536. if (typeof mLine.rtcpMux !== 'string' ||
  22537. mLine.rtcpMux !== 'rtcp-mux') {
  22538. throw new Error('Cannot convert to Plan B because m-lines ' +
  22539. 'without the rtcp-mux attribute were found.');
  22540. }
  22541. // If we don't have a channel for this mLine.type, then use this mLine
  22542. // as the channel basis.
  22543. if (typeof channels[mLine.type] === 'undefined') {
  22544. channels[mLine.type] = mLine;
  22545. }
  22546. // Add sources to the channel and handle a=msid.
  22547. if (typeof mLine.sources === 'object') {
  22548. Object.keys(mLine.sources).forEach(function(ssrc) {
  22549. // Assign the sources to the channel.
  22550. channels[mLine.type].sources[ssrc] = mLine.sources[ssrc];
  22551. // In Plan B the msid is an SSRC attribute. Also, we don't care
  22552. // about the obsolete label and mslabel attributes.
  22553. channels[mLine.type].sources[ssrc].msid = mLine.msid;
  22554. // NOTE ssrcs in ssrc groups will share msids, as
  22555. // draft-uberti-rtcweb-plan-00 mandates.
  22556. });
  22557. }
  22558. // Add ssrc groups to the channel.
  22559. if (typeof mLine.ssrcGroups !== 'undefined' &&
  22560. Array.isArray(mLine.ssrcGroups)) {
  22561. // Create the ssrcGroups array, if it's not defined.
  22562. if (typeof channel.ssrcGroups === 'undefined' ||
  22563. !Array.isArray(channel.ssrcGroups)) {
  22564. channel.ssrcGroups = [];
  22565. }
  22566. channel.ssrcGroups = channel.ssrcGroups.concat(mLine.ssrcGroups);
  22567. }
  22568. if (channels[mLine.type] === mLine) {
  22569. // Copy ICE related stuff from the principal media line.
  22570. mLine.candidates = media[0].candidates;
  22571. mLine.iceUfrag = media[0].iceUfrag;
  22572. mLine.icePwd = media[0].icePwd;
  22573. mLine.fingerprint = media[0].fingerprint;
  22574. // Plan B mids are in ['audio', 'video', 'data']
  22575. mLine.mid = mLine.type;
  22576. // Plan B doesn't support/need the bundle-only attribute.
  22577. delete mLine.bundleOnly;
  22578. // In Plan B the msid is an SSRC attribute.
  22579. delete mLine.msid;
  22580. // Used to build the group:BUNDLE value after this loop.
  22581. types.push(mLine.type);
  22582. // Add the channel to the new media array.
  22583. session.media.push(mLine);
  22584. }
  22585. });
  22586. // We regenerate the BUNDLE group with the new mids.
  22587. session.groups.every(function(group) {
  22588. if (group.type === 'BUNDLE') {
  22589. group.mids = types.join(' ');
  22590. return false;
  22591. } else {
  22592. return true;
  22593. }
  22594. });
  22595. // msid semantic
  22596. session.msidSemantic = {
  22597. semantic: 'WMS',
  22598. token: '*'
  22599. };
  22600. var resStr = transform.write(session);
  22601. return new RTCSessionDescription({
  22602. type: desc.type,
  22603. sdp: resStr
  22604. });
  22605. //#endregion
  22606. };
  22607. /**
  22608. * This method transforms a Plan B SDP to an equivalent Plan A SDP. A
  22609. * PeerConnection wrapper transforms the SDP to Plan A before passing it to FF.
  22610. *
  22611. * @param desc
  22612. * @returns {*}
  22613. */
  22614. Interop.prototype.toPlanA = function(desc) {
  22615. //#region Preliminary input validation.
  22616. if (typeof desc !== 'object' || desc === null ||
  22617. typeof desc.sdp !== 'string') {
  22618. console.warn('An empty description was passed as an argument.');
  22619. return desc;
  22620. }
  22621. var session = transform.parse(desc.sdp);
  22622. // If the SDP contains no media, there's nothing to transform.
  22623. if (typeof session.media === 'undefined' ||
  22624. !Array.isArray(session.media) || session.media.length === 0) {
  22625. console.warn('The description has no media.');
  22626. return desc;
  22627. }
  22628. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  22629. // a video, an audio and a data "channel" at most.
  22630. if (session.media.length > 3 || !session.media.every(function(m) {
  22631. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  22632. })) {
  22633. console.warn('This description does not look like Plan B.');
  22634. return desc;
  22635. }
  22636. // Make sure this Plan B SDP can be converted to a Plan A SDP.
  22637. var mids = [];
  22638. session.media.forEach(function(m) {
  22639. mids.push(m.mid);
  22640. });
  22641. var hasBundle = false;
  22642. if (typeof session.groups !== 'undefined' &&
  22643. Array.isArray(session.groups)) {
  22644. hasBundle = session.groups.every(function(g) {
  22645. return g.type !== 'BUNDLE' ||
  22646. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  22647. });
  22648. }
  22649. if (!hasBundle) {
  22650. throw new Error("Cannot convert to Plan A because m-lines that are " +
  22651. "not bundled were found.");
  22652. }
  22653. //#endregion
  22654. //#region Convert from Plan B to Plan A.
  22655. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  22656. // rebuild an equivalent Plan A offer/answer.
  22657. //
  22658. // For example, if this is a local answer (in Plan A style) that we convert
  22659. // to Plan B prior to handing it over to the application (the
  22660. // PeerConnection wrapper called us, for instance, after a successful
  22661. // createAnswer), we want to remember the m-line at which we've seen the
  22662. // (local) SSRC. That's because when the application wants to do call the
  22663. // SLD method, forcing us to do the inverse transformation (from Plan B to
  22664. // Plan A), we need to know to which m-line to assign the (local) SSRC. We
  22665. // also need to know all the other m-lines that the original answer had and
  22666. // include them in the transformed answer as well.
  22667. //
  22668. // Another example is if this is a remote offer that we convert to Plan B
  22669. // prior to giving it to the application, we want to remember the mid at
  22670. // which we've seen the (remote) SSRC.
  22671. //
  22672. // In the iteration that follows, we use the cached Plan A (if it exists)
  22673. // to assign mids to ssrcs.
  22674. var cached;
  22675. if (typeof cache[desc.type] !== 'undefined') {
  22676. cached = transform.parse(cache[desc.type]);
  22677. }
  22678. // A helper map that sends mids to m-line objects. We use it later to
  22679. // rebuild the Plan A style session.media array.
  22680. var media = {};
  22681. session.media.forEach(function(channel) {
  22682. if (typeof channel.rtcpMux !== 'string' ||
  22683. channel.rtcpMux !== 'rtcp-mux') {
  22684. throw new Error("Cannot convert to Plan A because m-lines " +
  22685. "without the rtcp-mux attribute were found.");
  22686. }
  22687. // With rtcp-mux and bundle all the channels should have the same ICE
  22688. // stuff.
  22689. var sources = channel.sources;
  22690. var ssrcGroups = channel.ssrcGroups;
  22691. var candidates = channel.candidates;
  22692. var iceUfrag = channel.iceUfrag;
  22693. var icePwd = channel.icePwd;
  22694. var fingerprint = channel.fingerprint;
  22695. var port = channel.port;
  22696. // We'll use the "channel" object as a prototype for each new "mLine"
  22697. // that we create, but first we need to clean it up a bit.
  22698. delete channel.sources;
  22699. delete channel.ssrcGroups;
  22700. delete channel.candidates;
  22701. delete channel.iceUfrag;
  22702. delete channel.icePwd;
  22703. delete channel.fingerprint;
  22704. delete channel.port;
  22705. delete channel.mid;
  22706. // inverted ssrc group map
  22707. var invertedGroups = {};
  22708. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  22709. ssrcGroups.forEach(function (ssrcGroup) {
  22710. // TODO(gp) find out how to receive simulcast with FF. For the
  22711. // time being, hide it.
  22712. if (ssrcGroup.semantics === 'SIM') {
  22713. return;
  22714. }
  22715. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  22716. Array.isArray(ssrcGroup.ssrcs)) {
  22717. ssrcGroup.ssrcs.forEach(function (ssrc) {
  22718. if (typeof invertedGroups[ssrc] === 'undefined') {
  22719. invertedGroups[ssrc] = [];
  22720. }
  22721. invertedGroups[ssrc].push(ssrcGroup);
  22722. });
  22723. }
  22724. });
  22725. }
  22726. // ssrc to m-line index.
  22727. var mLines = {};
  22728. if (typeof sources === 'object') {
  22729. // Explode the Plan B channel sources with one m-line per source.
  22730. Object.keys(sources).forEach(function(ssrc) {
  22731. var mLine;
  22732. if (typeof invertedGroups[ssrc] !== 'undefined' &&
  22733. Array.isArray(invertedGroups[ssrc])) {
  22734. invertedGroups[ssrc].every(function (ssrcGroup) {
  22735. // ssrcGroup.ssrcs *is* an Array, no need to check
  22736. // again here.
  22737. return ssrcGroup.ssrcs.every(function (related) {
  22738. if (typeof mLines[related] === 'object') {
  22739. mLine = mLines[related];
  22740. return false;
  22741. } else {
  22742. return true;
  22743. }
  22744. });
  22745. });
  22746. }
  22747. if (typeof mLine === 'object') {
  22748. // the m-line already exists. Just add the source.
  22749. mLine.sources[ssrc] = sources[ssrc];
  22750. delete sources[ssrc].msid;
  22751. } else {
  22752. // Use the "channel" as a prototype for the "mLine".
  22753. mLine = Object.create(channel);
  22754. mLines[ssrc] = mLine;
  22755. // Assign the msid of the source to the m-line.
  22756. mLine.msid = sources[ssrc].msid;
  22757. delete sources[ssrc].msid;
  22758. // We assign one SSRC per media line.
  22759. mLine.sources = {};
  22760. mLine.sources[ssrc] = sources[ssrc];
  22761. mLine.ssrcGroups = invertedGroups[ssrc];
  22762. // Use the cached Plan A SDP (if it exists) to assign SSRCs to
  22763. // mids.
  22764. if (typeof cached !== 'undefined' &&
  22765. typeof cached.media !== 'undefined' &&
  22766. Array.isArray(cached.media)) {
  22767. cached.media.forEach(function(m) {
  22768. if (typeof m.sources === 'object') {
  22769. Object.keys(m.sources).forEach(function(s) {
  22770. if (s === ssrc) {
  22771. mLine.mid = m.mid;
  22772. }
  22773. });
  22774. }
  22775. });
  22776. }
  22777. if (typeof mLine.mid === 'undefined') {
  22778. // If this is an SSRC that we see for the first time assign
  22779. // it a new mid. This is typically the case when this
  22780. // method is called to transform a remote description for
  22781. // the first time or when there is a new SSRC in the remote
  22782. // description because a new peer has joined the
  22783. // conference. Local SSRCs should have already been added
  22784. // to the map in the toPlanB method.
  22785. //
  22786. // Because FF generates answers in Plan A style, we MUST
  22787. // already have a cached answer with all the local SSRCs
  22788. // mapped to some mLine/mid.
  22789. if (desc.type === 'answer') {
  22790. throw new Error("An unmapped SSRC was found.");
  22791. }
  22792. mLine.mid = [channel.type, '-', ssrc].join('');
  22793. }
  22794. // Include the candidates in the 1st media line.
  22795. mLine.candidates = candidates;
  22796. mLine.iceUfrag = iceUfrag;
  22797. mLine.icePwd = icePwd;
  22798. mLine.fingerprint = fingerprint;
  22799. mLine.port = port;
  22800. media[mLine.mid] = mLine;
  22801. }
  22802. });
  22803. }
  22804. });
  22805. // Rebuild the media array in the right order and add the missing mLines
  22806. // (missing from the Plan B SDP).
  22807. session.media = [];
  22808. mids = []; // reuse
  22809. if (desc.type === 'answer') {
  22810. // The media lines in the answer must match the media lines in the
  22811. // offer. The order is important too. Here we use the cached offer to
  22812. // find the m-lines that are missing (from the converted answer), and
  22813. // use the cached answer to complete the converted answer.
  22814. if (typeof cache['offer'] === 'undefined') {
  22815. throw new Error("An answer is being processed but we couldn't " +
  22816. "find a cached offer.");
  22817. }
  22818. var cachedOffer = transform.parse(cache['offer']);
  22819. if (typeof cachedOffer === 'undefined' ||
  22820. typeof cachedOffer.media === 'undefined' ||
  22821. !Array.isArray(cachedOffer.media)) {
  22822. // FIXME(gp) is this really a problem in the general case?
  22823. throw new Error("The cached offer has no media.");
  22824. }
  22825. cachedOffer.media.forEach(function(mo) {
  22826. var mLine;
  22827. if (typeof media[mo.mid] === 'undefined') {
  22828. // This is probably an m-line containing a remote track only.
  22829. // It MUST exist in the cached answer as a remote track only
  22830. // mLine.
  22831. cached.media.every(function(ma) {
  22832. if (mo.mid == ma.mid) {
  22833. mLine = ma;
  22834. return false;
  22835. } else {
  22836. return true;
  22837. }
  22838. });
  22839. } else {
  22840. mLine = media[mo.mid];
  22841. }
  22842. if (typeof mLine === 'undefined') {
  22843. throw new Error("The cached offer contains an m-line that " +
  22844. "doesn't exist neither in the cached answer nor in " +
  22845. "the converted answer.");
  22846. }
  22847. session.media.push(mLine);
  22848. mids.push(mLine.mid);
  22849. });
  22850. } else {
  22851. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  22852. // under any circumstances. If we are no longer interested in sending a
  22853. // track, we just remove the msid and ssrc attributes and set it to
  22854. // either a=recvonly (as the reofferer, we must use recvonly if the
  22855. // other side was previously sending on the m-section, but we can also
  22856. // leave the possibility open if it wasn't previously in use), or
  22857. // a=inacive.
  22858. if (typeof cached !== 'undefined' &&
  22859. typeof cached.media !== 'undefined' &&
  22860. Array.isArray(cached.media)) {
  22861. cached.media.forEach(function(pm) {
  22862. mids.push(pm.mid);
  22863. if (typeof media[pm.mid] !== 'undefined') {
  22864. session.media.push(media[pm.mid]);
  22865. } else {
  22866. delete pm.msid;
  22867. delete pm.sources;
  22868. delete pm.ssrcGroups;
  22869. pm.direction = 'recvonly';
  22870. session.media.push(pm);
  22871. }
  22872. });
  22873. }
  22874. // Add all the remaining (new) m-lines of the transformed SDP.
  22875. Object.keys(media).forEach(function(mid) {
  22876. if (mids.indexOf(mid) === -1) {
  22877. mids.push(mid);
  22878. session.media.push(media[mid]);
  22879. }
  22880. });
  22881. }
  22882. // We regenerate the BUNDLE group (since we regenerated the mids)
  22883. session.groups.every(function(group) {
  22884. if (group.type === 'BUNDLE') {
  22885. group.mids = mids.join(' ');
  22886. return false;
  22887. } else {
  22888. return true;
  22889. }
  22890. });
  22891. // msid semantic
  22892. session.msidSemantic = {
  22893. semantic: 'WMS',
  22894. token: '*'
  22895. };
  22896. var resStr = transform.write(session);
  22897. // Cache the transformed SDP (Plan A) for later re-use in this function.
  22898. cache[desc.type] = resStr;
  22899. return new RTCSessionDescription({
  22900. type: desc.type,
  22901. sdp: resStr
  22902. });
  22903. //#endregion
  22904. };
  22905. },{"./array-equals":79,"./transform":82}],82:[function(require,module,exports){
  22906. var transform = require('sdp-transform');
  22907. exports.write = function(session, opts) {
  22908. if (typeof session !== 'undefined' &&
  22909. typeof session.media !== 'undefined' &&
  22910. Array.isArray(session.media)) {
  22911. session.media.forEach(function (mLine) {
  22912. // expand sources to ssrcs
  22913. if (typeof mLine.sources !== 'undefined' &&
  22914. Object.keys(mLine.sources).length !== 0) {
  22915. mLine.ssrcs = [];
  22916. Object.keys(mLine.sources).forEach(function (ssrc) {
  22917. var source = mLine.sources[ssrc];
  22918. Object.keys(source).forEach(function (attribute) {
  22919. mLine.ssrcs.push({
  22920. id: ssrc,
  22921. attribute: attribute,
  22922. value: source[attribute]
  22923. });
  22924. });
  22925. });
  22926. delete mLine.sources;
  22927. }
  22928. // join ssrcs in ssrc groups
  22929. if (typeof mLine.ssrcGroups !== 'undefined' &&
  22930. Array.isArray(mLine.ssrcGroups)) {
  22931. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  22932. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  22933. Array.isArray(ssrcGroup.ssrcs)) {
  22934. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  22935. }
  22936. });
  22937. }
  22938. });
  22939. }
  22940. // join group mids
  22941. if (typeof session !== 'undefined' &&
  22942. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  22943. session.groups.forEach(function (g) {
  22944. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  22945. g.mids = g.mids.join(' ');
  22946. }
  22947. });
  22948. }
  22949. return transform.write(session, opts);
  22950. };
  22951. exports.parse = function(sdp) {
  22952. var session = transform.parse(sdp);
  22953. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  22954. Array.isArray(session.media)) {
  22955. session.media.forEach(function (mLine) {
  22956. // group sources attributes by ssrc
  22957. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  22958. mLine.sources = {};
  22959. mLine.ssrcs.forEach(function (ssrc) {
  22960. if (!mLine.sources[ssrc.id])
  22961. mLine.sources[ssrc.id] = {};
  22962. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  22963. });
  22964. delete mLine.ssrcs;
  22965. }
  22966. // split ssrcs in ssrc groups
  22967. if (typeof mLine.ssrcGroups !== 'undefined' &&
  22968. Array.isArray(mLine.ssrcGroups)) {
  22969. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  22970. if (typeof ssrcGroup.ssrcs === 'string') {
  22971. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  22972. }
  22973. });
  22974. }
  22975. });
  22976. }
  22977. // split group mids
  22978. if (typeof session !== 'undefined' &&
  22979. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  22980. session.groups.forEach(function (g) {
  22981. if (typeof g.mids === 'string') {
  22982. g.mids = g.mids.split(' ');
  22983. }
  22984. });
  22985. }
  22986. return session;
  22987. };
  22988. },{"sdp-transform":84}],83:[function(require,module,exports){
  22989. var grammar = module.exports = {
  22990. v: [{
  22991. name: 'version',
  22992. reg: /^(\d*)$/
  22993. }],
  22994. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  22995. // NB: sessionId will be a String in most cases because it is huge
  22996. name: 'origin',
  22997. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  22998. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  22999. format: "%s %s %d %s IP%d %s"
  23000. }],
  23001. // default parsing of these only (though some of these feel outdated)
  23002. s: [{ name: 'name' }],
  23003. i: [{ name: 'description' }],
  23004. u: [{ name: 'uri' }],
  23005. e: [{ name: 'email' }],
  23006. p: [{ name: 'phone' }],
  23007. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  23008. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  23009. //k: [{}], // outdated thing ignored
  23010. t: [{ //t=0 0
  23011. name: 'timing',
  23012. reg: /^(\d*) (\d*)/,
  23013. names: ['start', 'stop'],
  23014. format: "%d %d"
  23015. }],
  23016. c: [{ //c=IN IP4 10.47.197.26
  23017. name: 'connection',
  23018. reg: /^IN IP(\d) (\S*)/,
  23019. names: ['version', 'ip'],
  23020. format: "IN IP%d %s"
  23021. }],
  23022. b: [{ //b=AS:4000
  23023. push: 'bandwidth',
  23024. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  23025. names: ['type', 'limit'],
  23026. format: "%s:%s"
  23027. }],
  23028. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  23029. // NB: special - pushes to session
  23030. // TODO: rtp/fmtp should be filtered by the payloads found here?
  23031. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  23032. names: ['type', 'port', 'protocol', 'payloads'],
  23033. format: "%s %d %s %s"
  23034. }],
  23035. a: [
  23036. { //a=rtpmap:110 opus/48000/2
  23037. push: 'rtp',
  23038. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  23039. names: ['payload', 'codec', 'rate', 'encoding'],
  23040. format: function (o) {
  23041. return (o.encoding) ?
  23042. "rtpmap:%d %s/%s/%s":
  23043. "rtpmap:%d %s/%s";
  23044. }
  23045. },
  23046. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  23047. push: 'fmtp',
  23048. reg: /^fmtp:(\d*) (\S*)/,
  23049. names: ['payload', 'config'],
  23050. format: "fmtp:%d %s"
  23051. },
  23052. { //a=control:streamid=0
  23053. name: 'control',
  23054. reg: /^control:(.*)/,
  23055. format: "control:%s"
  23056. },
  23057. { //a=rtcp:65179 IN IP4 193.84.77.194
  23058. name: 'rtcp',
  23059. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  23060. names: ['port', 'netType', 'ipVer', 'address'],
  23061. format: function (o) {
  23062. return (o.address != null) ?
  23063. "rtcp:%d %s IP%d %s":
  23064. "rtcp:%d";
  23065. }
  23066. },
  23067. { //a=rtcp-fb:98 trr-int 100
  23068. push: 'rtcpFbTrrInt',
  23069. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  23070. names: ['payload', 'value'],
  23071. format: "rtcp-fb:%d trr-int %d"
  23072. },
  23073. { //a=rtcp-fb:98 nack rpsi
  23074. push: 'rtcpFb',
  23075. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  23076. names: ['payload', 'type', 'subtype'],
  23077. format: function (o) {
  23078. return (o.subtype != null) ?
  23079. "rtcp-fb:%s %s %s":
  23080. "rtcp-fb:%s %s";
  23081. }
  23082. },
  23083. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  23084. //a=extmap:1/recvonly URI-gps-string
  23085. push: 'ext',
  23086. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  23087. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  23088. format: function (o) {
  23089. return (o.config != null) ?
  23090. "extmap:%s %s %s":
  23091. "extmap:%s %s";
  23092. }
  23093. },
  23094. {
  23095. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  23096. push: 'crypto',
  23097. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  23098. names: ['id', 'suite', 'config', 'sessionConfig'],
  23099. format: function (o) {
  23100. return (o.sessionConfig != null) ?
  23101. "crypto:%d %s %s %s":
  23102. "crypto:%d %s %s";
  23103. }
  23104. },
  23105. { //a=setup:actpass
  23106. name: 'setup',
  23107. reg: /^setup:(\w*)/,
  23108. format: "setup:%s"
  23109. },
  23110. { //a=mid:1
  23111. name: 'mid',
  23112. reg: /^mid:([^\s]*)/,
  23113. format: "mid:%s"
  23114. },
  23115. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  23116. name: 'msid',
  23117. reg: /^msid:(.*)/,
  23118. format: "msid:%s"
  23119. },
  23120. { //a=ptime:20
  23121. name: 'ptime',
  23122. reg: /^ptime:(\d*)/,
  23123. format: "ptime:%d"
  23124. },
  23125. { //a=maxptime:60
  23126. name: 'maxptime',
  23127. reg: /^maxptime:(\d*)/,
  23128. format: "maxptime:%d"
  23129. },
  23130. { //a=sendrecv
  23131. name: 'direction',
  23132. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  23133. },
  23134. { //a=ice-lite
  23135. name: 'icelite',
  23136. reg: /^(ice-lite)/
  23137. },
  23138. { //a=ice-ufrag:F7gI
  23139. name: 'iceUfrag',
  23140. reg: /^ice-ufrag:(\S*)/,
  23141. format: "ice-ufrag:%s"
  23142. },
  23143. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  23144. name: 'icePwd',
  23145. reg: /^ice-pwd:(\S*)/,
  23146. format: "ice-pwd:%s"
  23147. },
  23148. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  23149. name: 'fingerprint',
  23150. reg: /^fingerprint:(\S*) (\S*)/,
  23151. names: ['type', 'hash'],
  23152. format: "fingerprint:%s %s"
  23153. },
  23154. {
  23155. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  23156. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  23157. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  23158. push:'candidates',
  23159. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  23160. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  23161. format: function (o) {
  23162. var str = "candidate:%s %d %s %d %s %d typ %s";
  23163. // NB: candidate has two optional chunks, so %void middle one if it's missing
  23164. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  23165. if (o.generation != null) {
  23166. str += " generation %d";
  23167. }
  23168. return str;
  23169. }
  23170. },
  23171. { //a=end-of-candidates (keep after the candidates line for readability)
  23172. name: 'endOfCandidates',
  23173. reg: /^(end-of-candidates)/
  23174. },
  23175. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  23176. name: 'remoteCandidates',
  23177. reg: /^remote-candidates:(.*)/,
  23178. format: "remote-candidates:%s"
  23179. },
  23180. { //a=ice-options:google-ice
  23181. name: 'iceOptions',
  23182. reg: /^ice-options:(\S*)/,
  23183. format: "ice-options:%s"
  23184. },
  23185. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  23186. push: "ssrcs",
  23187. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  23188. names: ['id', 'attribute', 'value'],
  23189. format: "ssrc:%d %s:%s"
  23190. },
  23191. { //a=ssrc-group:FEC 1 2
  23192. push: "ssrcGroups",
  23193. reg: /^ssrc-group:(\w*) (.*)/,
  23194. names: ['semantics', 'ssrcs'],
  23195. format: "ssrc-group:%s %s"
  23196. },
  23197. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  23198. name: "msidSemantic",
  23199. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  23200. names: ['semantic', 'token'],
  23201. format: "msid-semantic: %s %s" // space after ":" is not accidental
  23202. },
  23203. { //a=group:BUNDLE audio video
  23204. push: 'groups',
  23205. reg: /^group:(\w*) (.*)/,
  23206. names: ['type', 'mids'],
  23207. format: "group:%s %s"
  23208. },
  23209. { //a=rtcp-mux
  23210. name: 'rtcpMux',
  23211. reg: /^(rtcp-mux)/
  23212. },
  23213. { // any a= that we don't understand is kepts verbatim on media.invalid
  23214. push: 'invalid',
  23215. names: ["value"]
  23216. }
  23217. ]
  23218. };
  23219. // set sensible defaults to avoid polluting the grammar with boring details
  23220. Object.keys(grammar).forEach(function (key) {
  23221. var objs = grammar[key];
  23222. objs.forEach(function (obj) {
  23223. if (!obj.reg) {
  23224. obj.reg = /(.*)/;
  23225. }
  23226. if (!obj.format) {
  23227. obj.format = "%s";
  23228. }
  23229. });
  23230. });
  23231. },{}],84:[function(require,module,exports){
  23232. var parser = require('./parser');
  23233. var writer = require('./writer');
  23234. exports.write = writer;
  23235. exports.parse = parser.parse;
  23236. exports.parseFmtpConfig = parser.parseFmtpConfig;
  23237. exports.parsePayloads = parser.parsePayloads;
  23238. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  23239. },{"./parser":85,"./writer":86}],85:[function(require,module,exports){
  23240. var toIntIfInt = function (v) {
  23241. return String(Number(v)) === v ? Number(v) : v;
  23242. };
  23243. var attachProperties = function (match, location, names, rawName) {
  23244. if (rawName && !names) {
  23245. location[rawName] = toIntIfInt(match[1]);
  23246. }
  23247. else {
  23248. for (var i = 0; i < names.length; i += 1) {
  23249. if (match[i+1] != null) {
  23250. location[names[i]] = toIntIfInt(match[i+1]);
  23251. }
  23252. }
  23253. }
  23254. };
  23255. var parseReg = function (obj, location, content) {
  23256. var needsBlank = obj.name && obj.names;
  23257. if (obj.push && !location[obj.push]) {
  23258. location[obj.push] = [];
  23259. }
  23260. else if (needsBlank && !location[obj.name]) {
  23261. location[obj.name] = {};
  23262. }
  23263. var keyLocation = obj.push ?
  23264. {} : // blank object that will be pushed
  23265. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  23266. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  23267. if (obj.push) {
  23268. location[obj.push].push(keyLocation);
  23269. }
  23270. };
  23271. var grammar = require('./grammar');
  23272. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  23273. exports.parse = function (sdp) {
  23274. var session = {}
  23275. , media = []
  23276. , location = session; // points at where properties go under (one of the above)
  23277. // parse lines we understand
  23278. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  23279. var type = l[0];
  23280. var content = l.slice(2);
  23281. if (type === 'm') {
  23282. media.push({rtp: [], fmtp: []});
  23283. location = media[media.length-1]; // point at latest media line
  23284. }
  23285. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  23286. var obj = grammar[type][j];
  23287. if (obj.reg.test(content)) {
  23288. return parseReg(obj, location, content);
  23289. }
  23290. }
  23291. });
  23292. session.media = media; // link it up
  23293. return session;
  23294. };
  23295. var fmtpReducer = function (acc, expr) {
  23296. var s = expr.split('=');
  23297. if (s.length === 2) {
  23298. acc[s[0]] = toIntIfInt(s[1]);
  23299. }
  23300. return acc;
  23301. };
  23302. exports.parseFmtpConfig = function (str) {
  23303. return str.split(';').reduce(fmtpReducer, {});
  23304. };
  23305. exports.parsePayloads = function (str) {
  23306. return str.split(' ').map(Number);
  23307. };
  23308. exports.parseRemoteCandidates = function (str) {
  23309. var candidates = [];
  23310. var parts = str.split(' ').map(toIntIfInt);
  23311. for (var i = 0; i < parts.length; i += 3) {
  23312. candidates.push({
  23313. component: parts[i],
  23314. ip: parts[i + 1],
  23315. port: parts[i + 2]
  23316. });
  23317. }
  23318. return candidates;
  23319. };
  23320. },{"./grammar":83}],86:[function(require,module,exports){
  23321. var grammar = require('./grammar');
  23322. // customized util.format - discards excess arguments and can void middle ones
  23323. var formatRegExp = /%[sdv%]/g;
  23324. var format = function (formatStr) {
  23325. var i = 1;
  23326. var args = arguments;
  23327. var len = args.length;
  23328. return formatStr.replace(formatRegExp, function (x) {
  23329. if (i >= len) {
  23330. return x; // missing argument
  23331. }
  23332. var arg = args[i];
  23333. i += 1;
  23334. switch (x) {
  23335. case '%%':
  23336. return '%';
  23337. case '%s':
  23338. return String(arg);
  23339. case '%d':
  23340. return Number(arg);
  23341. case '%v':
  23342. return '';
  23343. }
  23344. });
  23345. // NB: we discard excess arguments - they are typically undefined from makeLine
  23346. };
  23347. var makeLine = function (type, obj, location) {
  23348. var str = obj.format instanceof Function ?
  23349. (obj.format(obj.push ? location : location[obj.name])) :
  23350. obj.format;
  23351. var args = [type + '=' + str];
  23352. if (obj.names) {
  23353. for (var i = 0; i < obj.names.length; i += 1) {
  23354. var n = obj.names[i];
  23355. if (obj.name) {
  23356. args.push(location[obj.name][n]);
  23357. }
  23358. else { // for mLine and push attributes
  23359. args.push(location[obj.names[i]]);
  23360. }
  23361. }
  23362. }
  23363. else {
  23364. args.push(location[obj.name]);
  23365. }
  23366. return format.apply(null, args);
  23367. };
  23368. // RFC specified order
  23369. // TODO: extend this with all the rest
  23370. var defaultOuterOrder = [
  23371. 'v', 'o', 's', 'i',
  23372. 'u', 'e', 'p', 'c',
  23373. 'b', 't', 'r', 'z', 'a'
  23374. ];
  23375. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  23376. module.exports = function (session, opts) {
  23377. opts = opts || {};
  23378. // ensure certain properties exist
  23379. if (session.version == null) {
  23380. session.version = 0; // "v=0" must be there (only defined version atm)
  23381. }
  23382. if (session.name == null) {
  23383. session.name = " "; // "s= " must be there if no meaningful name set
  23384. }
  23385. session.media.forEach(function (mLine) {
  23386. if (mLine.payloads == null) {
  23387. mLine.payloads = "";
  23388. }
  23389. });
  23390. var outerOrder = opts.outerOrder || defaultOuterOrder;
  23391. var innerOrder = opts.innerOrder || defaultInnerOrder;
  23392. var sdp = [];
  23393. // loop through outerOrder for matching properties on session
  23394. outerOrder.forEach(function (type) {
  23395. grammar[type].forEach(function (obj) {
  23396. if (obj.name in session && session[obj.name] != null) {
  23397. sdp.push(makeLine(type, obj, session));
  23398. }
  23399. else if (obj.push in session && session[obj.push] != null) {
  23400. session[obj.push].forEach(function (el) {
  23401. sdp.push(makeLine(type, obj, el));
  23402. });
  23403. }
  23404. });
  23405. });
  23406. // then for each media line, follow the innerOrder
  23407. session.media.forEach(function (mLine) {
  23408. sdp.push(makeLine('m', grammar.m[0], mLine));
  23409. innerOrder.forEach(function (type) {
  23410. grammar[type].forEach(function (obj) {
  23411. if (obj.name in mLine && mLine[obj.name] != null) {
  23412. sdp.push(makeLine(type, obj, mLine));
  23413. }
  23414. else if (obj.push in mLine && mLine[obj.push] != null) {
  23415. mLine[obj.push].forEach(function (el) {
  23416. sdp.push(makeLine(type, obj, el));
  23417. });
  23418. }
  23419. });
  23420. });
  23421. });
  23422. return sdp.join('\r\n') + '\r\n';
  23423. };
  23424. },{"./grammar":83}],87:[function(require,module,exports){
  23425. var MediaStreamType = {
  23426. VIDEO_TYPE: "Video",
  23427. AUDIO_TYPE: "Audio"
  23428. };
  23429. module.exports = MediaStreamType;
  23430. },{}],88:[function(require,module,exports){
  23431. var RTCBrowserType = {
  23432. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  23433. RTC_BROWSER_FIREFOX: "rtc_browser.firefox"
  23434. };
  23435. module.exports = RTCBrowserType;
  23436. },{}],89:[function(require,module,exports){
  23437. var RTCEvents = {
  23438. LASTN_CHANGED: "rtc.lastn_changed",
  23439. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  23440. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  23441. SIMULCAST_LAYER_CHANGED: "rtc.simulcast_layer_changed",
  23442. SIMULCAST_LAYER_CHANGING: "rtc.simulcast_layer_changing",
  23443. SIMULCAST_START: "rtc.simlcast_start",
  23444. SIMULCAST_STOP: "rtc.simlcast_stop"
  23445. };
  23446. module.exports = RTCEvents;
  23447. },{}],90:[function(require,module,exports){
  23448. var Resolutions = {
  23449. "1080": {
  23450. width: 1920,
  23451. height: 1080,
  23452. order: 7
  23453. },
  23454. "fullhd": {
  23455. width: 1920,
  23456. height: 1080,
  23457. order: 7
  23458. },
  23459. "720": {
  23460. width: 1280,
  23461. height: 720,
  23462. order: 6
  23463. },
  23464. "hd": {
  23465. width: 1280,
  23466. height: 720,
  23467. order: 6
  23468. },
  23469. "960": {
  23470. width: 960,
  23471. height: 720,
  23472. order: 5
  23473. },
  23474. "640": {
  23475. width: 640,
  23476. height: 480,
  23477. order: 4
  23478. },
  23479. "vga": {
  23480. width: 640,
  23481. height: 480,
  23482. order: 4
  23483. },
  23484. "360": {
  23485. width: 640,
  23486. height: 360,
  23487. order: 3
  23488. },
  23489. "320": {
  23490. width: 320,
  23491. height: 240,
  23492. order: 2
  23493. },
  23494. "180": {
  23495. width: 320,
  23496. height: 180,
  23497. order: 1
  23498. }
  23499. };
  23500. module.exports = Resolutions;
  23501. },{}],91:[function(require,module,exports){
  23502. var StreamEventTypes = {
  23503. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  23504. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  23505. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  23506. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  23507. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended",
  23508. EVENT_TYPE_REMOTE_CHANGED: "stream.changed"
  23509. };
  23510. module.exports = StreamEventTypes;
  23511. },{}],92:[function(require,module,exports){
  23512. var UIEvents = {
  23513. NICKNAME_CHANGED: "UI.nickname_changed",
  23514. SELECTED_ENDPOINT: "UI.selected_endpoint",
  23515. PINNED_ENDPOINT: "UI.pinned_endpoint"
  23516. };
  23517. module.exports = UIEvents;
  23518. },{}],93:[function(require,module,exports){
  23519. var AuthenticationEvents = {
  23520. /**
  23521. * Event callback arguments:
  23522. * function(authenticationEnabled, userIdentity)
  23523. * authenticationEnabled - indicates whether authentication has been enabled
  23524. * in this session
  23525. * userIdentity - if user has been logged in then it contains user name. If
  23526. * contains 'null' or 'undefined' then user is not logged in.
  23527. */
  23528. IDENTITY_UPDATED: "authentication.identity_updated"
  23529. };
  23530. module.exports = AuthenticationEvents;
  23531. },{}],94:[function(require,module,exports){
  23532. var CQEvents = {
  23533. LOCALSTATS_UPDATED: "cq.localstats_updated",
  23534. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  23535. STOP: "cq.stop"
  23536. };
  23537. module.exports = CQEvents;
  23538. },{}],95:[function(require,module,exports){
  23539. var DesktopSharingEventTypes = {
  23540. INIT: "ds.init",
  23541. SWITCHING_DONE: "ds.switching_done",
  23542. NEW_STREAM_CREATED: "ds.new_stream_created"
  23543. };
  23544. module.exports = DesktopSharingEventTypes;
  23545. },{}],96:[function(require,module,exports){
  23546. module.exports = {
  23547. getLanguages : function () {
  23548. var languages = [];
  23549. for(var lang in this)
  23550. {
  23551. if(typeof this[lang] === "string")
  23552. languages.push(this[lang]);
  23553. }
  23554. return languages;
  23555. },
  23556. EN: "en",
  23557. BG: "bg",
  23558. DE: "de",
  23559. TR: "tr"
  23560. }
  23561. },{}],97:[function(require,module,exports){
  23562. var XMPPEvents = {
  23563. CONFERENCE_CERATED: "xmpp.conferenceCreated.jingle",
  23564. CALL_TERMINATED: "xmpp.callterminated.jingle",
  23565. CALL_INCOMING: "xmpp.callincoming.jingle",
  23566. DISPOSE_CONFERENCE: "xmpp.dispoce_confernce",
  23567. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  23568. KICKED: "xmpp.kicked",
  23569. BRIDGE_DOWN: "xmpp.bridge_down",
  23570. USER_ID_CHANGED: "xmpp.user_id_changed",
  23571. CHANGED_STREAMS: "xmpp.changed_streams",
  23572. MUC_JOINED: "xmpp.muc_joined",
  23573. MUC_ENTER: "xmpp.muc_enter",
  23574. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  23575. MUC_LEFT: "xmpp.muc_left",
  23576. MUC_DESTROYED: "xmpp.muc_destroyed",
  23577. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  23578. REMOTE_STATS: "xmpp.remote_stats",
  23579. LOCALROLE_CHANGED: "xmpp.localrole_changed",
  23580. PRESENCE_STATUS: "xmpp.presence_status",
  23581. RESERVATION_ERROR: "xmpp.room_reservation_error",
  23582. SUBJECT_CHANGED: "xmpp.subject_changed",
  23583. MESSAGE_RECEIVED: "xmpp.message_received",
  23584. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  23585. PASSWORD_REQUIRED: "xmpp.password_required",
  23586. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  23587. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  23588. ETHERPAD: "xmpp.etherpad"
  23589. };
  23590. module.exports = XMPPEvents;
  23591. },{}],98:[function(require,module,exports){
  23592. // Copyright Joyent, Inc. and other Node contributors.
  23593. //
  23594. // Permission is hereby granted, free of charge, to any person obtaining a
  23595. // copy of this software and associated documentation files (the
  23596. // "Software"), to deal in the Software without restriction, including
  23597. // without limitation the rights to use, copy, modify, merge, publish,
  23598. // distribute, sublicense, and/or sell copies of the Software, and to permit
  23599. // persons to whom the Software is furnished to do so, subject to the
  23600. // following conditions:
  23601. //
  23602. // The above copyright notice and this permission notice shall be included
  23603. // in all copies or substantial portions of the Software.
  23604. //
  23605. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  23606. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23607. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  23608. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  23609. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  23610. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  23611. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  23612. function EventEmitter() {
  23613. this._events = this._events || {};
  23614. this._maxListeners = this._maxListeners || undefined;
  23615. }
  23616. module.exports = EventEmitter;
  23617. // Backwards-compat with node 0.10.x
  23618. EventEmitter.EventEmitter = EventEmitter;
  23619. EventEmitter.prototype._events = undefined;
  23620. EventEmitter.prototype._maxListeners = undefined;
  23621. // By default EventEmitters will print a warning if more than 10 listeners are
  23622. // added to it. This is a useful default which helps finding memory leaks.
  23623. EventEmitter.defaultMaxListeners = 10;
  23624. // Obviously not all Emitters should be limited to 10. This function allows
  23625. // that to be increased. Set to zero for unlimited.
  23626. EventEmitter.prototype.setMaxListeners = function(n) {
  23627. if (!isNumber(n) || n < 0 || isNaN(n))
  23628. throw TypeError('n must be a positive number');
  23629. this._maxListeners = n;
  23630. return this;
  23631. };
  23632. EventEmitter.prototype.emit = function(type) {
  23633. var er, handler, len, args, i, listeners;
  23634. if (!this._events)
  23635. this._events = {};
  23636. // If there is no 'error' event listener then throw.
  23637. if (type === 'error') {
  23638. if (!this._events.error ||
  23639. (isObject(this._events.error) && !this._events.error.length)) {
  23640. er = arguments[1];
  23641. if (er instanceof Error) {
  23642. throw er; // Unhandled 'error' event
  23643. }
  23644. throw TypeError('Uncaught, unspecified "error" event.');
  23645. }
  23646. }
  23647. handler = this._events[type];
  23648. if (isUndefined(handler))
  23649. return false;
  23650. if (isFunction(handler)) {
  23651. switch (arguments.length) {
  23652. // fast cases
  23653. case 1:
  23654. handler.call(this);
  23655. break;
  23656. case 2:
  23657. handler.call(this, arguments[1]);
  23658. break;
  23659. case 3:
  23660. handler.call(this, arguments[1], arguments[2]);
  23661. break;
  23662. // slower
  23663. default:
  23664. len = arguments.length;
  23665. args = new Array(len - 1);
  23666. for (i = 1; i < len; i++)
  23667. args[i - 1] = arguments[i];
  23668. handler.apply(this, args);
  23669. }
  23670. } else if (isObject(handler)) {
  23671. len = arguments.length;
  23672. args = new Array(len - 1);
  23673. for (i = 1; i < len; i++)
  23674. args[i - 1] = arguments[i];
  23675. listeners = handler.slice();
  23676. len = listeners.length;
  23677. for (i = 0; i < len; i++)
  23678. listeners[i].apply(this, args);
  23679. }
  23680. return true;
  23681. };
  23682. EventEmitter.prototype.addListener = function(type, listener) {
  23683. var m;
  23684. if (!isFunction(listener))
  23685. throw TypeError('listener must be a function');
  23686. if (!this._events)
  23687. this._events = {};
  23688. // To avoid recursion in the case that type === "newListener"! Before
  23689. // adding it to the listeners, first emit "newListener".
  23690. if (this._events.newListener)
  23691. this.emit('newListener', type,
  23692. isFunction(listener.listener) ?
  23693. listener.listener : listener);
  23694. if (!this._events[type])
  23695. // Optimize the case of one listener. Don't need the extra array object.
  23696. this._events[type] = listener;
  23697. else if (isObject(this._events[type]))
  23698. // If we've already got an array, just append.
  23699. this._events[type].push(listener);
  23700. else
  23701. // Adding the second element, need to change to array.
  23702. this._events[type] = [this._events[type], listener];
  23703. // Check for listener leak
  23704. if (isObject(this._events[type]) && !this._events[type].warned) {
  23705. var m;
  23706. if (!isUndefined(this._maxListeners)) {
  23707. m = this._maxListeners;
  23708. } else {
  23709. m = EventEmitter.defaultMaxListeners;
  23710. }
  23711. if (m && m > 0 && this._events[type].length > m) {
  23712. this._events[type].warned = true;
  23713. console.error('(node) warning: possible EventEmitter memory ' +
  23714. 'leak detected. %d listeners added. ' +
  23715. 'Use emitter.setMaxListeners() to increase limit.',
  23716. this._events[type].length);
  23717. if (typeof console.trace === 'function') {
  23718. // not supported in IE 10
  23719. console.trace();
  23720. }
  23721. }
  23722. }
  23723. return this;
  23724. };
  23725. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  23726. EventEmitter.prototype.once = function(type, listener) {
  23727. if (!isFunction(listener))
  23728. throw TypeError('listener must be a function');
  23729. var fired = false;
  23730. function g() {
  23731. this.removeListener(type, g);
  23732. if (!fired) {
  23733. fired = true;
  23734. listener.apply(this, arguments);
  23735. }
  23736. }
  23737. g.listener = listener;
  23738. this.on(type, g);
  23739. return this;
  23740. };
  23741. // emits a 'removeListener' event iff the listener was removed
  23742. EventEmitter.prototype.removeListener = function(type, listener) {
  23743. var list, position, length, i;
  23744. if (!isFunction(listener))
  23745. throw TypeError('listener must be a function');
  23746. if (!this._events || !this._events[type])
  23747. return this;
  23748. list = this._events[type];
  23749. length = list.length;
  23750. position = -1;
  23751. if (list === listener ||
  23752. (isFunction(list.listener) && list.listener === listener)) {
  23753. delete this._events[type];
  23754. if (this._events.removeListener)
  23755. this.emit('removeListener', type, listener);
  23756. } else if (isObject(list)) {
  23757. for (i = length; i-- > 0;) {
  23758. if (list[i] === listener ||
  23759. (list[i].listener && list[i].listener === listener)) {
  23760. position = i;
  23761. break;
  23762. }
  23763. }
  23764. if (position < 0)
  23765. return this;
  23766. if (list.length === 1) {
  23767. list.length = 0;
  23768. delete this._events[type];
  23769. } else {
  23770. list.splice(position, 1);
  23771. }
  23772. if (this._events.removeListener)
  23773. this.emit('removeListener', type, listener);
  23774. }
  23775. return this;
  23776. };
  23777. EventEmitter.prototype.removeAllListeners = function(type) {
  23778. var key, listeners;
  23779. if (!this._events)
  23780. return this;
  23781. // not listening for removeListener, no need to emit
  23782. if (!this._events.removeListener) {
  23783. if (arguments.length === 0)
  23784. this._events = {};
  23785. else if (this._events[type])
  23786. delete this._events[type];
  23787. return this;
  23788. }
  23789. // emit removeListener for all listeners on all events
  23790. if (arguments.length === 0) {
  23791. for (key in this._events) {
  23792. if (key === 'removeListener') continue;
  23793. this.removeAllListeners(key);
  23794. }
  23795. this.removeAllListeners('removeListener');
  23796. this._events = {};
  23797. return this;
  23798. }
  23799. listeners = this._events[type];
  23800. if (isFunction(listeners)) {
  23801. this.removeListener(type, listeners);
  23802. } else {
  23803. // LIFO order
  23804. while (listeners.length)
  23805. this.removeListener(type, listeners[listeners.length - 1]);
  23806. }
  23807. delete this._events[type];
  23808. return this;
  23809. };
  23810. EventEmitter.prototype.listeners = function(type) {
  23811. var ret;
  23812. if (!this._events || !this._events[type])
  23813. ret = [];
  23814. else if (isFunction(this._events[type]))
  23815. ret = [this._events[type]];
  23816. else
  23817. ret = this._events[type].slice();
  23818. return ret;
  23819. };
  23820. EventEmitter.listenerCount = function(emitter, type) {
  23821. var ret;
  23822. if (!emitter._events || !emitter._events[type])
  23823. ret = 0;
  23824. else if (isFunction(emitter._events[type]))
  23825. ret = 1;
  23826. else
  23827. ret = emitter._events[type].length;
  23828. return ret;
  23829. };
  23830. function isFunction(arg) {
  23831. return typeof arg === 'function';
  23832. }
  23833. function isNumber(arg) {
  23834. return typeof arg === 'number';
  23835. }
  23836. function isObject(arg) {
  23837. return typeof arg === 'object' && arg !== null;
  23838. }
  23839. function isUndefined(arg) {
  23840. return arg === void 0;
  23841. }
  23842. },{}]},{},[1])(1)
  23843. });